This article will mainly explain the interface automation test Python Database assertions and related interface related tests , In addition, there is a portal for a series of articles below , It's still being updated , Interested partners can also go to check , Don't talk much , Let's have a look ~
Series articles :
Series articles 1:【Python automated testing 1】 meet Python The beauty of the
Series articles 2:【Python automated testing 2】Python Installation configuration and PyCharm Basic use
Series articles 3:【Python automated testing 3】 First knowledge of data types and basic syntax
Series articles 4:【Python automated testing 4】 Summary of string knowledge
Series articles 5:【Python automated testing 5】 List and tuple knowledge summary
Series articles 6:【Python automated testing 6】 Dictionary and collective knowledge summary
Series articles 7:【Python automated testing 7】 Data operator knowledge collection
Series articles 8:【Python automated testing 8】 Explanation of process control statement
Series articles 9:【Python automated testing 9】 Function knowledge collection
Series articles 10:【Python automated testing 10】 File basic operation
Series articles 11:【Python automated testing 11】 modular 、 Package and path knowledge collection
Series articles 12:【Python automated testing 12】 Knowledge collection of exception handling mechanism
Series articles 13:【Python automated testing 13】 class 、 object 、 Collection of attribute and method knowledge
Series articles 14:【Python automated testing 14】Python Basic and advanced exercises of automatic test
Series articles 15:【Python automated testing 15】unittest The core concept and function of test framework
Series articles 16:【Python automated testing 16】 Test case data separation
Series articles 17:【Python automated testing 17】openpyxl Secondary packaging and data driven
Series articles 18:【Python automated testing 18】 Configuration file analysis and practical application
Series articles 19:【Python automated testing 19】 Log system logging Explain
Series articles 20:【Python automated testing 20】 Construction of interface automation test framework model
Series articles 21:【Python automated testing 21】 Interface automation test practice 1 _ Interface concept 、 Project introduction and test process Q & A
Series articles 22:【Python automated testing 22】 Interface automation test practice II _ Interface framework modification and use case optimization
Series articles 23:【Python automated testing 23】 Interface automation test practice III _ Dynamic parameterization and data forgery
Series articles 24:【Python automated testing 24】 Interface automation test practice IV _Python Operating the database
After automated test case execution , Verify the database only after judging the successful test cases :
import unittest
import requests
import json
from common.db import DBHandler, db_module
from common.logger import log
from common.excel import read_excel
from common import helper
from config import path_config
from unittestreport import ddt, list_data
from config import setting
# get data
data = read_excel(path_config.case_path , 'XXXXXX')
@ddt
class TestRegister(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
""" Front of test class """
cls.db = DBHandler()
@classmethod
def tearDownClass(cls) -> None:
""" Front of test class """
cls.db.close()
@list_data(data)
def test_register(self, case_data):
print(case_data)
json_data = case_data['json']
if '#new_phone#' in json_data:
new_phone = helper.generate_new_phone()
json_data = json_data.replace('#new_phone#', new_phone)
# hold json Convert a formatted string into a dictionary
json_data = json.loads(json_data)
headers = json.loads(case_data['headers'])
print(" After replacement ", json_data)
resp = requests.request(
method=case_data['method'],
url= setting.host + case_data['url'],
json=json_data,
headers=headers
)
actual = resp.json()
print(actual)
try:
self.assertEqual(case_data['expected'], actual['code'])
except AssertionError as e:
raise e
""" 1、 Judge whether it is a test case with successful registration 2、 Query whether the database contains the record of mobile phone number 3、 Judge whether the number of database records is 1 """
if actual['msg'] == "OK":
# adopt setUp Create database connection
sql = f"select id from XXXX.XXXX where XXXXXX = {
json_data['XXXXXX']}"
result = self.db.query_all(sql)
self.assertEqual(1, len(result))
Interface associations often exist for interfaces in a project , And we need to deal with the interface separately :
import unittest
import requests
import json
from jsonpath import jsonpath
from decimal import Decimal
from common.db import DBHandler
from common.logger import log
from common.excel import read_excel
from common import helper
from config import path_config
from unittestreport import ddt, list_data
from config import setting
# get data
from middle import api
data = read_excel(path_config.case_path , 'XXXXXX')
@ddt
class TestRecharge(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
""" 1, Access the login interface , Get the return value 2, Extract data from the return value :resp["data"]["id"] 3, Extract data from the return value :resp["data"]["token_info"]["token"] 4, Set as class property , Convenient test case function calls :return: """
resp_data = api.login()
# Extraction method 1:
cls.member_id = resp_data["data"]["id"]
cls.token = resp_data["data"]["token_info"]["token"]
# Extraction method 2:jsonpath
cls.member_id = jsonpath(resp_data, '$..id')[0]
cls.token = jsonpath(resp_data, '$..token')[0]
cls.before = jsonpath(resp_data, '$..leave_amount')[0]
# Initialize database
cls.db = DBHandler()
@classmethod
def tearDownClass(cls) -> None:
pass
@list_data(data)
def test_recharge(self, case_data):
""" 1, obtain case_data The data ,headers, json Is the focus of attention . 2, Data preprocessing : Data substitution , Data conversion to Dictionary format :headers, json, expected 3, Send a request 4, Assertion :param case_data: :return: """
# obtain case_data The data ,headers, json Is the focus of attention .
headers_string = case_data['headers']
json_string = case_data['json']
# Data preprocessing : Data substitution , Convert data to dictionary format :headers, json, expected
if "#token#" in headers_string:
headers_string = headers_string.replace("#token#", self.token)
if "#member_id#" in json_string:
json_string = json_string.replace("#member_id#", str(self.member_id))
headers = json.loads(headers_string)
json_data = json.loads(json_string)
expected = json.loads(case_data['expected'])
# Get the balance of users in the database before recharging
sql = f"select XXXXXXX from XXXX.XXXXX where id={
self.XXXXX_id}"
before = self.db.query_one(sql)
# {"leave_amount": 200}
# 3, Send a request
resp = requests.request(
method=case_data['method'],
url=setting.host + case_data['url'],
json=json_data,
headers=headers
)
# 4, Assertion
json_response = resp.json()
try:
for key, value in expected.items():
self.assertEqual(value, json_response[key])
except AssertionError as e:
log.error(f" Test case failed :{
e}")
raise e
if json_response['msg'] == 'OK':
print(json_response)
# Through database assertion
sql = f"select leave_amount from futureloan.member where id={
self.member_id}"
after = self.db.query_one(sql)
money = str(json_data['amount'])
after = str(after['leave_amount'])
before = str(before['leave_amount'])
self.assertEqual(Decimal(money), Decimal(after) - Decimal(before))
All right. ~ The above is all the content shared in this article , Have you learned ? I hope I can help you !