对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作为参数一个一个传到每个测试方法中

原文地址:https://www.cnblogs.com/my_captain/p/12713415.html