Home > Software design >  How to double import a module for test purposes?
How to double import a module for test purposes?

Time:11-19

Currently I have a module that when It is imported a for loop is executed:

numbers.py

DICT_NUMBER = {
    'one': One,
    'two': Two,
    'three': Three,
    'four': Four,
    'five': Five,
}

for num in DICT_NUMBER.values():
    if not issubclass(num, Number):
        raise Exception(f'{num} is not extending Number')

The problem is that I don't know how to test it, I've tried to do the following code:

from numbers.py import DICT_NUMBER # the for is executed without raise Exception

DICT_NUMBER['A'] = A # 'A' don't extends Number

with self.assertRaises(Exception):
   from numbers.py import DICT_NUMBER

This does not work because DICT_NUMBER turns into a unresolved reference.

There is any way to do it?

CodePudding user response:

You cannot double import a module, only reload it as specified here: how to reload a python module. In your case module file is not changing so reload will not help. Try to move the for part into a function with a dict parameter and then test it with different inputs.

  • Related