Python + requests + unittest API test instance (detailed description), requestsunittest

Source: Internet
Author: User

Python + requests + unittest API test instance (detailed description), requestsunittest

I searched for information related to interface tests on the Internet. Most of them focused on maintaining use cases in a text or table in a data-driven manner without explaining how to generate the desired use cases,

Problem:

When testing interfaces, for example, parameters a, B, and c, I need to test the parameter first. There are (not transmitted, null, integer, floating point, String, object, too short, too long, SQL Injection) one of these situations is a use case. At the same time, ensure that the test of B and c is correct and that a is not affected by the errors of parameters B and c.

Solution:

Parameters that comply with the interface specifications can be filled in manually or prepared in the code library. Parameters that do not comply with the specifications (do not pass, null, integer, floating point, String, object, too short, too long, SQL injection) can also be used repeatedly as constants in the library.

Main functions:

1. Sort api parameters into dict to facilitate combination of parameters to generate Use Cases

2. Execute the generated use cases cyclically.

3. encapsulate some code for ease of use and maintenance

Source code analysis:

The canshuxinxi. py file is used to store api information. It is stored in dict format, so that you can obtain the information of API_ALL ['logon interface'] [url] in this way. It looks intuitive and you know which interface to obtain.

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: # canshuxinxi. py # API Information API_ALL = {'logon interface': {'number': '1', 'url': 'http: // www.baidu.com ', 'leixing ': 'post', 'head': {'A': 'bb', 'cc': 'dd',}, 'canonical': {'username': 'wbfxs001 ', 'Password': '1111qq', 'Grant _ type': 'Password',}, 'qiwang': {'code': 200, 'name ': 'wbfxs001',},}, 'exit interface ': {'number': '1', 'url': 'http: // www.baidu.com', 'leixing ': 'get', 'canshu': {'username': 'wbfxs001', 'Password': '1111qq', 'Grant _ type': 'Password ',}}}

Changliang. the py file is used to store unconventional parameters (which may cause interface response exceptions). Likewise, it is stored in dict for easy maintenance. For example, to add new SQL Injection code segments, you can directly add them later.

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: # changliang. py # common parameters are not passed, empty, integer, floating point, String, object, too short, too long, SQL Injection objects1 = 'xxxx' objects2 = 'sss' ZHCS = {'blank': [''], 'shape': [10, 23, 44, 88, 99], 'floating point ': [1.11, 2.342,-1.03], 'string': ['aaa', 'bbbbb', 'cccccc', 'ddd'], 'object': [objects1, objects2], 'too short ': ['1', '0'], 'ultra-long': ['20140901'], 'SQL injection ': ['; and 1 = 1; and 1 = 2', "; and (select count (*) from sysobjects)> 0 mssql ","; and 1 = (select IS_SRVROLEMEMBER ('sysadmin'); -- "],}

# Gongju. py is used as a tool class. The following methods are encapsulated for convenient calling. Parameters are combined to produce dict parameters of different combinations and save the dict parameters to the list for convenient use.

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: # gongju. py # generate different combinations of parameter class gj (): def listall( self, csTrue, csFalse): fzgcs = [] # Get the key of cycanshu, put all informal parameters in a list listall = [] # Save the dict parameter as list zhcs = dict (csTrue) listall. append (csTrue) aaa = list (csFalse. keys () for I in aaa: bbb = csFalse [I] # obtain the specific parameter list for k in bbb: fzgcs. append (k) # Every parameter is added to the fzgcs list zhcskey = list (zhcs. keys () # Get the parameter for I in zhcskey: a = zhcs [I] # retain the original parameter value, after replacement, the correct recovery parameter for k in fzgcs: zhcs [I] = k listall. append (str (zhcs) # restore the correct parameter zhcs [I] = a return listall after the loop

The jiaoben. py file is used as the script class to cyclically execute the combined parameters and carry them into the combined parameter requests in turn. (Only request and print response information can be added to the response result assertions)

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: # jiaoben. pyfrom changliang import ZHCSfrom canshuxinxi import API_ALLfrom gongju import gjimport requests # script class. Combine tool parameters to request gj = gj () def jball (): apikeys = extract () print (apikeys) for key in apikeys: apiname = key url = API_ALL [key] ['url'] number = API_ALL [key] ['number'] leixin = API_ALL [key] ['leixing'] canshus = gj. listall( API_ALL [key] ['canonical'], ZHCS) if leixin = 'post': print ("========" + "api Name: "+ apiname +" ======= ") for cs in canshus: mp = requests. post (url = url, data = cs) fhcode = str (mp. status_code) xysj = str (mp. elapsed. microseconds) print ("= response = api NO.:" + number + "response code:" + fhcode + "response time:" + xysj) if leixin = 'get ': print ("=" + "api name:" + apiname + "=") for cs in canshus: mp = requests. get (url = url, data = cs) fhcode = str (mp. status_code) xysj = str (mp. elapsed. microseconds) print ("= response = api NO.:" + number + "response code:" + fhcode + "response time:" + xysj) jball ()

Tesone. as an example execution file, The py file is familiar with the unittest framework and has a clear understanding of its principles. The black bear is mainly used to control script execution. Combined with the unittest framework, it facilitates subsequent extension.

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: # tesone. pyimport requestsimport unittestimport timefrom jiaoben import jballclass testclassone (unittest. testCase): def setUp (self): print (111) pass def test_1 (self): jball () # Run the script pass def tearDown (self): print (333) passif _ name _ = '_ main _': unittest. main ()

Attached to the execution of the use case:

The above python + requests + unittest API test instance (detailed description) is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.