pytest自动化测试框架--pytest.fixtures

1 篇文章 0 订阅
1 篇文章 0 订阅

1.1 pytest fixtures

 在方法前边加@pytest.fixture装饰器,该方法可作为一个参数传入到调用方法中。可以方便的完成方法初始化,或者返回数据给测试函数。

1.1.1 作为函数参数

 例如场景:有2个网页中有的页面需要获取token进行登录,有1个网页则不需要。可以在登录方法前边增加@pytest.fixture,做一个初始化。
 首先,创建一个名为test_fixture.py的文件,代码如下:

import pytest


@pytest.fixture()
def login():
    return 'token=1213vnfjv'
    print("返回token值")

@pytest.fixture()
def operate():
    return("登录后执行的一些方法")

def test_case1(login):
    print("1,需要登录")
    print(login)


def test_case2(login,operate):
    print("2,需要登录,后续有一些操作。。。")
    print(login)
    print(operate)


def test_case3():
    print("3,不需要登录")

 在上边的例子中,1,2的测试用例需要获取token进行登录,调用了@pytest.fixture标记的login方法,运行结果如下:
Testing started at 15:25 …
============================= test session starts =============================
collected 3 items

test_one.py .1,需要登录
token=1213vnfjv
.2,需要登录,后续有一些操作。。。
token=1213vnfjv
登录后执行的一些方法
.3,不需要登录

1.1.2 指定范围内共享

 通过scope参数,控制作用范围session> module> class> function:

  1. function 函数或者方法级别都会被调用
  2. class 类级别调用一次
  3. module 模块级别调用一次
  4. session 是多个文件调用一次(可以跨.py文件调用,每个.py文件就是module)
     举个例子:
import pytest

# 作用域:module是在模块之前执行, 模块之后执行
@pytest.fixture(scope="module")
def open():
    print("打开浏览器")
    yield

    print("执行teardown !")
    print("最后关闭浏览器")

@pytest.mark.usefixtures("open")
def test_search1():
    print("test_search1")
    raise NameError
    pass

def test_search2(open):
    print("test_search2")
    pass

def test_search3(open):
    print("test_search3")
    pass

@pytest.fixture(scope=‘module’)表示在当前py脚本里面所有的用例开始前只执行一次。全部用例运行之前执行了yield前的语句,全部用例执行后执行了yield后面的语句。

1.1.3autouse参数自动执行fixture

 使用 autouse=“true” 可以实现在每个方法前自动执行,无需传入方法名。

@pytest.fixture(autouse="true")
def myfix():
    print("autouse")

class TestAutouse:
    def test_case1(self):
        print("case1")
        pass
    
     def test_case2(self):
        print("case2")
        pass   

    def test_case3(self):
        print("case3")
        pass

结果为:
test_a.py::TestAutouse::test_case1 autouse
test_case1
PASSED
test_a.py::TestAutouse::test_case2 autouse
test_case2
PASSED
test_a.py::TestAutouse::test_case3
autouse
test_case3
PASSED

1.1.4 传递参数

 使用params参数,实现参数值的传递。
@pytest.fixture(params=[4,1,3]),将4,1,3分别传入到用例中,相当于三个测试数据。使用request.param传递数据。
使用方法如下:

import pytest

@pytest.fixture(params=[4, 1, 3])
def data(request):
    return request.param

def test_not_2(data):
    print(f"测试数据:{data}")
    assert data < 5  

运行结果如下:
test_params.py::test_not_2[4]PASSED
test_params.py::test_not_2[1] PASSED
test_params.py::test_not_2[3] PASSED

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值