码迷,mamicode.com
首页 > 其他好文 > 详细

6. 重点来啦,pytest的各种装饰圈fixtures

时间:2018-09-11 00:59:02      阅读:464      评论:0      收藏:0      [点我收藏+]

标签:就是   tmp   --   装饰器   ssi   断言   一个   import   foo   

一、fixture可以作为一个函数的参数被使用

import pytest

@pytest.fixture
def smtp_connection():
    import smtplib
    return smtplib.SMTP("smtp.gmai.com", 587, timeout=5)

def test_ehlo(smtp_connection):
    response, msg = smtp_connection.ehlo()
    assert response == 250
    assert 0    #强制断言失败

这里的 test_ehlo函数,需要参数值smtp_connection,pytest就是找到并且调用这个用@pytest.fixture装饰的smtp_connection函数,
换句话讲,被装饰器装饰的函数或者方法,仍然可以被调用。步骤是这样:

  • pytest 找到test_ 开头的函数,于是找到了test_ehlo
  • test_ehlo这个测试函数,需要一个参数smtp_connection,于是函数smtp_connection被找到
  • smtp_connection被调用来创建一个实例

二、fixture可以在一个类、或者一个模块、或者整个session中被共享,加上范围即可

比如

import pytest

@pytest.fixture(scope="module")
def smtp_connection():
    import smtplib
    return smtplib.SMTP("smtp.gmai.com", 587,说timeout=5)

def test_ehlo(smtp_connection):
    response, msg = smtp_connection.ehlo()
    assert response == 250
    assert 0    #强制断言失败

def test_noop(smtp_connection):
    response, msg = smtp_connection.noop()
    assert response == 250
    assert 0

这里的smtp_connection,就可以在这个文件中,共享使用,同样的
如果想在一个类中使用,那么@pytest.fixture(scope="class")
如果想在全部会话中使用,那么@pytest.fixture(scope="session")

三、 当出现多个范围装饰的时候,优先实例化范围优先级高的,依次是,session-->module-->session

比如

@pytest.fixture(scope="session")
def s1():
    pass
@pytest.fixture(scope="module")
def m1():
    pass
@pytest.fixture
def f1(tmpdir):
    pass
@pytest.fixture
def f2():
    pass
def test_foo(f1, m1, f2, s1):
...
  • s1 优先级是最高的,最先实例化它,
  • m1 优先级次之

6. 重点来啦,pytest的各种装饰圈fixtures

标签:就是   tmp   --   装饰器   ssi   断言   一个   import   foo   

原文地址:https://www.cnblogs.com/pingguo-softwaretesting/p/9623371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!