Ich habe mein Python-Unittest-Skript wie unten. Um festzustellen, ob die Testfälle das Basismodul von foo_PC_A.py
oder foo_PC_B.py
laden sollen, benötigt man ein Argument '-a
'. Ich verwende shutil.move()
, um eine .py-Datei in foo.py umzubenennen, so dass alle Testfallmodule (z. B. tm1.py
, tm2.py
) einfach import foo
lauten können. Obwohl dies wie ein Workaround und nicht Pythonic aussieht. Gibt es einen besseren Weg, dies zu tun? Oder ein besseres Design, um dieses Problem grundlegend zu lösen.Python-Laufzeit bestimmen, welches Modul geladen werden soll
(run_all_unittest.py)
if sys.argv[1] = '-a':
shutil.move('foo_PC_A.py', 'foo.py')
else:
shutil.move('foo_PC_B.py', 'foo.py')
test_module_list = ['tm1', 'tm2', ...]
for test_module_name in test_module_list:
test_module = __import__(test_module_name)
test_suites.append(unittest.TestLoader().loadTestsFromModule(test_module))
alltests = unittest.TestSuite(test_suites)
unittest.TextTestRunner().run(alltests)
if sys.argv[1] = '-a':
shutil.move('foo.py', 'foo_PC_A.py')
else:
shutil.move('foo.py', 'foo_PC_B.py')
(tm1.py)
from foo import MyTestCase
...
(foo_PC_A.py)
import <some module only available on PC A>
class MyTestCase(unittest.TestCase):
...
(foo_PC_B.py)
# since the PC A modules are not available on PC B,
# just call the pre-built executable via subprocess
import subprocess
class MyTestCase(unittest.TestCase):
...
def test_run(self):
subprocess.call(...)