单元测试:如何动态导入测试类并运行?

2024-03-28 10:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个简单的脚本来运行和测试我的代码。我可以直接运行我的类吗?你知道吗


Tags: 代码脚本
3条回答

这个解决方案太简单,执行我想要的。你知道吗

import unittest

def execute_all_tests(tests_folder):
    suites = unittest.TestLoader().discover(tests_folder)
    text_runner = unittest.TextTestRunner().run(suites)

安装pytest,并使用如下命令运行测试:

py.test src

就这样。Py.试验将加载所有test_*.py文件,查找其中的所有def test_*调用,并为您运行每个调用。你知道吗

董事会很难回答你的问题,因为它在“为什么水是湿的?”territory;所有测试装备都带有自动执行代码剪接操作的运行程序,因此您只需阅读教程就可以开始使用。你知道吗

以及编写自动测试的基本道具;它们使你超过所有程序员的75%。你知道吗

这是我找到的导入和动态运行测试类的解决方案。你知道吗

import glob
import os
import imp
import unittest

def execute_all_tests(tests_folder):
    test_file_strings = glob.glob(os.path.join(tests_folder, 'test_*.py'))
    suites = []
    for test in test_file_strings:
        mod_name, file_ext = os.path.splitext(os.path.split(test)[-1])
        py_mod = imp.load_source(mod_name, test)
        suites.append(unittest.defaultTestLoader.loadTestsFromModule(py_mod))
    text_runner = unittest.TextTestRunner().run(unittest.TestSuite(suites))

相关问题 更多 >