如何从其他模块调用 运行 unittest.main() 函数?

How to run unittest.main() function from other module?

我有一个 API,里面写有单元测试。问题是 API 不能是 运行 作为来自终端的 'stand-alone' 脚本,它必须是来自自定义框架的 运行。在那个 API 中有一个函数基本上调用 unittest.main() 但如果函数是 'outside' 的 运行 则找不到测试用例。这种问题有通用的解决方案吗?

您可以告诉 unittest.main() 通过将该模块的名称作为第一个(或 module=)参数传递来从另一个模块加载测试。

例如,要使用 current 模块名称,请使用:

unittest.main(__name__)

您可能想要study the code that implements this functionality; unittest.main is an alias for the TestProgram class, which uses the standard unittest API to discover, load and run tests。如果您需要更多控制,直接使用 API 会很有用。