1、为什么要写代码实现接口自动化

大家知道很多接口测试工具可以实现对接口的测试,如postman、jmeter、fiddler等等,而且使用方便,那么为什么还要写代码实现接口自动化呢? Although the tool is convenient, there are also shortcomings:

test data is not controllable.

interface test is essentially testing data, calling interface and input some data, and then, interface returns some data. The validation interface returns the correctness of the data. You have to manually insert test data into the database before you run the test case with a tool. In this way, our interface test is not so "automated".

to test the encryption interface this is a flawed interface test tools, such as the development of the interface in front of us with the tools of test no problem, but when the need for interface encryption / decryption of interface parameters, such as MD5, Base64, AES and other common encryption method. The eleventh chapter of this book will introduce the encryption interface. Or the parameters of the interface need to use a timestamp, which is difficult to simulate by the tool.

expansion capability is insufficient,

. When we enjoy the convenience brought by tools, we are often limited by the limitations of tools. For example, I want to generate the test results in the HMTL format test report, and I want to send the test report to the specified mailbox. I want to do the timing task for the interface test. I want to make continuous integration of interface tests. These requirements are hard to be realized by tools.

2,

interface design interface test automation test call process can be summarized below, increased

general interface tool testing process:

1, interface tools call system under test the interface (parameters username= "Zhangsan").

2, the system interface queries data from the formal database based on the username= "Zhangsan".

3, assemble the query result into a certain format of data, and return it to the caller.

4, manually or through the tool's assertion function to check the correctness of the interface test.

interface automation test project, in order to enable interface test to control data, the testing process is as follows:

1 and interface test project first insert test data (Zhangsan personal information) into test database .

2, call the measured system interface (pass the username= "Zhangsan").

3, the system interface is queried in the test database and obtained Zhangsan personal information according to the username= "Zhangsan").

4, assemble the query result into a certain format of data, and return it to the caller.

5, through the unit test framework, asserts the data returned by the interface (the personal information of the Zhangsan) and generates a test report.

proposes to use an independent test database in order to make the data of the formal database not contaminated.

2, requests library

Requests uses urllib3, so it inherits all its characteristics. Requests supports HTTP connection maintenance and connection pool , supports using cookie to maintain session , supports file upload , and supports to automatically determine the encoding of response content. request library for more details can see my previous article:

interface test based

http://www.jb51.net/article/122571.htm? Pc

http://www.jb51.net/article/108168.htm

"_blank"

< strong>

interface test code example below to sign in before the user python+django system development as the background, display interface test code. Why does

develop interfaces? Who is the main interface for the development of the interface? The separation of

front-end and back end is a developing trend in the development of Web applications in recent years. This mode will bring the following advantages:

1 and backend can not necessarily be proficient in front-end technology (HTML/JavaScript/CSS), only focus on data processing, and provide API interface to external.

2, the front-end professionalism is getting higher and higher, through the API interface to get data, so that focus on the design of the page.

3, front and back separation increase the application scope of the interface, the developed interface can be applied to the Web page, and can also be applied to the mobile APP.

in this development mode, interface testing work will become particularly important.

development and implementation of the interface code example:

 def add_event # add conference interface (request): Eid = request.POST.get ('eid', ID') # conference name = request.POST.get ('name'') # conference title limit ('limit'= request.POST.get, status = #') limit the number of request.POST.get ('status'') # address = request.POST.get ('address'') # address start_time = request.POST.get ('start_time', if, Eid') # conference time ==''or name' or limit or '= = = = = = = =' 'start_time' 'or address: return JsonResponse ({'status': 10021,'message':'parameter error'} result) = Event.objects.filter (id=eid) if result: return JsonResponse ({'status': 10022,'message':'event ID already exists '}) result = Event.objects.filter (name=name) if result: return JsonResponse ({'status': 10023,'message':'event name already exists'}) if status = = ': status = 1 try: Event.objects.create (id=eid, name=name, limit=limit, address=, address, status=int (status), start_time=start_time) except ValidationError: error format error. It must ='start_time be in YYYY-MM-DD HH:MM:SS format.' return JsonResponse ({'status': 10024,'message': error} JsonResponse (return) {'status': 200,'message':'add event success'} 

POST) by request receiving parameters: ID conference, conference title, number, address and time.

first determines that the fields such as Eid, name, limit, address, start_time can not be empty, otherwise JsonResponse () returns the corresponding state code and prompt. JsonResponse () is a very useful method that can directly convert the dictionary into the Json format and return to the client.

next determines whether the press conference ID exists, and whether the conference name (name) exists. If it exists, it will return the corresponding status code and prompt information.

then then determines whether the state of the press conference is empty, and if it is empty, the state is set to 1 (True).

the data to be inserted into the Event table, in the inserting process if the date format error, ValidationError exception will be thrown, and receiving the abnormal return status and the corresponding prompt, otherwise, successful insertion, return a status code 200 and "add event success" message. The realization of def get_event_list interface

 # conference query (request): Eid = request.GET.get ("Eid", "Id") # conference name = request.GET.get ("name", "if Eid") # conference name 'and name': = = = = return JsonResponse ({'status': 10021,'message':'parameter error'} if) Eid! = ': event = {} = Event.objects.get (id=eid) try: result except ObjectDoesNotExist: return JsonResponse ({'status': 10022,'message':'query result is empty'}) else: event['eid'] = result.id event['name'] = result.name event['limit'] = result.limit event['status'] = result.status event['address'] = result.address event['start_time'] = result.start_time return JsonResponse ({'status': 200, 'message':'success','data': event}) if name! =': datas = results [] = Event.objects.filter (name__contains=name) if results: for R in results: event event['eid'] = r.id event['name'] = {} = r.name event['limit'] = r.limit event['status'] = r.status event['address'] = r.address event['start_time'] = r.start_time datas.append (event) return JsonResponse ({'status': 200,'message':'success''data', else:: datas}) return JsonResponse ({'status': 10022,'message':'query result is empty'}) 

by GET ID and name parameter request receiving conference. The two parameters are optional. First, it is judged that when the two parameters are empty at the same time, the interface returns the state code 10021, and the parameter is wrong.

if Id conference is not empty, first through the ID query, only because of ID, so the results will only have a query result to key:value on the way to the definition of the event stored in the dictionary, and the data dictionary as the return value corresponding to the returned dictionary data.

name query fuzzy query, query data may be more than one, the returned data is more complicated; firstly, each data query in a dictionary in event, then each one dictionary again in the array datas, and finally the entire array as the return value corresponding to the data dictionary in return.

interface test code example

 # conference import requests query interface test code url = "http://127.0.0.1:8000/api/get_event_list/" r = requests.get (URL, params={'eid':'1'}) = r.json (result) print (result) assert result['status'] 200 assert result['message'] = = = = = = "assert" success "result['data']['name'] XX product launch assert result['data']['address'] = =" forest in Beijing PEAK Park Water Cube "assert result['data']['start_time'] =" 2016-10-15T18:00:00 "

" conference because the query interface is the GET type, so, through the requests Library (get) method, the first argument is the address of URL call interface, parameter setting interface params, parameters to form a dictionary. The

json () method can convert the data of the JSON format returned by the interface to a dictionary.

is followed by an assertion of the data in the dictionary through the assert statement. The related data of status, message and data are asserted respectively.

uses the unittest unit test framework development interface test cases

 # conference query interface test code import unittest import requests class GetEventListTest (unittest.TestCase): def setUp (self): self.base_url = "http://127.0.0.1:8000/api/get_event_list/" def test_get_event_list_eid_null (self): 'Eid' is null r = requests.get (self.base_url, params={'eid',''}) result = r.json (self.assertEqual) (result['status'], 10021) self.assertEqual (result['message']'parameter error') def test_get_event_list_eid_error (self): 'eid=901 query result is empty' r = re


This concludes the body part