我正在编写一个Pythonic工具,用于验证某个系统的正确性.每个验证都是用Python编写的unittest,报告如下:
test_exclude_list_not_empty (__main__.TestRepoLists)
Assert the the exclude list is not empty ... ok
test_include_list_not_empty (__main__.TestRepoLists)
Assert the the include list is not empty ... ok
test_repo_list_not_empty (__main__.TestRepoLists)
Assert the the repo list is not empty ... ok
Run Code Online (Sandbox Code Playgroud)
在我看来,这种格式很难阅读,特别是对于非Python主义者.是否有任何报告生成器可以以漂亮的表格形式生成报告,例如:
+----------------------------------------------------------------+-----------+
| Test | Status |
+----------------------------------------------------------------+-----------+
| Assert the the exclude list is not empty | OK |
| Assert the the include list is not empty | OK |
| Assert the the repo list is not empty …Run Code Online (Sandbox Code Playgroud) 我试图用Python编写一个解析器,用于特殊的文本文件格式.为了了解如何构造代码,我查看了JSON解析器的源代码,它是Python标准库(Python/Lib/json)的一部分.
在这个json目录中有一个tests目录,它包含许多单元测试.我用我的测试替换了json测试,但现在我不知道如何调用它们.
查看目录有一个__init__.py文件使它成为一个模块,在这个文件里面有以下用于运行测试的代码片段:
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith("test") and fn.endswith(".py"):
modname = "json.tests." + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (json, json.encoder, json.decoder):
suite.addTest(doctest.DocTestSuite(mod))
suite.addTest(TestPyTest('test_pyjson'))
suite.addTest(TestCTest('test_cjson'))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
main()
Run Code Online (Sandbox Code Playgroud)
我现在的问题是如何执行这些单元测试?我感到困惑,因为if __name__ == '__main__':如果直接调用此文件而不将其作为模块导入,则if子句将验证为true.但是因为它在__init__.py模块的文件中,所以应该在导入后立即执行. …