zoukankan      html  css  js  c++  java
  • [翻译]pytest测试框架(二):使用

    此文已由作者吴琪惠授权网易云社区发布。

    欢迎访问网易云社区,了解更多网易技术产品运营经验。


    调用pytest

    调用命令:

    python -m pytest [...]

    上面的命令相当于在命令行直接调用脚本 pytest [...](前提是python已经加入环境变量)

    一些帮助信息

    pytest --version   # shows where pytest was imported from 查看版本
    pytest --fixtures  # show available builtin function arguments 查看内置参数
    pytest -h | --help # show help on command line and config file options 命令行和配置文件帮助

    失败后停止

    pytest -x            # stop after first failure 首次失败后停止运行
    pytest --maxfail=2    # stop after two failures 两次失败后停止执行

    选择测试用例

    pytest test_mod.py   # run tests in module 执行模块中的用例
    pytest somepath      # run all tests below somepath 执行路径中的用例
    pytest -k stringexpr # only run tests with names that match the  执行字符串表达式中的用例
                         # "string expression", e.g. "MyClass and not method" 如:"MyClass and not method"
                         # will select TestMyClass.test_something 将会选择TestMyClass.test_something
                         # but not TestMyClass.test_method_simple 而不会选择TestMyClass.test_method_simple
    pytest test_mod.py::test_func  # only run tests that match the "node ID", 仅运行匹配"node ID"的用例
                                   # e.g. "test_mod.py::test_func" will select 如选择:"test_mod.py::test_func"时只运行test_mod.py文件内的test_func 
                                   # only test_func in test_mod.py
    pytest test_mod.py::TestClass::test_method  # run a single method in a single class 在单独类中运行单独方法
    pytest --pyargs pkg # 导入pkg,使用其文件系统位置来查找和执行用例,执行pkg目录下的所有用例

    调试输出

    pytest --showlocals # show local variables in tracebacks 在tracebacks中显示本地变量
    pytest -l           # show local variables (shortcut)    在tracebacks中显示本地变量(快捷方式)
    
    pytest --tb=auto    # (default) 'long' tracebacks for the first and last(默认)第一个和最后一个使用长tracebacks信息,其他使用短的
                        # entry, but 'short' style for the other entries
    pytest --tb=long    # exhaustive, informative traceback formatting  完整的格式化的traceback信息
    pytest --tb=short   # shorter traceback format  短的traceback信息
    pytest --tb=line    # only one line per failure  每个错误信息显示一行
    pytest --tb=native  # Python standard library formatting 标准格式化输出
    pytest --tb=no      # no traceback at all 无traceback信息

    Python带有一个内置的Python调试器称为PDB。pytest可以在命令行选项指定调用:

    pytest --pdb

    这将每次失败时调用Python调试器。通常,您可能只希望这样做的第一个失败的测试,以了解某些故障情况:

    pytest -x --pdb   # drop to PDB on first failure, then end test session 下降到PDB上的第一次失败,然后结束测试阶段pytest --pdb --maxfail=3  # drop to PDB for first three failures 下降到PDB前三失败

    注意,任何失败的异常信息都会存储在sys.last_value,sys.last_type 以及 sys_last_traceback。在交互使用中,允许使用任意debug工具进行调试,也可手动访问异常信息,例如:

    >>> import sys>>> sys.last_traceback.tb_lineno42>>> sys.last_valueAssertionError('assert result == "ok"',)

    断点设置

    import pytestdef test_function():
        ...
        pytest.set_trace()    # invoke PDB debugger and tracing

    在pytest2.0.0版本之前,如果你没有能够通过 pytest -s 捕捉到trace信息,你只能查阅PDB traceing。在以后的版本中,当你输入PDB traceing,pytest自动禁用捕捉异常信息:

    1.捕获输出不影响其他测试用例

    2.任何prior测试输出已经被捕获,并且被处理

    3.同一个测试中,任何later测试输出不会被捕获,输出内容将会直接发送到sys.stdout。注意,这条也适用于交互式PDB会话已经被退出,但测试输出已经开始了,也会继续定期运行测试。

    从pytest2.4.0版本开始,你可以不需要使用pytest.set_trace()包装,也不需要禁用pytest -s命令,你可以使用本地Python命令:importpdb;pdb.set_trace()调用进入PBD traceing。


    测试执行时间

    获取运行最慢的10个测试执行时间:

    pytest --durations=10

    创建JUnitXML格式文件

    为了创建一些可以让Jenkins或者其他持续继承服务器可识别的测试结果文件,可使用如下命令:

    pytest --junitxml=path

    记录xml(2.8版本支持)

    如果你想要为一个测试日志提供额外信息,可使用recode_xml_property 参数:

    def test_function(record_xml_property):
        record_xml_property("example_key", 1)
        assert 0

    这段代码将会为测试用例标签添加一个额外的属性:example_key="1":

    <testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009">
      <properties>
        <property name="example_key" value="1" />
      </properties></testcase>

    注:

    record_xml_property

    Add extra xml properties to the tag for the calling test.

    The fixture is callable with ``(name, value)``, with value being automatically xml-encoded.

    注意:这是一个测试中的参数,这个接口在未来版本中可能会被更强大的接口取到,但他本身功能会保留


    LogXML: add_global_property(3.0版本支持)

    如果你希望在testsuite级别添加一个属性节点(properties node),这个属性会使得所有关联的测试用例都生效。

    import pytest@pytest.fixture(scope="session")def log_global_env_facts(f):
    
        if pytest.config.pluginmanager.hasplugin('junitxml'):
            my_junit = getattr(pytest.config, '_xml', None)
    
        my_junit.add_global_property('ARCH', 'PPC')
        my_junit.add_global_property('STORAGE_TYPE', 'CEPH')@pytest.mark.usefixtures(log_global_env_facts)def start_and_prepare_env():
        passclass TestMe:
        def test_foo(self):
            assert True

    上面的代码将在testsuite下添加一个属性节点:

    <testsuite errors="0" failures="0" name="pytest" skips="0" tests="1" time="0.006">
      <properties>
        <property name="ARCH" value="PPC"/>
        <property name="STORAGE_TYPE" value="CEPH"/>
      </properties>
      <testcase classname="test_me.TestMe" file="test_me.py" line="16" name="test_foo" time="0.000243663787842"/></testsuite>

    注意:这是一个测试中的参数,这个接口在未来版本中可能会被更强大的接口取到,但他本身功能会保留


    测试结果格式化文件

    这个功能在3.0版本已经弃用,并于4.0版本移除

    创建一个machine-readable的文本测试结果文件,可使用:

    pytest --resultlog=path

    这些文件会被如PyPy-test web页面使用,来显示测试结果的几个修改。

    在线发送测试报告服务

    为每个测试失败用例创建URL:

    pytest --pastebin=failed

    上面命令将提交测试运行信息到远程服务,并且会为每个失败用例提供一个URL。如果你只是想发送一个特别的失败信息,你可以利用 -x 命令像往常一样选择测试用例集或者添加用例。

    为整个会话日志创建URL:

    pytest --pastebin=all

    目前仅可以复制到 http://bpaste.net

    禁用插件

    使用 -p no 命令,在调用的时候禁用加载特定的插件,比如,禁用加载doctest插件,这个插件是从text文件列表中执行doctest用例,调用:

    pytest -p no:doctest

    使用Python调用pytest(2.0版本)

    直接调用:

    pytest.main()

    这句语句跟你从命令行执行pytest命令是一样的,他不会出现SystemExit,但会返回exitcode,可选参数:

    pytest.main(['-x', 'mytestdir'])

    给pytest.main指定附加插件:

    # content of myinvoke.pyimport pytestclass MyPlugin:
        def pytest_sessionfinish(self):
            print("*** test run reporting finishing")pytest.main(["-qq"], plugins=[MyPlugin()])

    运行之后,将会显示 MyPlugin被添加了,他的钩子函数被调用:

    $ python myinvoke.py
    *** test run reporting finishing


    网易云免费体验馆,0成本体验20+款云产品! 

    更多网易技术、产品、运营经验分享请点击


    相关文章:
    【推荐】 年轻设计师如何做好商业设计
    【推荐】 知物由学|见招拆招,Android应用破解及防护秘籍

  • 相关阅读:
    hdu 5723 Abandoned country 最小生成树 期望
    OpenJ_POJ C16G Challenge Your Template 迪杰斯特拉
    OpenJ_POJ C16D Extracurricular Sports 打表找规律
    OpenJ_POJ C16B Robot Game 打表找规律
    CCCC 成都信息工程大学游记
    UVALive 6893 The Big Painting hash
    UVALive 6889 City Park 并查集
    UVALive 6888 Ricochet Robots bfs
    UVALive 6886 Golf Bot FFT
    UVALive 6885 Flowery Trails 最短路
  • 原文地址:https://www.cnblogs.com/163yun/p/9814557.html
Copyright © 2011-2022 走看看