• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1package go_embed_data
2
3import (
4	"io"
5	"log"
6	"os"
7	"path/filepath"
8	"testing"
9
10	"github.com/bazelbuild/rules_go/go/tools/bazel"
11)
12
13func TestMain(m *testing.M) {
14	// This test must run from the workspace root since it accesses files using
15	// relative paths. We look at parent directories until we find AUTHORS,
16	// then change to that directory.
17	for {
18		if _, err := os.Stat("AUTHORS"); err == nil {
19			break
20		}
21		if err := os.Chdir(".."); err != nil {
22			log.Fatal(err)
23		}
24		if wd, err := os.Getwd(); err != nil {
25			log.Fatal(err)
26		} else if wd == "/" {
27			log.Fatal("could not locate workspace root")
28		}
29	}
30	os.Exit(m.Run())
31}
32
33func TestCgo(t *testing.T) {
34	if len(cgo) == 0 {
35		t.Fatalf("cgo is empty")
36	}
37}
38
39func TestEmpty(t *testing.T) {
40	if len(empty) != 0 {
41		t.Fatalf("empty is not empty")
42	}
43}
44
45func TestSingle(t *testing.T) {
46	checkFile(t, "AUTHORS", single)
47}
48
49func TestLocal(t *testing.T) {
50	for path, data := range local {
51		checkFile(t, path, data)
52	}
53}
54
55func TestExternal(t *testing.T) {
56	for path, data := range ext {
57		checkFile(t, path, data)
58	}
59}
60
61func TestFlat(t *testing.T) {
62	for key := range flat {
63		if filepath.Base(key) != key {
64			t.Errorf("filename %q is not flat", key)
65		}
66	}
67}
68
69func TestString(t *testing.T) {
70	for _, data := range str {
71		var _ string = data // just check the type; contents covered by other tests.
72	}
73}
74
75func TestUnpack(t *testing.T) {
76	for _, data := range unpack {
77		checkFile(t, "tests/extras/go_embed_data/BUILD.bazel", data)
78	}
79	for _, key := range []string{
80		"from-zip/BUILD.bazel",
81		// Note: Bazel's pkg_tar always adds a leading "./" to its outputs,
82		// but tars generated from other sources can match the original
83		// inputs more exactly.
84		"./from-tar/BUILD.bazel",
85	} {
86		if _, ok := unpack[key]; !ok {
87			t.Errorf("filename %q is not in unpacked set", key)
88		}
89	}
90}
91
92func checkFile(t *testing.T, rawPath string, data []byte) {
93	path, err := bazel.Runfile(rawPath)
94	if err != nil {
95		t.Error(err)
96		return
97	}
98
99	f, err := os.Open(path)
100	if err != nil {
101		t.Error(err)
102		return
103	}
104	defer f.Close()
105
106	count := 0
107	buffer := make([]byte, 8192)
108	for {
109		n, err := f.Read(buffer)
110		if err != nil && err != io.EOF {
111			t.Error(err)
112			return
113		}
114		if n == 0 {
115			return
116		}
117		if n > len(data) {
118			t.Errorf("%q: file on disk is longer than embedded data", path)
119			return
120		}
121
122		for i := 0; i < n; i++ {
123			if buffer[i] != data[i] {
124				t.Errorf("data mismatch on file %q at offset %d", path, count+i)
125				return
126			}
127		}
128		count += n
129		data = data[n:]
130	}
131}
132