在 Python 中的测试包中运行单元测试 [英] Running Unit Tests in Test Bundle in Python

查看:32
本文介绍了在 Python 中的测试包中运行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 Python 编写一个用于特殊文本文件格式的解析器.为了了解如何构建代码,我查看了 JSON 解析器的源代码,它是 Python 标准库 (Python/Lib/json) 的一部分.

I am trying to write a parser in Python for a special text file format. To get an idea how to structure the code I looked into the source code of the JSON parser which is part of the Python standard library (Python/Lib/json).

在这个 json 目录中有一个 tests 目录,它保存了许多单元测试.我用我的测试替换了 json 测试,但现在我不知道如何调用它们.

In this json directory there is a tests directory which holds a number of unit tests. I replaced the json tests with my tests but now I do not know how to call them.

查看目录中有一个 __init__.py 文件使它成为一个模块,在这个文件中有以下用于运行测试的代码片段:

Looking into the directory there is a __init__.py file making it a module and inside of this file there is the following code snippet for running the tests:

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()

我现在的问题是这些单元测试是如何执行的?我很困惑,因为 if __name__ == '__main__': 如果这个文件被直接调用而不是作为模块导入,则 if 子句验证为真.然而,由于它在模块的 __init__.py 文件中,它应该在导入后立即执行.

My problem is now how are these unit tests executed? I am confused because the if __name__ == '__main__': if clause validates to true if this file is called directly and not being imported as a module. However as it is in the __init__.py file of the module it should be executed right after import.

python 控制台中的 import tests 是否应该启动所有单元测试?

Should an import tests in the python console start all the unit tests?

推荐答案

第一:目录中的 __init__.py 文件将目录标记为包和所有其他以 .py 结尾的文件是模块.

First: the __init__.py file in a directory marks the directory as a package and all other files with the .py ending therein are modules.

第二:要验证 __name__ == '__main__' 条件,您必须执行文件.所以简单的 import 行不通.

Second: To validate the __name__ == '__main__' conditional you have to execute the file. So a simple import won't do.

有关包和模块结构的进一步问题,我建议您阅读 官方 Python 文档包裹.

For further question on package and module structure i would suggest ro read the Official Python Documentation on Packages.

单元测试被构建成测试套件,其中可以包含一个或多个由一个或多个测试组成的测试用例.

The unittests are structured into testsuites, which can contain one ore more TestCases which consists of one or more tests.

测试通常是 TestCase 派生类的方法.您可以通过定义一个 runTest() 方法或定义多个 test_* 方法来运行测试,这些方法将自动执行.要执行单元测试,您可以使用便利函数 unittest.main(),该函数基本上尝试使用默认规则构建测试套件、测试结果和测试运行器对象.

The tests are usually methods of a TestCase derived class. You can either run the tests by defining a runTest() method or defining multiple test_* methods, which will be executed autmatically. To execute a Unittest you can either use the convenience function unittest.main() which basicaly tries to construct a testsuite, testresult and testrunner object by using default-rules.

您的单元测试本身的执行是由 testrunner 对象完成的.标准的 testrunner-class 是 TextTestRunner,它使用 TextTestResult-class 来存储测试结果并将它们打印到 stdout.有关最简单的变体,请参阅unittest.main() 的官方单元测试文档.

The execution of your unittest itself is done by the testrunner object. The standard testrunner-class is TextTestRunner, which uses a TextTestResult-class to store the testresults and prints them to stdout. See Official unittest Documentation for unittest.main() for the simplest variant.

1) 单元测试基本上是一个包含一个或多个测试用例的测试套件:

1) A unittest is basically a TestSuite containing one ore more TestCases:

TestSuite      <---executed by--- TestRunner
   + TestCaseA                        |
       +test_a()                      |
       +test_b()             stores test-results 
           ...                      into
       +test_z()                      |
    + TestCaseB                       V
    + TestCaseC                  TestResult

2) 测试用例是 unittest.TestCase 的子类.您可以通过使用加载器(例如:unittest.defaultTestLoader)来创建测试套件,它基本上是测试套件的工厂,或者您可以手动添加测试用例(suite.addTest(test)/suite.addTests(tests) - tests 可能是 TestCases 或什至其他 TestSuites) 或组合这两种方法.

2) The TestCases are subclasses of unittest.TestCase. You can create a TestSuite, by using a loader (e.g.: unittest.defaultTestLoader) which is basically a factory for a testsuite, or you can add the TestCases manually (suite.addTest(test) / suite.addTests(tests) - tests may be TestCases or even other TestSuites) or by combining those two methods.

3) 要执行测试套件,您可以使用 unittest.TestRunner 对象,该对象将结果保存在 unittest.TestResult 对象中.

3) To execute a testsuite you use a unittest.TestRunner-object which saves the results in a unittest.TestResult object.

通常您会使用 unittest.TextTestRunner-object 将测试结果的简单输出输出到标准输出.

Normaly you would be using unittest.TextTestRunner-object to get a simple output of the testresults to stdout.

这正是你的主程序中发生的事情:

That's excatly what happens also in your main-routine:

def main():
    suite = test_suite()                #1 create a TestSuite object
    runner = unittest.TextTestRunner()  #2 create a TextTestRunner object
    runner.run(suite)                   #3 executes the TestSuite with TestSuite
                                        #  build by the function test_suite()

要执行您的测试套件,您必须执行 python __init__.py .

To execute your testsuite you would have then to execute python __init__.py .

这篇关于在 Python 中的测试包中运行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆