现象 + 疑问: 使用 unittest 时 ,loader.loadTestsFromModule( ) 遇到搜集不到测试用例 。
1、项目结构层级如下:
2、各目录代码如下:
test_aa.py 代码:
class TestMath: def __init__(self, a, b): self.a = int(a) self.b = int(b) def add(self): return self.a + self.b
test_bb.py 代码如下:
from unittest import TestCase from aa.test_aa import TestMath class TestMy(TestCase): def setUp(self): print("开始测试") def test_add(self): add = TestMath(3,5) actually_result = add.add() except_result = 8 self.assertEqual(actually_result,except_result) def test_add_02(self): add = TestMath(2,5) actually_result = add.add() except_result = 7 self.assertEqual(actually_result,except_result) def tearDown(self): print("测试结束")
test_cc.py 代码如下:
import importlib from unittest import TestLoader, TestSuite test_modlue = importlib.import_module(‘.test_bb‘, package=‘bb‘) #相对导入 suite = TestSuite() loader = TestLoader() suite.addTest(loader.loadTestsFromModule(test_modlue)) # suite.addTest(loader.loadTestsFromTestCase(TestMy))
用pytest 的方式执行
执行结果如下,搜集不到测试用例:
D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day14\venv\Scripts\python.exe "C:\SkyWorkSpace\WorkTools\PyCharm\PyCharm_Community_Edition_202003\PyCharm Community Edition 2020.3\plugins\python-ce\helpers\pycharm\_jb_pytest_runner.py" --path D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day14/cc/test_cc.py Testing started at 19:22 ... Launching pytest with arguments D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day14/cc/test_cc.py in D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day14\cc ============================= test session starts ============================= platform win32 -- Python 3.8.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day14\venv\Scripts\python.exe cachedir: .pytest_cache rootdir: D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day14\cc collecting ... collected 0 items ============================== warnings summary =============================== C:\SkyWorkSpace\WorkTools\python\Python38\lib\unittest\loader.py:66 C:\SkyWorkSpace\WorkTools\python\Python38\lib\unittest\loader.py:66: PytestCollectionWarning: cannot collect test class ‘TestLoader‘ because it has a __init__ constructor (from: test_cc.py) class TestLoader(object): C:\SkyWorkSpace\WorkTools\python\Python38\lib\unittest\suite.py:92 C:\SkyWorkSpace\WorkTools\python\Python38\lib\unittest\suite.py:92: PytestCollectionWarning: cannot collect test class ‘TestSuite‘ because it has a __init__ constructor (from: test_cc.py) class TestSuite(BaseTestSuite): -- Docs: https://docs.pytest.org/en/stable/warnings.html ============================= 2 warnings in 0.02s ============================= Process finished with exit code 5 Empty suite
如果我用 suite.addTest(loader.loadTestsFromTestCase(TestMath)) 是 正常的 。
网上查看下原因,说是 loadTestsFromModule() 动态导模块的问题 。但是我还是没解决。
动态导包参考: https://blog.csdn.net/edward_zcl/article/details/88809212