1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 type writerTestEntry struct {
21 type writerTest struct {
22 file string // filename of expected output
23 entries []*writerTestEntry
26 var writerTests = []*writerTest{
28 file: "testdata/writer.tar",
29 entries: []*writerTestEntry{
56 contents: "Google.com\n",
60 // The truncated test file was produced using these commands:
61 // dd if=/dev/zero bs=1048576 count=16384 > /tmp/16gig.txt
62 // tar -b 1 -c -f- /tmp/16gig.txt | dd bs=512 count=8 > writer-big.tar
64 file: "testdata/writer-big.tar",
65 entries: []*writerTestEntry{
68 Name: "tmp/16gig.txt",
84 // Render byte array in a two-character hexadecimal string, spaced for easy visual inspection.
85 func bytestr(offset int, b []byte) string {
87 s := fmt.Sprintf("%04x ", offset)
88 for _, ch := range b {
90 case '0' <= ch && ch <= '9', 'A' <= ch && ch <= 'Z', 'a' <= ch && ch <= 'z':
91 s += fmt.Sprintf(" %c", ch)
93 s += fmt.Sprintf(" %02x", ch)
99 // Render a pseudo-diff between two blocks of bytes.
100 func bytediff(a []byte, b []byte) string {
102 s := fmt.Sprintf("(%d bytes vs. %d bytes)\n", len(a), len(b))
103 for offset := 0; len(a)+len(b) > 0; offset += rowLen {
104 na, nb := rowLen, rowLen
111 sa := bytestr(offset, a[0:na])
112 sb := bytestr(offset, b[0:nb])
114 s += fmt.Sprintf("-%v\n+%v\n", sa, sb)
122 func TestWriter(t *testing.T) {
124 for i, test := range writerTests {
125 expected, err := ioutil.ReadFile(test.file)
127 t.Errorf("test %d: Unexpected error: %v", i, err)
131 buf := new(bytes.Buffer)
132 tw := NewWriter(iotest.TruncateWriter(buf, 4<<10)) // only catch the first 4 KB
133 for j, entry := range test.entries {
134 if err := tw.WriteHeader(entry.header); err != nil {
135 t.Errorf("test %d, entry %d: Failed writing header: %v", i, j, err)
138 if _, err := io.WriteString(tw, entry.contents); err != nil {
139 t.Errorf("test %d, entry %d: Failed writing contents: %v", i, j, err)
143 if err := tw.Close(); err != nil {
144 t.Errorf("test %d: Failed closing archive: %v", err)
148 actual := buf.Bytes()
149 if !bytes.Equal(expected, actual) {
150 t.Errorf("test %d: Incorrect result: (-=expected, +=actual)\n%v",
151 i, bytediff(expected, actual))