Marking test functions with attributes¶

pytest.mark可以用来在测试函数上设置metadata。pytest自带了一些markers,比如:

  • skip,跳过某个测试
  • skipif, 按条件跳过某个测试
  • xfail,表明用例失败是预期的行为
  • parametrize,将某个测试用例进行参数化,从而产生多个调用,每个调用使用不同的参数

可以很容易创建定制的标记,并把标记应用到某个测试用例,甚至一整套测试用例。标记可以被插件使用,也可以用来在执行的时候区分不同的测试用例(命令行-m选项)

标记只能应用在测试用例上,不能应用在测试装置上

可以在pytest.ini中自定义标记:

[pytest]
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')
    serial

冒号之后的是对标记的描述。

也可以在pytest_configure钩子中注册:

def pytest_configure(config):
    config.addinivalue_line(
        "markers", "env(name): mark test to run only on named environment"
    )

如果一个标记没有注册的话,会产生告警信息。如果使用–strict-markers命令行选项,那么使用没有注册的标记会产生错误信息而不是告警。可以在pytest.ini中强制这一行为:

[pytest]
addopts = --strict-markers
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')
    serial

Logging

pytest会自动捕获WARNING级别以上的信息,然后再用例失败的时候显示出来。

可以通过命令行指定log的头格式:

pytest --log-format="%(asctime)s %(levelname)s %(message)s" \
        --log-date-format="%Y-%m-%d %H:%M:%S"

输出示例:

----------------------- Captured stdlog call ----------------------
2010-04-10 14:48:44 WARNING text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================

caplog测试装置可以用来捕捉用例中的log:

def test_foo(caplog):
    caplog.set_level(logging.CRITICAL, logger="root.baz")
    pass

通过caplog.records(类型是logging.LogRecord)可以查看该测试用例中捕获的log。也可以使用record_tuples :

def test_foo(caplog):
    logging.getLogger().info("boo %s", "arg")

    assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]

通过caplog.clear() 可以重设再caplog中捕获的log。

通过caplog.get_records(when)可以获取其他阶段(比如setup以及call)的log。

Live Logs

如果把 log_cli 配置设置为true,那么pytest会直接将log打印到控制台。通过–log-cli-level可以指定log_cli打印的log的等级。–log-cli-format和–log-cli-date-format 可以用来控制输出格式。

通过 –log-file=/path/to/log/file可以将log输出到文件。同样的,–log-file-format和-log-file-date-format可以对输出进行格式化。

一个实验性的函数set_log_path() 可以用来动态控制输出。

这个功能原先是在 pytest-catchlog插件中做的。

其他

Working with custom markers¶

(本篇完)