美文网首页
pytest-fixture

pytest-fixture

作者: huashen_9126 | 来源:发表于2020-04-13 01:05 被阅读0次

执行测试后自动执行某些操作,用到关键字yeild

import smtplib
import pytest

@pytest.fixture(scope="module")
def smtp():
    smtp = smtplib.SMTP("smtp.qq.com", 587, timeout=5)
    yield smtp
    print("拆卸smtp")
    smtp.close()

scope="module"代表在模块的最后一次测试完成后执行smtp.close()
scope还可以等于session, class, function

进阶写法,用到关键字with

import smtplib
import pytest

@pytest.fixture(scope="module")
def smtp():
    with smtplib.SMTP("smtp.qq.com", 587, timeout=5) as smtp:
        yield smtp

说明:如果在yield之前发生了异常,smtp.close()不会被执行,关键字addfinalizer解决这一痛点

import smtplib
import pytest

@pytest.fixture(scope="module")
def smtp(request):
    smtp = smtplib.SMTP("smtp.qq.com", 587, timeout=5)
    def fin():
        print("拆卸smtp")
        smtp.close()
    request.addfinalizer(fin)
    return smtp

相关文章

  • pytest-fixture

    作用 1、完成setup和teardown操作,处理数据库、文件等资源的打开和关闭

  • pytest-fixture

    执行测试后自动执行某些操作,用到关键字yeild scope="module"代表在模块的最后一次测试完成后执行s...

  • pytest-fixture用法

    fixture简介 fixture的目的是提供一个固定基线,在该基线上测试可以可靠地和重复地执行。fixture提...

  • pytest-fixture的使用

    http://doc.pytest.org/en/latest/fixture.html fixture的优点 显...

  • pytest-fixture的使用

    fixture可以让我们自定义测试用例的前置条件 fixture实现teardown后置条件操作

  • pytest-fixture使用详解03(上)

    一、fixture的特点 在测试函数运行前后,由pytest执行的外壳函数,代码可定制用于将测试前后进行预备或清理...

  • pytest-fixture使用详解03(下)

    结合上一篇,补充fixture的用法 一、什么是fixture? fixture属于pytest中的一种方法,可以...

  • pytest-fixture中的yield及autouse

    记录一下fixture中关于yield以及autouse参数的两个小细节。 yield yield在fixture...

网友评论

      本文标题:pytest-fixture

      本文链接:https://www.haomeiwen.com/subject/pyekphtx.html