2017-07-09 16:17:20 -04:00
|
|
|
package utils
|
2017-06-22 22:03:18 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
2017-06-29 06:46:47 -04:00
|
|
|
"path/filepath"
|
2017-06-22 22:03:18 -04:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
2017-07-03 11:48:06 -04:00
|
|
|
var testDataDir = filepath.Join("testdata")
|
2017-06-29 06:46:47 -04:00
|
|
|
|
|
|
|
func testFile(name string) string {
|
|
|
|
return filepath.Join(testDataDir, name)
|
|
|
|
}
|
|
|
|
|
2017-06-22 22:03:18 -04:00
|
|
|
func TestCopyFileContents(t *testing.T) {
|
|
|
|
f, err := ioutil.TempFile("", "ioutil-test")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
2017-07-02 09:10:40 -04:00
|
|
|
err = f.Close()
|
|
|
|
require.NoError(t, err)
|
2017-06-29 06:46:47 -04:00
|
|
|
err = CopyFileContents(f.Name(), testFile("test.txt"), 0x644)
|
2017-06-22 22:03:18 -04:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
b, err := ioutil.ReadFile(f.Name())
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
require.Equal(t, "content\n", string(b))
|
|
|
|
|
2017-06-29 06:46:47 -04:00
|
|
|
err = CopyFileContents(f.Name(), testFile("missing.txt"), 0x644)
|
2017-06-22 22:03:18 -04:00
|
|
|
require.Error(t, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestReadFileMagic(t *testing.T) {
|
2017-06-29 06:46:47 -04:00
|
|
|
b, err := ReadFileMagic(testFile("test.txt"))
|
2017-06-22 22:03:18 -04:00
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "cont", string(b))
|
|
|
|
|
2017-06-29 06:46:47 -04:00
|
|
|
b, err = ReadFileMagic(testFile("empty.txt"))
|
2017-06-22 22:03:18 -04:00
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, []byte{0, 0, 0, 0}, b)
|
|
|
|
|
2017-07-01 20:49:15 -04:00
|
|
|
_, err = ReadFileMagic(testFile("missing.txt"))
|
2017-06-22 22:03:18 -04:00
|
|
|
require.Error(t, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestVisitCreatedFile(t *testing.T) {
|
|
|
|
f, err := ioutil.TempFile("", "ioutil-test")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
2017-07-02 09:10:40 -04:00
|
|
|
err = f.Close()
|
|
|
|
require.NoError(t, err)
|
|
|
|
err = VisitCreatedFile(f.Name(), func(w io.Writer) error {
|
|
|
|
_, e := w.Write([]byte("test"))
|
|
|
|
return e
|
2017-06-22 22:03:18 -04:00
|
|
|
})
|
2017-07-02 09:10:40 -04:00
|
|
|
require.NoError(t, err)
|
2017-06-22 22:03:18 -04:00
|
|
|
|
|
|
|
b, err := ioutil.ReadFile(f.Name())
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
require.Equal(t, "test", string(b))
|
|
|
|
}
|