It is sometimes useful to capture output files from a test (for additional analysis, perhaps). Instead of hard-coding a location into your test code, you can take advantage of Go’s artifact directory support. Use the ArtifactDir method to get the name of the directory where the file should be written. By default, this is a temporary directory that is deleted when the test completes. This gives you control over when an artifact is permanently written; the code to generate the artifact can always be present, but you decide when to capture a new artifact. To make an artifact permanent, set the -artifacts flag when running go test. This changes the artifact directory to a subdirectory of the directory where go test is running.
func TestArtifacts(t *testing.T) {
myDir := t.ArtifactDir()
t.Log(myDir)
f, err := os.Create(myDir + "/test.txt")
if err != nil {
t.Fatal(err)
}
defer f.Close()
f.Write([]byte("valuable test data"))
}
$ go test -v
=== RUN TestArtifacts
artifact_test.go:10: /var/folders/hj/mr53lrfj1bqf4hg62wqkp4000000gn/T/
TestArtifacts1377298058/001
--- PASS: TestArtifacts (0.00s)
$ go test -v -artifacts
=== RUN TestArtifacts
=== ARTIFACTS TestArtifacts /Users/gobook/projects/learning-go-3e-code/ch15/
examples/artifact/_artifacts/1837011095
artifact_test.go:10: /Users/gobook/projects/learning-go-3e-code/ch15/
examples/artifact/_artifacts/1837011095
--- PASS: TestArtifacts (0.00s)
Note
If you want to customize the artifact output directory, set the -outputdir flag on go test.