pytest中fixture使用,控制使用域

pytest中使用fixture装饰器是来固定的工厂函数,fixture函数可以在测试执行前和执行后进行必要的准备和清理工作

1. fixture做为函数引用使用

 比如以下

import pytest
# fixture作为函数引用

@pytest.fixture()
def before():
    print("before执行啦。。。")

#@pytest.mark.usefixtures("before")    #在每个方法前运行
class Test_b():
    def setup(self):
        print("setup....")
    def test_a(self):
        print("test a")
    def test_b(self):
        print("test b")

 注释掉 pytest.mark.usefixtures("before")  执行效果

 开启 pytest.mark.usefixtures("before")  执行效果

每个运行方法前都会打印before函数的内容

1.1设置自动执行

在before中设置自动执行,不用在每个类中进行执行,

@pytest.fixture(autouse=True)
def before():
print("before执行啦。。。")
class Test_b():
def setup(self):
print("setup....")
def test_a(self):
print("test a")
def test_b(self):
print("test b")
执行效果是如上图

2.做为函数使用

@pytest.fixture
def  param_numbenr():
    return 5


def test_cacult(param_numbenr):
    print(param_numbenr)
    assert 5==param_numbenr

3.设置作用域为function

作用域:每个函数、类中的每个方法都运行一次

@pytest.fixture(scope="function",autouse=True)
def before():
    print("before执行啦。。。")


class Test_b():
    def setup(self):
        print("setup....")
    def test_a(self):
        print("test a")
    def test_b(self):
        print("test b")
class Test_c():
    def test_c(self):
        print("test c")

 4.设置作用域为class

一个类只运行一次

@pytest.fixture(scope="class",autouse=True)
def before():
    print("before执行啦。。。")

class Test_b():
    def setup(self):
        print("setup....")
    def test_a(self):
        print("test a")
    def test_b(self):
        print("test b")
class Test_c():
    def test_c(self):
        print("test c")

  

 5.设置作用域module

作用域:作用于整个模块,每个module的所有test只运行一次

@pytest.fixture(scope="module",autouse=True)
def before():
    print("before执行啦。。。")

class Test_b():
    def setup(self):
        print("setup....")
    def test_a(self):
        print("test a")
    def test_b(self):
        print("test b")
class Test_c():
    def test_c(self):
        print("test c")

  

6.设置作用域session

作用于整个session,每个session只运行一次,比如以下

@pytest.fixture(scope="session",autouse=True)
def before():
    print("before执行啦。。。")

class Test_b():
    def setup(self):
        print("setup....")
    def test_a(self):
        print("test a")
    def test_b(self):
        print("test b")
class Test_c():
    def test_c(self):
        print("test c")

 7.设置参数

@pytest.fixture(params=[1,2,3])  #固定用法
def  param_numbenr(request):  
    return request.param  #固定用法


def test_a(param_numbenr):
    print(param_numbenr)

def test_b (param_numbenr):
    print(param_numbenr)

  

原文地址:https://www.cnblogs.com/chongyou/p/12634658.html