Eric O. Lebigot
Eric O. Lebigot

Reputation: 94595

Unit testing with nose: tests at compile time?

Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module?

In fact, I'd like to test something with the following structure:

x = 123
# [x is used here...]
def test_x():
  assert (x == 123)
del x  # Deleted because I don't want to clutter the module with unnecessary attributes

nosetests tells me that x is undefined, as it apparently runs test_x() after importing the module. Is there a way of having nose perform test during the compilation phase while having the module free unnecessary resources after using them?

Upvotes: 3

Views: 965

Answers (2)

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94595

According to nose's main developer Jason Pellerin, the nose unit testing framework cannot run tests during compilation. This is a potential annoyance if both the module "construction" and the test routines need to access a certain variable (which would be deleted in the absence of tests).

One option is to discourage the user from using any of these unnecessarily saved variables by prepending "__" to their name (this works also for variables used in class construction: they can be one of these "private" globals).

Another, perhaps cleaner option is to dedicate a module to the task: this module would contain variables that are shared by the module "itself" (i.e. without tests) and its tests (and that would not have to be shared were it not for the tests).

The problem with these option is that variables that could be deleted if there were no tests are instead kept in memory, just because it is better for the test code to use them. At least, with the above two options, the user should not be tempted to use these variables, nor should he feel the need to wonder what they are!

Upvotes: 2

Singletoned
Singletoned

Reputation: 5129

A simple way to handle this would be to have a TESTING flag, and write:

if not TESTING:
    del x

However, you won't really be properly testing your modules as the tests will be running under different circumstances to your code.

The proper answer is that you shouldn't really be bothering with manually cleaning up variables, unless you have actually had some major performance problems because of them. Read up on Premature Optimization, it's an important concept. Fix the problems you have, not the ones you maybe could have one day.

Upvotes: 2

Related Questions