欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

pytest use 1:setup_class 可以使用(类名)向测试用例传递参数

最编程 2024-05-20 11:45:31
...

在pytest框架中,有一个特殊的函数可以实现在一个类的所有命名规范的用例执行之前执行,一般用来执行一次性的操作,比如ui测试时,需要测试搜索功能,他的一次性操作就是打开浏览器,输入网址,跳转到搜索页面

使用selenium完成这个一次性操作,并且要保证剩下的每个测试用例都能接着这个一次性操作运行,这里就会有一个问题:setup_class是一个类函数,接受的参数是一个类对象,而每个测试用例是一个实例函数,接受实例对象,想要保证每个测试用例都能接着这个一次性操作运行,就需要setup_class中使用的实例对象和每一个测试用例中使用的实例对象相同.

这样的代码,用例方法便可以接着setup_class函数运行

import pytest


class Test_p():

    @classmethod
    def setup_class(cls):
        cls.creat(Test_p)

    def creat(self):
        self.q = 9

    def test_o(self):
        print(self.q)


if __name__ == '__main__':
    pytest.main(['-s', 'Test556.py'])

以上只是为了在setup_class中执行一次性操作,这种需求有另一种实现方法:使用fixtrue和conftest.py文件

# conftest.py
import pytest
from selenium import webdriver

driver = None


@pytest.fixture(scope='session', autouse=True)
def bianliang():
    global driver

    if driver is None:
        driver = webdriver.Chrome()  

    return driver
# Testconftest.py
import pytest


class Test_9():

    def test_login_failed(self, bianliang):
        bianliang.get('http://www.51testing.com/html/97/category-catid-97.html')


if __name__ == '__main__':
    pytest.main(['-s', 'Testconftest.py'])

此时在pytest运行用例时,bianliang函数返回的driver在用例中都可以使用,使用driver时需要传入参数bianliang而不是driver

原文地址:https://www.cnblogs.com/lqs244/p/14349974.html