使用unittest框架接口测试中,yaml文件中上一个接口的返回值在下一个接口的data中作为参数,yaml文件中如何进行编写
5条回答 默认 最新
- 极客智能体-在线 2023-03-11 19:37关注
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
在yaml文件中,可以使用以下格式来设置参数关联的情况:test_case: - name: Test1 url: http://www.example.com/api/login method: post data: username: testuser password: Test@123 - name: Test2 url: http://www.example.com/api/userinfo method: get headers: Authorization: $Token data: user_id: $user_info.user_id
在上面的示例中,Test2接口的headers中使用了$Token参数,该参数是从上一个接口(Test1)的返回值中获取的。而Test2接口的data中,使用了$user_info.user_id参数,该参数是从上一个接口(Test1)返回值中的user_id字段获取的。
在使用unittest框架进行接口测试时,需要在测试类中编写函数来读取yaml文件中的测试用例、执行测试,并进行断言。下面是一个示例代码:
import unittest import requests import yaml class TestAPI(unittest.TestCase): def setUp(self): self.base_url = "http://www.example.com/api/" def test_api(self): with open("test_case.yaml", "r") as f: test_cases = yaml.safe_load(f) for test_case in test_cases: name = test_case["name"] url = self.base_url + test_case["url"] method = test_case["method"] headers = test_case.get("headers", {}) data = test_case.get("data", {}) # 处理参数关联 for key, value in data.items(): if isinstance(value, str) and value.startswith("$"): previous_key = value[1:] previous_resp = previous_resp if previous_resp else {} data[key] = eval("previous_resp" + previous_key) # 发送请求 resp = requests.request(method, url, headers=headers, json=data) resp_json = resp.json() previous_resp = resp_json # 将当前接口的返回值存储到previous_resp中,供下一个接口使用 # 断言 self.assertEqual(resp.status_code, 200) if __name__ == "__main__": unittest.main()
在上面的代码中,setUp函数用于设置测试用例的基础URL。test_api函数读取test_case.yaml文件中的测试用例,遍历每个接口,并对参数关联进行处理,然后发送请求并断言。previous_resp变量用于存储上一个接口的返回值,在下一个接口中使用。
如果我的回答解决了您的问题,请采纳!解决 无用评论 打赏 举报