1// Copyright 2011 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 test
6
7import (
8	"bytes"
9	"crypto/sha256"
10	"errors"
11	"fmt"
12	"go/ast"
13	"go/build"
14	"go/doc"
15	"go/parser"
16	"go/token"
17	"io"
18	"io/ioutil"
19	"os"
20	"os/exec"
21	"path"
22	"path/filepath"
23	"regexp"
24	"sort"
25	"strconv"
26	"strings"
27	"sync"
28	"text/template"
29	"time"
30	"unicode"
31	"unicode/utf8"
32
33	"cmd/go/internal/base"
34	"cmd/go/internal/cache"
35	"cmd/go/internal/cfg"
36	"cmd/go/internal/load"
37	"cmd/go/internal/str"
38	"cmd/go/internal/work"
39	"cmd/internal/test2json"
40)
41
42// Break init loop.
43func init() {
44	CmdTest.Run = runTest
45}
46
47const testUsage = "test [build/test flags] [packages] [build/test flags & test binary flags]"
48
49var CmdTest = &base.Command{
50	CustomFlags: true,
51	UsageLine:   testUsage,
52	Short:       "test packages",
53	Long: `
54'Go test' automates testing the packages named by the import paths.
55It prints a summary of the test results in the format:
56
57	ok   archive/tar   0.011s
58	FAIL archive/zip   0.022s
59	ok   compress/gzip 0.033s
60	...
61
62followed by detailed output for each failed package.
63
64'Go test' recompiles each package along with any files with names matching
65the file pattern "*_test.go".
66These additional files can contain test functions, benchmark functions, and
67example functions. See 'go help testfunc' for more.
68Each listed package causes the execution of a separate test binary.
69Files whose names begin with "_" (including "_test.go") or "." are ignored.
70
71Test files that declare a package with the suffix "_test" will be compiled as a
72separate package, and then linked and run with the main test binary.
73
74The go tool will ignore a directory named "testdata", making it available
75to hold ancillary data needed by the tests.
76
77As part of building a test binary, go test runs go vet on the package
78and its test source files to identify significant problems. If go vet
79finds any problems, go test reports those and does not run the test binary.
80Only a high-confidence subset of the default go vet checks are used.
81To disable the running of go vet, use the -vet=off flag.
82
83All test output and summary lines are printed to the go command's
84standard output, even if the test printed them to its own standard
85error. (The go command's standard error is reserved for printing
86errors building the tests.)
87
88Go test runs in two different modes:
89
90The first, called local directory mode, occurs when go test is
91invoked with no package arguments (for example, 'go test' or 'go
92test -v'). In this mode, go test compiles the package sources and
93tests found in the current directory and then runs the resulting
94test binary. In this mode, caching (discussed below) is disabled.
95After the package test finishes, go test prints a summary line
96showing the test status ('ok' or 'FAIL'), package name, and elapsed
97time.
98
99The second, called package list mode, occurs when go test is invoked
100with explicit package arguments (for example 'go test math', 'go
101test ./...', and even 'go test .'). In this mode, go test compiles
102and tests each of the packages listed on the command line. If a
103package test passes, go test prints only the final 'ok' summary
104line. If a package test fails, go test prints the full test output.
105If invoked with the -bench or -v flag, go test prints the full
106output even for passing package tests, in order to display the
107requested benchmark results or verbose logging.
108
109In package list mode only, go test caches successful package test
110results to avoid unnecessary repeated running of tests. When the
111result of a test can be recovered from the cache, go test will
112redisplay the previous output instead of running the test binary
113again. When this happens, go test prints '(cached)' in place of the
114elapsed time in the summary line.
115
116The rule for a match in the cache is that the run involves the same
117test binary and the flags on the command line come entirely from a
118restricted set of 'cacheable' test flags, defined as -cpu, -list,
119-parallel, -run, -short, and -v. If a run of go test has any test
120or non-test flags outside this set, the result is not cached. To
121disable test caching, use any test flag or argument other than the
122cacheable flags. The idiomatic way to disable test caching explicitly
123is to use -count=1. Tests that open files within the package's source
124root (usually $GOPATH) or that consult environment variables only
125match future runs in which the files and environment variables are unchanged.
126A cached test result is treated as executing in no time at all,
127so a successful package test result will be cached and reused
128regardless of -timeout setting.
129
130` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
131
132For more about build flags, see 'go help build'.
133For more about specifying packages, see 'go help packages'.
134
135See also: go build, go vet.
136`,
137}
138
139const testFlag1 = `
140In addition to the build flags, the flags handled by 'go test' itself are:
141
142	-args
143	    Pass the remainder of the command line (everything after -args)
144	    to the test binary, uninterpreted and unchanged.
145	    Because this flag consumes the remainder of the command line,
146	    the package list (if present) must appear before this flag.
147
148	-c
149	    Compile the test binary to pkg.test but do not run it
150	    (where pkg is the last element of the package's import path).
151	    The file name can be changed with the -o flag.
152
153	-exec xprog
154	    Run the test binary using xprog. The behavior is the same as
155	    in 'go run'. See 'go help run' for details.
156
157	-i
158	    Install packages that are dependencies of the test.
159	    Do not run the test.
160
161	-json
162	    Convert test output to JSON suitable for automated processing.
163	    See 'go doc test2json' for the encoding details.
164
165	-o file
166	    Compile the test binary to the named file.
167	    The test still runs (unless -c or -i is specified).
168
169The test binary also accepts flags that control execution of the test; these
170flags are also accessible by 'go test'.
171`
172
173// Usage prints the usage message for 'go test -h' and exits.
174func Usage() {
175	os.Stderr.WriteString(testUsage + "\n\n" +
176		strings.TrimSpace(testFlag1) + "\n\n\t" +
177		strings.TrimSpace(testFlag2) + "\n")
178	os.Exit(2)
179}
180
181var HelpTestflag = &base.Command{
182	UsageLine: "testflag",
183	Short:     "testing flags",
184	Long: `
185The 'go test' command takes both flags that apply to 'go test' itself
186and flags that apply to the resulting test binary.
187
188Several of the flags control profiling and write an execution profile
189suitable for "go tool pprof"; run "go tool pprof -h" for more
190information. The --alloc_space, --alloc_objects, and --show_bytes
191options of pprof control how the information is presented.
192
193The following flags are recognized by the 'go test' command and
194control the execution of any test:
195
196	` + strings.TrimSpace(testFlag2) + `
197`,
198}
199
200const testFlag2 = `
201	-bench regexp
202	    Run only those benchmarks matching a regular expression.
203	    By default, no benchmarks are run.
204	    To run all benchmarks, use '-bench .' or '-bench=.'.
205	    The regular expression is split by unbracketed slash (/)
206	    characters into a sequence of regular expressions, and each
207	    part of a benchmark's identifier must match the corresponding
208	    element in the sequence, if any. Possible parents of matches
209	    are run with b.N=1 to identify sub-benchmarks. For example,
210	    given -bench=X/Y, top-level benchmarks matching X are run
211	    with b.N=1 to find any sub-benchmarks matching Y, which are
212	    then run in full.
213
214	-benchtime t
215	    Run enough iterations of each benchmark to take t, specified
216	    as a time.Duration (for example, -benchtime 1h30s).
217	    The default is 1 second (1s).
218
219	-count n
220	    Run each test and benchmark n times (default 1).
221	    If -cpu is set, run n times for each GOMAXPROCS value.
222	    Examples are always run once.
223
224	-cover
225	    Enable coverage analysis.
226	    Note that because coverage works by annotating the source
227	    code before compilation, compilation and test failures with
228	    coverage enabled may report line numbers that don't correspond
229	    to the original sources.
230
231	-covermode set,count,atomic
232	    Set the mode for coverage analysis for the package[s]
233	    being tested. The default is "set" unless -race is enabled,
234	    in which case it is "atomic".
235	    The values:
236		set: bool: does this statement run?
237		count: int: how many times does this statement run?
238		atomic: int: count, but correct in multithreaded tests;
239			significantly more expensive.
240	    Sets -cover.
241
242	-coverpkg pattern1,pattern2,pattern3
243	    Apply coverage analysis in each test to packages matching the patterns.
244	    The default is for each test to analyze only the package being tested.
245	    See 'go help packages' for a description of package patterns.
246	    Sets -cover.
247
248	-cpu 1,2,4
249	    Specify a list of GOMAXPROCS values for which the tests or
250	    benchmarks should be executed. The default is the current value
251	    of GOMAXPROCS.
252
253	-failfast
254	    Do not start new tests after the first test failure.
255
256	-list regexp
257	    List tests, benchmarks, or examples matching the regular expression.
258	    No tests, benchmarks or examples will be run. This will only
259	    list top-level tests. No subtest or subbenchmarks will be shown.
260
261	-parallel n
262	    Allow parallel execution of test functions that call t.Parallel.
263	    The value of this flag is the maximum number of tests to run
264	    simultaneously; by default, it is set to the value of GOMAXPROCS.
265	    Note that -parallel only applies within a single test binary.
266	    The 'go test' command may run tests for different packages
267	    in parallel as well, according to the setting of the -p flag
268	    (see 'go help build').
269
270	-run regexp
271	    Run only those tests and examples matching the regular expression.
272	    For tests, the regular expression is split by unbracketed slash (/)
273	    characters into a sequence of regular expressions, and each part
274	    of a test's identifier must match the corresponding element in
275	    the sequence, if any. Note that possible parents of matches are
276	    run too, so that -run=X/Y matches and runs and reports the result
277	    of all tests matching X, even those without sub-tests matching Y,
278	    because it must run them to look for those sub-tests.
279
280	-short
281	    Tell long-running tests to shorten their run time.
282	    It is off by default but set during all.bash so that installing
283	    the Go tree can run a sanity check but not spend time running
284	    exhaustive tests.
285
286	-timeout d
287	    If a test binary runs longer than duration d, panic.
288	    If d is 0, the timeout is disabled.
289	    The default is 10 minutes (10m).
290
291	-v
292	    Verbose output: log all tests as they are run. Also print all
293	    text from Log and Logf calls even if the test succeeds.
294
295	-vet list
296	    Configure the invocation of "go vet" during "go test"
297	    to use the comma-separated list of vet checks.
298	    If list is empty, "go test" runs "go vet" with a curated list of
299	    checks believed to be always worth addressing.
300	    If list is "off", "go test" does not run "go vet" at all.
301
302The following flags are also recognized by 'go test' and can be used to
303profile the tests during execution:
304
305	-benchmem
306	    Print memory allocation statistics for benchmarks.
307
308	-blockprofile block.out
309	    Write a goroutine blocking profile to the specified file
310	    when all tests are complete.
311	    Writes test binary as -c would.
312
313	-blockprofilerate n
314	    Control the detail provided in goroutine blocking profiles by
315	    calling runtime.SetBlockProfileRate with n.
316	    See 'go doc runtime.SetBlockProfileRate'.
317	    The profiler aims to sample, on average, one blocking event every
318	    n nanoseconds the program spends blocked. By default,
319	    if -test.blockprofile is set without this flag, all blocking events
320	    are recorded, equivalent to -test.blockprofilerate=1.
321
322	-coverprofile cover.out
323	    Write a coverage profile to the file after all tests have passed.
324	    Sets -cover.
325
326	-cpuprofile cpu.out
327	    Write a CPU profile to the specified file before exiting.
328	    Writes test binary as -c would.
329
330	-memprofile mem.out
331	    Write a memory profile to the file after all tests have passed.
332	    Writes test binary as -c would.
333
334	-memprofilerate n
335	    Enable more precise (and expensive) memory profiles by setting
336	    runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
337	    To profile all memory allocations, use -test.memprofilerate=1
338	    and pass --alloc_space flag to the pprof tool.
339
340	-mutexprofile mutex.out
341	    Write a mutex contention profile to the specified file
342	    when all tests are complete.
343	    Writes test binary as -c would.
344
345	-mutexprofilefraction n
346	    Sample 1 in n stack traces of goroutines holding a
347	    contended mutex.
348
349	-outputdir directory
350	    Place output files from profiling in the specified directory,
351	    by default the directory in which "go test" is running.
352
353	-trace trace.out
354	    Write an execution trace to the specified file before exiting.
355
356Each of these flags is also recognized with an optional 'test.' prefix,
357as in -test.v. When invoking the generated test binary (the result of
358'go test -c') directly, however, the prefix is mandatory.
359
360The 'go test' command rewrites or removes recognized flags,
361as appropriate, both before and after the optional package list,
362before invoking the test binary.
363
364For instance, the command
365
366	go test -v -myflag testdata -cpuprofile=prof.out -x
367
368will compile the test binary and then run it as
369
370	pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
371
372(The -x flag is removed because it applies only to the go command's
373execution, not to the test itself.)
374
375The test flags that generate profiles (other than for coverage) also
376leave the test binary in pkg.test for use when analyzing the profiles.
377
378When 'go test' runs a test binary, it does so from within the
379corresponding package's source code directory. Depending on the test,
380it may be necessary to do the same when invoking a generated test
381binary directly.
382
383The command-line package list, if present, must appear before any
384flag not known to the go test command. Continuing the example above,
385the package list would have to appear before -myflag, but could appear
386on either side of -v.
387
388To keep an argument for a test binary from being interpreted as a
389known flag or a package name, use -args (see 'go help test') which
390passes the remainder of the command line through to the test binary
391uninterpreted and unaltered.
392
393For instance, the command
394
395	go test -v -args -x -v
396
397will compile the test binary and then run it as
398
399	pkg.test -test.v -x -v
400
401Similarly,
402
403	go test -args math
404
405will compile the test binary and then run it as
406
407	pkg.test math
408
409In the first example, the -x and the second -v are passed through to the
410test binary unchanged and with no effect on the go command itself.
411In the second example, the argument math is passed through to the test
412binary, instead of being interpreted as the package list.
413`
414
415var HelpTestfunc = &base.Command{
416	UsageLine: "testfunc",
417	Short:     "testing functions",
418	Long: `
419The 'go test' command expects to find test, benchmark, and example functions
420in the "*_test.go" files corresponding to the package under test.
421
422A test function is one named TestXxx (where Xxx does not start with a
423lower case letter) and should have the signature,
424
425	func TestXxx(t *testing.T) { ... }
426
427A benchmark function is one named BenchmarkXxx and should have the signature,
428
429	func BenchmarkXxx(b *testing.B) { ... }
430
431An example function is similar to a test function but, instead of using
432*testing.T to report success or failure, prints output to os.Stdout.
433If the last comment in the function starts with "Output:" then the output
434is compared exactly against the comment (see examples below). If the last
435comment begins with "Unordered output:" then the output is compared to the
436comment, however the order of the lines is ignored. An example with no such
437comment is compiled but not executed. An example with no text after
438"Output:" is compiled, executed, and expected to produce no output.
439
440Godoc displays the body of ExampleXxx to demonstrate the use
441of the function, constant, or variable Xxx. An example of a method M with
442receiver type T or *T is named ExampleT_M. There may be multiple examples
443for a given function, constant, or variable, distinguished by a trailing _xxx,
444where xxx is a suffix not beginning with an upper case letter.
445
446Here is an example of an example:
447
448	func ExamplePrintln() {
449		Println("The output of\nthis example.")
450		// Output: The output of
451		// this example.
452	}
453
454Here is another example where the ordering of the output is ignored:
455
456	func ExamplePerm() {
457		for _, value := range Perm(4) {
458			fmt.Println(value)
459		}
460
461		// Unordered output: 4
462		// 2
463		// 1
464		// 3
465		// 0
466	}
467
468The entire test file is presented as the example when it contains a single
469example function, at least one other function, type, variable, or constant
470declaration, and no test or benchmark functions.
471
472See the documentation of the testing package for more information.
473`,
474}
475
476var (
477	testC            bool            // -c flag
478	testCover        bool            // -cover flag
479	testCoverMode    string          // -covermode flag
480	testCoverPaths   []string        // -coverpkg flag
481	testCoverPkgs    []*load.Package // -coverpkg flag
482	testCoverProfile string          // -coverprofile flag
483	testOutputDir    string          // -outputdir flag
484	testO            string          // -o flag
485	testProfile      string          // profiling flag that limits test to one package
486	testNeedBinary   bool            // profile needs to keep binary around
487	testJSON         bool            // -json flag
488	testV            bool            // -v flag
489	testTimeout      string          // -timeout flag
490	testArgs         []string
491	testBench        bool
492	testList         bool
493	testShowPass     bool   // show passing output
494	testVetList      string // -vet flag
495	pkgArgs          []string
496	pkgs             []*load.Package
497
498	testKillTimeout = 10 * time.Minute
499	testCacheExpire time.Time // ignore cached test results before this time
500)
501
502var testMainDeps = []string{
503	// Dependencies for testmain.
504	"os",
505	"testing",
506	"testing/internal/testdeps",
507}
508
509// testVetFlags is the list of flags to pass to vet when invoked automatically during go test.
510var testVetFlags = []string{
511	// TODO(rsc): Decide which tests are enabled by default.
512	// See golang.org/issue/18085.
513	// "-asmdecl",
514	// "-assign",
515	"-atomic",
516	"-bool",
517	"-buildtags",
518	// "-cgocall",
519	// "-composites",
520	// "-copylocks",
521	// "-httpresponse",
522	// "-lostcancel",
523	// "-methods",
524	"-nilfunc",
525	"-printf",
526	// "-rangeloops",
527	// "-shift",
528	// "-structtags",
529	// "-tests",
530	// "-unreachable",
531	// "-unsafeptr",
532	// "-unusedresult",
533}
534
535func runTest(cmd *base.Command, args []string) {
536	pkgArgs, testArgs = testFlags(args)
537
538	work.FindExecCmd() // initialize cached result
539
540	work.BuildInit()
541	work.VetFlags = testVetFlags
542
543	pkgs = load.PackagesForBuild(pkgArgs)
544	if len(pkgs) == 0 {
545		base.Fatalf("no packages to test")
546	}
547
548	if testC && len(pkgs) != 1 {
549		base.Fatalf("cannot use -c flag with multiple packages")
550	}
551	if testO != "" && len(pkgs) != 1 {
552		base.Fatalf("cannot use -o flag with multiple packages")
553	}
554	if testProfile != "" && len(pkgs) != 1 {
555		base.Fatalf("cannot use %s flag with multiple packages", testProfile)
556	}
557	initCoverProfile()
558	defer closeCoverProfile()
559
560	// If a test timeout was given and is parseable, set our kill timeout
561	// to that timeout plus one minute. This is a backup alarm in case
562	// the test wedges with a goroutine spinning and its background
563	// timer does not get a chance to fire.
564	if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
565		testKillTimeout = dt + 1*time.Minute
566	} else if err == nil && dt == 0 {
567		// An explicit zero disables the test timeout.
568		// Let it have one century (almost) before we kill it.
569		testKillTimeout = 100 * 365 * 24 * time.Hour
570	}
571
572	// show passing test output (after buffering) with -v flag.
573	// must buffer because tests are running in parallel, and
574	// otherwise the output will get mixed.
575	testShowPass = testV || testList
576
577	// For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
578	if cfg.BuildI && testO != "" {
579		testC = true
580	}
581
582	// Read testcache expiration time, if present.
583	// (We implement go clean -testcache by writing an expiration date
584	// instead of searching out and deleting test result cache entries.)
585	if dir := cache.DefaultDir(); dir != "off" {
586		if data, _ := ioutil.ReadFile(filepath.Join(dir, "testexpire.txt")); len(data) > 0 && data[len(data)-1] == '\n' {
587			if t, err := strconv.ParseInt(string(data[:len(data)-1]), 10, 64); err == nil {
588				testCacheExpire = time.Unix(0, t)
589			}
590		}
591	}
592
593	var b work.Builder
594	b.Init()
595
596	if cfg.BuildI {
597		cfg.BuildV = testV
598
599		deps := make(map[string]bool)
600		for _, dep := range testMainDeps {
601			deps[dep] = true
602		}
603
604		for _, p := range pkgs {
605			// Dependencies for each test.
606			for _, path := range p.Imports {
607				deps[path] = true
608			}
609			for _, path := range p.Resolve(p.TestImports) {
610				deps[path] = true
611			}
612			for _, path := range p.Resolve(p.XTestImports) {
613				deps[path] = true
614			}
615		}
616
617		// translate C to runtime/cgo
618		if deps["C"] {
619			delete(deps, "C")
620			deps["runtime/cgo"] = true
621		}
622		// Ignore pseudo-packages.
623		delete(deps, "unsafe")
624
625		all := []string{}
626		for path := range deps {
627			if !build.IsLocalImport(path) {
628				all = append(all, path)
629			}
630		}
631		sort.Strings(all)
632
633		a := &work.Action{Mode: "go test -i"}
634		for _, p := range load.PackagesForBuild(all) {
635			if cfg.BuildToolchainName == "gccgo" && p.Standard {
636				// gccgo's standard library packages
637				// can not be reinstalled.
638				continue
639			}
640			a.Deps = append(a.Deps, b.CompileAction(work.ModeInstall, work.ModeInstall, p))
641		}
642		b.Do(a)
643		if !testC || a.Failed {
644			return
645		}
646		b.Init()
647	}
648
649	var builds, runs, prints []*work.Action
650
651	if testCoverPaths != nil {
652		match := make([]func(*load.Package) bool, len(testCoverPaths))
653		matched := make([]bool, len(testCoverPaths))
654		for i := range testCoverPaths {
655			match[i] = load.MatchPackage(testCoverPaths[i], base.Cwd)
656		}
657
658		// Select for coverage all dependencies matching the testCoverPaths patterns.
659		for _, p := range load.PackageList(pkgs) {
660			haveMatch := false
661			for i := range testCoverPaths {
662				if match[i](p) {
663					matched[i] = true
664					haveMatch = true
665				}
666			}
667
668			// Silently ignore attempts to run coverage on
669			// sync/atomic when using atomic coverage mode.
670			// Atomic coverage mode uses sync/atomic, so
671			// we can't also do coverage on it.
672			if testCoverMode == "atomic" && p.Standard && p.ImportPath == "sync/atomic" {
673				continue
674			}
675
676			// If using the race detector, silently ignore
677			// attempts to run coverage on the runtime
678			// packages. It will cause the race detector
679			// to be invoked before it has been initialized.
680			if cfg.BuildRace && p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal")) {
681				continue
682			}
683
684			if haveMatch {
685				testCoverPkgs = append(testCoverPkgs, p)
686			}
687		}
688
689		// Warn about -coverpkg arguments that are not actually used.
690		for i := range testCoverPaths {
691			if !matched[i] {
692				fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on matches for pattern %s\n", testCoverPaths[i])
693			}
694		}
695
696		// Mark all the coverage packages for rebuilding with coverage.
697		for _, p := range testCoverPkgs {
698			// There is nothing to cover in package unsafe; it comes from the compiler.
699			if p.ImportPath == "unsafe" {
700				continue
701			}
702			p.Internal.CoverMode = testCoverMode
703			var coverFiles []string
704			coverFiles = append(coverFiles, p.GoFiles...)
705			coverFiles = append(coverFiles, p.CgoFiles...)
706			coverFiles = append(coverFiles, p.TestGoFiles...)
707			p.Internal.CoverVars = declareCoverVars(p.ImportPath, coverFiles...)
708			if testCover && testCoverMode == "atomic" {
709				ensureImport(p, "sync/atomic")
710			}
711		}
712	}
713
714	// Prepare build + run + print actions for all packages being tested.
715	for _, p := range pkgs {
716		// sync/atomic import is inserted by the cover tool. See #18486
717		if testCover && testCoverMode == "atomic" {
718			ensureImport(p, "sync/atomic")
719		}
720
721		buildTest, runTest, printTest, err := builderTest(&b, p)
722		if err != nil {
723			str := err.Error()
724			if strings.HasPrefix(str, "\n") {
725				str = str[1:]
726			}
727			failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)
728
729			if p.ImportPath != "" {
730				base.Errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
731			} else {
732				base.Errorf("%s\n%s", str, failed)
733			}
734			continue
735		}
736		builds = append(builds, buildTest)
737		runs = append(runs, runTest)
738		prints = append(prints, printTest)
739	}
740
741	// Ultimately the goal is to print the output.
742	root := &work.Action{Mode: "go test", Deps: prints}
743
744	// Force the printing of results to happen in order,
745	// one at a time.
746	for i, a := range prints {
747		if i > 0 {
748			a.Deps = append(a.Deps, prints[i-1])
749		}
750	}
751
752	// Force benchmarks to run in serial.
753	if !testC && testBench {
754		// The first run must wait for all builds.
755		// Later runs must wait for the previous run's print.
756		for i, run := range runs {
757			if i == 0 {
758				run.Deps = append(run.Deps, builds...)
759			} else {
760				run.Deps = append(run.Deps, prints[i-1])
761			}
762		}
763	}
764
765	b.Do(root)
766}
767
768// ensures that package p imports the named package
769func ensureImport(p *load.Package, pkg string) {
770	for _, d := range p.Internal.Imports {
771		if d.Name == pkg {
772			return
773		}
774	}
775
776	p1 := load.LoadPackage(pkg, &load.ImportStack{})
777	if p1.Error != nil {
778		base.Fatalf("load %s: %v", pkg, p1.Error)
779	}
780
781	p.Internal.Imports = append(p.Internal.Imports, p1)
782}
783
784var windowsBadWords = []string{
785	"install",
786	"patch",
787	"setup",
788	"update",
789}
790
791func builderTest(b *work.Builder, p *load.Package) (buildAction, runAction, printAction *work.Action, err error) {
792	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
793		build := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
794		run := &work.Action{Mode: "test run", Package: p, Deps: []*work.Action{build}}
795		addTestVet(b, p, run, nil)
796		print := &work.Action{Mode: "test print", Func: builderNoTest, Package: p, Deps: []*work.Action{run}}
797		return build, run, print, nil
798	}
799
800	// Build Package structs describing:
801	//	ptest - package + test files
802	//	pxtest - package of external test files
803	//	pmain - pkg.test binary
804	var ptest, pxtest, pmain *load.Package
805
806	localCover := testCover && testCoverPaths == nil
807
808	ptest, pxtest, err = load.GetTestPackagesFor(p, localCover || p.Name == "main")
809	if err != nil {
810		return nil, nil, nil, err
811	}
812
813	// Use last element of import path, not package name.
814	// They differ when package name is "main".
815	// But if the import path is "command-line-arguments",
816	// like it is during 'go run', use the package name.
817	var elem string
818	if p.ImportPath == "command-line-arguments" {
819		elem = p.Name
820	} else {
821		_, elem = path.Split(p.ImportPath)
822	}
823	testBinary := elem + ".test"
824
825	// Should we apply coverage analysis locally,
826	// only for this package and only for this test?
827	// Yes, if -cover is on but -coverpkg has not specified
828	// a list of packages for global coverage.
829	if localCover {
830		ptest.Internal.CoverMode = testCoverMode
831		var coverFiles []string
832		coverFiles = append(coverFiles, ptest.GoFiles...)
833		coverFiles = append(coverFiles, ptest.CgoFiles...)
834		ptest.Internal.CoverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
835	}
836
837	testDir := b.NewObjdir()
838	if err := b.Mkdir(testDir); err != nil {
839		return nil, nil, nil, err
840	}
841
842	// Action for building pkg.test.
843	pmain = &load.Package{
844		PackagePublic: load.PackagePublic{
845			Name:       "main",
846			Dir:        testDir,
847			GoFiles:    []string{"_testmain.go"},
848			ImportPath: p.ImportPath + " (testmain)",
849			Root:       p.Root,
850		},
851		Internal: load.PackageInternal{
852			Build:     &build.Package{Name: "main"},
853			OmitDebug: !testC && !testNeedBinary,
854
855			Asmflags:   p.Internal.Asmflags,
856			Gcflags:    p.Internal.Gcflags,
857			Ldflags:    p.Internal.Ldflags,
858			Gccgoflags: p.Internal.Gccgoflags,
859		},
860	}
861
862	// The generated main also imports testing, regexp, and os.
863	// Also the linker introduces implicit dependencies reported by LinkerDeps.
864	var stk load.ImportStack
865	stk.Push("testmain")
866	deps := testMainDeps // cap==len, so safe for append
867	for _, d := range load.LinkerDeps(p) {
868		deps = append(deps, d)
869	}
870	for _, dep := range deps {
871		if dep == ptest.ImportPath {
872			pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
873		} else {
874			p1 := load.LoadImport(dep, "", nil, &stk, nil, 0)
875			if p1.Error != nil {
876				return nil, nil, nil, p1.Error
877			}
878			pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
879		}
880	}
881
882	if testCoverPkgs != nil {
883		// Add imports, but avoid duplicates.
884		seen := map[*load.Package]bool{p: true, ptest: true}
885		for _, p1 := range pmain.Internal.Imports {
886			seen[p1] = true
887		}
888		for _, p1 := range testCoverPkgs {
889			if !seen[p1] {
890				seen[p1] = true
891				pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
892			}
893		}
894	}
895
896	// Do initial scan for metadata needed for writing _testmain.go
897	// Use that metadata to update the list of imports for package main.
898	// The list of imports is used by recompileForTest and by the loop
899	// afterward that gathers t.Cover information.
900	t, err := loadTestFuncs(ptest)
901	if err != nil {
902		return nil, nil, nil, err
903	}
904	if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
905		pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
906		t.ImportTest = true
907	}
908	if pxtest != nil {
909		pmain.Internal.Imports = append(pmain.Internal.Imports, pxtest)
910		t.ImportXtest = true
911	}
912
913	if ptest != p {
914		// We have made modifications to the package p being tested
915		// and are rebuilding p (as ptest).
916		// Arrange to rebuild all packages q such that
917		// the test depends on q and q depends on p.
918		// This makes sure that q sees the modifications to p.
919		// Strictly speaking, the rebuild is only necessary if the
920		// modifications to p change its export metadata, but
921		// determining that is a bit tricky, so we rebuild always.
922		recompileForTest(pmain, p, ptest, pxtest)
923	}
924
925	for _, cp := range pmain.Internal.Imports {
926		if len(cp.Internal.CoverVars) > 0 {
927			t.Cover = append(t.Cover, coverInfo{cp, cp.Internal.CoverVars})
928		}
929	}
930
931	if !cfg.BuildN {
932		// writeTestmain writes _testmain.go,
933		// using the test description gathered in t.
934		if err := writeTestmain(testDir+"_testmain.go", t); err != nil {
935			return nil, nil, nil, err
936		}
937	}
938
939	// Set compile objdir to testDir we've already created,
940	// so that the default file path stripping applies to _testmain.go.
941	b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir = testDir
942
943	a := b.LinkAction(work.ModeBuild, work.ModeBuild, pmain)
944	a.Target = testDir + testBinary + cfg.ExeSuffix
945	if cfg.Goos == "windows" {
946		// There are many reserved words on Windows that,
947		// if used in the name of an executable, cause Windows
948		// to try to ask for extra permissions.
949		// The word list includes setup, install, update, and patch,
950		// but it does not appear to be defined anywhere.
951		// We have run into this trying to run the
952		// go.codereview/patch tests.
953		// For package names containing those words, use test.test.exe
954		// instead of pkgname.test.exe.
955		// Note that this file name is only used in the Go command's
956		// temporary directory. If the -c or other flags are
957		// given, the code below will still use pkgname.test.exe.
958		// There are two user-visible effects of this change.
959		// First, you can actually run 'go test' in directories that
960		// have names that Windows thinks are installer-like,
961		// without getting a dialog box asking for more permissions.
962		// Second, in the Windows process listing during go test,
963		// the test shows up as test.test.exe, not pkgname.test.exe.
964		// That second one is a drawback, but it seems a small
965		// price to pay for the test running at all.
966		// If maintaining the list of bad words is too onerous,
967		// we could just do this always on Windows.
968		for _, bad := range windowsBadWords {
969			if strings.Contains(testBinary, bad) {
970				a.Target = testDir + "test.test" + cfg.ExeSuffix
971				break
972			}
973		}
974	}
975	buildAction = a
976	var installAction, cleanAction *work.Action
977	if testC || testNeedBinary {
978		// -c or profiling flag: create action to copy binary to ./test.out.
979		target := filepath.Join(base.Cwd, testBinary+cfg.ExeSuffix)
980		if testO != "" {
981			target = testO
982			if !filepath.IsAbs(target) {
983				target = filepath.Join(base.Cwd, target)
984			}
985		}
986		pmain.Target = target
987		installAction = &work.Action{
988			Mode:    "test build",
989			Func:    work.BuildInstallFunc,
990			Deps:    []*work.Action{buildAction},
991			Package: pmain,
992			Target:  target,
993		}
994		runAction = installAction // make sure runAction != nil even if not running test
995	}
996	if testC {
997		printAction = &work.Action{Mode: "test print (nop)", Package: p, Deps: []*work.Action{runAction}} // nop
998	} else {
999		// run test
1000		c := new(runCache)
1001		runAction = &work.Action{
1002			Mode:       "test run",
1003			Func:       c.builderRunTest,
1004			Deps:       []*work.Action{buildAction},
1005			Package:    p,
1006			IgnoreFail: true, // run (prepare output) even if build failed
1007			TryCache:   c.tryCache,
1008			Objdir:     testDir,
1009		}
1010		if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
1011			addTestVet(b, ptest, runAction, installAction)
1012		}
1013		if pxtest != nil {
1014			addTestVet(b, pxtest, runAction, installAction)
1015		}
1016		cleanAction = &work.Action{
1017			Mode:       "test clean",
1018			Func:       builderCleanTest,
1019			Deps:       []*work.Action{runAction},
1020			Package:    p,
1021			IgnoreFail: true, // clean even if test failed
1022			Objdir:     testDir,
1023		}
1024		printAction = &work.Action{
1025			Mode:       "test print",
1026			Func:       builderPrintTest,
1027			Deps:       []*work.Action{cleanAction},
1028			Package:    p,
1029			IgnoreFail: true, // print even if test failed
1030		}
1031	}
1032	if installAction != nil {
1033		if runAction != installAction {
1034			installAction.Deps = append(installAction.Deps, runAction)
1035		}
1036		if cleanAction != nil {
1037			cleanAction.Deps = append(cleanAction.Deps, installAction)
1038		}
1039	}
1040
1041	return buildAction, runAction, printAction, nil
1042}
1043
1044func addTestVet(b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
1045	if testVetList == "off" {
1046		return
1047	}
1048
1049	vet := b.VetAction(work.ModeBuild, work.ModeBuild, p)
1050	runAction.Deps = append(runAction.Deps, vet)
1051	// Install will clean the build directory.
1052	// Make sure vet runs first.
1053	// The install ordering in b.VetAction does not apply here
1054	// because we are using a custom installAction (created above).
1055	if installAction != nil {
1056		installAction.Deps = append(installAction.Deps, vet)
1057	}
1058}
1059
1060func recompileForTest(pmain, preal, ptest, pxtest *load.Package) {
1061	// The "test copy" of preal is ptest.
1062	// For each package that depends on preal, make a "test copy"
1063	// that depends on ptest. And so on, up the dependency tree.
1064	testCopy := map[*load.Package]*load.Package{preal: ptest}
1065	for _, p := range load.PackageList([]*load.Package{pmain}) {
1066		if p == preal {
1067			continue
1068		}
1069		// Copy on write.
1070		didSplit := p == pmain || p == pxtest
1071		split := func() {
1072			if didSplit {
1073				return
1074			}
1075			didSplit = true
1076			if testCopy[p] != nil {
1077				panic("recompileForTest loop")
1078			}
1079			p1 := new(load.Package)
1080			testCopy[p] = p1
1081			*p1 = *p
1082			p1.Internal.Imports = make([]*load.Package, len(p.Internal.Imports))
1083			copy(p1.Internal.Imports, p.Internal.Imports)
1084			p = p1
1085			p.Target = ""
1086		}
1087
1088		// Update p.Internal.Imports to use test copies.
1089		for i, imp := range p.Internal.Imports {
1090			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
1091				split()
1092				p.Internal.Imports[i] = p1
1093			}
1094		}
1095	}
1096}
1097
1098// isTestFile reports whether the source file is a set of tests and should therefore
1099// be excluded from coverage analysis.
1100func isTestFile(file string) bool {
1101	// We don't cover tests, only the code they test.
1102	return strings.HasSuffix(file, "_test.go")
1103}
1104
1105// declareCoverVars attaches the required cover variables names
1106// to the files, to be used when annotating the files.
1107func declareCoverVars(importPath string, files ...string) map[string]*load.CoverVar {
1108	coverVars := make(map[string]*load.CoverVar)
1109	coverIndex := 0
1110	// We create the cover counters as new top-level variables in the package.
1111	// We need to avoid collisions with user variables (GoCover_0 is unlikely but still)
1112	// and more importantly with dot imports of other covered packages,
1113	// so we append 12 hex digits from the SHA-256 of the import path.
1114	// The point is only to avoid accidents, not to defeat users determined to
1115	// break things.
1116	sum := sha256.Sum256([]byte(importPath))
1117	h := fmt.Sprintf("%x", sum[:6])
1118	for _, file := range files {
1119		if isTestFile(file) {
1120			continue
1121		}
1122		coverVars[file] = &load.CoverVar{
1123			File: filepath.Join(importPath, file),
1124			Var:  fmt.Sprintf("GoCover_%d_%x", coverIndex, h),
1125		}
1126		coverIndex++
1127	}
1128	return coverVars
1129}
1130
1131var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
1132
1133type runCache struct {
1134	disableCache bool // cache should be disabled for this run
1135
1136	buf *bytes.Buffer
1137	id1 cache.ActionID
1138	id2 cache.ActionID
1139}
1140
1141// stdoutMu and lockedStdout provide a locked standard output
1142// that guarantees never to interlace writes from multiple
1143// goroutines, so that we can have multiple JSON streams writing
1144// to a lockedStdout simultaneously and know that events will
1145// still be intelligible.
1146var stdoutMu sync.Mutex
1147
1148type lockedStdout struct{}
1149
1150func (lockedStdout) Write(b []byte) (int, error) {
1151	stdoutMu.Lock()
1152	defer stdoutMu.Unlock()
1153	return os.Stdout.Write(b)
1154}
1155
1156// builderRunTest is the action for running a test binary.
1157func (c *runCache) builderRunTest(b *work.Builder, a *work.Action) error {
1158	if a.Failed {
1159		// We were unable to build the binary.
1160		a.Failed = false
1161		a.TestOutput = new(bytes.Buffer)
1162		fmt.Fprintf(a.TestOutput, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
1163		base.SetExitStatus(1)
1164		return nil
1165	}
1166
1167	var stdout io.Writer = os.Stdout
1168	if testJSON {
1169		json := test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
1170		defer json.Close()
1171		stdout = json
1172	}
1173
1174	var buf bytes.Buffer
1175	if len(pkgArgs) == 0 || testBench {
1176		// Stream test output (no buffering) when no package has
1177		// been given on the command line (implicit current directory)
1178		// or when benchmarking.
1179		// No change to stdout.
1180	} else {
1181		// If we're only running a single package under test or if parallelism is
1182		// set to 1, and if we're displaying all output (testShowPass), we can
1183		// hurry the output along, echoing it as soon as it comes in.
1184		// We still have to copy to &buf for caching the result. This special
1185		// case was introduced in Go 1.5 and is intentionally undocumented:
1186		// the exact details of output buffering are up to the go command and
1187		// subject to change. It would be nice to remove this special case
1188		// entirely, but it is surely very helpful to see progress being made
1189		// when tests are run on slow single-CPU ARM systems.
1190		//
1191		// If we're showing JSON output, then display output as soon as
1192		// possible even when multiple tests are being run: the JSON output
1193		// events are attributed to specific package tests, so interlacing them
1194		// is OK.
1195		if testShowPass && (len(pkgs) == 1 || cfg.BuildP == 1) || testJSON {
1196			// Write both to stdout and buf, for possible saving
1197			// to cache, and for looking for the "no tests to run" message.
1198			stdout = io.MultiWriter(stdout, &buf)
1199		} else {
1200			stdout = &buf
1201		}
1202	}
1203
1204	if c.buf == nil {
1205		// We did not find a cached result using the link step action ID,
1206		// so we ran the link step. Try again now with the link output
1207		// content ID. The attempt using the action ID makes sure that
1208		// if the link inputs don't change, we reuse the cached test
1209		// result without even rerunning the linker. The attempt using
1210		// the link output (test binary) content ID makes sure that if
1211		// we have different link inputs but the same final binary,
1212		// we still reuse the cached test result.
1213		// c.saveOutput will store the result under both IDs.
1214		c.tryCacheWithID(b, a, a.Deps[0].BuildContentID())
1215	}
1216	if c.buf != nil {
1217		if stdout != &buf {
1218			stdout.Write(c.buf.Bytes())
1219			c.buf.Reset()
1220		}
1221		a.TestOutput = c.buf
1222		return nil
1223	}
1224
1225	execCmd := work.FindExecCmd()
1226	testlogArg := []string{}
1227	if !c.disableCache && len(execCmd) == 0 {
1228		testlogArg = []string{"-test.testlogfile=" + a.Objdir + "testlog.txt"}
1229	}
1230	args := str.StringList(execCmd, a.Deps[0].BuiltTarget(), testlogArg, testArgs)
1231
1232	if testCoverProfile != "" {
1233		// Write coverage to temporary profile, for merging later.
1234		for i, arg := range args {
1235			if strings.HasPrefix(arg, "-test.coverprofile=") {
1236				args[i] = "-test.coverprofile=" + a.Objdir + "_cover_.out"
1237			}
1238		}
1239	}
1240
1241	if cfg.BuildN || cfg.BuildX {
1242		b.Showcmd("", "%s", strings.Join(args, " "))
1243		if cfg.BuildN {
1244			return nil
1245		}
1246	}
1247
1248	cmd := exec.Command(args[0], args[1:]...)
1249	cmd.Dir = a.Package.Dir
1250	cmd.Env = base.EnvForDir(cmd.Dir, cfg.OrigEnv)
1251	cmd.Stdout = stdout
1252	cmd.Stderr = stdout
1253
1254	// If there are any local SWIG dependencies, we want to load
1255	// the shared library from the build directory.
1256	if a.Package.UsesSwig() {
1257		env := cmd.Env
1258		found := false
1259		prefix := "LD_LIBRARY_PATH="
1260		for i, v := range env {
1261			if strings.HasPrefix(v, prefix) {
1262				env[i] = v + ":."
1263				found = true
1264				break
1265			}
1266		}
1267		if !found {
1268			env = append(env, "LD_LIBRARY_PATH=.")
1269		}
1270		cmd.Env = env
1271	}
1272
1273	t0 := time.Now()
1274	err := cmd.Start()
1275
1276	// This is a last-ditch deadline to detect and
1277	// stop wedged test binaries, to keep the builders
1278	// running.
1279	if err == nil {
1280		tick := time.NewTimer(testKillTimeout)
1281		base.StartSigHandlers()
1282		done := make(chan error)
1283		go func() {
1284			done <- cmd.Wait()
1285		}()
1286	Outer:
1287		select {
1288		case err = <-done:
1289			// ok
1290		case <-tick.C:
1291			if base.SignalTrace != nil {
1292				// Send a quit signal in the hope that the program will print
1293				// a stack trace and exit. Give it five seconds before resorting
1294				// to Kill.
1295				cmd.Process.Signal(base.SignalTrace)
1296				select {
1297				case err = <-done:
1298					fmt.Fprintf(cmd.Stdout, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
1299					break Outer
1300				case <-time.After(5 * time.Second):
1301				}
1302			}
1303			cmd.Process.Kill()
1304			err = <-done
1305			fmt.Fprintf(cmd.Stdout, "*** Test killed: ran too long (%v).\n", testKillTimeout)
1306		}
1307		tick.Stop()
1308	}
1309	out := buf.Bytes()
1310	a.TestOutput = &buf
1311	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
1312
1313	mergeCoverProfile(cmd.Stdout, a.Objdir+"_cover_.out")
1314
1315	if err == nil {
1316		norun := ""
1317		if !testShowPass && !testJSON {
1318			buf.Reset()
1319		}
1320		if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
1321			norun = " [no tests to run]"
1322		}
1323		fmt.Fprintf(cmd.Stdout, "ok  \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
1324		c.saveOutput(a)
1325	} else {
1326		base.SetExitStatus(1)
1327		// If there was test output, assume we don't need to print the exit status.
1328		// Buf there's no test output, do print the exit status.
1329		if len(out) == 0 {
1330			fmt.Fprintf(cmd.Stdout, "%s\n", err)
1331		}
1332		fmt.Fprintf(cmd.Stdout, "FAIL\t%s\t%s\n", a.Package.ImportPath, t)
1333	}
1334
1335	if cmd.Stdout != &buf {
1336		buf.Reset() // cmd.Stdout was going to os.Stdout already
1337	}
1338	return nil
1339}
1340
1341// tryCache is called just before the link attempt,
1342// to see if the test result is cached and therefore the link is unneeded.
1343// It reports whether the result can be satisfied from cache.
1344func (c *runCache) tryCache(b *work.Builder, a *work.Action) bool {
1345	return c.tryCacheWithID(b, a, a.Deps[0].BuildActionID())
1346}
1347
1348func (c *runCache) tryCacheWithID(b *work.Builder, a *work.Action, id string) bool {
1349	if len(pkgArgs) == 0 {
1350		// Caching does not apply to "go test",
1351		// only to "go test foo" (including "go test .").
1352		if cache.DebugTest {
1353			fmt.Fprintf(os.Stderr, "testcache: caching disabled in local directory mode\n")
1354		}
1355		c.disableCache = true
1356		return false
1357	}
1358
1359	var cacheArgs []string
1360	for _, arg := range testArgs {
1361		i := strings.Index(arg, "=")
1362		if i < 0 || !strings.HasPrefix(arg, "-test.") {
1363			if cache.DebugTest {
1364				fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
1365			}
1366			c.disableCache = true
1367			return false
1368		}
1369		switch arg[:i] {
1370		case "-test.cpu",
1371			"-test.list",
1372			"-test.parallel",
1373			"-test.run",
1374			"-test.short",
1375			"-test.v":
1376			// These are cacheable.
1377			// Note that this list is documented above,
1378			// so if you add to this list, update the docs too.
1379			cacheArgs = append(cacheArgs, arg)
1380
1381		case "-test.timeout":
1382			// Special case: this is cacheable but ignored during the hash.
1383			// Do not add to cacheArgs.
1384
1385		default:
1386			// nothing else is cacheable
1387			if cache.DebugTest {
1388				fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
1389			}
1390			c.disableCache = true
1391			return false
1392		}
1393	}
1394
1395	if cache.Default() == nil {
1396		if cache.DebugTest {
1397			fmt.Fprintf(os.Stderr, "testcache: GOCACHE=off\n")
1398		}
1399		c.disableCache = true
1400		return false
1401	}
1402
1403	// The test cache result fetch is a two-level lookup.
1404	//
1405	// First, we use the content hash of the test binary
1406	// and its command-line arguments to find the
1407	// list of environment variables and files consulted
1408	// the last time the test was run with those arguments.
1409	// (To avoid unnecessary links, we store this entry
1410	// under two hashes: id1 uses the linker inputs as a
1411	// proxy for the test binary, and id2 uses the actual
1412	// test binary. If the linker inputs are unchanged,
1413	// this way we avoid the link step, even though we
1414	// do not cache link outputs.)
1415	//
1416	// Second, we compute a hash of the values of the
1417	// environment variables and the content of the files
1418	// listed in the log from the previous run.
1419	// Then we look up test output using a combination of
1420	// the hash from the first part (testID) and the hash of the
1421	// test inputs (testInputsID).
1422	//
1423	// In order to store a new test result, we must redo the
1424	// testInputsID computation using the log from the run
1425	// we want to cache, and then we store that new log and
1426	// the new outputs.
1427
1428	h := cache.NewHash("testResult")
1429	fmt.Fprintf(h, "test binary %s args %q execcmd %q", id, cacheArgs, work.ExecCmd)
1430	testID := h.Sum()
1431	if c.id1 == (cache.ActionID{}) {
1432		c.id1 = testID
1433	} else {
1434		c.id2 = testID
1435	}
1436	if cache.DebugTest {
1437		fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => %x\n", a.Package.ImportPath, id, testID)
1438	}
1439
1440	// Load list of referenced environment variables and files
1441	// from last run of testID, and compute hash of that content.
1442	data, entry, err := cache.Default().GetBytes(testID)
1443	if !bytes.HasPrefix(data, testlogMagic) || data[len(data)-1] != '\n' {
1444		if cache.DebugTest {
1445			if err != nil {
1446				fmt.Fprintf(os.Stderr, "testcache: %s: input list not found: %v\n", a.Package.ImportPath, err)
1447			} else {
1448				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed\n", a.Package.ImportPath)
1449			}
1450		}
1451		return false
1452	}
1453	testInputsID, err := computeTestInputsID(a, data)
1454	if err != nil {
1455		return false
1456	}
1457	if cache.DebugTest {
1458		fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => input ID %x => %x\n", a.Package.ImportPath, testID, testInputsID, testAndInputKey(testID, testInputsID))
1459	}
1460
1461	// Parse cached result in preparation for changing run time to "(cached)".
1462	// If we can't parse the cached result, don't use it.
1463	data, entry, err = cache.Default().GetBytes(testAndInputKey(testID, testInputsID))
1464	if len(data) == 0 || data[len(data)-1] != '\n' {
1465		if cache.DebugTest {
1466			if err != nil {
1467				fmt.Fprintf(os.Stderr, "testcache: %s: test output not found: %v\n", a.Package.ImportPath, err)
1468			} else {
1469				fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
1470			}
1471		}
1472		return false
1473	}
1474	if entry.Time.Before(testCacheExpire) {
1475		if cache.DebugTest {
1476			fmt.Fprintf(os.Stderr, "testcache: %s: test output expired due to go clean -testcache\n", a.Package.ImportPath)
1477		}
1478		return false
1479	}
1480	i := bytes.LastIndexByte(data[:len(data)-1], '\n') + 1
1481	if !bytes.HasPrefix(data[i:], []byte("ok  \t")) {
1482		if cache.DebugTest {
1483			fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
1484		}
1485		return false
1486	}
1487	j := bytes.IndexByte(data[i+len("ok  \t"):], '\t')
1488	if j < 0 {
1489		if cache.DebugTest {
1490			fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
1491		}
1492		return false
1493	}
1494	j += i + len("ok  \t") + 1
1495
1496	// Committed to printing.
1497	c.buf = new(bytes.Buffer)
1498	c.buf.Write(data[:j])
1499	c.buf.WriteString("(cached)")
1500	for j < len(data) && ('0' <= data[j] && data[j] <= '9' || data[j] == '.' || data[j] == 's') {
1501		j++
1502	}
1503	c.buf.Write(data[j:])
1504	return true
1505}
1506
1507var errBadTestInputs = errors.New("error parsing test inputs")
1508var testlogMagic = []byte("# test log\n") // known to testing/internal/testdeps/deps.go
1509
1510// computeTestInputsID computes the "test inputs ID"
1511// (see comment in tryCacheWithID above) for the
1512// test log.
1513func computeTestInputsID(a *work.Action, testlog []byte) (cache.ActionID, error) {
1514	testlog = bytes.TrimPrefix(testlog, testlogMagic)
1515	h := cache.NewHash("testInputs")
1516	pwd := a.Package.Dir
1517	for _, line := range bytes.Split(testlog, []byte("\n")) {
1518		if len(line) == 0 {
1519			continue
1520		}
1521		s := string(line)
1522		i := strings.Index(s, " ")
1523		if i < 0 {
1524			if cache.DebugTest {
1525				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
1526			}
1527			return cache.ActionID{}, errBadTestInputs
1528		}
1529		op := s[:i]
1530		name := s[i+1:]
1531		switch op {
1532		default:
1533			if cache.DebugTest {
1534				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
1535			}
1536			return cache.ActionID{}, errBadTestInputs
1537		case "getenv":
1538			fmt.Fprintf(h, "env %s %x\n", name, hashGetenv(name))
1539		case "chdir":
1540			pwd = name // always absolute
1541			fmt.Fprintf(h, "cbdir %s %x\n", name, hashStat(name))
1542		case "stat":
1543			if !filepath.IsAbs(name) {
1544				name = filepath.Join(pwd, name)
1545			}
1546			if !inDir(name, a.Package.Root) {
1547				// Do not recheck files outside the GOPATH or GOROOT root.
1548				break
1549			}
1550			fmt.Fprintf(h, "stat %s %x\n", name, hashStat(name))
1551		case "open":
1552			if !filepath.IsAbs(name) {
1553				name = filepath.Join(pwd, name)
1554			}
1555			if !inDir(name, a.Package.Root) {
1556				// Do not recheck files outside the GOPATH or GOROOT root.
1557				break
1558			}
1559			fh, err := hashOpen(name)
1560			if err != nil {
1561				if cache.DebugTest {
1562					fmt.Fprintf(os.Stderr, "testcache: %s: input file %s: %s\n", a.Package.ImportPath, name, err)
1563				}
1564				return cache.ActionID{}, err
1565			}
1566			fmt.Fprintf(h, "open %s %x\n", name, fh)
1567		}
1568	}
1569	sum := h.Sum()
1570	return sum, nil
1571}
1572
1573func inDir(path, dir string) bool {
1574	if str.HasFilePathPrefix(path, dir) {
1575		return true
1576	}
1577	xpath, err1 := filepath.EvalSymlinks(path)
1578	xdir, err2 := filepath.EvalSymlinks(dir)
1579	if err1 == nil && err2 == nil && str.HasFilePathPrefix(xpath, xdir) {
1580		return true
1581	}
1582	return false
1583}
1584
1585func hashGetenv(name string) cache.ActionID {
1586	h := cache.NewHash("getenv")
1587	v, ok := os.LookupEnv(name)
1588	if !ok {
1589		h.Write([]byte{0})
1590	} else {
1591		h.Write([]byte{1})
1592		h.Write([]byte(v))
1593	}
1594	return h.Sum()
1595}
1596
1597const modTimeCutoff = 2 * time.Second
1598
1599var errFileTooNew = errors.New("file used as input is too new")
1600
1601func hashOpen(name string) (cache.ActionID, error) {
1602	h := cache.NewHash("open")
1603	info, err := os.Stat(name)
1604	if err != nil {
1605		fmt.Fprintf(h, "err %v\n", err)
1606		return h.Sum(), nil
1607	}
1608	hashWriteStat(h, info)
1609	if info.IsDir() {
1610		names, err := ioutil.ReadDir(name)
1611		if err != nil {
1612			fmt.Fprintf(h, "err %v\n", err)
1613		}
1614		for _, f := range names {
1615			fmt.Fprintf(h, "file %s ", f.Name())
1616			hashWriteStat(h, f)
1617		}
1618	} else if info.Mode().IsRegular() {
1619		// Because files might be very large, do not attempt
1620		// to hash the entirety of their content. Instead assume
1621		// the mtime and size recorded in hashWriteStat above
1622		// are good enough.
1623		//
1624		// To avoid problems for very recent files where a new
1625		// write might not change the mtime due to file system
1626		// mtime precision, reject caching if a file was read that
1627		// is less than modTimeCutoff old.
1628		if time.Since(info.ModTime()) < modTimeCutoff {
1629			return cache.ActionID{}, errFileTooNew
1630		}
1631	}
1632	return h.Sum(), nil
1633}
1634
1635func hashStat(name string) cache.ActionID {
1636	h := cache.NewHash("stat")
1637	if info, err := os.Stat(name); err != nil {
1638		fmt.Fprintf(h, "err %v\n", err)
1639	} else {
1640		hashWriteStat(h, info)
1641	}
1642	if info, err := os.Lstat(name); err != nil {
1643		fmt.Fprintf(h, "err %v\n", err)
1644	} else {
1645		hashWriteStat(h, info)
1646	}
1647	return h.Sum()
1648}
1649
1650func hashWriteStat(h io.Writer, info os.FileInfo) {
1651	fmt.Fprintf(h, "stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
1652}
1653
1654// testAndInputKey returns the actual cache key for the pair (testID, testInputsID).
1655func testAndInputKey(testID, testInputsID cache.ActionID) cache.ActionID {
1656	return cache.Subkey(testID, fmt.Sprintf("inputs:%x", testInputsID))
1657}
1658
1659func (c *runCache) saveOutput(a *work.Action) {
1660	if c.id1 == (cache.ActionID{}) && c.id2 == (cache.ActionID{}) {
1661		return
1662	}
1663
1664	// See comment about two-level lookup in tryCacheWithID above.
1665	testlog, err := ioutil.ReadFile(a.Objdir + "testlog.txt")
1666	if err != nil || !bytes.HasPrefix(testlog, testlogMagic) || testlog[len(testlog)-1] != '\n' {
1667		if cache.DebugTest {
1668			if err != nil {
1669				fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: %v\n", a.Package.ImportPath, err)
1670			} else {
1671				fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: malformed\n", a.Package.ImportPath)
1672			}
1673		}
1674		return
1675	}
1676	testInputsID, err := computeTestInputsID(a, testlog)
1677	if err != nil {
1678		return
1679	}
1680	if c.id1 != (cache.ActionID{}) {
1681		if cache.DebugTest {
1682			fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id1, testInputsID, testAndInputKey(c.id1, testInputsID))
1683		}
1684		cache.Default().PutNoVerify(c.id1, bytes.NewReader(testlog))
1685		cache.Default().PutNoVerify(testAndInputKey(c.id1, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
1686	}
1687	if c.id2 != (cache.ActionID{}) {
1688		if cache.DebugTest {
1689			fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id2, testInputsID, testAndInputKey(c.id2, testInputsID))
1690		}
1691		cache.Default().PutNoVerify(c.id2, bytes.NewReader(testlog))
1692		cache.Default().PutNoVerify(testAndInputKey(c.id2, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
1693	}
1694}
1695
1696// coveragePercentage returns the coverage results (if enabled) for the
1697// test. It uncovers the data by scanning the output from the test run.
1698func coveragePercentage(out []byte) string {
1699	if !testCover {
1700		return ""
1701	}
1702	// The string looks like
1703	//	test coverage for encoding/binary: 79.9% of statements
1704	// Extract the piece from the percentage to the end of the line.
1705	re := regexp.MustCompile(`coverage: (.*)\n`)
1706	matches := re.FindSubmatch(out)
1707	if matches == nil {
1708		// Probably running "go test -cover" not "go test -cover fmt".
1709		// The coverage output will appear in the output directly.
1710		return ""
1711	}
1712	return fmt.Sprintf("\tcoverage: %s", matches[1])
1713}
1714
1715// builderCleanTest is the action for cleaning up after a test.
1716func builderCleanTest(b *work.Builder, a *work.Action) error {
1717	if cfg.BuildWork {
1718		return nil
1719	}
1720	if cfg.BuildX {
1721		b.Showcmd("", "rm -r %s", a.Objdir)
1722	}
1723	os.RemoveAll(a.Objdir)
1724	return nil
1725}
1726
1727// builderPrintTest is the action for printing a test result.
1728func builderPrintTest(b *work.Builder, a *work.Action) error {
1729	clean := a.Deps[0]
1730	run := clean.Deps[0]
1731	if run.TestOutput != nil {
1732		os.Stdout.Write(run.TestOutput.Bytes())
1733		run.TestOutput = nil
1734	}
1735	return nil
1736}
1737
1738// builderNoTest is the action for testing a package with no test files.
1739func builderNoTest(b *work.Builder, a *work.Action) error {
1740	var stdout io.Writer = os.Stdout
1741	if testJSON {
1742		json := test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
1743		defer json.Close()
1744		stdout = json
1745	}
1746	fmt.Fprintf(stdout, "?   \t%s\t[no test files]\n", a.Package.ImportPath)
1747	return nil
1748}
1749
1750// isTestFunc tells whether fn has the type of a testing function. arg
1751// specifies the parameter type we look for: B, M or T.
1752func isTestFunc(fn *ast.FuncDecl, arg string) bool {
1753	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
1754		fn.Type.Params.List == nil ||
1755		len(fn.Type.Params.List) != 1 ||
1756		len(fn.Type.Params.List[0].Names) > 1 {
1757		return false
1758	}
1759	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
1760	if !ok {
1761		return false
1762	}
1763	// We can't easily check that the type is *testing.M
1764	// because we don't know how testing has been imported,
1765	// but at least check that it's *M or *something.M.
1766	// Same applies for B and T.
1767	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
1768		return true
1769	}
1770	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
1771		return true
1772	}
1773	return false
1774}
1775
1776// isTest tells whether name looks like a test (or benchmark, according to prefix).
1777// It is a Test (say) if there is a character after Test that is not a lower-case letter.
1778// We don't want TesticularCancer.
1779func isTest(name, prefix string) bool {
1780	if !strings.HasPrefix(name, prefix) {
1781		return false
1782	}
1783	if len(name) == len(prefix) { // "Test" is ok
1784		return true
1785	}
1786	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
1787	return !unicode.IsLower(rune)
1788}
1789
1790type coverInfo struct {
1791	Package *load.Package
1792	Vars    map[string]*load.CoverVar
1793}
1794
1795// loadTestFuncs returns the testFuncs describing the tests that will be run.
1796func loadTestFuncs(ptest *load.Package) (*testFuncs, error) {
1797	t := &testFuncs{
1798		Package: ptest,
1799	}
1800	for _, file := range ptest.TestGoFiles {
1801		if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil {
1802			return nil, err
1803		}
1804	}
1805	for _, file := range ptest.XTestGoFiles {
1806		if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil {
1807			return nil, err
1808		}
1809	}
1810	return t, nil
1811}
1812
1813// writeTestmain writes the _testmain.go file for t to the file named out.
1814func writeTestmain(out string, t *testFuncs) error {
1815	f, err := os.Create(out)
1816	if err != nil {
1817		return err
1818	}
1819	defer f.Close()
1820
1821	if err := testmainTmpl.Execute(f, t); err != nil {
1822		return err
1823	}
1824
1825	return nil
1826}
1827
1828type testFuncs struct {
1829	Tests       []testFunc
1830	Benchmarks  []testFunc
1831	Examples    []testFunc
1832	TestMain    *testFunc
1833	Package     *load.Package
1834	ImportTest  bool
1835	NeedTest    bool
1836	ImportXtest bool
1837	NeedXtest   bool
1838	Cover       []coverInfo
1839}
1840
1841func (t *testFuncs) CoverMode() string {
1842	return testCoverMode
1843}
1844
1845func (t *testFuncs) CoverEnabled() bool {
1846	return testCover
1847}
1848
1849// ImportPath returns the import path of the package being tested, if it is within GOPATH.
1850// This is printed by the testing package when running benchmarks.
1851func (t *testFuncs) ImportPath() string {
1852	pkg := t.Package.ImportPath
1853	if strings.HasPrefix(pkg, "_/") {
1854		return ""
1855	}
1856	if pkg == "command-line-arguments" {
1857		return ""
1858	}
1859	return pkg
1860}
1861
1862// Covered returns a string describing which packages are being tested for coverage.
1863// If the covered package is the same as the tested package, it returns the empty string.
1864// Otherwise it is a comma-separated human-readable list of packages beginning with
1865// " in", ready for use in the coverage message.
1866func (t *testFuncs) Covered() string {
1867	if testCoverPaths == nil {
1868		return ""
1869	}
1870	return " in " + strings.Join(testCoverPaths, ", ")
1871}
1872
1873// Tested returns the name of the package being tested.
1874func (t *testFuncs) Tested() string {
1875	return t.Package.Name
1876}
1877
1878type testFunc struct {
1879	Package   string // imported package name (_test or _xtest)
1880	Name      string // function name
1881	Output    string // output, for examples
1882	Unordered bool   // output is allowed to be unordered.
1883}
1884
1885var testFileSet = token.NewFileSet()
1886
1887func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
1888	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
1889	if err != nil {
1890		return base.ExpandScanner(err)
1891	}
1892	for _, d := range f.Decls {
1893		n, ok := d.(*ast.FuncDecl)
1894		if !ok {
1895			continue
1896		}
1897		if n.Recv != nil {
1898			continue
1899		}
1900		name := n.Name.String()
1901		switch {
1902		case name == "TestMain":
1903			if isTestFunc(n, "T") {
1904				t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
1905				*doImport, *seen = true, true
1906				continue
1907			}
1908			err := checkTestFunc(n, "M")
1909			if err != nil {
1910				return err
1911			}
1912			if t.TestMain != nil {
1913				return errors.New("multiple definitions of TestMain")
1914			}
1915			t.TestMain = &testFunc{pkg, name, "", false}
1916			*doImport, *seen = true, true
1917		case isTest(name, "Test"):
1918			err := checkTestFunc(n, "T")
1919			if err != nil {
1920				return err
1921			}
1922			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
1923			*doImport, *seen = true, true
1924		case isTest(name, "Benchmark"):
1925			err := checkTestFunc(n, "B")
1926			if err != nil {
1927				return err
1928			}
1929			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
1930			*doImport, *seen = true, true
1931		}
1932	}
1933	ex := doc.Examples(f)
1934	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
1935	for _, e := range ex {
1936		*doImport = true // import test file whether executed or not
1937		if e.Output == "" && !e.EmptyOutput {
1938			// Don't run examples with no output.
1939			continue
1940		}
1941		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
1942		*seen = true
1943	}
1944	return nil
1945}
1946
1947func checkTestFunc(fn *ast.FuncDecl, arg string) error {
1948	if !isTestFunc(fn, arg) {
1949		name := fn.Name.String()
1950		pos := testFileSet.Position(fn.Pos())
1951		return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg)
1952	}
1953	return nil
1954}
1955
1956var testmainTmpl = template.Must(template.New("main").Parse(`
1957package main
1958
1959import (
1960{{if not .TestMain}}
1961	"os"
1962{{end}}
1963	"testing"
1964	"testing/internal/testdeps"
1965
1966{{if .ImportTest}}
1967	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
1968{{end}}
1969{{if .ImportXtest}}
1970	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
1971{{end}}
1972{{range $i, $p := .Cover}}
1973	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
1974{{end}}
1975)
1976
1977var tests = []testing.InternalTest{
1978{{range .Tests}}
1979	{"{{.Name}}", {{.Package}}.{{.Name}}},
1980{{end}}
1981}
1982
1983var benchmarks = []testing.InternalBenchmark{
1984{{range .Benchmarks}}
1985	{"{{.Name}}", {{.Package}}.{{.Name}}},
1986{{end}}
1987}
1988
1989var examples = []testing.InternalExample{
1990{{range .Examples}}
1991	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
1992{{end}}
1993}
1994
1995func init() {
1996	testdeps.ImportPath = {{.ImportPath | printf "%q"}}
1997}
1998
1999{{if .CoverEnabled}}
2000
2001// Only updated by init functions, so no need for atomicity.
2002var (
2003	coverCounters = make(map[string][]uint32)
2004	coverBlocks = make(map[string][]testing.CoverBlock)
2005)
2006
2007func init() {
2008	{{range $i, $p := .Cover}}
2009	{{range $file, $cover := $p.Vars}}
2010	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
2011	{{end}}
2012	{{end}}
2013}
2014
2015func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
2016	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
2017		panic("coverage: mismatched sizes")
2018	}
2019	if coverCounters[fileName] != nil {
2020		// Already registered.
2021		return
2022	}
2023	coverCounters[fileName] = counter
2024	block := make([]testing.CoverBlock, len(counter))
2025	for i := range counter {
2026		block[i] = testing.CoverBlock{
2027			Line0: pos[3*i+0],
2028			Col0: uint16(pos[3*i+2]),
2029			Line1: pos[3*i+1],
2030			Col1: uint16(pos[3*i+2]>>16),
2031			Stmts: numStmts[i],
2032		}
2033	}
2034	coverBlocks[fileName] = block
2035}
2036{{end}}
2037
2038func main() {
2039{{if .CoverEnabled}}
2040	testing.RegisterCover(testing.Cover{
2041		Mode: {{printf "%q" .CoverMode}},
2042		Counters: coverCounters,
2043		Blocks: coverBlocks,
2044		CoveredPackages: {{printf "%q" .Covered}},
2045	})
2046{{end}}
2047	m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples)
2048{{with .TestMain}}
2049	{{.Package}}.{{.Name}}(m)
2050{{else}}
2051	os.Exit(m.Run())
2052{{end}}
2053}
2054
2055`))
2056