Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reload module

Tags:

python

testing

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.

like image 999
ffledgling Avatar asked Jun 19 '13 17:06

ffledgling


People also ask

How do I reload a Python module?

The reload() - reloads a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have mades changes to the code.

What is reload function in Python?

The function reload(moduleName) reloads a previously loaded module (assuming you loaded it with the syntax "import moduleName". It is intended for conversational use, where you have edited the source file for a module and want to test it without leaving Python and starting it again.


1 Answers

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
like image 165
ChristopherC Avatar answered Oct 23 '22 01:10

ChristopherC