Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
103 lines (87 sloc) 2.01 KB
// 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 <gustavo@niemeyer.net>
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.String())
}
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")
}
}