github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/mmap/mmap_test.go (about) 1 package mmap 2 3 import ( 4 "github.com/flower-corp/rosedb/logger" 5 "github.com/stretchr/testify/assert" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 "testing" 10 ) 11 12 func TestMmap(t *testing.T) { 13 dir, err := ioutil.TempDir("", "rosedb-mmap-test") 14 assert.Nil(t, err) 15 path := filepath.Join(dir, "mmap.txt") 16 17 fd, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644) 18 assert.Nil(t, err) 19 defer func() { 20 if fd != nil { 21 _ = fd.Close() 22 destroyDir(path) 23 } 24 }() 25 type args struct { 26 fd *os.File 27 writable bool 28 size int64 29 } 30 tests := []struct { 31 name string 32 args args 33 wantErr bool 34 }{ 35 { 36 "normal-size", args{fd: fd, writable: true, size: 100}, false, 37 }, 38 { 39 "big-size", args{fd: fd, writable: true, size: 128 << 20}, false, 40 }, 41 } 42 for _, tt := range tests { 43 t.Run(tt.name, func(t *testing.T) { 44 got, err := Mmap(tt.args.fd, tt.args.writable, tt.args.size) 45 if (err != nil) != tt.wantErr { 46 t.Errorf("Mmap() error = %v, wantErr %v", err, tt.wantErr) 47 return 48 } 49 if int64(len(got)) != tt.args.size { 50 t.Errorf("Mmap() want buf size = %d, actual = %d", tt.args.size, len(got)) 51 } 52 }) 53 } 54 } 55 56 func TestMunmap(t *testing.T) { 57 dir, err := ioutil.TempDir("", "rosedb-mmap-test") 58 assert.Nil(t, err) 59 path := filepath.Join(dir, "mmap.txt") 60 61 fd, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644) 62 assert.Nil(t, err) 63 defer func() { 64 if fd != nil { 65 _ = fd.Close() 66 destroyDir(path) 67 } 68 }() 69 70 buf, err := Mmap(fd, true, 100) 71 assert.Nil(t, err) 72 err = Munmap(buf) 73 assert.Nil(t, err) 74 } 75 76 func TestMsync(t *testing.T) { 77 dir, err := ioutil.TempDir("", "rosedb-mmap-test") 78 assert.Nil(t, err) 79 path := filepath.Join(dir, "mmap.txt") 80 81 fd, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644) 82 assert.Nil(t, err) 83 defer func() { 84 if fd != nil { 85 _ = fd.Close() 86 destroyDir(path) 87 } 88 }() 89 90 buf, err := Mmap(fd, true, 128) 91 assert.Nil(t, err) 92 err = Msync(buf) 93 assert.Nil(t, err) 94 } 95 96 func TestMadvise(t *testing.T) { 97 dir, err := ioutil.TempDir("", "rosedb-mmap-test") 98 assert.Nil(t, err) 99 path := filepath.Join(dir, "mmap.txt") 100 101 fd, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644) 102 assert.Nil(t, err) 103 defer func() { 104 if fd != nil { 105 _ = fd.Close() 106 destroyDir(path) 107 } 108 }() 109 110 buf, err := Mmap(fd, true, 128) 111 assert.Nil(t, err) 112 err = Madvise(buf, false) 113 assert.Nil(t, err) 114 } 115 116 func destroyDir(dir string) { 117 if err := os.RemoveAll(dir); err != nil { 118 logger.Warnf("remove dir err: %v", err) 119 } 120 }