Testing patterns in Golang src/pkg

122 views
Skip to first unread message

Vasko Zdravevski

unread,
Mar 19, 2014, 2:38:27 PM3/19/14
to golan...@googlegroups.com
While reading the Go language source code for various packages, I've noticed an inconsistency in how tests are organized. I'm hoping someone here can help me understand why.

net/http/client.go is in package 'http' but net/http/client_test.go is in package 'http_test'

While net/http/cookie.go is in package 'http' and net/http/cookie_test.go is in package 'http'

There are multiple instances of these inconsistencies. If you know why, or if you can describe the strengths and weaknesses of each, I'd really appreciate it.

Thanks.

Brad Fitzpatrick

unread,
Mar 19, 2014, 2:44:26 PM3/19/14
to Vasko Zdravevski, golang-nuts
foo.go and foo_test.go should both be in package foo if possible.

Sometimes it's not possible if your test code needs other packages which will then lead to circular dependencies.  In that case you need to move your test code out into foo_test (its own package) instead.  But then that means you can't get at foo internals from foo_test and can't poke around them and test your internal state.

Hence all the export_test.go files. That's a convention that bridges foo and foo_test: export_test.go gets compiled into package foo and exports normally-hidden stuff out into capitalized exported symbols so other tests in foo_test.go (package foo_test) can poke at it.  That is a pain, so only do it if required.  Otherwise prefer everything be in the same package.



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gustavo Niemeyer

unread,
Mar 19, 2014, 2:59:40 PM3/19/14
to Brad Fitzpatrick, Vasko Zdravevski, golang-nuts
On Wed, Mar 19, 2014 at 3:44 PM, Brad Fitzpatrick <brad...@golang.org> wrote:
> foo.go and foo_test.go should both be in package foo if possible.

I actually prefer to have things in package foo_test if possible. It
helps making it clear what is whiteboxed and what is not, and also
makes the use of the package in tests look closer to how people will
be interacting with the package in the wild, which often helps
improving naming while the API is being put in place. It also means
that handling circular imports is not an exception.

YMMV


gustavo @ http://niemeyer.net
Reply all
Reply to author
Forward
0 new messages