Skip to content

testing: add func Testing() bool #52600

Closed

Description

@misha-ridge

This is a proposal to add a build tag during compilation of unit tests.

Background & motivation

Sometimes it is handy to have some code not available for unit testing, e.g. some volatile data that should not be relied upon in tests. Code reviews help to catch accidental or intentional misuses, but it's exhausting to check that no test code refers to this data directly or indirectly.

There are workarounds that allow distinguishing if the code is running tests, but they are inadequate:

  • Checking presence of "test.v" flag does not work for code running from global initializers or package-level init() clauses.
  • Opening currently running executable to match some string that is present only in internals of testing package may produce false positives, slow, and OS-dependent.
  • Manually specifying build tags for testing (likely via shell wrappers) forces every developer of the project to learn that go test is not the right tool to run tests, and creates toil for integrating with IDEs.

Proposal

Add a build tag that is available during compilation of unit tests. This will trivially allow marking some data/functions as "not available in unit tests".

Activity

  1. added this to the Proposal milestone on Apr 28, 2022
  2. misha-ridge commented on Apr 28, 2022

    @misha-ridge
    Author

    flag.Lookup("test.v") idiom is seen in the wild: https://github.com/search?q=flag.Lookup%28%22test.v%22%29&type=code

  3. ianlancetaylor commented on May 4, 2022

    @ianlancetaylor
    Contributor

    This may be a dup of #14668.

  4. misha-ridge commented on May 5, 2022

    @misha-ridge
    Author

    It is. New information in this ticket:

    • a new legitimate use-case
    • survey of existing codebases that shows that inadequate workarounds do get applied
  5. moved this to Incoming in Proposalson Aug 10, 2022
  6. rsc commented on Feb 1, 2023

    @rsc
    Contributor

    I'm trying to understand why you would want to create untestable code.
    The justification on StackOverflow is "I want to use a different configuration file." during a test.
    The comment above says "some volatile data that should not be relied upon in tests".
    Are there more examples?

  7. moved this from Incoming to Active in Proposalson Feb 1, 2023
  8. rsc commented on Feb 1, 2023

    @rsc
    Contributor

    This proposal has been added to the active column of the proposals project
    and will now be reviewed at the weekly proposal review meetings.
    — rsc for the proposal review group

  9. misha-ridge commented on Feb 1, 2023

    @misha-ridge
    Author

    The simplified situation that caused me to open the ticket:

    shared/config:
      prod_env.go
      dev_env.go
    service1/
      main.go (selects one of environments and passes it down the call stack)
    service2/
      main.go (ditto)
    lib/a/
      something.go
      something_test.go
      env_test.go // contains test environment that must be used instead in tests
    

    I'd like to ensure that something_test.go (and anything that it transitively depends on) does not reference shared/config, because this data changes over time, so changes in shared/config cause breakage of unrelated unit tests that accidentally depend on current state of environment data. Instead tests and system under test should use test environment.

    It's a pretty non-fun situation when an urgent change in environment forces the person who needs to do it to chase all the implicit assumptions in tests that were violated.

  10. ChrisHines commented on Feb 1, 2023

    @ChrisHines
    Contributor

    Another possible use case: Excluding code used for production resiliency that hinders local testing and debugging. The specific example I've seen is disabling the use of github.com/mitchellh/panicwrap when running tests.

  11. ianlancetaylor commented on Feb 1, 2023

    @ianlancetaylor
    Contributor

    I just want to note that you could get the same effect by running go test -tags test. And you could enforce the use of the -tags option by adding a file tags_test.go.

    //go:build !test
    func init() { log.Fatal("running a test without -tags test") }

    So it doesn't seem that hard for people to get this functionality already. The question is whether this is a common enough need to add to the standard tools. Note in particular that actually using the build tag will tend to make the build cache less effective, so it's not something we necessarily want to encourage.

  12. misha-ridge commented on Feb 1, 2023

    @misha-ridge
    Author

    I have mentioned it in the bug description:

    Manually specifying build tags for testing (likely via shell wrappers) forces every developer of the project to learn that go test is not the right tool to run tests, and creates toil for integrating with IDEs.

  13. bcmills commented on Feb 1, 2023

    @bcmills
    Contributor

    Excluding code used for production resiliency that hinders local testing and debugging.

    For that kind of use case, why not make the debugging-hostile behavior opt-in instead of opt-out?
    (For example: why not have func main enable it explicitly after parsing flags, so that you can also debug your production binary without recompiling it if the need arises?)

  14. 30 remaining items

  15. adamluzsi commented on Mar 29, 2023

    @adamluzsi

    Hey there, I hope you don't mind me chiming in a bit late to the conversation! 😊
    I was just wondering if it's a good idea to import the testing package into production code?

    For instance, let's say you're developing a custom logger and want to use STDOUT as the default output.
    However, during testing, you'd prefer to use io.Discard to keep the testing output clean.
    In this scenario, the logging package would depend on the testing package,
    and it's possible that the entire project could end up depending on the testing package as a result.

    I was wondering if it might be more efficient to create a separate testing/testcheck package that doesn't have a dependency on testing. Instead, we could have the testing package set a flag in testing/testcheck to show when tests are being executed. This way, package designers working with STDOUT can easily adhere to testing library conventions and suppress output using io.Dispose, without any unintended consequences from importing the testing package.

    I'd really love to hear your thoughts on this approach! 😊

  16. misha-ridge commented on Mar 29, 2023

    @misha-ridge
    Author

    @adamluzsi You're right, there are side-effects of importing testing.

    Any program that uses testing.Testing() will end up having the whole suite of testing flags added.

    @ianlancetaylor Any chance we could address it before it ends up in a release?

  17. ianlancetaylor commented on Mar 29, 2023

    @ianlancetaylor
    Contributor

    Simply importing the "testing" package will not define any flags. The flags are only defined if something calls testing.Init. The testing harness will do that, but it won't happen by itself.

    I see that it's possible to introduce a dependency on the testing package via something like logging, but the testing package is not all that large. And the linker will discard unused functions, so if the program only calls testing.Testing there won't be much left.

    In any case, if you do think we should do something about this, please open a new issue and mark it as a release blocker for 1.21. Thanks.

  18. dottedmag commented on Mar 30, 2023

    @dottedmag
    Contributor

    Right, the flags situation is fixed in https://go-review.googlesource.com/c/go/+/173722 (I was looking at old Go source code accidentally), so importing testing does not have any side-effects, and linker should take care of the rest.

    Incidentally this also means that the brittle workarounds applied due to lack of Testing() function are also broken due to this change, which is a good thing, as it will force everyone to use testing.Testing().

    @adamluzsi So this is fine?

  19. adamluzsi commented on Mar 30, 2023

    @adamluzsi

    Yes, of course, and thank you so much for taking your time and helping me understand.
    I wrongly thought that importing the testing package might have unintended side effects.
    I'm sorry if I caused any panic at this late stage. 🤦

  20. ladydascalie commented on May 5, 2023

    @ladydascalie
    Contributor

    Incidentally this also means that the brittle workarounds applied due to lack of Testing() function are also broken due to this change, which is a good thing, as it will force everyone to use testing.Testing().

    How does the behaviour break @dottedmag?
    Is it a panic, an error?

    I think this is important to know before this break occurs.

  21. misha-ridge commented on May 5, 2023

    @misha-ridge
    Author

    @ladydascalie Such code (checking pflag.Lookup("test.v") to detect if the code is running as a part of unit tests) always returns "not in unit tests" nowadays.

  22. removed this from Proposalson Mar 15, 2024
  23. mvdan commented on Mar 28, 2024

    @mvdan
    Member

    Started using this function in a program that didn't previously import testing, and I notice the binary size increased by about 20KiB. While this is not huge, it is still surprising - is that expected? I would hope that, since the Testing func is simple, and the testing package shouldn't have init funcs keeping types or funcs alive, the size increase should be near zero.

  24. ianlancetaylor commented on Mar 28, 2024

    @ianlancetaylor
    Contributor

    The testing package does import a lot of other packages.

  25. locked and limited conversation to collaborators on Mar 28, 2025
  26. added a commit that references this issue on Sep 29, 2026
    7f38067
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions