forked from edsrzf/mmap-go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
mmap_test.go
102 lines (87 loc) · 2 KB
/
mmap_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright 2011 Evan Shaw. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// These tests are adapted from gommap: http://labix.org/gommap
// Copyright (c) 2010, Gustavo Niemeyer <[email protected]>
package mmap
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
var testData = []byte("0123456789ABCDEF")
var testPath = filepath.Join(os.TempDir(), "testdata")
func init() {
f := openFile(os.O_RDWR|os.O_CREATE)
f.Write(testData)
f.Close()
}
func openFile(flags int) *os.File {
f, err := os.OpenFile(testPath, flags, 0644)
if err != nil {
panic(err.Error())
}
return f
}
func TestUnmap(t *testing.T) {
f := openFile(os.O_RDONLY)
defer f.Close()
mmap, err := Map(f, RDONLY, 0)
if err != nil {
t.Errorf("error mapping: %s", err)
}
if err := mmap.Unmap(); err != nil {
t.Errorf("error unmapping: %s", err)
}
}
func TestReadWrite(t *testing.T) {
f := openFile(os.O_RDWR)
defer f.Close()
mmap, err := Map(f, RDWR, 0)
if err != nil {
t.Errorf("error mapping: %s", err)
}
defer mmap.Unmap()
if !bytes.Equal(testData, mmap) {
t.Errorf("mmap != testData: %q, %q", mmap, testData)
}
mmap[9] = 'X'
mmap.Flush()
fileData, err := ioutil.ReadAll(f)
if err != nil {
t.Errorf("error reading file: %s", err)
}
if !bytes.Equal(fileData, []byte("012345678XABCDEF")) {
t.Errorf("file wasn't modified")
}
// leave things how we found them
mmap[9] = '9'
mmap.Flush()
}
func TestProtFlagsAndErr(t *testing.T) {
f := openFile(os.O_RDONLY)
defer f.Close()
if _, err := Map(f, RDWR, 0); err == nil {
t.Errorf("expected error")
}
}
func TestFlags(t *testing.T) {
f := openFile(os.O_RDWR)
defer f.Close()
mmap, err := Map(f, COPY, 0)
if err != nil {
t.Errorf("error mapping: %s", err)
}
defer mmap.Unmap()
mmap[9] = 'X'
mmap.Flush()
fileData, err := ioutil.ReadAll(f)
if err != nil {
t.Errorf("error reading file: %s", err)
}
if !bytes.Equal(fileData, testData) {
t.Errorf("file was modified")
}
}