自动化测试实战:模拟HTTP调用与测试场景准备
1. 使用HTTP调用模拟进行测试
在测试过程中,模拟操作是常见的,特别是对于外部HTTP调用这类依赖项。进行外部HTTP调用成本高、速度慢,而且网络连接失败时结果不可靠。虽然可以使用Python标准库中的 mock
库来模拟外部调用,但有些特定的测试模块能更好地模拟HTTP调用和响应。
1.1 准备工作
我们将使用 pytest
模块,以及 requests
和 responses
库。按以下步骤安装这些模块并添加到 requirements.txt
文件中:
$ echo "pytest==5.4.1" >> requirements.txt
$ echo "requests==2.23.0" >> requirements.txt
$ echo "responses==0.10.12" >> requirements.txt
$ pip install -r requirements.txt
从GitHub仓库下载测试文件 tests/test_requests.py
和代码文件 code/code_requests.py
,文件结构如下:
├── code
│ ├── __init__.py
│ └── code_reque