testing: *_test.go files package declaration

226 views
Skip to first unread message

Francisco Souza

unread,
Apr 27, 2012, 6:04:31 PM4/27/12
to golang-nuts
I've seen people using two different approaches for package declaration in *_test.go files: some use the package name itself, and some use <package_name>_test. The standard library has cases of both approaches [1] [2], the documentation [3] shows only a very simple example using the package name.

*_test.go files are ignored by go (get|install|build), right? So, why use <package_name>_test?

[1] http://golang.org/src/pkg/net/net_test.go
[2] http://golang.org/src/pkg/sort/sort_test.go
[3] http://golang.org/doc/code.html#Testing

--
~f

John Asmuth

unread,
Apr 27, 2012, 6:09:12 PM4/27/12
to golan...@googlegroups.com
Choosing a package name other than the one used by the non-testing files ensures that your tests don't have access to unexported identifiers.

Michael Jones

unread,
Apr 27, 2012, 6:11:09 PM4/27/12
to John Asmuth, golan...@googlegroups.com
and vice versa...if you need that access.
--
Michael T. Jones | Chief Technology Advocate  | m...@google.com |  +1 650-335-5765

Patrick Mylund Nielsen

unread,
Apr 27, 2012, 6:11:45 PM4/27/12
to Francisco Souza, golang-nuts
You could have two packages which both rely on something in my_test.

Francisco Souza

unread,
Apr 27, 2012, 7:04:34 PM4/27/12
to John Asmuth, golan...@googlegroups.com
On Fri, Apr 27, 2012 at 7:09 PM, John Asmuth <jas...@gmail.com> wrote:
Choosing a package name other than the one used by the non-testing files ensures that your tests don't have access to unexported identifiers.

Hmm, I see.

Thank you ;)

--
~f

David Symonds

unread,
Apr 27, 2012, 7:28:04 PM4/27/12
to Francisco Souza, golang-nuts
On Sat, Apr 28, 2012 at 8:04 AM, Francisco Souza <f...@souza.cc> wrote:

> The standard library has cases of both approaches [1] [2], the documentation
> [3] shows only a very simple example using the package name.

Others have given good reasons for the choice in general; the standard
Go style is to put tests in the same package as the code under test.

In the specific case of the standard library, the exceptions (e.g.
sort_test.go) are to avoid a circular dependency. The "testing"
package depends on a bunch of packages itself, and those packages may
not depend on "testing", so therefore the tests for those packages may
not be in the same package.


Dave.

Sanjay

unread,
Apr 27, 2012, 9:59:05 PM4/27/12
to golan...@googlegroups.com, Francisco Souza
Also, if you have Examples in your files, they're more authentic if they say package.Func, rather than just Func, as it will read more like what the users of your package will have to write.

Sanjay
Reply all
Reply to author
Forward
0 new messages