自动生成robot自动化测试用例
背景:java项目使用swagger管理接口,随着需求的开发接口也有增加,要从swagger界面中去查找出新增的接口是件很费时,效率很低的事情.
适用情况: java项目且适用swagger管理接口
脚本解析:
- 使用requests包调用swagger的api-docs接口(http://localhost/api/v1/api-docs),此接口会返回swagger中所有接口的模块名,url,接口名字,参数名,参数描述,案列值等相关信息
- 解析上面接口的返回值组装成自动化测试用例并写入指定文件中,且写入前会判断此接口的url是否在文件中已存在,存在则表示此接口已经实现自动化,不会重复写入.
使用方法:
一. 打开脚本修改filename和url参数的默认值为对应项目robot工程的文件名和swagger的api-docs接口的url后直接在Python编辑器中运行此文件.
二. 在cmd窗口中进入到脚本和robot工程目录执行命令: python AutoCreateRobotCase.py robot.txt http://localhost/api/v1/api-docs (robot.txt和后面的url修改为对应项目的值)
执行完后新增的用例会在robot工程文件中关键字后面,所以需要将用例设置好对应参数的值后移动到关键字上面
执行后生成的自动化用例如下:
#!/usr/bin/env python """解析swagger接口返回值自动生成接口自动化用例 将新增的用例写入到文件末尾,已存在的用例则不重新写入 """ import requests import json import sys def auto_create_robotcase(filename='robot.txt', url='http://localhost/v2/api-docs'): try: f = open(filename, 'a+', encoding='utf-8') f.seek(0, 0) content = f.read() f.write('\n') f.write('\n') f.write('\n') r = requests.get(url) print(r.text) # 将返回的文本转换成json格式,并取paths部分的值,因为这个部分包含了所有需要的信息 api_docs = json.loads(r.text) paths = api_docs['paths'] definitions = api_docs['definitions'] k = 1 print(len(paths.items())) for i in paths.items(): print(i) interface_api = i[0] if interface_api in content: continue interface_type = list(i[1].keys())[0] mode_name = dict(list(i[1].values())[0])['tags'][0] interface_name = dict(list(i[1].values())[0])['summary'] print(str(mode_name) + "模块下第" + str(k) + "个接口为:" + str(interface_name) + " 类型为:" + str( interface_type) + " URI:" + str(interface_api)) head = [] data = [] if list(i[1].values())[0].__contains__('parameters'): params = dict(list(i[1].values())[0])['parameters'] for param in params: param_name = param['name'] param_position = param['in'] param_required = param['required'] print("参数名:", param_name, "参数位置:", param_position, "必填否:", param_required) # 有些参数没有描述字段,这里做个判断,有的时候取描述,没有赋空值 if param.get('description'): param_description = param['description'] else: param_description = '' if param_required: if param_position == 'header': pa = param_name + "=" + param_description head.append(pa) elif param_position == 'query': pa = param_name + "=" + param_description data.append(pa) elif param_position == 'body': param_schema = param['schema'] if param_schema.get('items'): define_name = param_schema['items']['$ref'].split('/')[-1] else: define_name = param_schema['$ref'].split('/')[-1] data = definitions[define_name]['properties'] case_name = mode_name + "-" + interface_name f.write(case_name + '\n') head_s = "" for i in head: head_s = head_s + " " + str(i) if head_s: create_head = ' ${headers} Create Dictionary Content-Type=${Content-Type} Accept=${Accept}' + head_s else: create_head = ' ${headers} Create Dictionary Content-Type=${Content-Type} Accept=${Accept}' f.write(create_head + '\n') create_api = ' Create Session api ${host} ${headers}' f.write(create_api + '\n') if str(data).startswith("{"): create_data = ' ${data} Set Variable ' + str(data) else: data_s = '' for i in data: data_s = data_s + ' ' + str(i) create_data = ' ${data} Create Dictionary ' + data_s create_params = ' ${params} Create Dictionary ' + data_s create_get_request = ' ${result} Get Request api ' + interface_api + ' params=${params}' create_get_request_noparams = ' ${result} Get Request api ' + interface_api create_post_request = ' ${result} Post Request api ' + interface_api + ' data=${data}' create_post_request_noparams = ' ${result} Post Request api ' + interface_api if interface_type == 'get': if data: f.write(create_params + '\n') f.write(create_get_request + '\n') else: f.write(create_get_request_noparams + '\n') else: if data: f.write(create_data + '\n') f.write(create_post_request + '\n') else: f.write(create_post_request_noparams + '\n') create_response = ' ${response} Set Variable ${result.content}' create_response_to_json = ' ${response} To Json ${response}' create_assert_code = ' should be equal as integers ${response["code"]} 200' create_assert_msg = ' should be equal ${response["msg"]} 操作成功' f.write(create_response + '\n') f.write(create_response_to_json + '\n') f.write(create_assert_code + '\n') f.write(create_assert_msg + '\n') f.write('\n') k = k + 1 f.close() except Exception as e: raise e if __name__ == "__main__": if len(sys.argv) == 1: auto_create_robotcase() else: auto_create_robotcase(sys.argv[1], sys.argv[2])