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.

2
  • Please see the discussion here stackoverflow.com/questions/437589/… Commented Jun 19, 2013 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? Commented Jun 19, 2013 at 17:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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__()?
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.
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.
Instead of del sys.modules[myModule.__name__] you can simply do: reload(myModule) or importlib.reload(myModule) in python3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.