VoltairePunk
VoltairePunk

Reputation: 302

Reset global variables during python unit testing runtime

I am currently writing tests for a bit of Python (using the 3.5 version) software for the company I'm working with, but am stumbling upon a problem which I currently believe is because of global variables if I could call it that.

The software architecture is extremely modular, hence to test individual modules a separate test file (perhaps called test_somemodule_py) is created containing one class that extends the unittest.TestCase one.

NOTE that what I call modules here is not really a Python module, but rather an application module

All of the tests are triggered through a single runner script which contains a custom loader:

def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
for all_tests in loader.discover('tests', pattern='test_*.py'):
    for test_suite in all_tests:
        suite.addTests(test_suite)

return suite

During actual runtime all of the individual modules are held (contained) in a master like wrapper, which is basically a Singleton.

Now my problem is that whenever I run the tests as individual files (changing the loader from test_*.py to test_somemodule.py), all tests succeed, however if they are run all together (leaving the test_*.py pattern), some of the tests start failing.

I am pretty sure it was never the case when I hadn't implemented the master wrapper as a singleton, but the application functionality and architecture really requires that kind of approach. Since I am suspecting that only one instance of it is created, can anyone advise me on how to best solve this issue?

My theory is that if there was a method to reset all 'globals' to an initial state, it would work like a charm. Or perhaps there is some sort of method to isolate memory which is then discarded when test goes out of scope.

Many thanks in advance.

Upvotes: 2

Views: 2978

Answers (1)

Qwerty
Qwerty

Reputation: 1267

Why not do this?

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

Upvotes: 1

Related Questions