pytest fixture

  • Post author:
  • Post category:其他



Fixture终结/执行teardown代码


pytest支持当fixture超出范围时执行指定的终结代码。通过接受一个request对象在你的fixture函数中,你可以调用它的request.addfinalizer一次或多次。


# content of conftest.py

import smtplib
import pytest

@pytest.fixture(scope="module")
def smtp(request):
    smtp = smtplib.SMTP("smtp.gmail.com")
    def fin():
        print ("teardown smtp")
        smtp.close()
    request.addfinalizer(fin)
    return smtp  # provide the fixture value

当在模块中最后一个使用fixture的test被执行完毕后,fin函数会被执行。

让我们执行它:


$ py.test -s -q --tb=no
FFteardown smtp

2 failed in 0.12 seconds

我们可以看到当两个test执行结束后,smtp实例被终结。


本文翻译自:

pytest官网