基于 HttpRunner4.0 的接口自动化测试实践 · 测试之家
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
# 配置数据库连接信息
config = (
Config("database test")
.variables(
**{
"db_host": "127.0.0.1",
"db_port": 3306,
"db_user": "root",
"db_password": "password",
"db_name": "test_db",
}
)
.export(*["db_connection"]) # 可以在下面的步骤中使用这个连接
)
# 编写SQL查询并验证返回的数据
test_step = Step(
RunRequest("query data from database")
.get("http://${db_host}:${db_port}/api/query") # 假设有这样的API用于执行数据库查询
.with_headers(**{"User": "${db_user}", "Password": "${db_password}"})
.with_json(
**{
"sql": "SELECT * FROM ${db_name} WHERE id = 1",
# 其他需要的参数
}
)
.validate(
**{
"json": {
"code": 200,
"message": "success",
"data": {
"id": 1,
# 其他期望的字段和值
},
}
}
)
)
testcase = test_step
# 运行测试
test_runner = HttpRunner()
test_runner.test_start(config)
test_runner.run_test(testcase)
test_runner.test_stop()