其他分享
首页 > 其他分享> > Pytest进阶 -- fixture/yield

Pytest进阶 -- fixture/yield

作者:互联网

fixture

 

使用介绍:

@pytest.fixture()   #加fixture装饰器,可以让这个方法后面被调用
def login():
    print("\nlogin.....\n")


def test_search():
    print("search")

def test_order(login):    #只需要在括号内填入加了fixture装饰器的方法,就可以实现在这个测试用例前调用login方法
    print("ordering")

def test_cart():
    print("shopping cart..")

 

作用域:

取值 范围 说明
function 函数级 每一个函数或方法都会调用
class 类级别 每个测试类只运行一次
module 模块级 每一个.py文件调用一次
package 包级 每一个python包只调用一次(暂不支持)
session 会话级 每次会话只需要运行一次,会话内所有方法及类,模块都共享这个方法

module

import pytest


#fixture作用域 -- module
@pytest.fixture(scope= "module")   #避免以test开头
def login():
    print("\nlogin.....\n")


def test_search():
    print("search")

def test_order(login):    
    print("ordering")

def test_cart(login):
    print("shopping cart..")

class TestDemo:
    def test_case_1(self):
        print("test case 1")
    def test_case_2(self,login):
        print("test case 2")

输出:

test_demo.py::test_search search
PASSED
test_demo.py::test_order
login.....    #整个py文件只执行一次

ordering
PASSED
test_demo.py::test_cart shopping cart..
PASSED
test_demo.py::TestDemo::test_case_1 test case 1
PASSED
test_demo.py::TestDemo::test_case_2 test case 2
PASSED

 

class

类里面只运行一次

#fixture作用域
@pytest.fixture(scope= "class")   #避免以test开头
def login():
    print("\nlogin.....\n")


def test_search():
    print("search")

def test_order(login):    #只需要在括号内填入加了fixture装饰器的方法,就可以实现在这个测试用例前调用login方法
    print("ordering")

def test_cart(login):
    print("shopping cart..")

class TestDemo:
    def test_case_1(self,login):
        print("test case 1")
    def test_case_2(self,login):
        print("test case 2")

输出:

test_demo.py::test_search search
PASSED
test_demo.py::test_order
login.....#类外每次都会调用

ordering
PASSED
test_demo.py::test_cart
login.....#类外每次都会调用

shopping cart..
PASSED
test_demo.py::TestDemo::test_case_1
login.....#类内只调用一次

test case 1
PASSED
test_demo.py::TestDemo::test_case_2 test case 2
PASSED

 

 yield

 

#fixture作用域
"""
@pytest.fixture
def fixture_name():
    setup操作
    yield 返回值
    teardown操作
"""
@pytest.fixture()   #避免以test开头
def login():
    print("\nlogin.....\n")
    token = '123'
    yield token #返回token值
    print("\nlogout.....\n")

def test_search():
    print("search")

def test_order(login):    #只需要在括号内填入加了fixture装饰器的方法,就可以实现在这个测试用例前调用login方法
    print("ordering")
    print(f"token:{login}") #这时候使用fixture的方法来代表yield返回的值token

yield也可以返回多个数值

yield token,name

标签:case,--,fixture,print,Pytest,test,login,def
来源: https://www.cnblogs.com/manshuoli/p/16267796.html