Automated testing framework Pytest - requests encapsulation

requests is a python third-party library used to send http requests and receive http responses, mainly for interface automation. Today we will learn how to package it into pytest.

1. Install requests

pip install requests

2. Common methods of the requests library. Including several common requests and required parameters of http

requests.get(url, params=None, **kwargs)requests.post(url, data=None, json=None, **kwargs)requests.put(url, data=None, **kwargs)requests.delete(url, **kwargs)requests.request(method, url, **kwargs)

3. The common return value of the get request, the test here is a jira method written by myself

import requests
class TestApi:
    def test_get(self):        url = "http://172.19.1.34:8015/emanage/getissue"        datas = {
   
               "issue":"PAY"        }
        res = requests.get(url=url,params=datas)        print(res.text) #返回body的文本信息        print(res.json) #返回body的json格式        print(res.content) #返回body的byte类型        print(res.status_code)  # 返回状态码        print(res.reason)  # 返回状态信息        print(res.cookies)  # 返回响应的cookie信息        print(res.encoding)  # 返回编码格式        print(res.headers)  # 返回响应头        print(res.request.method)  # 返回请求的数据

4. The post request is similar to the get request. It should be noted that the conversion between json and string

json.loads() converts json strings into dict
json.dumps() converts dict into json strings

    def test_post(self):        urls = "http://172.19.1.34:8016/hdj/s1/"        datas = {
   
                 "user": "wufan",              "sqlword": "select * from t_11"        }
        res = requests.post(url=urls, data=datas)        print(res.json())

5. Actual case:

Obtain the token interface of the WeChat applet and use the token to obtain the applet label

  • To obtain the appid and secret of the WeChat applet, visit the address below and log in with WeChat

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
  • After obtaining the appid and secret, you can obtain the token of the applet

import jsonimport re
import requests
class TestProductApi:
    access_token = ""    session = requests.session() #通过session去关联,session默认情况下会自动关联cookie

    def test_get_token(self):         print("获取token鉴权码")         urls = "https://api.weixin.qq.com/cgi-bin/token"         datas = {
   
                 "grant_type":"client_credential",              "appid":"wx8e8b67ced3c4b884",              "secret":"27c524bd9ca932e31e229be30b0a805b"         }
         res = TestProductApi.session.request("get",url=urls,params=datas)
         TestProductApi.access_token = res.json()['access_token']         print(TestProductApi.access_token)

6. In the above case, data and url are written directly in the use case, which is not convenient for later maintenance.

Next, we encapsulate the requests at the first level and read the parameters in the yaml file.

Add a new method in the commons/yaml_util.py tool:

#读取测试用例def read_testcase_yaml(yaml_path):    with open(get_object_path()+yaml_path,encoding='utf-8') as f:        value = yaml.load(f,Loader=yaml.FullLoader)        return value

Write the parameters required by the get request in the pm_get_token.yaml file:​​​​​​​​

-  name: 获取token鉴权码  request:    method: get    url: https://api.weixin.qq.com/cgi-bin/token    params:      grant_type: client_credential      appid: wx8e8b67ced3c4b884      secret: 27c524bd9ca932e31e229be30b0a805b  validate: none

To modify the use case, the parameters are read from the yaml file:​​​​​​​​

# 测试类名必须以Test开头,并且不能有init方法import pytestimport requests
from test6.commons.yaml_util import read_testcase_yaml
class TestProductApi:
    #测试方法必须以test开头    @pytest.mark.parametrize("args_name", read_testcase_yaml('/testcase/pm_get_token.yaml'))    def test_get_token(self, args_name):        url = args_name['request']['url']        params = args_name['request']['params']        res = requests.get(url=url,params=params)        print(res.json()['access_token'])

The interface is called successfully, and the token is successfully output

7. Although the parameters are all written in the yaml file, the code is still a bit complicated.

Let's do the second encapsulation and create a new /commons/request_util.py,

It contains the verification yaml file format:​​​​​​​​

import reimport requests
class RequestUtil:    session = requests.session()    #规范YAML测试用例    def standard_yaml(self,caseinfo):        caseinfo_keys = caseinfo.keys()        # 判断关键词是否完整        if "name" in caseinfo_keys and "request" in caseinfo_keys and "validate" in caseinfo_keys:            cs_request = caseinfo['request']            cs_request_keys = cs_request.keys()            if "method" in cs_request_keys and "url" in cs_request_keys:                method = cs_request.pop("method") #pop-删除列表里最后一个并且返回这个值                url = cs_request.pop("url")                res = self.send_request(method,url,**cs_request)                # return_text = res.text                print(res.json()['access_token'])                return res            else:                print("二级关键字必须包含:method,url")        else:            print("一级关键字必须包含:name,request,validate")
    #统一请求封装    def send_request(self, method, url, **kwargs):        method = str(method).lower()        res = RequestUtil.session.request(method,url,**kwargs)        return res

Create a new use case, call the request_util tool,

This time you only need one sentence to request the interface:​​​​​​​​

 @pytest.mark.parametrize("caseinfo", read_testcase_yaml('/testcase/pm_get_token.yaml'))    def test_get_token2(self, caseinfo):        RequestUtil().standard_yaml(caseinfo)

Check the results, and the token can also be obtained successfully, but the code is much simpler, and the token can be obtained in two use cases:

The following is the supporting information. For friends who do [software testing], it should be the most comprehensive and complete preparation warehouse. This warehouse also accompanied me 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

Information acquisition method:

Guess you like

Origin blog.csdn.net/myh919/article/details/131831566