对pytest.mark.usefixtures的理解

在之前的学习中,代码中一直是传入了fixture函数common_driver,又使用了pytest.mark.usefixtures:

@pytest.mark.usefixtures("common_driver") def test_welcome(self, common_driver): WelcomePage(common_driver).swipe_screen() WelcomePage(common_driver).get_spe_screenshot() image_text = WelcomePage(common_driver).identify_screenshot() assert image_text == "立即体验"

今天看pytest官方文档,发现可以不这么用,主要分为两种情况

1. 当不需要使用fixture中的返回时,直接使用pytest.mark.usefixtures(funcname)。举个例子:测试中需要创建空目录,把空目录作为当前目录进行操作,但不用关心具体的空目录,这时可以使用tempfile和pytest fixtures来实现:

conftest.py代码

import os import shutil import tempfile import pytest @pytest.fixture def cleandir(): old_cwd = os.getcwd() #创建临时目录 newpath = tempfile.mkdtemp() #将当前路径切换到临时目录 os.chdir(newpath) yield #将当前路径切换到原来的目录 os.chdir(old_cwd) #递归的删除临时目录 shutil.rmtree(newpath)

test_setenv.py

import os import pytest @pytest.mark.usefixtures("cleandir") class TestDirectoryInit: def test_cwd_starts_empty(self): #断言临时目录下的文件是不是空 assert os.listdir(os.getcwd()) == [] #新建一个file文件 with open("myfile", "w") as f: f.write("hello") def test_cwd_again_starts_empty(self): #由于pytest.mark.usefixtures作用在类上,表示这两个测试方法都是要了cleandir fixture,所以会创建两次新的临时目录,这个方法中,临时目录没有新建文件,所以为空。另外,pytest的执行顺序与a-zA-Z0-9无关 assert os.listdir(os.getcwd()) == []

2. 如果需要fixture中的返回值,在测试方法中直接传入被fixture装饰的方法名就行,例如:common_driver

def test_welcome(self, common_driver): WelcomePage(common_driver).swipe_screen() WelcomePage(common_driver).get_spe_screenshot() image_text = WelcomePage(common_driver).identify_screenshot() assert image_text == "立即体验"

 

=========================4月18日更新======================

 

如果没有返回值,fixture装饰整个类时,只能使用@pytest.mark.usefixtures,比如这样的:

conftest.py

#conftest.py import pytest @pytest.fixture def back_url(): print("环境准备") print("环境清理")

test_something.py

import pytest @pytest.mark.usefixtures("back_url") class TestSomething(): def test_1(self): print("test_1") def test_2(self): print("test_2")

如果有返回值,fixture装饰整个类时,不能使用class TestSomething(back_url),因为这样就被当作继承。只能将back_url作为参数一个一个传到每个测试方法中

 


__EOF__

本文作者cnhkzyy
本文链接https://www.cnblogs.com/my_captain/p/12713415.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   cnhkzyy  阅读(2988)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示