1
0
mirror of https://github.com/golang/go synced 2024-11-05 16:46:10 -07:00
go/internal/txtar/archive_test.go
Heschi Kreinick 9c309ee22f imports: stop using go/packages for modules
go/packages needs to call `go list` multiple times, which causes
redundant work and slows down goimports. If we reimplement `go list` in
memory, we can reuse state, saving time. `go list` also does work we
don't really need, like adding stuff to go.mod, and skipping that saves
more time.

We start with `go list -m`, which does MVS and such. The remaining work
is mostly mapping import paths and directories through the in-scope
modules to make sure we're giving the right answers. Unfortunately this
is quite subtle, and I don't know where all the traps are. I did my
best.

cmd/go already has tests for `go list`, of course, and packagestest is
not well suited to tests of this complexity. So I ripped off the script
tests in cmd/go that seemed relevant and made sure that our logic
returns the right stuff in each case. I'm sure that there are more cases
to cover, but this hit all the stuff I knew about and quite a bit I
didn't.

Since we may want to use the go/packages code path in the future, e.g.
for Bazel, I left that in place. It won't be used unless the magic env
var is set.

Files in internal and imports/testdata/mod were copied verbatim from
cmd/go.

Change-Id: I1248d99c400c1a0c7ef180d4460b9b8a3db0246b
Reviewed-on: https://go-review.googlesource.com/c/158097
Run-TryBot: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-01-22 20:29:12 +00:00

68 lines
1.4 KiB
Go

// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package txtar
import (
"bytes"
"fmt"
"reflect"
"testing"
)
var tests = []struct {
name string
text string
parsed *Archive
}{
{
name: "basic",
text: `comment1
comment2
-- file1 --
File 1 text.
-- foo ---
More file 1 text.
-- file 2 --
File 2 text.
-- empty --
-- noNL --
hello world`,
parsed: &Archive{
Comment: []byte("comment1\ncomment2\n"),
Files: []File{
{"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")},
{"file 2", []byte("File 2 text.\n")},
{"empty", []byte{}},
{"noNL", []byte("hello world\n")},
},
},
},
}
func Test(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
a := Parse([]byte(tt.text))
if !reflect.DeepEqual(a, tt.parsed) {
t.Fatalf("Parse: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
}
text := Format(a)
a = Parse(text)
if !reflect.DeepEqual(a, tt.parsed) {
t.Fatalf("Parse after Format: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed))
}
})
}
}
func shortArchive(a *Archive) string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "comment: %q\n", a.Comment)
for _, f := range a.Files {
fmt.Fprintf(&buf, "file %q: %q\n", f.Name, f.Data)
}
return buf.String()
}