Python 接口自动化

pytest测试框架-Fixture用法

2022-04-20  本文已影响0人  吱吱菌啦啦

Fixture 特点及优势

1、命令灵活:相当于setup,teardown,但是可以自定义命名
2、数据共享:在 conftest.py 配置⾥写⽅法可以实现数据共享,不需要 import 导⼊。可以跨⽂件共享
3、scope 的层次及神奇的 yield 组合相当于各种 setup 和 teardown
4、实现参数化

Fixture 在自动化中的应用- 基本用法

import pytest

@pytest.fixture()
def login():
    print("登录")

def test_search():
    pass

def test_cart(login):
    print("加购")

def test_order(login):
    print("下单")

Fixture 在自动化中的应用 - 作用域

image.png

定义某功能的fixture,尽量避免test_开头

import pytest

@pytest.fixture(scope="module")
#@pytest.fixture(scope="class")
def login():
    print("登录")

def test_search():
    pass

def test_cart(login):
    print("加购")

def test_order(login):
    print("下单")

class TestDemo:
    def test_case1(self, login):
        print("case1")

Fixture 在自动化中的应用 - yield 关键字

"""
@pytest.fixture()
def fixture_name():
    setup操作
    yield返回值
    teardown操作
"""
@pytest.fixture(scope="module")
def login():
    print("登录")
    yield
    print("退出")

def test_order(login):
    print("下单")
@pytest.fixture(scope="module")
def login():
    print("登录")
    token = "212332ewee"
    name = "zizi"
    yield token,name# 相当于return,可以一个或多个参数,逗号分隔
    print("退出")

def test_cart(login):
    token,name = login
    print(f"token:{login},name:{name}")
    print("加购")

Fixture 在自动化中的应用 - 数据共享conftest.py

使用时conftest.py时不需要导包,直接用


image.png image.png

Fixture 在自动化中的应用 - 自动应用

Fixture 在自动化中的应用 -参数化

import pytest


@pytest.fixture(params=["selenum","appium"])
def login(request):
    print(f"用户名{request.param}")
    return request.param

def test_case1(login):
    print(f"test1数据为{login}")
上一篇 下一篇

猜你喜欢

热点阅读