gotests icon indicating copy to clipboard operation
gotests copied to clipboard

Use '_test' package when appropriate

Open ammario opened this issue 8 years ago • 7 comments

If the -exported flag is set, it makes more sense to use the _test package by default in the generated code.

ammario avatar Nov 11 '16 08:11 ammario

Can you please give me an example? I'm not exactly sure what you mean by "_test package".

cweill avatar Nov 13 '16 18:11 cweill

When testing only exported functions, tests are encouraged to use the <package>_test package instead of just <package>. It has the effect of making the user be more careful about what he exports and forces him to only test exported methods. It is the exception to the only one package per directory rule.

ammario avatar Nov 14 '16 08:11 ammario

Oh wow, TIL! I had never heard of that before, but I just tested it out, and it works. Since which Go version is that a thing?

Could you please point me to some documentation for this feature? I have trouble finding it. I would need to read about the best practices before implementing such a feature.

cweill avatar Nov 15 '16 04:11 cweill

Unfortunately I can't find any official documentation of the feature... There's a good amount of blog posts and stackoverflow answers alluding to it positively though. There doesn't seem to be a general consensus on when to use it. The official blog uses it here but doesn't specify why. I assume it's to isolate the scope of test related variables.

Maybe it would be best to just make it optional?

ammario avatar Nov 15 '16 08:11 ammario

The other time I've seen it used is to make ExampleXXX functions copy and paste friendly. Since they need to be compilable, if you write them in the regular package name you won't have the package name for your example code. https://blog.golang.org/examples

Although I like the idea of -exported using it to help enforce the public API compatibility.

itsjamie avatar Nov 17 '16 04:11 itsjamie

This feature is documented here.

Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.

This would be a great feature to have

SteelPhase avatar May 15 '20 19:05 SteelPhase

I would like to see this feature too. Testing a library from a _test package proves that the library can be used by others.

josdotso avatar Sep 11 '23 15:09 josdotso