Pytest自动化测试框架学习(三)
程序员文章站
2022-07-12 14:50:17
...
在自动化测试中我们经常会针对某些测试方法编写前置测试数据,当测试方法执行完毕后再清理这些测试数据。之前我们接触的unittest框架中,使用setUp、tearDown方法来解决前置数据、后置数据销毁的问题。pytest为我们提供了更加强大灵活的fixtrue来完成该实现,本质上还是函数和装饰器的使用。
fixtrue基础使用
- 该方法可任意命名没有setUp、tearDown的命名限制
- 方法默认返回值是None,可配置返回值供测试方法使用
- 该方法有执行范围,默认是function级别
下面是fixtrue的基础示例。
前置用例创建测试数据
import pytest
@pytest.fixture()
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
return 1
def test_assert_result(get_test_data):
print("第二步:执行测试方法")
assert 1 == get_test_data
def test_assert_result2(get_test_data):
print("第二步:执行测试方法")
assert 1 == get_test_data
执行结果:
从上面的执行结果我们可以看到,每个测试方法执行前都会去先执行我们配置的前置方法来获取数据,这就是fixture最基本的作用。
配置多个fixture
import pytest
@pytest.fixture()
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
return 1
@pytest.fixture()
def get_test_data2():
print("第二个fixture配置:执行测试方法之前,会先调用我")
return 2
def test_assert_result(get_test_data, get_test_data2):
print("第二步:执行测试方法")
assert 1 == get_test_data
assert 2 == get_test_data2
def test_assert_result2(get_test_data):
print("第二步:执行测试方法")
assert 1 == get_test_data
执行结果:
我们为testassertresult方法配置了2个前置方法,执行结果中可以看到成功接受了2个前置方法的返回结果。
后置数据销毁-yield
import pytest
@pytest.fixture()
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
yield 1
print("最后一步:执行数据清理操作")
def test_assert_result(get_test_data):
print("第二步:执行测试方法")
assert 1 == get_test_data
def test_assert_result2(get_test_data):
print("第二步:执行测试方法")
assert 1 == get_test_data
执行结果:
从执行结果上看每个方法都执行了最后一步的操作,在这里唯一需要注意的是返回值需要放在yield之后。
fixture作用域
通过scope参数我们可以指定作用域,前面我们也提到了默认情况下是function。
- function 指每个测试函数都会去执行
- class 指测试类只执行一次
- module 指执行整个module文件时执行一次
- session 指一次测试只执行一次
import pytest
@pytest.fixture(scope="function")
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
yield 1
print("最后一步:执行数据清理操作")
@pytest.fixture(scope="class")
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
yield 1
print("最后一步:执行数据清理操作")
@pytest.fixture(scope="module")
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
yield 1
print("最后一步:执行数据清理操作")
@pytest.fixture(scope="session")
def get_test_data():
print("第一步:执行测试方法之前,会先调用我")
yield 1
print("最后一步:执行数据清理操作")
以上是fixture最基本的使用,大家可以在实际工作中实践应用。fixture还是很强大灵活的,那个测试方法需要就传递给那个方法,不需要的就不传递。fixture标记的方法也是支持参数传递的,赶快实践下吧!
上一篇: fiddler抓取不到python-request的包?InsecureRequestWarning: Unverified HTTPS request is being made to host '
推荐阅读
-
小白学 Python 爬虫:自动化测试框架 Selenium 从入门到实战
-
移动端自动化测试框架搭建
-
Python Selenium框架设计使自动化测试报告的生成
-
学习ASP.NET MVC5框架揭秘笔记-ASP.NET MVC路由(三)
-
python 配置web自动化测试框架 selenium
-
Python+Selenium+Unittest+Ddt+HTMLReport分布式数据驱动自动化测试框架结构
-
Spring 框架学习第三节:核心理念之一 —— IoC(控制反转)
-
从零写一个具有IOC-AOP-MVC功能的框架---学习笔记---08.框架的AOP功能和IOC功能测试
-
Appium python自动化测试系列教程之关于Android知识的讲解(三)
-
Python http接口自动化测试框架实现方法示例