自动化测试平台设计与实现(三、自动化用例对象成为可实验文件,用例实验机 ...

打印 上一主题 下一主题

主题 867|帖子 867|积分 2601

1、将数据库内自动化用例相关信息读取出来,天生可实验(测试)文件
通过之前的设计,我们实现了在平台上,增删改查用例、关键字、断言等操作。但最终数据库中用例的数据,要组合成可实验文件,来进行测试活动。
我们需要设计一个方法,输入project name, testcase title,定位唯一的testcase,然后通过testcase、TestCaseKeyword、assertion,这些是构成一个http请求测试的充分必要元素。然后把这个写到当前目次的新py文件,文件名就是project_name和title的拼接。构建一个可实验的python文件,实验python文件内的函数,我们就得到本次测试的结果。
回顾通常的python测试脚本,它一样平常有:
  1. import requests
  2. import json
  3. def projectA_testcase1():
  4.     # step1: 有几步keyword,就有几个step注释
  5.     url = "example.com"
  6.     headers = {'Content-Type': 'application/json'}
  7.     data = {
  8.         "name": "abc",
  9.         "email": "abc@example.com"
  10.     }
  11.     response = requests.post(url, data=json.dumps(data), headers=headers)
  12.     assert response.status_code == 200
  13.     assert response.message == "success"
复制代码
而这个测试脚本需要的元素,刚好存储在我们的数据库内。我们读取数据库,传递project和testcase title,拿到需要的信息,然后天生测试文件。
[code]import osimport jsonimport djangofrom django.core.exceptions import ValidationError# 设置 Django 环境os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TestBench.settings')  # 修改为您的 settings 模块路径django.setup()from testplatform.models import Project, Testcase, TestCaseKeyword, Assertiondef create_test_script(project_name, testcase_title):    try:        project = Project.objects.get(name=project_name)    except Project.DoesNotExist:        raise ValidationError(f"roject '{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 requestsimport jsondef {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}
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用户国营

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表