Python interface automated testing – request request encapsulation

When we are doing automated testing, we all hope that the code we write should be as concise as possible, and the less repetitive the code, the better. Then, we can consider encapsulating the request types (such as Get, Post, and Delect requests). In this way, we can directly make requests when writing use cases.

1. Source code analysis

Let’s take a look at the source code of requests such as Get, Post, and Delet first, and see what characteristics they have.

(1) Get request source code

def get(self, url, **kwargs):
r"""Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
\t\t
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs)
Copy Code

(2) Post request source code

def post(self, url, data=None, json=None, **kwargs):
r"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
\t
return self.request('POST', url, data=data, json=json, **kwargs)
Copy Code

(3) Delect request source code

    def delete(self, url, **kwargs):
        r"""Sends a DELETE request. Returns :class:`Response` object.
        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """
    
        return self.request('DELETE', url, **kwargs)

Copy Code

(4) Analysis results

We found that whether it is a Get request, a Post request or a Delet request, they all return the request function at the end. So, let’s take a look at the source code of the request function.

def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
\t
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
"""
# Create the Request.
req = Request(
method = method. upper(),
url=url,
headers=headers,
files=files,
data = data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self. prepare_request(req)
\t
proxies = proxies or {}
\t
settings = self. merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
\t
# Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
}
send_kwargs. update(settings)
resp = self. send(prep, **send_kwargs)
\t
return resp

Copy Code

As can be seen from the request source code, it first creates a Request, then puts all the passed parameters in it, and then calls self.send(), and passes the Request. Here we will not analyze the source code of methods such as send later, and interested students can learn by themselves.

After analyzing the source code, we found that we don’t need to define other methods such as Get and Post in a separate class, and then call request separately. In fact, we can call request directly.

2. requests request encapsulation

Code example:

import requests
\t
class RequestMain:
def __init__(self):
"""
\t
session manager
requests.session(): maintain the session and save parameters across requests
"""
# instantiate session
self.session = requests.session()
\t
def request_main(self, method, url, params=None, data=None, json=None, headers=None, **kwargs):
"""
\t
:param method: request method
:param url: Request URL
:param params: dictionary or bytes, added to url as parameters
:param data: parameter of data type, dictionary, byte sequence or file object, as the content of Request
:param json: json pass parameter, as the content of Request
:param headers: request headers, dictionary
:param kwargs: If there are other parameters, pass them in the form of variable parameter dictionary
:return:
"""
\t
# catch the exception
try:
"""
\t            
Encapsulate the request request, and enter the request method, request address, request parameters, request header and other information into parameters.
Note: verify: True/False, the default is True, verify the SSL certificate switch; cert: local SSL certificate. If ssl authentication is not required, these two input parameters can be removed
"""
re_data = self.session.request(method, url, params=params, data=data, json=json, headers=headers, cert=(client_crt, client_key), verify=False, **kwargs)
# Exception handling Error display specific information
except Exception as e:
# print exception
print("Request failed: {0}".format(e))
# return the response result
return re_data


if __name__ == '__main__':
# request address
url = 'request URL'
# request parameters
payload = {"request parameters"}
# request header
header = {"headers"}
# Instantiate RequestMain()
re = RequestMain()
# Call request_main and pass the parameters
request_data = re.request_main("request method", url, json=payload, headers=header)
# print response result
print(request_data.text)
Copy Code

Note: If the interface you are calling does not require SSL authentication, you can remove the two parameters cert and verify.

3. Summary

This article just briefly introduces the request encapsulation of Python interface automation. There are still many optimizations in the later stage, and I hope to discuss it with you.

END’s humble strength

Finally, I would like to thank everyone who has read my article carefully. Seeing the fans’ growth and attention all the way, there is always a need for reciprocity. Although it is not a very valuable thing, if you need it, you can take it away: strong>

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

How to get it:

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeHomepageOverview 281903 people are studying systematically