1
2
3
4
5 package txtar
6
7 import (
8 "bytes"
9 "fmt"
10 "reflect"
11 "testing"
12 )
13
14 func TestParse(t *testing.T) {
15 var tests = []struct {
16 name string
17 text string
18 parsed *Archive
19 }{
20 {
21 name: "basic",
22 text: `comment1
23 comment2
24 -- file1 --
25 File 1 text.
26 -- foo ---
27 More file 1 text.
28 -- file 2 --
29 File 2 text.
30 -- empty --
31 -- noNL --
32 hello world
33 -- empty filename line --
34 some content
35 -- --`,
36 parsed: &Archive{
37 Comment: []byte("comment1\ncomment2\n"),
38 Files: []File{
39 {"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")},
40 {"file 2", []byte("File 2 text.\n")},
41 {"empty", []byte{}},
42 {"noNL", []byte("hello world\n")},
43 {"empty filename line", []byte("some content\n-- --\n")},
44 },
45 },
46 },
47 }
48 for _, tt := range tests {
49 t.Run(tt.name, func(t *testing.T) {
50 a := Parse([]byte(tt.text))
51 if !reflect.DeepEqual(a, tt.parsed) {
52 t.Fatalf("Parse: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
53 }
54 text := Format(a)
55 a = Parse(text)
56 if !reflect.DeepEqual(a, tt.parsed) {
57 t.Fatalf("Parse after Format: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
58 }
59 })
60 }
61 }
62
63 func TestFormat(t *testing.T) {
64 var tests = []struct {
65 name string
66 input *Archive
67 wanted string
68 }{
69 {
70 name: "basic",
71 input: &Archive{
72 Comment: []byte("comment1\ncomment2\n"),
73 Files: []File{
74 {"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")},
75 {"file 2", []byte("File 2 text.\n")},
76 {"empty", []byte{}},
77 {"noNL", []byte("hello world")},
78 },
79 },
80 wanted: `comment1
81 comment2
82 -- file1 --
83 File 1 text.
84 -- foo ---
85 More file 1 text.
86 -- file 2 --
87 File 2 text.
88 -- empty --
89 -- noNL --
90 hello world
91 `,
92 },
93 }
94 for _, tt := range tests {
95 t.Run(tt.name, func(t *testing.T) {
96 result := Format(tt.input)
97 if string(result) != tt.wanted {
98 t.Errorf("Wrong output. \nGot:\n%s\nWant:\n%s\n", string(result), tt.wanted)
99 }
100 })
101 }
102 }
103
104 func shortArchive(a *Archive) string {
105 var buf bytes.Buffer
106 fmt.Fprintf(&buf, "comment: %q\n", a.Comment)
107 for _, f := range a.Files {
108 fmt.Fprintf(&buf, "file %q: %q\n", f.Name, f.Data)
109 }
110 return buf.String()
111 }
112
View as plain text