xref: /aosp_15_r20/external/bazelbuild-rules_go/go/tools/internal/txtar/archive_test.go (revision 9bb1b549b6a84214c53be0924760be030e66b93a)
1// 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
14var tests = []struct {
15	name   string
16	text   string
17	parsed *Archive
18}{
19	{
20		name: "basic",
21		text: `comment1
22comment2
23-- file1 --
24File 1 text.
25-- foo ---
26More file 1 text.
27-- file 2 --
28File 2 text.
29-- empty --
30-- noNL --
31hello world`,
32		parsed: &Archive{
33			Comment: []byte("comment1\ncomment2\n"),
34			Files: []File{
35				{"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")},
36				{"file 2", []byte("File 2 text.\n")},
37				{"empty", []byte{}},
38				{"noNL", []byte("hello world\n")},
39			},
40		},
41	},
42}
43
44func Test(t *testing.T) {
45	for _, tt := range tests {
46		t.Run(tt.name, func(t *testing.T) {
47			a := Parse([]byte(tt.text))
48			if !reflect.DeepEqual(a, tt.parsed) {
49				t.Fatalf("Parse: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
50			}
51			text := Format(a)
52			a = Parse(text)
53			if !reflect.DeepEqual(a, tt.parsed) {
54				t.Fatalf("Parse after Format: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
55			}
56		})
57	}
58}
59
60func shortArchive(a *Archive) string {
61	var buf bytes.Buffer
62	fmt.Fprintf(&buf, "comment: %q\n", a.Comment)
63	for _, f := range a.Files {
64		fmt.Fprintf(&buf, "file %q: %q\n", f.Name, f.Data)
65	}
66	return buf.String()
67}
68