-
-
Save invidian/0aabe5170e7d3a58a643ae1abf59fc18 to your computer and use it in GitHub Desktop.
Bad CopyWalker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results as expected: