Skip to content

Instantly share code, notes, and snippets.

@invidian
Created February 26, 2020 13:18
Show Gist options
  • Save invidian/0aabe5170e7d3a58a643ae1abf59fc18 to your computer and use it in GitHub Desktop.
Save invidian/0aabe5170e7d3a58a643ae1abf59fc18 to your computer and use it in GitHub Desktop.
Bad CopyWalker
package main
import (
"io"
"io/ioutil"
"os"
"reflect"
"strings"
"testing"
)
const v1 = `
This
is
my
test
data
of
version
1
`
const v2 = `
Version
2
`
func TestCopyWalker(t *testing.T) {
// Create temp file to test on.
tmpfile, err := ioutil.TempFile("", "example")
if err != nil {
t.Fatalf("Creating temp file should succeed, got: %v", err)
}
defer os.Remove(tmpfile.Name())
foo(t, tmpfile.Name(), v1)
foo(t, tmpfile.Name(), v2)
}
func foo(t *testing.T, p string, data string) {
// Re-implement CopyingWalker.
targetFile, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
t.Fatalf("Opening tmp file %s should succeed, got: %v", p, err)
}
defer targetFile.Close()
if _, err := io.Copy(targetFile, strings.NewReader(data)); err != nil {
t.Fatalf("Writing to tmp file should succeed, got: %v", err)
}
// Read the file to make sure we wrote correct output.
dataRead, err := ioutil.ReadFile(p)
if err != nil {
t.Fatalf("Reading tmp file should succeed, got: %v", err)
}
if !reflect.DeepEqual(data, string(dataRead)) {
t.Fatalf("expected:\n===\n%s\n===\n, got:\n===\n%s\n===\n", data, dataRead)
}
}
@invidian
Copy link
Author

Results as expected:

--- FAIL: TestCopyWalker (0.00s)
    test_test.go:62: expected:
        ===
        
        Version
        2
        
        ===
        , got:
        ===
        
        Version
        2
        
        test
        data
        of
        version
        1
        
        ===
FAIL
exit status 1
FAIL	foo	0.001s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment