Kartoch
Kartoch

Reputation: 7779

Unit testing and import

My program reads a python script for configuration. So far I'm loading the script called lab.py like this:

self.lab_file = "/not/interesting/path/lab.py"
sys.path.insert(0, os.path.dirname(self.lab_file))
import lab as _config

But when I'm unit-testing it, I've a strange behavior:

Tracing the problem with logging, It seems the lab script is imported only the first time. This behavior seems coherent in respect of python but I was assuming than unit tests are isolated between each other. I am wrong ? If test are not independant in respect of the import, how can I write test to force the loading of my script each time ?

Upvotes: 1

Views: 721

Answers (3)

Chris S.
Chris S.

Reputation: 21

Try using reload.

For example:

    import lab as _config
    reload(_config)

Upvotes: 2

Daniel Figueroa
Daniel Figueroa

Reputation: 10676

Maybe it helps if you run nose with this flag:

--with-isolation

From the nosedoc

Enable plugin IsolationPlugin: Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin should not be used with the coverage plugin, or in any other case where module reloading may produce undesirable side-effects. [NOSE_WITH_ISOLATION]

Upvotes: 1

Shani
Shani

Reputation: 418

I would suggest deleting the module from sys.modules

 import sys
 if 'lab' in sys.modules:
     del sys.modules['lab']
 import lab as _config

just deleting the import will not work because import checks in sys.modules if the module is already imported.

if you import then reload it works because it first loads the module from sys.modules into the local namespace and then reloads the module from file.

Upvotes: 1

Related Questions