Save A Reloaded Python Module For Testing Purposes

admin

Administrator
Staff member
I have a Python module that I am testing, and because of the way that the module works (it does some initialization upon import) have been reloading the module during each
Code:
unittest
that is testing the initialization. The
Code:
reload
is done in the
Code:
setUp
method, so all tests are actually reloading the module, which is fine.

This all works great if I am only running tests in that file during any given Python session because I never required a reference to the previous instance of the module. But when I use Pydev or
Code:
unittest
's
Code:
discover
I get errors as seen <a href="http://thingspython.wordpress.com/2010/09/27/another-super-wrinkle-raising-typeerror/" rel="nofollow noreferrer">here</a> because other tests which import this module have lost their reference to objects in the module since they were imported before all of the reloading business in my tests.

There are similar questions around SO like <a href="https://stackoverflow.com/a/9165855/576333">this one</a>, but those all deal with updating objects after reloads have occurred. What I would like to do is save the state of the module after the initial import, run my tests that do all of the reloading, and then in the test
Code:
tearDown
to put the initial reference to the module back so that tests that run downstream that use the module still have the correct reference. Note that I am not making any changes to the module, I am only reloading it to test some initialization pieces that it does.

There are also some solutions that include hooks in the module code which I am not interested in. I don't want to ask developers to push things into the codebase just so tests can run. I am using Python 2.6 and
Code:
unittest
. I see that some projects exist like <a href="https://github.com/alexflint/process-isolation" rel="nofollow noreferrer" title="process-isolation">process-isolation</a>, and while I am not sure if that does entirely what I am asking for, it does not work for Python 2.6 and I don't want to add new packages to our stack if possible. Stub code follows:

Code:
import mypackage.mymodule
saved_module = mypackage.mymodule

class SomeTestThatReloads(unittest.TestCase):
    def setUp(self):
        reload(mypackage.mymodule)

    def tearDown(self):
        # What to do here with saved_module?

    def test_initialization(self):
        # testing scenario code