func TestCopy(t *testing.T) { srcb, dstb := new(bytes.Buffer), new(bytes.Buffer) for tname, tt := range copyTests() { // Reset buffers between tests srcb.Reset() dstb.Reset() // Last file name (needed for gzip.NewReader) var fname string // Seed the src srcw := writer(t, tname, srcb, tt.srcType) for _, f := range tt.in { srcw.NextFile(f.name, iotest.FileInfo(t, f.contents)) mustCopy(t, tname, srcw, bytes.NewReader(f.contents)) fname = f.name } mustClose(t, tname, srcw) // Perform the copy srcr := reader(t, tname, srcb, tt.srcType, fname) dstw := writer(t, tname, dstb, tt.dstType) if err := archive.Copy(dstw, srcr); err != nil { t.Fatalf("%s: %v", tname, err) } srcr.Close() // Read-only mustClose(t, tname, dstw) // Read back dst to confirm our expectations dstr := reader(t, tname, dstb, tt.dstType, fname) for _, want := range tt.in { buf := new(bytes.Buffer) name, err := dstr.NextFile() if err != nil { t.Fatalf("%s: %v", tname, err) } mustCopy(t, tname, buf, dstr) got := file{ name: name, contents: buf.Bytes(), } switch { case got.name != want.name: t.Errorf("%s: got file %q but want file %q", tname, got.name, want.name) case !bytes.Equal(got.contents, want.contents): t.Errorf("%s: mismatched contents in %q: got %q but want %q", tname, got.name, got.contents, want.contents) } } dstr.Close() } }
// writeFiles iterates through the files we want and writes them as a zipped // file. func writeFiles(t *testing.T, f *os.File, tname string, want map[string][]byte) { w := zip.NewWriter(f) defer w.Close() // Write zipped files for fname, fbytes := range want { fi := iotest.FileInfo(t, fbytes) // Write the file err := w.NextFile(fname, fi) switch err { case io.EOF: break default: t.Fatalf("%s: write header for next file: %v", tname, err) case nil: // Proceed below } if _, err := io.Copy(w, bytes.NewReader(fbytes)); err != nil { t.Fatalf("%s: copy to writer: %v", tname, err) } } }