Installation 如何在pytest/unittest测试中共享在fixture中创建的会话对象,其作用域为会话
我们通过在python中实现unittest和pytest来创建测试。我们希望使用夹具在会话和测试级别进行设置和拆卸。 如何使用在设置会话夹具中创建的对象,以用于功能夹具的设置。示例我想创建一个驱动程序对象,如driver=webdriver.Chrome(),用于初始化浏览器并在测试方法和函数范围夹具中使用驱动程序对象 conftest.py 导入pytestInstallation 如何在pytest/unittest测试中共享在fixture中创建的会话对象,其作用域为会话,installation,pytest,fixtures,Installation,Pytest,Fixtures,我们通过在python中实现unittest和pytest来创建测试。我们希望使用夹具在会话和测试级别进行设置和拆卸。 如何使用在设置会话夹具中创建的对象,以用于功能夹具的设置。示例我想创建一个驱动程序对象,如driver=webdriver.Chrome(),用于初始化浏览器并在测试方法和函数范围夹具中使用驱动程序对象 conftest.py 导入pytest @pytest.fixture(scope="session") def setupsession(): print("Sta
@pytest.fixture(scope="session")
def setupsession():
print("Starting Session")
yield
print("Ending Session")
@pytest.fixture(scope="module")
def setupmodule(request):
print("starting module")
yield
print("Ending Module")
@pytest.fixture(scope="class")
def setupclass(request):
print("starting module")
yield
print("Ending Module")
Basetest.py
导入单元测试
class BaseTest(unittest.TestCase):
def setUp(self):
print("inside Base setup")
def tearDown(self):
print("inside base teardown")
test.py
导入pytest
从wav2.fixtures.base_test导入BaseTest
@pytest.mark.usefixtures("setupsession", "setupmodule")
class TestSample(BaseTest):
def test1(self):
print("calling inside test test1")
self.assertTrue(False)
def test2(self):
print("calling inside test tes`enter code here`t2")
夹具也可以使用其他夹具。这意味着您可以在模块装置内使用会话装置,也可以在类装置内使用模块装置,等等。也可以在其他设备中使用相同的范围设备。只有2个限制是不能向后导入装置(如在类级装置中使用函数级装置),并且不能存在循环依赖关系 请找到与所给出的示例相同的示例,该示例包含一个具有
scope=function
的附加夹具,并在另一个夹具中使用一个夹具
conftest.py
import pytest
import unittest
@pytest.fixture(scope="session")
def setupsession(request):
print("Starting Session")
yield "session_obj"
print("Ending Session")
@pytest.fixture(scope="module")
def setupmodule(request, setupsession):
print("starting module")
yield setupsession, "module_obj"
print("Ending Module")
@pytest.fixture(scope="class")
def setupclass(request, setupmodule):
print("starting class")
yield (*setupmodule, "class_obj")
print("Ending class")
@pytest.fixture(scope="function")
def setupmethod(request, setupclass):
print("starting method")
yield (*setupclass, "class_obj")
print("Ending method")
注意:由于我们已经创建了setupmethodfixture,因此不需要使用setUp
和tearDown
方法创建BaseTest。但是,这取决于测试用例的结构
test_file.py
@pytest.mark.usefixtures("setupmethod")
class TestSample(BaseTest):
def test1(self):
print("calling inside test test1")
self.assertTrue(False)
def test2(self):
print("calling inside test tes`enter code here`t2")
参考:如果我在会话装置中创建了一个对象/变量,并且如果我在测试或功能装置中更改了它的值,那么该对象/变量的值是否会保留在会话装置屈服语句Yes中。但这取决于会话装置产生的价值类型。如果是字符串或数字(不可变对象),则会产生相同的值。但是,如果它是一个列表或字典(将通过引用传递的内容),则会在值更改时产生问题。您可以在会话中引用i create a driver=webdriver.Chrome()selenium对象,并将此驱动程序对象添加到类的所有实例中
session=request.node for item in session.items cls=item.getparent(pytest.Class)setattr(cls.obj,“driver”,driver)
当我在一个测试中更改驱动程序实例时,其他测试中不会反映出相同的情况。这应该可以工作。只需确保任何两个测试用例之间没有依赖关系。每个测试用例在测试用例开始时再次打开所需的网页,并完成整个过程。当然。您可以将驱动程序设置为pytest.config
的属性并获取它。