1、将数据库内自动化用例相关信息读取出来,生成可执行(测试)文件
通过之前的设计,我们实现了在平台上,增删改查用例、关键字、断言等操作。但最终数据库中用例的数据,要组合成可执行文件,来进行测试活动。
我们需要设计一个方法,输入project name, testcase title,定位唯一的testcase,然后通过testcase、TestCaseKeyword、assertion,这些是组成一个http请求测试的充分必要元素。然后把这个写到当前目录的新py文件,文件名就是project_name和title的拼接。构建一个可执行的python文件,执行python文件内的函数,我们就得到本次测试的结果。
回顾通常的python测试脚本,它一般有:
import requests import json def projectA_testcase1(): # step1: 有几步keyword,就有几个step注释 url = "example.com" headers = {'Content-Type': 'application/json'} data = { "name": "abc", "email": "abc@example.com" } response = requests.post(url, data=json.dumps(data), headers=headers) assert response.status_code == 200 assert response.message == "success"
而这个测试脚本需要的元素,刚好存储在我们的数据库内。我们读取数据库,传递project和testcase title,拿到需要的信息,然后生成测试文件。
import os import json import django from django.core.exceptions import ValidationError # 设置 Django 环境 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TestBench.settings') # 修改为您的 settings 模块路径 django.setup() from testplatform.models import Project, Testcase, TestCaseKeyword, Assertion def create_test_script(project_name, testcase_title): try: project = Project.objects.get(name=project_name) except Project.DoesNotExist: raise ValidationError(f"Project '{project_name}' not found") try: testcase = Testcase.objects.get(project=project, title=testcase_title) except Testcase.DoesNotExist: raise ValidationError(f"Testcase with title '{testcase_title}' not found in project '{project_name}'") testcase_keywords = TestCaseKeyword.objects.filter(test_case=testcase) steps = [] for tk in testcase_keywords: assertions = Assertion.objects.filter(testcase_keyword=tk).values('target_value', 'operator', 'compared_value') steps.append({ 'url': tk.url, 'method': tk.method, 'params': tk.params, 'headers': tk.headers, 'body_type': tk.body_type, 'body': tk.body, 'assertions': list(assertions) }) # 生成文件内容 script_content = f""" import requests import json def {project_name}_{testcase_title}(): """ for i, step in enumerate(steps, start=1): script_content += f""" # step{i}: 执行请求并验证断言 url = "{step['url']}" method = "{step['method']}" params = {step['params']} headers = {step['headers']} body = {step['body']} """ if step['body_type'] == "application/x-www-form-urlencoded": script_content += f""" response = requests.request(method, url, params=params, headers=headers, data=body) """ else: script_content += f""" response = requests.request(method, url, params=params, headers=headers, json=json.dumps(body)) """ for assertion in step['assertions']: target_value = assertion['target_value'] operator = assertion['operator'] compared_value = assertion['compared_value'] if operator == 'greater_than': script_content += f" assert {target_value} > {compared_value}\n" elif operator == 'less_than': script_content += f" assert {target_value} < {compared_value}\n" elif operator == 'equal': script_content += f" assert {target_value} == {compared_value}\n" elif operator == 'greater_than_or_equal': script_content += f" assert {target_value} >= {compared_value}\n" elif operator == 'less_than_or_equal': script_content += f" assert {target_value} <= {compared_value}\n" elif operator == 'equal_to': script_content += f" assert '{compared_value}' in {target_value}\n" elif operator == 'contains': script_content += f" assert '{compared_value}' in {target_value}\n" elif operator == 'in': script_content += f" assert {target_value} in '{compared_value}'\n" script_content += f""" if __name__ == "__main__": {project_name}_{testcase_title}() """ # 文件名 file_name = f"{project_name}_{testcase_title}.py" # 上一级目录的casefile文件夹路径 casefile_dir = os.path.join(os.path.dirname(os.getcwd()), 'casefile') # 确保casefile文件夹存在 os.makedirs(casefile_dir, exist_ok=True) # 完整的文件路径 file_path = os.path.join(casefile_dir, file_name) # 写入文件 with open(file_path, 'w', encoding='utf-8') as file: file.write(script_content) print(f"Test script written to {file_path}") if __name__ == '__main__': create_test_script(project_name="Project B", testcase_title="autocase0807_001")
1.本站内容仅供参考,不作为任何法律依据。用户在使用本站内容时,应自行判断其真实性、准确性和完整性,并承担相应风险。
2.本站部分内容来源于互联网,仅用于交流学习研究知识,若侵犯了您的合法权益,请及时邮件或站内私信与本站联系,我们将尽快予以处理。
3.本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
4.根据《计算机软件保护条例》第十七条规定“为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。”您需知晓本站所有内容资源均来源于网络,仅供用户交流学习与研究使用,版权归属原版权方所有,版权争议与本站无关,用户本人下载后不能用作商业或非法用途,需在24个小时之内从您的电脑中彻底删除上述内容,否则后果均由用户承担责任;如果您访问和下载此文件,表示您同意只将此文件用于参考、学习而非其他用途,否则一切后果请您自行承担,如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
5.本站是非经营性个人站点,所有软件信息均来自网络,所有资源仅供学习参考研究目的,并不贩卖软件,不存在任何商业目的及用途
暂无评论内容