1. 并行测试
- 使用
pytest - xdist
实现并行测试:
pytest - xdist
是pytest
的一个插件,允许在多个CPU核心上并行运行测试。
- 安装:
pip install pytest - xdist
- 示例代码:
import pytest
@pytest.mark.parametrize('input', range(10))
def test_parallel(input):
assert input < 10
- 运行方式:
pytest - n 4
,其中-n 4
表示使用4个进程并行运行测试,数字可根据机器CPU核心数调整。
2. 缓存机制
- 使用
functools.lru_cache
实现缓存:
- 在
unittest
或pytest
测试中,如果某些测试函数有重复计算的部分,可以使用functools.lru_cache
来缓存结果。
- 示例代码(假设是一个对API请求结果处理的函数,这里简单模拟):
import functools
@functools.lru_cache(maxsize=128)
def process_api_result(result):
# 假设这里是复杂的结果处理逻辑
return result * 2
def test_cache():
result1 = process_api_result(5)
result2 = process_api_result(5)
assert result1 == result2
- 这里
maxsize
参数指定缓存的最大条目数,设置为None
则缓存无限制大小。
3. 数据复用与批量请求
- 减少重复请求:
- 在测试RESTful API时,如果有多个测试用例依赖相同的数据,可以先获取一次数据并在多个测试用例中复用。
- 示例代码(以
pytest
为例,使用fixture
):
import pytest
import requests
@pytest.fixture(scope='module')
def api_data():
response = requests.get('http://example.com/api/data')
return response.json()
def test_api_data_length(api_data):
assert len(api_data) > 0
def test_api_data_type(api_data):
assert isinstance(api_data, list)
- 这里
scope='module'
表示这个fixture
在整个测试模块中只执行一次,避免了多次请求相同API。
4. 异步测试
- 使用
pytest - asyncio
实现异步测试:
- 如果API请求支持异步操作,可以使用异步测试来提高效率。
- 安装:
pip install pytest - asyncio
- 示例代码:
import asyncio
import pytest
async def async_api_call():
await asyncio.sleep(1)
return 42
@pytest.mark.asyncio
async def test_async_api():
result = await async_api_call()
assert result == 42
- 这样在异步操作(如异步API请求)时,测试可以在等待时执行其他任务,提高整体效率。