Save A Reloaded Python Module For Testing Purposes


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
that is testing the initialization. The
is done in the
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
I get errors as seen <a href="" 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="">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
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
. I see that some projects exist like <a href="" 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:

import mypackage.mymodule
saved_module = mypackage.mymodule

class SomeTestThatReloads(unittest.TestCase):
    def setUp(self):

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

    def test_initialization(self):
        # testing scenario code