Background: The Java project uses the swagger management interface.As the demand development interface also increases, it is very time-consuming and inefficient to find the new interface from the swagger interface.
Applicability: java project and applicable swagger management interface
Script analysis:
- Use the requests package to call swagger's api-docs interface ( http: // localhost / api / v1 / api-docs ), this interface will return the module name, url, interface name, parameter name, parameter description, case of all interfaces in swagger Column value and other related information
- Parse the return value of the above interface into an automated test case and write it into the specified file.Before writing, it will determine whether the URL of this interface already exists in the file.If it exists, it means that this interface has been automated and will not be written repeatedly.
Instructions:
1. Open the script and modify the default values of the filename and url parameters to the file name of the corresponding robot project and the url of the api-docs interface of swagger, and run this file directly in the Python editor.
2. In the cmd window, enter the script and robot project directory and execute the command: python AutoCreateRobotCase.py robot.txt http: // localhost / api / v1 / api-docs (robot.txt and the following url are modified to the value of the corresponding project )
After the execution, the new use case will be behind the keyword in the robot project file, so you need to set the use case to the value of the corresponding parameter and move it to the keyword
Examples of the automation generated after execution are as follows:
# ! / usr / bin / env python "" " Analyze the return value of the swagger interface to automatically generate interface automation use cases Write new use cases to the end of the file, and existing use cases are not rewritten to " "" import requests import json import sys def auto_create_robotcase (filename = ' robot.txt ' , url = ' http://test-customer-api.chuxingyouhui.com/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 & lt = requests.get (URL) Print (r.text) # returns the text format is converted into json And take the value of the paths section, because this section contains all the required information 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 ( " Parameter name: " , param_name, " Parameters location: " , param_position, " Required NO: " , param_required) # Some parameters are not Description field, make a judgment here, sometimes take a description, no empty value is assigned 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])