gotestinggo-modulesgo-toolchain

How to import testing code from one module to another without exposing it to production code?


TLDR: I placed a TestLogger struct in logutils/test-logger_test.go and tried referencing it in authentication/login_tests.go. When building tests for the authentication module, the compiler complains that TestLogger is not declared. The only workaround is to rename test-logger_test.go to test-logger.go but this runs the risk of having TestLogger referenced in production code.

It seems golang does not import testing code (code declared in a file with the _test.go suffix) from one module to another when running go tests. Am i doing something wrong or is this the way golang was designed? Is there a workaround?

Simple example to clarify:

I have a 'library' module (let's call il logutils) and 'applicaton' module (let's call it 'authentication'). The logutils module has its own tests which cover all the implementation specific funcionality of loggers (eg. FileLogger, HttpLogger) and all is good.

The logutils module also declares a TestLogger which can be used by 'client' modules (like 'authentication') to make sure they are logging everything correctly without the need to setup file or http logging. It basically just implements the Logger interface but just logs everything to a buffer that can be verified at the end of the tests.

So the 'authentication' module can declare its own _test.go files that instance a TestLogger and it all works like a charm.

What bothers me is that the TestLogger needs to be declared in a regular production file (logutils/test-logger.go) and not in a test file (logutils/test-logger_test.go), otherwise the authentication tests will complain the TestLogger is not defined. But by doing this there is nothing stopping TestLogger from being referenced/used in production code.

What I want is the code in any logutils _test.go file to be importable in any authentication _test.go file (but not in production .go files).

Any insight/advice?

Edit: fixed typos


Solution

  • What I want is the code in any logutils _test.go file to be importable in any authentication _test.go file (but not in production .go files).

    You cannot have this. Dead simple. (There no such thing as "production .go files". Test code is not "not-production".)