-3

TL;DR:

Do test written within a package end up in the final exported package? Do they add any garbage or weight to a compiled binary?

Longer version:

Let's say that I have a foo Go package:

pkg/
  foo/
    bar.go
    bar_test.go

I'm aware of the black box vs white box approaches to testing in go. A short recap is that I can either:

  1. have bar_test.go declare a foo_test package, or
  2. have it part of the main foo package.

Approach 1 provides better isolation because it allows to focus on the public API of the package, as one only access the exported identifiers of foo. Also, when application code imports the foo package with import "pkg/foo", only the files containing the main foo package are compiled. That's nice. [1]

However, there are cases where putting the tests in foo is a convenient compromise. I don't particularly like it myself, but I can see it in several codebases and I understand why at times it's necessary.

My question is about what happens to these tests. Since they're part of the package foo, when foo is imported somewhere, I'd expect the tests to be brought along. Or is the compiler smart enough to strip them?


[1] this is not a question on what approach is "better". It's doesn't really matter. Please abstain from commenting with "that approach is not better".

Community
  • 1
  • 1
tompave
  • 11,952
  • 7
  • 37
  • 63
  • Approach 1 is not considered "better", it's just a different set of tests. Most packages still use unit tests within the same package. As for "polluting" the binary, what's not compiled can't effect the binary, so I'm not sure what effect you think it could have. – JimB Jan 17 '19 at 18:48
  • Hi @JimB, thanks. I've edited the question to make it clear that it's not really about what approach is better. Also, can you explain the point of what's not compiled? I think that's the answer I'm looking for, and some more details in the form of an answer would help. – tompave Jan 17 '19 at 18:52
  • 4
    The `_test` filename constraints work just like the others, and are only compiled by `go test`. From go help build: `When compiling packages, build ignores files that end in '_test.go'.`, and also in the [online docs here](https://golang.org/cmd/go/#hdr-Compile_packages_and_dependencies) (also, dead code is eliminated from the binary during linking, so even if they were compiled in, there little impact on the binary output in most cases) – JimB Jan 17 '19 at 18:54

1 Answers1

3

Yes, the Go tool is smart enough not to pass them to the compiler.

https://github.com/golang/go/issues/10184

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
  • 3
    When building a package, the Go Tool does not include _test.go files in the list of files to compile. The compiler plays no role in this. – Charlie Tumahai Jan 17 '19 at 19:16