6

I'm writing unit-tests for a python module module, using python's unittest framework.

This module does a little "pre-proccessing" using a json file when it is loaded so it has things like: module.info['xyz'] that can be accessed and used.

When writing tests for this I want to reload the module before every test so that for every test the older keys of the dictionary module.info are no longer present before starting the current test.

Right now I have a reload(module) in setUp() but that doesn't seem to be doing the trick. I sitll have old keys introduced by test_A in other tests such as test_B and test_C that are executed after it.

I'd like to know if there's a way to do what I'm trying to achieve, or if you can point me to documentation that says it can not be done.

ffledgling
  • 11,502
  • 8
  • 47
  • 69
  • Please see the discussion here http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module – Maxim Khesin Jun 19 '13 at 17:39
  • @MaximKhesin I've gone through that question before posting this one, which part of the discussion do you feel answers my question? – ffledgling Jun 19 '13 at 17:42

1 Answers1

2

Manually deleting the module from the sys.modules dictionary seems to work for me.

import sys
import unittest
import myModule

class MyTest( unittest.TestCase ):
    def setUp( self ):
        global myModule
        myModule = __import__( 'path.to.myModule', globals(), locals(), [''], -1 )
        return

    def tearDown( self ):
        global myModule
        del sys.modules[myModule.__name__]
        return
ChristopherC
  • 1,635
  • 16
  • 31
  • Why are you using `__import__()` in `setUp()` rather than just `import myModule` again? If this is to maintain `myModule` in the global namespace, is there a simpler way that does not require knowing how to use `__import__()`? – CivFan Apr 08 '15 at 18:36
  • Also, the `return` calls for `setUp` and `tearDown` are redundant. Methods and functions have an implied `return None` if execution falls off the end without hitting a `return` call. – CivFan Apr 08 '15 at 19:08
  • I'm using `__import__()` is because it accepts a string variable which can be provided at runtime. The `return` calls are redundant but I liked to use them as a visual cue that a functiion ends. – ChristopherC Apr 09 '15 at 23:25
  • 1
    Instead of `del sys.modules[myModule.__name__]` you can simply do: `reload(myModule)` or `importlib.reload(myModule)` in python3 – Matt Palmerlee Sep 14 '17 at 21:45