package testscript

import "github.com/rogpeppe/go-internal/testscript"

Package testscript provides support for defining filesystem-based tests by creating scripts in a directory.

To invoke the tests, call testscript.Run. For example:

func TestFoo(t *testing.T) {
	testscript.Run(t, testscript.Params{
		Dir: "scripts",
	})
}

A testscript directory holds test scripts *.txt run during 'go test'. Each script defines a subtest; the exact set of allowable commands in a script are defined by the parameters passed to the Run function. To run a specific script foo.txt

go test cmd/go -run=TestName/^foo$

where TestName is the name of the test that Run is called from.

To define an executable command (or several) that can be run as part of the script, call RunMain with the functions that implement the command's functionality. The command functions will be called in a separate process, so are free to mutate global variables without polluting the top level test binary.

func TestMain(m *testing.M) {
	os.Exit(testscript.RunMain(m, map[string] func() int{
		"testscript": testscriptMain,
	}))
}

In general script files should have short names: a few words, not whole sentences. The first word should be the general category of behavior being tested, often the name of a subcommand to be tested or a concept (vendor, pattern).

Each script is a text archive (go doc github.com/rogpeppe/go-internal/txtar). The script begins with an actual command script to run followed by the content of zero or more supporting files to create in the script's temporary file system before it starts executing.

As an example:

# hello world
exec cat hello
stdout "hello world\n"
! stderr .

-- hello.txt--
hello world

Each script runs in a fresh temporary work directory tree, available to scripts as $WORK. Scripts also have access to these other environment variables:

HOME=/no-home
PATH=<actual PATH>
TMPDIR=$WORK/tmp
devnull=<value of os.DevNull>

The environment variable $exe (lowercase) is an empty string on most systems, ".exe" on Windows.

The script's supporting files are unpacked relative to $WORK and then the script begins execution in that directory as well. Thus the example above runs in $WORK with $WORK/hello.txt containing the listed contents.

The lines at the top of the script are a sequence of commands to be executed by a small script engine in the testscript package (not the system shell). The script stops and the overall test fails if any particular command fails.

Each line is parsed into a sequence of space-separated command words, with environment variable expansion and # marking an end-of-line comment. Adding single quotes around text keeps spaces in that text from being treated as word separators and also disables environment variable expansion. Inside a single-quoted block of text, a repeated single quote indicates a literal single quote, as in:

'Don''t communicate by sharing memory.'

A line beginning with # is a comment and conventionally explains what is being done or tested at the start of a new phase in the script.

The command prefix ! indicates that the command on the rest of the line (typically go or a matching predicate) must fail, not succeed. Only certain commands support this prefix. They are indicated below by [!] in the synopsis.

The command prefix [cond] indicates that the command on the rest of the line should only run when the condition is satisfied. The predefined conditions are:

A condition can be negated: [!short] means to run the rest of the line when testing.Short() is false.

Additional conditions can be added by passing a function to Params.Condition.

The predefined commands are:

- chmod mode file

Change the permissions of file or directory to the given octal mode (000 to 777).

When TestScript runs a script and the script fails, by default TestScript shows the execution of the most recent phase of the script (since the last # comment) and only shows the # comments for earlier phases. For example, here is a multi-phase script with a bug in it (TODO: make this example less go-command specific):

# GOPATH with p1 in d2, p2 in d2
env GOPATH=$WORK/d1${:}$WORK/d2

# build & install p1
env
go install -i p1
! stale p1
! stale p2

# modify p2 - p1 should appear stale
cp $WORK/p2x.go $WORK/d2/src/p2/p2.go
stale p1 p2

# build & install p1 again
go install -i p11
! stale p1
! stale p2

-- $WORK/d1/src/p1/p1.go --
package p1
import "p2"
func F() { p2.F() }
-- $WORK/d2/src/p2/p2.go --
package p2
func F() {}
-- $WORK/p2x.go --
package p2
func F() {}
func G() {}

The bug is that the final phase installs p11 instead of p1. The test failure looks like:

$ go test -run=Script
--- FAIL: TestScript (3.75s)
    --- FAIL: TestScript/install_rebuild_gopath (0.16s)
        script_test.go:223:
            # GOPATH with p1 in d2, p2 in d2 (0.000s)
            # build & install p1 (0.087s)
            # modify p2 - p1 should appear stale (0.029s)
            # build & install p1 again (0.022s)
            > go install -i p11
            [stderr]
            can't load package: package p11: cannot find package "p11" in any of:
            	/Users/rsc/go/src/p11 (from $GOROOT)
            	$WORK/d1/src/p11 (from $GOPATH)
            	$WORK/d2/src/p11
            [exit status 1]
            FAIL: unexpected go command failure

        script_test.go:73: failed at testdata/script/install_rebuild_gopath.txt:15 in $WORK/gopath/src

FAIL
exit status 1
FAIL	cmd/go	4.875s
$

Note that the commands in earlier phases have been hidden, so that the relevant commands are more easily found, and the elapsed time for a completed phase is shown next to the phase heading. To see the entire execution, use "go test -v", which also adds an initial environment dump to the beginning of the log.

Note also that in reported output, the actual name of the per-script temporary directory has been consistently replaced with the literal string $WORK.

If Params.TestWork is true, it causes each test to log the name of its $WORK directory and other environment variable settings and also to leave that directory behind when it exits, for manual debugging of failing tests:

$ go test -run=Script -work
--- FAIL: TestScript (3.75s)
    --- FAIL: TestScript/install_rebuild_gopath (0.16s)
        script_test.go:223:
            WORK=/tmp/cmd-go-test-745953508/script-install_rebuild_gopath
            GOARCH=
            GOCACHE=/Users/rsc/Library/Caches/go-build
            GOOS=
            GOPATH=$WORK/gopath
            GOROOT=/Users/rsc/go
            HOME=/no-home
            TMPDIR=$WORK/tmp
            exe=

            # GOPATH with p1 in d2, p2 in d2 (0.000s)
            # build & install p1 (0.085s)
            # modify p2 - p1 should appear stale (0.030s)
            # build & install p1 again (0.019s)
            > go install -i p11
            [stderr]
            can't load package: package p11: cannot find package "p11" in any of:
            	/Users/rsc/go/src/p11 (from $GOROOT)
            	$WORK/d1/src/p11 (from $GOPATH)
            	$WORK/d2/src/p11
            [exit status 1]
            FAIL: unexpected go command failure

        script_test.go:73: failed at testdata/script/install_rebuild_gopath.txt:15 in $WORK/gopath/src

FAIL
exit status 1
FAIL	cmd/go	4.875s
$

$ WORK=/tmp/cmd-go-test-745953508/script-install_rebuild_gopath
$ cd $WORK/d1/src/p1
$ cat p1.go
package p1
import "p2"
func F() { p2.F() }
$

Index

Functions

func IgnoreMissedCoverage

func IgnoreMissedCoverage()

IgnoreMissedCoverage causes any missed coverage information (for example when a function passed to RunMain calls os.Exit, for example) to be ignored. This function should be called before calling RunMain.

func Run

func Run(t *testing.T, p Params)

RunDir runs the tests in the given directory. All files in dir with a ".txt" are considered to be test files.

func RunMain

func RunMain(m TestingM, commands map[string]func() int) (exitCode int)

RunMain should be called within a TestMain function to allow subcommands to be run in the testscript context.

The commands map holds the set of command names, each with an associated run function which should return the code to pass to os.Exit. It's OK for a command function to exit itself, but this may result in loss of coverage information.

This function returns an exit code to pass to os.Exit, after calling m.Run.

Types

type Env

type Env struct {
	WorkDir string
	Vars    []string
	Cd      string
}

Env holds the environment to use at the start of a test script invocation.

type Params

type Params struct {
	// Dir holds the name of the directory holding the scripts.
	// All files in the directory with a .txt suffix will be considered
	// as test scripts. By default the current directory is used.
	// Dir is interpreted relative to the current test directory.
	Dir string

	// Setup is called, if not nil, to complete any setup required
	// for a test. The WorkDir and Vars fields will have already
	// been initialized, and Cd will be the same as WorkDir.
	// The Setup function may modify Vars and Cd as it wishes.
	Setup func(*Env) error

	// Condition is called, if not nil, to determine whether a particular
	// condition is true. It's called only for conditions not in the
	// standard set, and may be nil.
	Condition func(cond string) (bool, error)

	// Cmds holds a map of commands available to the script.
	// It will only be consulted for commands not part of the standard set.
	Cmds map[string]func(ts *TestScript, neg bool, args []string)

	// TestWork specifies that working directories should be
	// left intact for later inspection.
	TestWork bool

	// IgnoreMissedCoverage specifies that if coverage information
	// is being generated (with the -test.coverprofile flag) and a subcommand
	// function passed to RunMain fails to generate coverage information
	// (for example because the function invoked os.Exit), then the
	// error will be ignored.
	IgnoreMissedCoverage bool
}

Params holds parameters for a call to Run.

type TestScript

type TestScript struct {
	// contains filtered or unexported fields
}

A TestScript holds execution state for a single test script.

func (*TestScript) Check

func (ts *TestScript) Check(err error)

Check calls ts.Fatalf if err != nil.

func (*TestScript) Exec

func (ts *TestScript) Exec(command string, args ...string) error

Exec runs the given command and saves its stdout and stderr so they can be inspected by subsequent script commands.

func (*TestScript) Fatalf

func (ts *TestScript) Fatalf(format string, args ...interface{})

fatalf aborts the test with the given failure message.

func (*TestScript) Logf

func (ts *TestScript) Logf(format string, args ...interface{})

Logf appends the given formatted message to the test log transcript.

func (*TestScript) MkAbs

func (ts *TestScript) MkAbs(file string) string

MkAbs interprets file relative to the test script's current directory and returns the corresponding absolute path.

type TestingM

type TestingM interface {
	Run() int
}

TestingM is implemented by *testing.M. It's defined as an interface to allow testscript to co-exist with other testing frameworks that might also wish to call M.Run.

Source Files

cmd.go cover.go doc.go exe.go testscript.go

Version
v1.0.0
Published
Oct 25, 2018
Platform
darwin/amd64
Imports
21 packages
Last checked
29 minutes ago

Tools for package owners.