Pytest----如何通过usefixtures为一个测试类调用fixture

DevOps技术社区 2022-08-29 15:54:17

一、通过usefixtures为一个测试类调用fixture

假如想为一个测试类中的每个测试函数都去调用一个fixture,则此时可以在类上通过使用@pytest.mark.usefixtures()来指定

test_demo.py代码如下:

import pytest

@pytest.fixture(scope="function")
def f1():
    print("in f1 fixture setup...")
    yield
    print("in f1 fixture teardown...")

@pytest.mark.usefixtures("f1")
class TestDemo(object):
    def test_01(self):
        print("in test_01...")
        assert 1==1

    def test_02(self):
        print("in test_02...")
        assert 1==1

    def test_03(self):
        print("in test_03...")
        assert 1==1

执行结果如下:

$ pytest -s
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: G:\src\blog\tests
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 3 items                                                                                                                                                       

test_demo.py in f1 fixture setup...
in test_01...
.in f1 fixture teardown...
in f1 fixture setup...
in test_02...
.in f1 fixture teardown...
in f1 fixture setup...
in test_03...
.in f1 fixture teardown...


========================================================================== 3 passed in 0.04s ===========================================================================
...全文
114 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

32

社区成员

发帖
与我相关
我的任务
社区描述
围绕测试开发、Devops、软件工程等方向,学习交流,共享技术新动态、新方向。求助工作中的问题,困惑等,互相交流,共同成长
软件工程测试工具devops 技术论坛(原bbs) 江苏省·南京市
社区管理员
  • redrose2100
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

1、社区话题和文章主要围绕DevOps技术栈

2、有广告需求请联系微信 Redrose2100

 

试试用AI创作助手写篇文章吧