Static files in tests

When I write tests in Go that require static files (for example, the hello.txt file, where do I test my program that hello.txt reads), where should I put the static files? How should I access them in a test file?

That is, currently my installation is a local directory, GOPATH installed in this directory. There I have

 src/ mypkg/ myfile.go myfile_test.go testfiles/ hello.txt world.txt 

Now in myfile_test.go I do not want to use the absolute path to link to testfiles/hello.txt . Is there any idiomatic way to do this?

Is this a reasonable layout?

+4
source share
1 answer

A general approach is to have, for example,

 $GOPATH/src/ mypkg/ myfile.go myfile_test.go _testdata/ hello.txt world.txt 

Then in your foo_test use

 f, err := os.Open("_testdata/hello.txt") .... 

or

 b, err := ioutil.ReadFile("_testdata/hello.txt") .... 

The test package ensures that CWD will be $GOPATH/src/mypkg when the test binary is executed.

+5
source

Source: https://habr.com/ru/post/1498848/


All Articles