blob: 1f79f8d112a5e4cd4a420670284587353245dfb9 [file] [log] [blame]
Heschi Kreinick9c309ee2019-01-16 16:24:49 -05001// Copyright 2018 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.
4
5package txtar
6
7import (
8 "bytes"
9 "fmt"
10 "reflect"
11 "testing"
12)
13
Arda Güçlü17847a82019-11-20 22:29:10 +030014func 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
Heschi Kreinick9c309ee2019-01-16 16:24:49 -050023comment2
24-- file1 --
25File 1 text.
26-- foo ---
27More file 1 text.
28-- file 2 --
29File 2 text.
30-- empty --
31-- noNL --
32hello world`,
Arda Güçlü17847a82019-11-20 22:29:10 +030033 parsed: &Archive{
34 Comment: []byte("comment1\ncomment2\n"),
35 Files: []File{
36 {"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")},
37 {"file 2", []byte("File 2 text.\n")},
38 {"empty", []byte{}},
39 {"noNL", []byte("hello world\n")},
40 },
Heschi Kreinick9c309ee2019-01-16 16:24:49 -050041 },
42 },
Arda Güçlü17847a82019-11-20 22:29:10 +030043 }
Heschi Kreinick9c309ee2019-01-16 16:24:49 -050044 for _, tt := range tests {
45 t.Run(tt.name, func(t *testing.T) {
46 a := Parse([]byte(tt.text))
47 if !reflect.DeepEqual(a, tt.parsed) {
48 t.Fatalf("Parse: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
49 }
50 text := Format(a)
51 a = Parse(text)
52 if !reflect.DeepEqual(a, tt.parsed) {
53 t.Fatalf("Parse after Format: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
54 }
55 })
56 }
57}
58
Arda Güçlü17847a82019-11-20 22:29:10 +030059func TestFormat(t *testing.T) {
60 var tests = []struct {
61 name string
62 input *Archive
63 wanted string
64 }{
65 {
66 name: "basic",
67 input: &Archive{
68 Comment: []byte("comment1\ncomment2\n"),
69 Files: []File{
70 {"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")},
71 {"file 2", []byte("File 2 text.\n")},
72 {"empty", []byte{}},
73 {"noNL", []byte("hello world\n")},
74 },
75 },
76 wanted: `comment1
77comment2
78-- file1 --
79File 1 text.
80-- foo ---
81More file 1 text.
82-- file 2 --
83File 2 text.
84-- empty --
85-- noNL --
86hello world
87`,
88 },
89 }
90 for _, tt := range tests {
91 t.Run(tt.name, func(t *testing.T) {
92 result := Format(tt.input)
93 if !reflect.DeepEqual(string(result), tt.wanted) {
94 t.Errorf("Wrong output. \nGot:\n%s\nWant:\n%s\n", string(result), tt.wanted)
95 }
96 })
97 }
98}
99
Heschi Kreinick9c309ee2019-01-16 16:24:49 -0500100func shortArchive(a *Archive) string {
101 var buf bytes.Buffer
102 fmt.Fprintf(&buf, "comment: %q\n", a.Comment)
103 for _, f := range a.Files {
104 fmt.Fprintf(&buf, "file %q: %q\n", f.Name, f.Data)
105 }
106 return buf.String()
107}