Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create shared test utilities?

Tags:

go

I'm wondering whether it's possible to share test utility code across packages in go. Specifically, I'm writing a TCP server that will be used by multiple handlers for different message types, and want to reuse a set of common test utils.

The main TCP server code is in mypkg/tcpserver:

mypkg/tcpserver/tcp_server.go
mypkg/tcpserver/tcp_server_test.go
mypkg/tcpserver/testutils_test.go

The testutils_test.go code is intended to be a shared library that can be used by mypkg/tcpserver and other packages to set up a test server and client for their tests. For example in the handler subpackage I have:

mypkg/tcpserver/handler/handler.go
mypkg/tcpserver/handler/csv_handler.go
mypkg/tcpserver/handler/csv_handler_test.go
mypkg/tcpserver/handler/delim_handler.go
mypkg/tcpserver/handler/delim_handler_test.go

The handler/*_test.go files all import mypkg/tcpserver, but they are unable to access the test utilities defined in mypkg/tcpserver/testutils_test.go:

$ wgo test mypkg/tcpserver/handler
# mypkg/tcpserver/handler
src/mypkg/tcpserver/handler/csv_handler_test.go:37: undefined: tcpserver.CreateTestServer
src/mypkg/tcpserver/handler/csv_handler_test.go:40: undefined: tcpserver.TestSender
FAIL    mypkg/tcpserver/handler [build failed]

It appears that tests can import other packages, but not test code defined within those packages? Is this the intent? If so, is there an idiomatic way to share test utilities across packages in go?

like image 958
mmindenhall Avatar asked Aug 03 '15 18:08

mmindenhall


2 Answers

Create a package containing the testing utilities in non _test.go files. A couple of examples of this approach are httptest and iotest.

like image 195
Bayta Darell Avatar answered Nov 09 '22 14:11

Bayta Darell


If you can't create a testing utilities package (due to docs, dependencies, etc.), try to move testing utiities to a single go file, and add comment //go:build testing on the top of the file. Then you can run tests with go test -tags testing ./.... This codes won't be contained in go build binaries.

See more about go build tags: https://pkg.go.dev/cmd/go#hdr-Build_constraints

like image 22
zwtop Avatar answered Nov 09 '22 15:11

zwtop