Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static files in tests

Tags:

testing

go

When I write tests in Go that require static files (for example a file hello.txt where I test my program that hello.txt is read correctly), where should I place the static files? How should I address them in the test file?

That is, currently my setup is a local directory, GOPATH is set to this directory. There I have

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

Now in myfile_test.go, I don't want to use an absolute path to refer to testfiles/hello.txt. Is there any idiomatic way to do that?

Is this a sensible layout?

like image 858
topskip Avatar asked Aug 25 '13 16:08

topskip


1 Answers

Common 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 testing package makes sure that the CWD is $GOPATH/src/mypkg when the test binary executes.

like image 115
zzzz Avatar answered Sep 19 '22 10:09

zzzz