| package fs | |
| import ( | |
| "bytes" | |
| "os" | |
| "path" | |
| "path/filepath" | |
| "testing" | |
| ) | |
| func TestCopySourceFileToExistingDestination(t *testing.T) { | |
| dir := t.TempDir() | |
| sourcePath := path.Join(dir, "source.txt") | |
| if err := os.WriteFile(sourcePath, []byte("abc"), 0666); err != nil { | |
| t.Fatalf("%v", err) | |
| } | |
| destPath := path.Join(dir, "dest.txt") | |
| if err := os.WriteFile(destPath, []byte("defghi"), 0666); err != nil { | |
| t.Fatalf("%v", err) | |
| } | |
| if err := CopyFile(sourcePath, destPath, 0666); err != nil { | |
| t.Fatalf("%v", err) | |
| } | |
| contents, err := os.ReadFile(destPath) | |
| if err != nil { | |
| t.Fatalf("%v", err) | |
| } | |
| if string(contents) != "abc" { | |
| t.Fatalf("expected dest.txt to have contents 'abc' after copying source.txt; got %s", string(contents)) | |
| } | |
| } | |
| func TestCopyDir(t *testing.T) { | |
| var err error | |
| src := t.TempDir() | |
| dst := t.TempDir() | |
| testData := []struct { | |
| path string | |
| data string | |
| }{ | |
| { | |
| "a/b.txt", | |
| "abc", | |
| }, | |
| { | |
| "a/c/d.txt", | |
| "def", | |
| }, | |
| { | |
| "a/c/e.txt", | |
| "ghi", | |
| }, | |
| } | |
| for _, data := range testData { | |
| srcDir := path.Join(src, filepath.Dir(data.path)) | |
| err = os.MkdirAll(srcDir, 0777) | |
| if err != nil { | |
| t.Fatalf("could not make dir %s: %v", srcDir, err) | |
| } | |
| srcPath := path.Join(src, data.path) | |
| err = os.WriteFile(srcPath, []byte(data.data), 0666) | |
| if err != nil { | |
| t.Fatalf("could not write data to file %s: %v", srcPath, err) | |
| } | |
| } | |
| err = CopyDir(src, dst, 0777) | |
| if err != nil { | |
| t.Fatalf("failed to copy %s to %s: %v", src, dst, err) | |
| } | |
| for _, data := range testData { | |
| dstPath := path.Join(dst, data.path) | |
| contents, err := os.ReadFile(dstPath) | |
| if err != nil { | |
| t.Fatalf("could not read contents for %s: %v", dstPath, err) | |
| } | |
| if !bytes.Equal(contents, []byte(data.data)) { | |
| t.Fatalf("wrong contents for %s (expected %s, got %s)", dstPath, contents, data.data) | |
| } | |
| } | |
| } |