Pytest进阶 — 数据共享/fixture(Advanced pytest — data sharing / fixture)-其他
Pytest进阶 — 数据共享/fixture(Advanced pytest — data sharing / fixture)
使用fixture和conftest文件可以让数据共享
Fixture 在自动化中的应用 – 数据共享
- 场景:
你与其他测试程师合作起开发时,公共的模块要在不同件中,要在家都访问到的地。
- 解决:
使 conftest.py 这个件进数据共享,并且他可以放在不同位置起着不同的范围共享作。
- 前提:
conftest 件名是不能换的
放在项下是全局的数据共享的地 - conftest 件名是不能换的
- 放在项下是全局的数据共享的地
- 执:
系统执到参数 login 时先从本模块中查找是否有这个名字的变量什么的,
之后在 conftest.py 中找是否有。 - 系统执到参数 login 时先从本模块中查找是否有这个名字的变量什么的,
- 之后在 conftest.py 中找是否有。
- 步骤:
将登陆模块带@pytest.fixture 写在 conftest.py
举例:
conftest.py
import pytest
@pytest.fixture(scope="session") #session级别在执行pytest所有用例之前执行一次,即整个项目只执行一次
def login():
print("\nlogin.....\n")
token = 123
yield token #返回token值
print(f"\nlogout.....\n")
test_demo.py
conftest定义好后,可以在用例中使用,使用方法和fixture相同
import pytest
def test_search():
print("search")
def test_order(login): #在用例加上fixture的方法login,即可在测试前调用该方法。并不需要import操作
print("ordering")
print(f"token:{login}") #这时候使用fixture的方法来代表yield返回的值token
def test_cart(login):
print("shopping cart..")
class TestDemo:
def test_case_1(self,login):
print("test case 1")
def test_case_2(self,login):
print("test case 2")
Data can be shared using fixture and confitest files
Application of fixture in Automation – data sharing
- Scenario:
When you work with other test engineers to develop, the public modules should be in different parts and accessible at home.
- solve:
Make conf test Py is used for data sharing, and it can be placed in different locations to play a different role in sharing.
- Premise:
The name of the conftest piece cannot be changed
Placed under the item is the place for global data sharing - conftest 件名是不能换的
- Placed under the item is the place for global data sharing
- Executive:
When the system executes the parameter login, first find out whether there is a variable with this name from this module,
Then in conf test Py. - When the system executes the parameter login, first find out whether there is a variable with this name from this module,
- Then in conf test Py.
- Steps:
Bring the login module to @ pytest Fixture is written in confitest py
give an example:
conftest.py
import pytest
@pytest.fixture(scope="session") #session级别在执行pytest所有用例之前执行一次,即整个项目只执行一次
def login():
print("\nlogin.....\n")
token = 123
yield token #返回token值
print(f"\nlogout.....\n")
test_demo.py
After confist is defined, it can be used in use cases in the same way as fixture
import pytest
def test_search():
print("search")
def test_order(login): #在用例加上fixture的方法login,即可在测试前调用该方法。并不需要import操作
print("ordering")
print(f"token:{login}") #这时候使用fixture的方法来代表yield返回的值token
def test_cart(login):
print("shopping cart..")
class TestDemo:
def test_case_1(self,login):
print("test case 1")
def test_case_2(self,login):
print("test case 2")