如何从 python 脚本 运行 python 文件中的所有测试?

How to run all tests in a python file from a python script?

如何在脚本中 运行 来自 python 文件的所有测试 (unittest.TestCase)?

我试过使用 nose,但它似乎总是 运行 测试发现。 我只想导入一个模块,给一些函数一个路径并得到测试结果,有什么建议吗?

在测试脚本的底部放置

if __name__ == '__main__':
    unittest.main()

然后正常调用你的文件

$ python my_test_script.py

可选地,如果你想使用nosepytest,你可以只给它你想要的脚本的名称运行,它仍然会进行发现,但是仅在那个文件上。

$ nosetests my_test_script.py

$ py.test my_test_script.py

如果你运行从里面偷窥python,你可以使用nose.run()

my_script.py

import nose
nose.run()

默认情况下,它将使用您传递给脚本的参数,因此如果您只想 运行 一个 test_script

$ python my_script.py /path/to/test_script.py

或者,您可以直接在脚本中传递参数

nose.run(argv=[__file__, '/path/to/test_script'])