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