bitfield / tpg-tools2

Code examples from the book 'The Power of Go: Tools'
MIT License
26 stars 5 forks source link

Why is a `.txtar` file at root of the match package? #3

Open cassamajor opened 7 months ago

cassamajor commented 7 months ago

As the title suggests.. why does the test.txtar file exist?

bitfield commented 7 months ago

Great question, @cassamajor! I'd be interested to hear what your guess would be.

cassamajor commented 7 months ago

Based on the content of the file, e.g. exec go test, I imagine the goal is to run tests how someone would on the command line.

First, I modified the directory passed to testscript.Run from "testdata/script" to "." to indicate the root of the package:

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

This resulted in:

        > exec go test
        [stderr]
        go: go.mod file not found in current directory or any parent directory; see 'go help modules'
        [exit status 1]
        FAIL: test.txtar:1: unexpected command failure

Additionally, in my terminal, I ran zsh test.txtar, which passed, but I am not sure if this is the intended way of executing these tests. Similar to the issue raised in #2, these tests will pass even with incorrect data.

Here's an example where I modified the stdout directive and input.txt content:

exec go test
stdin input.txt
exec go run ./cmd/match/main.go TARGET
stdout '^contains the TARGE\n'

-- input.txt --
this input
contais the TARGET
on one matching line

Running zsh test.txtar result in tests passing successfully, e.g.

comp@uter % zsh test.txtar
PASS
ok      github.com/bitfield/match       0.438s

So that's my guess. I'm curious what the reality is.

bitfield commented 7 months ago

Have a look at the run_testscript and run_all_testscripts files in the repo root, and you'll see they're set up to run a test script against each of the example folders. In some cases, the test is just to run the Go tests and check that they pass. In other cases, the tests are supposed to fail, so the script checks that they do!

Check out my article on Standalone test scripts to see how this works.