为多个 Python 文件编写单元测试

Eva*_*ica 5 python unit-testing argparse python-3.x

我正在尝试编写一个测试程序来测试许多(相同的)学生作业。我有一个使用unittest 库编写的测试。该文档似乎表明每个测试应与一个文件关联。相反,我想要一个测试文件,并使用命令行参数将测试指向它应该测试的文件。

我知道我可以通过在单元测试中使用argparse模块来做到这一点,但是有更好的方法吗?似乎单元测试应该支持这种行为,但我在文档中找不到任何内容......

Pra*_*mar 1

创建主测试目录并添加子测试包。为您创建一个指向测试目录的测试运行程序。它可以充当套房。我附上了一段用于我的测试套件的代码。

import os
import unittest

def main(test_path, test_pattern):
    print(('Discovering tests in : {}'.format(test_path)))
    suite = unittest.TestLoader().discover(test_path, test_pattern)
    unittest.TextTestRunner(verbosity=2).run(suite)

if __name__ == '__main__':
    root_path = os.path.abspath('.')
    test_path = os.path.join(root_path, 'src/tests/')
    test_pattern = 'test_*'
    main(test_path, test_pattern)

Run Code Online (Sandbox Code Playgroud)