【pytest】fixture笔记整理

【fixture是pytest框架的精髓】
通过装饰器的形式使用 @pytest.fixture()
fixture按模块化的方式实现,每个fixture可以互相调用。

fixture的作用主要有:

  • 设置前置函数,并在不同范围调用,如 @pytest.fixture(scope="class")
  • 参数化

1. fixture用作前置函数

import pytest

@pytest.fixture()
def before():
    a = "JChuan"
    print("--前置函数--\n")
    return a

def test_a(before):
    assert before == "JChuan"

if __name__ == '__main__':
    pytest.main(['-s','pytest_fixture.py'])
  • fixture不写return时默认返回None

可通过两种方式调用fixture,(例:fixture函数名为before)

  • 直接将fixture的函数名称当作变量名称传入, def test_a(before):
  • 同时调用多个fixture时,可传入多个fixture函数名, def test_a(before1,before2)
  • 使用装饰器 @pytest.mark.usefixtures('before')
  • 同时调用多个fixture时,可叠加使用。执行时先执行下面的,后执行上面的。如下先执行before1,后执行before2
@pytest.mark.usefixtures('before2')
@pytest.mark.usefixtures('before1')
def test_a():
    pass

区别: 使用装饰器调用fixture无法获取fixture返回值

import pytest

@pytest.fixture()
def before():
    a = "JChuan128"
    return a

def test_a(before):
    assert before == "JChuan128"

@pytest.mark.usefixtures("before")
def test_b():
    assert before == "JChuan128"

if __name__ == "__main__":
    pytest.main(["-s","pytest_fixture.py"])
@pytest.fixture(scope='function',params=None,autouse=False,ids=None,name=None)

scope:可声明使用范围(函数function、类class、模块module、整个项目session),默认为function

  • function 每个函数或方法都会调用fixture
  • class 一个类仅调用一次,且类外面的每个函数、方法都会调用
  • module 当前.py文件仅调用一次
  • session 可以跨.py文件调用,该类fixture函数一般单独写到项目根目录的 conftest.py文件中,其他文件可直接通过fixture函数名进行调用。
  • session作用范围只在该层级及以下目录

params:参数化时使用,传入列表

autouse:autouse=True时,每个函数、方法(假设scope=”function”)会自动调用fixture。autouse=Flase时,需在相应位置书写调用,根据书写的调用方式进行调用

2. fixture参数化

@pytest.fixture(params=[1,2,3,4])

import pytest

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

def test_a(data):
    print(f'\ntest_a的值是{data}')
    assert need_data != 4

if __name__ == '__main__':
    pytest.main(["-s","pytest_fixture_param.py"])
  • 以上request参数及request.param取值为固定形式,不能更改

运行结果

test_a的值是1
.
test_a的值是2
.
test_a的值是3
.
test_a的值是4
F

Original: https://blog.csdn.net/qq_37721291/article/details/115477894
Author: JChuan128
Title: 【pytest】fixture笔记整理

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/776192/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球