Detailed explanation of pytest-fixture

fixture

Advantage:

  • The naming of pytest fixtures is no longer limited to the setup and teardown naming methods
  • All fixtures can be in a conftest.py file for all test cases

Fixture creation and use method
fixture creation

#1. @pytest.fixture()
#2. 编写一个普通函数
@pytest.fixture()
def login():
	print("执行登录")

fixture use

#在需要使用fixture的测试用例中,当做参数传入即可
def test_shopping(login):
	print("测试购物")

Use a fixture to implement setup and teardown
syntax: the yield keyword

@pytest.fixture()
def login():
	print("打开浏览器,登录成功")
	yield     #用例执行成功后执行,相当于teardown
	print("关闭浏览器")

def test(login):     #相当于setup在test用例前执行
	print("执行")

Yield encounters an exception
1. It will not affect the execution of subsequent use cases.
2. When the use case is executed, the code behind yield will be executed, but it cannot return

The implementation function of addfinalizer is the same as yield and can return parameters. Pass to the following use cases, examples:

import pytest
#创建fixture
def open(request):
	driver=webdriver.chrome()
	print("打开浏览器")
				def end():
					driver.quit()
	request.addfinalizer(end)  #终结函数 --作用和yield一样
	return driver

def test.baidu(open):
	open.get("http://www.baidu.com")
	title=open.title
	print("标题",title)
_fixture other methods use

1.fixture return value
2.fixture parameterization

@pytest.fixture(params:[1,2,3])
def need_data(request):          #传入参数params
	return request.param          #取列表中单个值

class Test_ABC:
	def test_a(self,need_data):
		print("---------------------test_a")
		assert need_data !=3   #断言need_data不等于3

Use decorators to reference fixtures

import pytest
@pytest.fixture()   #fixture标记的函数可以应用于测试类外部
def before():
	print("------------before")
@pytest.mark.usefixture("before")
class Test_ABC:
	def setup(self):
		print("---------setup")
	def test_a(self):
		print("-------test_a")
		assert 1

Fixture(scope="function",params=None,autouse=False,ids=None,name=None)
Advantages: (Compared to setup and teardown, fixture should have the following advantages)

  • The naming method is flexible, not limited to the naming of setup and teardown
  • Data sharing can be realized in the conftest.py configuration, and some configurations can be found automatically without import
  • scope = "module" can realize multiple .py cross-file sharing front, each .py file is called once
  • scope = "session" can achieve multiple .py cross files and use one session to complete multiple use cases

Guess you like

Origin blog.csdn.net/qq_36875803/article/details/109232197