1// Copyright 2017 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 objabi
6
7import (
8	"internal/testenv"
9	"os/exec"
10	"strings"
11	"testing"
12)
13
14var escapeTests = []struct {
15		Path    string
16		Escaped string
17	}{
18		{"foo/bar/v1", "foo/bar/v1"},
19		{"foo/bar/v.1", "foo/bar/v%2e1"},
20		{"f.o.o/b.a.r/v1", "f.o.o/b.a.r/v1"},
21		{"f.o.o/b.a.r/v.1", "f.o.o/b.a.r/v%2e1"},
22		{"f.o.o/b.a.r/v..1", "f.o.o/b.a.r/v%2e%2e1"},
23		{"f.o.o/b.a.r/v..1.", "f.o.o/b.a.r/v%2e%2e1%2e"},
24		{"f.o.o/b.a.r/v%1", "f.o.o/b.a.r/v%251"},
25		{"runtime", "runtime"},
26		{"sync/atomic", "sync/atomic"},
27		{"golang.org/x/tools/godoc", "golang.org/x/tools/godoc"},
28		{"foo.bar/baz.quux", "foo.bar/baz%2equux"},
29		{"", ""},
30		{"%foo%bar", "%25foo%25bar"},
31		{"\x01\x00\x7F☺", "%01%00%7f%e2%98%ba"},
32	}
33
34func TestPathToPrefix(t *testing.T) {
35	for _, tc := range escapeTests {
36		if got := PathToPrefix(tc.Path); got != tc.Escaped {
37			t.Errorf("expected PathToPrefix(%s) = %s, got %s", tc.Path, tc.Escaped, got)
38		}
39	}
40}
41
42func TestPrefixToPath(t *testing.T) {
43	for _, tc := range escapeTests {
44		got, err := PrefixToPath(tc.Escaped)
45		if err != nil {
46			t.Errorf("expected PrefixToPath(%s) err = nil, got %v", tc.Escaped, err)
47		}
48		if got != tc.Path {
49			t.Errorf("expected PrefixToPath(%s) = %s, got %s", tc.Escaped, tc.Path, got)
50		}
51	}
52}
53
54func TestPrefixToPathError(t *testing.T) {
55	tests := []string{
56		"foo%",
57		"foo%1",
58		"foo%%12",
59		"foo%1g",
60	}
61	for _, tc := range tests {
62		_, err := PrefixToPath(tc)
63		if err == nil {
64			t.Errorf("expected PrefixToPath(%s) err != nil, got nil", tc)
65		}
66	}
67}
68
69func TestRuntimePackageList(t *testing.T) {
70	// Test that all packages imported by the runtime are marked as runtime
71	// packages.
72	testenv.MustHaveGoBuild(t)
73	goCmd, err := testenv.GoTool()
74	if err != nil {
75		t.Fatal(err)
76	}
77	pkgList, err := exec.Command(goCmd, "list", "-deps", "runtime").Output()
78	if err != nil {
79		if err, ok := err.(*exec.ExitError); ok {
80			t.Log(string(err.Stderr))
81		}
82		t.Fatal(err)
83	}
84	for _, pkg := range strings.Split(strings.TrimRight(string(pkgList), "\n"), "\n") {
85		if pkg == "unsafe" {
86			continue
87		}
88		if !LookupPkgSpecial(pkg).Runtime {
89			t.Errorf("package %s is imported by runtime, but not marked Runtime", pkg)
90		}
91	}
92}
93