Requests library for automated testing of Python interfaces & Pytest framework

Posted by habuchas on Fri, 03 Sep 2021 05:48:28 +0200

preface:

Thank you for reading uncle Qi's article. Thank you to all readers. If it's convenient, please move your hands to make a fortune and pay attention. Uncle Qi's article may not be so vivid and interesting, but I still hope it can bring you improvement. At the end of the article, some of Uncle Qi's dry goods are also the resources reserved by Uncle Qi's 13-year test, If you are interested, you can come and have a look

  1. Send get request

#Guide Package
import requests
#Define a url
url = "http://xxxxxxx"
#Transfer parameters
payload="{\"head\":{\"accessToken\":\"\",\"lastnotice\":0,\"msgid\":\"\"},\"body\":{\"user_name\":\"super_admin\",\"password\":\"b50c34503a97e7d0d44c38f72d2e91ad\",\"role_type\":1}}"
headers = {
  'Content-Type': 'text/plain',
  'Cookie': 'akpsysessionid=bafc0ad457d5a99f3a4e53a1d4b32519'
}
#Send get request
r = requests.get( url=url,headers=headers, data=payload)
#Print results
print(r.text)
#decode
print(r.encoding)
print(r.text.encode('utf-8').decode('unicode_escape'))#First convert the returned result into utf-8, and then decode it into Chinese code
  1. Send post request

#Guide Package
import requests
#Define a url
url = "http://xxxxxxx"
#Transfer parameters
payload="{\"head\":{\"accessToken\":\"\",\"lastnotice\":0,\"msgid\":\"\"},\"body\":{\"user_name\":\"super_admin\",\"password\":\"b50c34503a97e7d0d44c38f72d2e91ad\",\"role_type\":1}}"
headers = {
 'Content-Type': 'text/plain',
 'Cookie': 'akpsysessionid=bafc0ad457d5a99f3a4e53a1d4b32519'
}
#Send post request
r = requests.post( url=url,headers=headers, data=payload)
#Print results
print(r.text)
  1. Send https request

import requests
url='https://www.ctrip.com/'
#The first solution is to ignore the certificate when sending the request. The verify parameter of the certificate is used more
r=requests.post(url=url,verify=False)#The verify parameter defaults to True and the value is False, indicating that the certificate is ignored
#The second solution is to add the path of the certificate in verify
r=requests.post(url=url,verify='Path to certificate')#The verify parameter defaults to True and the value is False, indicating that the certificate is ignored
print(r.text)
  1. File upload

import requests
file = {
    'filename':open('File name','rb')
}
response = requests.post("website",file)
print(response.text)
  1. File download

#Small file download
import requests
r = requests.get("https://img.sitven.cn/Tencent_blog_detail.jpg")
with open(r"D:\a.jpg", "wb") as f:
    f.write(r.content)

#Large file download
import requests
def test_downloads(url, file):
    s = requests.session()
    r = s.get(url, stream=True, verify=False)
    with open(file, "wb") as f:
        for chunk in r.iter_content(chunk_size=512):
            f.write(chunk) 
if __name__ == "__main__":
    url = "https://www.url.com/test/export"
    file = "D:\\a.xlsx"
    test_downloads(url=url, file=file)
#Reprinted to: https://blog.csdn.net/weixin_43507959/article/details/107326912
  1. Timeout timeout

#Guide Package
import requests
#Cycle 10 times
for i in range(0,10):
    try:
        url="http://xxxxxxxxxxxxxxxx"
        data={
            "head":{"lastnotice":0,"msgid":"","accessToken":"89a08bff-15d7-4d7a-9967-0b5f4fb699ce"},
            "body":{"clinicid":"978f661e-1782-43bd-8675-b0ff1138ab7c","deptid":"09b8515b-b01b-4771-9356-aed6b5aa01bf","doctorid":"65ac0251-10ff-473a-af8a-20e8969176f7","registtype":0,"card_num":"","bcc334":"","patientopt":1,"bkc368":"1","patient":{"cardid":"","medicalcardid":"","label":"","sourcetype":1,"nationid":"01","maritalstatus":0,"address":"","company":"","jobname":"","email":"","remark":"","bcc334":"","name":"11","gender":1,"phone":"","birthdate":"2020-03-23","patienttype":1,"szsbcardid":""}}
        }
#Send post request, timeout 0.03s
        r=requests.post(url=url,json=data,timeout=0.03)
        print(r.text)
        print(r.cookies)
    except:
        print('error')
#Refer to: https://blog.csdn.net/weixin_44350337/article/details/99655387
  1. authentication

7.1 auth parameter authentication

import requests
url = 'http://192.168.1.1'
headers = {} #  Some can ask without taking the lead   No, you can ignore this line   And headers=headers, these two places
r = requests.get(url, auth=('admin', '123456'), headers=headers, timeout=10)
print(r.text)

7.2 session operation

#Instantiate session
session = requests.session()
#Initiate a request using session
response = session.post(url,headers=req_header,data=form_data)

7.3 token operation

import requests
url="http://xxxxxxxxxxxxxxx"

json={
    "head":{"accessToken":"","lastnotice":0,"msgid":""},
    "body":{"username":"15623720880","password":"48028d2558577c526a017883211b4066","forceLogin":0}
}
r=requests.post(url=url,json=json)
print(r.text)
print(r.cookies)

#After successful login, a token will be returned and the next interface will be brought in
for i in range(0,1):
    try:
        url="xxxxxxxxxxxxxxxxxx"
        data={
            "head":{"lastnotice":0,"msgid":"","accessToken":"89a08bff-15d7-4d7a-9967-0b5f4fb699ce"},
            "body":{"clinicid":"978f661e-1782-43bd-8675-b0ff1138ab7c","deptid":"09b8515b-b01b-4771-9356-aed6b5aa01bf","doctorid":"65ac0251-10ff-473a-af8a-20e8969176f7","registtype":0,"card_num":"","bcc334":"","patientopt":1,"bkc368":"1","patient":{"cardid":"","medicalcardid":"","label":"","sourcetype":1,"nationid":"01","maritalstatus":0,"address":"","company":"","jobname":"","email":"","remark":"","bcc334":"","name":"11","gender":1,"phone":"","birthdate":"2020-03-23","patienttype":1,"szsbcardid":""}}
        }
        r=requests.post(url=url,json=data,timeout=0.09)
        print(r.text)
        print(r.cookies)
    except:
        print('error')

7.4 sign signature

# appid: wxd930ea5d5a258f4f
# mch_id: 10000100
# device_info: 1000
# body: test
# nonce_str: ibuaiVcKdpRxkhJA
import hashlib
#String that needs to be encrypted
stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA";
#Build an object for md
md=hashlib.md5()
#Encode the stringA string
md.update(stringA.encode()) 
#Encrypted value after generation
AES=md.hexdigest()
#Convert the encrypted result from lowercase to uppercase   upper function
AES=AES.upper()
print(AES)
Refer to wechat payment: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
  1. Automatic module division

config configuration file (python package) #directory is similar to python package
common public method (python package)
testdata test data (python package)
test_case test case (python package)
report (directory)
run_case test execution (python package)
Log log

8.1 config configuration file

def server_ip():
    '''
    ait_ip=''Server for development environment ip
    sit_ip=''Server for test environment ip
    :return: Returns the addresses of different servers
    '''


    server_add={
        'dev_ip' : 'http://his.xxxxxxxxxxx.com',
        'sit_ip' : 'http://his.xxxxxxxxxxxx.comm'
    }
    return server_add['dev_ip']
------------------------------------------------------------------------------------
def sql_conf():
    '''
    host database ip
    user Database user name
    password Database password
    database:Connection database name
    port Database port
    chrset Database character set chinese utf-8
    :return:
    '''
    host='localhost'
    user='root'
    password='123456'
    database='mysql'
    port=3306
    charset='utf8' #Using utf8, utf-8 will report an error
    return host,user,password,database,port,charset

8.2 common method

#  Encapsulates a function that reads Excel table data
#  A library - xlrd library is needed to read Excel table data
import xlrd
def get_excel_value(i):
    '''
    Read the data of a row in the table
    :return:Return 2 and 3 rows of data
    '''
    filename = r"../testdata/jiekou.xls" #File to use relative path
    book = xlrd.open_workbook(filename)  #  Open a workbook without closing it manually
    #  sheet  =  book.sheet_by_name("Sheet1")   Get a worksheet object according to the name of the worksheet
    sheet = book.sheet_by_index(0)  #  Get a worksheet in the form of index. Here is the first worksheet
    return sheet.cell_value(i,1),sheet.cell_value(i,2)
# print(sheet.nrows) #Print all lines
# print(sheet.ncols) #Print all columns
# print(sheet.row_values(0))  #Print first line
# print(sheet.col_values(0))  #Print first column
# print(sheet.cell_value(0,1)) #Print first row, second column
# for i in range(1, sheet.nrows):

    # print(sheet.cell_value(i,1),sheet.cell_value(i,2))#  Print the value of cell [all data]
    # str='(sheet.cell_value(i,1),sheet.cell_value(i,2)))'
    # print(str)
# for i in range(1, sheet.nrows):
#     # for j in range(0, sheet.ncols):
#         print(sheet.cell_value(i,j)) #  Print the value of cell [i,j]
---------------------------------------------------------------------------------------------
import pymysql
from config.sql_conf import *
def get_sql(sql):
    '''
    :param sql:To run a query sql sentence
    :return:Database query results
    '''
    #Establish a connection object
    host, user, password, database, port, charset=sql_conf()
    db=pymysql.connect(host=host,user=user,password=password,database=database,port=port,charset=charset)
    #Create a cursor
    cursor=db.cursor()
    #Execute sql statement
    cursor.execute(sql)
    #Save the data of sql operation in the data variable
    data=cursor.fetchall() #Get all the queried values
    cursor.close() #Close cursor
    db.close() #Close database connection
    return data
# print(get_sql("SELECT help_topic_id FROM help_topic WHERE Name='MOD'")) #Execute sql statement
# print(type(get_sql("SELECT help_topic_id FROM help_topic WHERE Name='MOD'")))

8.3 testdata test data

Main storage xls,txt,csv test data

8.4 test_case test case

from common.get_mysql import get_sql
from config.cof import server_ip
from common.get_excel import *
from config.sql_conf import *
import requests
# user_id=get_sql("SELECT help_topic_id FROM help_topic WHERE Name='MOD'")#Extract database data
# print(user_id)#Print results
# assert get_sql("SELECT help_topic_id FROM help_topic WHERE Name='MOD'")#Assert whether the data in the database exists

def test_aokao_login():
     url=server_ip()+'/service/user/login'
     username,password=get_excel_value(1) #Read the second line of the file
     json={
          "head":{"accessToken":"","lastnotice":0,"msgid":""},
          "body":{"username":username,"password":password,"forceLogin":0}
     }

     # usernamepassword=get_excel_value(4)[0] #Read the second line of the file
     # print(type(usernamepassword))
     # #Convert str type to dictionary format   eval   function
     # json=eval(usernamepassword)
     r=requests.post(url=url,json=json)
     print(r.text)
     assert r.status_code==200 #Asserts whether the status code is equal to 200
     assert '"accessToken":"89a08bff-15d7-4d7a-9967-0b5f4fb699ce",' in r.text #Assert whether the returned information contains an accesstoken

def test_aokao_registadd():
     url = server_ip()+'/service/registration/registadd'
     data = {
          "head": {"lastnotice": 0, "msgid": "", "accessToken": "89a08bff-15d7-4d7a-9967-0b5f4fb699ce"},
          "body": {"clinicid": "978f661e-1782-43bd-8675-b0ff1138ab7c", "deptid": "09b8515b-b01b-4771-9356-aed6b5aa01bf",
                   "doctorid": "65ac0251-10ff-473a-af8a-20e8969176f7", "registtype": 0, "card_num": "", "bcc334": "",
                   "patientopt": 1, "bkc368": "1",
                   "patient": {"cardid": "", "medicalcardid": "", "label": "", "sourcetype": 1, "nationid": "01",
                               "maritalstatus": 0, "address": "", "company": "", "jobname": "", "email": "",
                               "remark": "", "bcc334": "", "name": "11", "gender": 1, "phone": "",
                               "birthdate": "2020-03-23", "patienttype": 1, "szsbcardid": ""}}
     }

     r = requests.post(url=url, json=data, timeout=0.09)
     print(r.text)
     print(r.cookies)
     assert r.status_code == 200  #  Asserts whether the status code is equal to 200

8.5 report

Main storage html,xml report

8.6 run_case test execution

import pytest

'''
Test files to test_Beginning with -_test (the end is also OK)
Test class to Test Start, and cannot have init method
 Test function to test_start
 Assertions use basic assert that will do
'''
#How to run test cases_ The function starting with test can judge whether the use case runs successfully, and assert asserts
if __name__=="__main__":
    #When a single file is run and added, the corresponding file path should be a relative path
    # pytest.main(['../test_case//test_case_01.py'])
    #Run multiple files, add multiple corresponding file paths, and add multiple file paths in the form of a list
    # pytest.main(['../test_case/test_fore.py','../test_case/Dynamic correlation_token.py'])
    #Run the entire directory and add the path of the directory
    pytest.main(['../test_case/','--html=../report/report.html','--junitxml=../report/report.xml'])

'''
pytest Generate report:
1,generate html report
'--html=../report/report.html'
2,generate xml report
'--junitxml=../report/report.xml'

 

Thanks to everyone who reads my article carefully. Seeing the rise and attention of fans all the way, reciprocity is always necessary. Although it is not very valuable, you can take it directly if you can use it:

① More than 2000 Python e-books (both mainstream and classic books should be available)

② Python standard library materials (the most complete Chinese version)

③ Project source code (forty or fifty interesting and classic hand training projects and source code)

④ Videos on basic introduction to Python, crawler, web development and big data analysis (suitable for Xiaobai)


  ⑤ Python learning roadmap (bid farewell to non stream learning)

In my QQ technology exchange group (technology exchange and resource sharing, advertising comes in and your legs are interrupted)

It can be taken away by oneself. The free information in group 913569736 (note "csdn000") is the essence of the author's more than 10 year test career. There are also great gods in the same industry to exchange technology together.
 

Topics: Python unit testing Testing pytest requests