封装公用的测试用例前置和后置操作
在 Pytest 中,我们可以使用 fixture 来封装测试用例的前置和后置操作。fixture 是一个带有装饰器@pytest.fixture 的函数,它可以在测试用例执行前后执行一些代码,例如登录、退出登录、清理测试数据等
import pytest
@pytest.fixture(scope="module")
def login():
# 执行登录操作
yield
# 执行退出操作
@pytest.fixture(scope="function")
def clear_data():
# 执行清除测试数据操作
pass
def test_case1(login, clear_data):
# 执行测试用例1,需要登录和清除测试数据的支持
def test_case2(login, clear_data):
# 执行测试用例2,需要登录和清除测试数据的支持
@pytest.fixture(scope="module")
def logout():
# 执行退出操作
pass
def test_case3(logout):
# 执行测试用例3,只需要退出操作的支持
封装公用的测试数据
例如测试环境的配置、测试数据的读取等,可以使用yaml 或者 json 等配置文件进行管理。
#使用pytest和json文件封装测试环境配置和测试数据读取
import pytest
import os
import json
@pytest.fixture(scope='session')
def test_config():
# 读取测试环境配置
config_file = os.path.join(os.path.dirname(__file__), 'config.json')
with open(config_file, 'r') as f:
config = json.load(f)
return config
@pytest.fixture(scope='session')
def test_data():
# 读取测试数据
data_file = os.path.join(os.path.dirname(__file__), 'test_data.json')
with open(data_file, 'r') as f:
data = json.load(f)
return data
如上,我们将配置信息和测试数据分别存储在了config.json和test_data.json文件中。在fixture函数中,我们通过读取这两个文件来获取配置信息和测试数据。需要注意的是,我们需要使用os模块来获取json文件的路径。
封装公用的测试方法
例如发送 HTTP 请求、解析响应结果、断言等,可以使用 requests、jsonpath 等库进行实现。
#封装发送 HTTP 请求、解析响应结果、断言
import requests
def send_request(method, url, data=None, headers=No