in init(); is there a flag to detect if I'm inside a test-build?

1,941 views
Skip to first unread message

Jason E. Aten

unread,
Dec 18, 2013, 3:05:50 PM12/18/13
to golan...@googlegroups.com
During my testing runs I load a bunch of data with an init() function so that all tests have it available, no matter what order the tests run in (aside: the order in which tests run seems non-deterministics, so I figured it had to go in an init, is there any alternative?)

For production however, I don't want to load the test data, since it is time consuming.  Is there a flag I can use inside the init() routine to tell if I'm under a test-build or not, and then skip loading the test data if it isn't needed?

Thanks,

Jason

Kevin Malachowski

unread,
Dec 18, 2013, 3:16:58 PM12/18/13
to golan...@googlegroups.com
I'm not exactly sure if this will work, but have you looked into sync.Once? You could set up the Once either explicitly in an init or just in a package level variable and use it at the beginning of each test. That way unless a test method is called it won't run, and no matter what tests are run it will only ever run once. It may be a bit of overkill if tests are always run serially, but if they could possibly be run in parallel I think it would be a very good solution.

jimmy frasche

unread,
Dec 18, 2013, 3:21:31 PM12/18/13
to Kevin Malachowski, golang-nuts
You could just put that init func in a _test.go file. That way it
won't even get compiled unless you're running tests.

Jason E. Aten

unread,
Dec 18, 2013, 3:29:09 PM12/18/13
to jimmy frasche, Kevin Malachowski, golang-nuts
Ah! Move the init() to a _test.go file. Perfect. Exactly the idea I needed. Thanks Jimmy!

p.s. Thanks for for the sync.Once() idea, Kevin, I'll keep that in my back pocket and I'm sure it will be useful in the future.

Steve McCoy

unread,
Dec 18, 2013, 3:29:48 PM12/18/13
to golan...@googlegroups.com
If the init function is defined in a *_test.go file, it will not be compiled into the package. Remember that you can define inits in multiple files in the same package.

Matthew Kane

unread,
Dec 18, 2013, 3:55:37 PM12/18/13
to Jason E. Aten, golang-nuts
Wouldn't you just write a separate init() function in your *_test.go
files? That way it is not compiled or called for your actual
production builds.
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.



--
matt kane
twitter: the_real_mkb / nynexrepublic
http://hydrogenproject.com
Reply all
Reply to author
Forward
0 new messages