Python unittest - 额外 运行 0.000 秒内的测试

Python unittest - Extra Ran 0 tests in 0.000s

这是我的测试脚本:

# tests/runner.py
import unittest

# import your test modules
import TC110
import TC112

# initialize the test suite
loader = unittest.TestLoader()
suite  = unittest.TestSuite()

# add tests to the test suite
suite.addTests(loader.loadTestsFromModule(TC110))
suite.addTests(loader.loadTestsFromModule(TC112))

# initialize a runner, pass it your suite and run it
runner = unittest.TextTestRunner(verbosity=3)
result = runner.run(suite)

我在同一个目录中有 TC110.py 和 TC112.py,运行 我的测试是这样的,

"python -m unittest runner"

我得到这样的输出,

test_ldap_login (TC110.TestTC110) ... ok
test_download_artifact (TC112.TestTC112) ... ok

----------------------------------------------------------------------
Ran 2 tests in 1.929s

OK

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

为什么我得到 "Ran 0 tests",如何摆脱它?

你得到一个额外的 "Ran 0 tests" 与 print(print("asdf")) 打印一个额外的 None 基本相同的原因:你正在发出两个测试命令。

您的 runner.py 脚本从其他文件加载测试并 运行s 它们。如果你只是告诉 Python 到 运行 脚本 (python runner.py),你就不会得到虚假的额外输出。

您没有告诉 Python 到 运行 脚本,而是告诉 unittest 模块加载 运行 来自 runner.py 的所有测试。作为副作用,此 运行 是 runner.py 的主体,运行 包含您想要的测试。 unittest 然后加载并 运行 包含在 runner.py 中的所有 0 个测试,因为你告诉它这样做。