Pytest系列(二)


一、Fixture固件 部分用例之前或之后执行,部分类之前或之后执行。模块或会话之前或之后的操 作。 Fixture完整的方法如下: @pytest.fixture(scope="作用域",params="数据驱动",autouse="是否自动执 行",ids=“参数别名”,name="Fixture别名") scope:可选值: function(函数,默认),class(类),module(模块) ,package/session(会 话) 1.基础应用:scope是function 1 import pytest 2 3 @pytest.fixture(scope="function") 4 def execute_sql(): 5 print("执行SQL语句") 6 yield "张三" 7 print("关闭数据库连接") 8 9 class TestApi: 10 11 def test_01_mashang(self): 12 print("土拨鼠1") 13 14 def test_02_jiaoyu(self,execute_sql): 15 print("土拨鼠2"+execute_sql) 在函数中的参数中通过execute_sql名称调用。 return:返回函数的结果,return之后的代码不会执行。yield:带有yield函数叫生成器。yield之后的代码会执行。 2.scope为class 1 import pytest 2 3 @pytest.fixture(scope="class") 4 def execute_sql(): 5 print("执行SQL语句") 6 yield "张三" 7 print("关闭数据库连接") 8 9 @pytest.mark.usefixtures("execute_sql") 10 class TestApi: 11 12 def test_01_mashang(self): 13 print("土拨鼠a1") 14 15 def test_02_jiaoyu(self): 16 print("土拨鼠b2") 17 18 class TestMashang: 19 def test_baili(self): 20 print("土拨鼠哈哈哈") 通过装饰器@pytest.mark.usefixtures("execute_sql")调用。 3.scope作用域是module或package/session,那么需要结合conftest.py使 用。 (1)conftest.py专门用于存放固件fixtue的配置文件,名称是固定的,不能更改。 (2)在conftest.py文件中的fixtue在调用时都不需要导包。 (3)conftest.py文件可以有多个,并且多个conftest.py文件的多个fixture之间没有冲突。 (4)模块级别和session模块一般都是自动执行。