程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python automated test 22] interface Automated Test Practice II_ Interface framework modification and use case optimization

編輯:Python

List of articles

  • One 、 Preface
  • Two 、 Practical drill
    • 2.1 The interface is introduced
    • 2.2 Interface excel The test case
    • 2.3 frame common Catalog
    • 2.4 Test case design
    • 2.5 Use case design optimization

One 、 Preface

This article mainly explains Python Framework construction and modification of interface automation test , Automatic test case design, etc , This article will skip some frame building content , Build a detailed framework for teaching jump : Construction of interface automation test framework model

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

Two 、 Practical drill

2.1 The interface is introduced

Let's start with an interface , This interface is the login interface , The request method is POST, After logging in, you can perform various operations , The basic information is as follows :

2.2 Interface excel The test case

Follow the login interface documentation , Design test cases :

2.3 frame common Catalog

Test cases belong to data , Then we must read excel, We also have configuration files , And the log system , These are general content , We can add the corresponding code module to common in :

""" Read excel, There's a simpler way , This method is suitable for novices to learn """
import openpyxl
def read_excel(file_path, sheet_name):
""" Read excel Data in """
workbook = openpyxl.load_workbook(file_path)
sheet = workbook[sheet_name]
values = list(sheet.values)
workbook.close()
title = values[0]
rows = values[1:]
new_rows = [dict(zip(title, rows)) for rows in rows]
return new_rows
""" Log system """
import logging
def get_logger(logging_name=" The collector ",
logger_level="DEBUG",
stream_level="DEBUG",
file=None,
file_level="INFO",
fmt="%(asctime)s--%(levelname)s--%(filename)s--%(lineno)d--%(message)s"):
""" obtain logger The collector """
logger = logging.getLogger(logging_name)
logger.setLevel(logger_level)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(stream_level)
logger.addHandler(stream_handler)
fmt_obj = logging.Formatter(fmt)
stream_handler.setFormatter(fmt_obj)
# Determine whether there are documents , If there is , initialization file_handler, If there is no file, do not execute 
if file:
file_handler = logging.FileHandler(file, encoding="utf-8")
file_handler.setLevel("INFO")
logger.addHandler(file_handler)
file_handler.setFormatter(fmt_obj)
return logger
log = get_logger()
"""yaml Read the results """
import yaml
def read_yaml(file, encoding="utf-8"):
with open(file, encoding="utf-8") as f:
data = yaml.safe_load(f)
return data

2.4 Test case design

stay testcase New under the directory test_login Used to test login and realize excel Read and data-driven , After obtaining the use case data, let's print the data first :

import unittest
import requests
from common.excel import read_excel
from config import path_config
from unittestreport import ddt, list_data
# get data 
data = read_excel(path_config.case_path, "login")
@ddt
class TestLogin(unittest.TestCase):
@list_data(data)
def test_login_success(self, case_data):
print(case_data)

The complete supplementary code is as follows :

import unittest
import requests
import json
from common.excel import read_excel
from config import path_config
from unittestreport import ddt, list_data
# get data 
data = read_excel(path_config.case_path, "login")
@ddt
class TestLogin(unittest.TestCase):
@list_data(data)
def test_login_success(self, case_data):
print(case_data
""" 1、 The first step is to get the response data 2、 Get the expected results 3、 Comparison between expected results and actual results """
# hold json Format string into a dictionary , Avoid reading string instead of dictionary format when reading 
json_data = json.loads(case_data["data"])
headers = json.loads(case_data["headers"])
expect = json.loads(case_data["expected"])
respon = requests.request(
method=case_data["method"],
url=case_data["Api_Url"],
json=json_data,
headers=headers
)
actual = respon.json()
self.assertEqual(actual["code"], expect["code"])

2.5 Use case design optimization

stay config Create under directory setting.py, Add the corresponding host domain name , Then you can url The joining together of :

# domain name 
host = "http://IP: port "
""" Fragment code """
respon = requests.request(
method=case_data["method"],
# Splicing , Import before splicing setting
url=setting.host + case_data["Api_Url"],
json=json_data,
headers=headers
)

In addition, we also need to capture the exception of assertion , The complete code after modification again :

import logging
import unittest
import requests
import json
from common.excel import read_excel
from config import path_config
from unittestreport import ddt, list_data
from config import setting
# get data 
data = read_excel(path_config.case_path, "login")
@ddt
class TestLogin(unittest.TestCase):
@list_data(data)
def test_login_success(self, case_data):
print(case_data)
""" 1、 The first step is to get the response data 2、 Get the expected results 3、 Comparison between expected results and actual results """
# hold json Format string into a dictionary , Avoid reading string instead of dictionary format when reading 
json_data = json.loads(case_data["data"])
headers = json.loads(case_data["headers"])
expect = json.loads(case_data["expected"])
respon = requests.request(
method=case_data["method"],
url=setting.host + case_data["Api_Url"],
json=json_data,
headers=headers
)
actual = respon.json()
try:
self.assertEqual(actual["code"], expect["code"])
log.info(f" The test case passed :{
case_data}")
except AssertionError as err:
log.error(f" Test case failed :{
case_data}, The error message is :{
err}")
# After the test case fails to be captured , Use raise Throw out 
raise err


All right. ~ The above is all the content shared in this article , Have you learned ? I hope I can help you !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved