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

[Python automated testing 20] interface automated testing framework model building

編輯:Python

List of articles

  • One 、 Preface
  • Two 、 Framework building process
    • 2.1 Project creation
    • 2.2 README file
    • 2.3 .gitignore file
    • 2.4 What is a test framework ?
    • 2.5 Layered design
    • 2.6 Frame building
      • 2.6.1 Public directory (common)
      • 2.6.2 Test case catalog (testcase)
      • 2.6.3 Test data directory (data)
      • 2.6.4 Test report table of contents (reports)
      • 2.6.5 Profile directory (config)
      • 2.6.6 Log storage directory (logs)
      • 2.6.7 Directory of functions under test (funcs)
      • 2.6.8 Run the file (run.py)
    • 2.7 Test functions
    • 2.8 Executable files
    • 2.9 Test report
    • 2.10 Path processing
    • 2.11 A summary of knowledge

One 、 Preface

This article mainly explains Python Construction of interface automation test framework model , It mainly introduces how to design the framework , And the operation of the basic framework , 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

Two 、 Framework building process

2.1 Project creation

Before the framework is built, it must exist in the form of a project , So we need to build a new project , You can go through Open Open a package of the original project , In order to become an independent project , It can also be used directly New Project To create a new project .

2.2 README file

In any project , We can all see README This file ,README A file is a description document of a project , It will include the basic document description 、 Author of framework construction and maintenance , Frame cognition 、 Framework system 、 Frame structure 、 Frame function 、 Project description 、 Code usage specifications and precautions , The specific content is usually documented according to individual or project needs , Documents can be md form , You can also use txt form , Some instructions can be attached , for example :

2.3 .gitignore file

generally , The code in our project needs version control , Common in the industry is svn And git,.gitignore File is used to git version control , and .gitignore The purpose of the document is : Remove specific files , Will not enter the version control system , No upload .

For example, the cache file generated by code running , Most of these cache files will be put into __pycache__ In the folder , So we can choose this folder , Not included in the version control system . And what is generated by project creation ,idea/ Folder , We can also not include version control .

In real projects, special attention should be paid to , Sensitive data involved , Never put it into version control , For example, test account 、 Database address, etc , This will expose the content of the project , Serious cases will be investigated for legal responsibility , If you are a reader of my article and are using the company's project practice , Please be careful !

It's easy not to include version control , Only need .gitignore Add the corresponding folder or file to the file , Add one and wrap to add a second , It means that the file or folder is not under version control , If you are interested in the following specific contents, you can continue to understand .

2.4 What is a test framework ?

Frameworks can also be common in life , For example, when building a tall building , We need to fix the outer structure of the building , Make sure the building is straight when built , Make sure not to shake , This is the frame of a tall building , The indoor and outdoor of the house belong to the filling content .

The same is true of the test framework , We need to build an automated testing framework , Reusable content , The code you write is just filling in the frame , The code will include :

""" Tools 、 Components .-- Designed to handle excel Tools for 、 Record logger Logging tools 、 Tools for generating logs, etc """

Means that the rules mean the framework 、 The rules , Anyone using the framework cannot violate , There is no standard answer to the framework , As long as you are the designer of the framework , Then it is to have the right to speak , For example, when we import the framework written by others , Their grammatical framework must also be observed 、 The rules .

2.5 Layered design

What is layered design ? The concept of layered design is how to divide modules and packages , Every directory is like a department , Attend to each one's own duties , The final result will be close to perfection , Independent division is the idea and idea of layered design .

Why layered design is needed ? I believe you can have basic concepts through the following figure , Layered design is to better integrate the framework 、 Code management and maintenance , In a certain " Catalog " When something unusual happens , I just need to be specific " Catalog " Management can effectively solve the problem , Without implicating other directories .

""" Frame structure - common Public method catalog - testcase Test case catalog - data Test data directory - reports Test report table of contents - config Profile directory - logs Log system directory - funcs Directory of functions under test - run.py Project start up documents """

2.6 Frame building

2.6.1 Public directory (common)

Create a new one Python package, Name it common, The reason we want to create Python The main reason why a package is not a folder is Python package There is __init__, If you don't have this file , May fail when importing files . So choose Python package. generally , If there is in this folder Python file , Then we will use Python package Create .

A public directory is a common code content , It can be understood that no matter how the framework moves 、 modify , The contents of the public directory can remain unchanged and in other projects , The contents of the public directory can be completely copied for use .

2.6.2 Test case catalog (testcase)

testcase It mainly stores the code of automatic test cases , It includes all kinds of functions , Because of existence py file , So we need Python package newly build .

2.6.3 Test data directory (data)

data Test data is mainly stored in the , The data can be Excel In the form of , It can also be Python The form of the module , Therefore, our creation here still uses Python package.

2.6.4 Test report table of contents (reports)

The storage path of the test report is reports, The final test report is not Python modular , Most of them are based on html The way that exists , Basic data information and chart information can be displayed in the web page , Therefore, we only need to create ordinary folders when creating , Without the need for Python package.

2.6.5 Profile directory (config)

The profile directory is config, It may include the database address 、 User name, password and other common contents , The configuration file may exist Python modular , We still choose Python package.

2.6.6 Log storage directory (logs)

The log storage directory will store the log contents about the operation of the program , Also use Python package establish .

2.6.7 Directory of functions under test (funcs)

The function under test directory is mainly used for Python Function code storage , Storage and development Python Function file , Use Python package establish .

2.6.8 Run the file (run.py)

Create in top level directory Python file , be known as run, When executed run.py All test cases will be executed , It mainly plays the role of program operation .

2.7 Test functions

stay funcs Create login.py, Complete the filling of the measured function , stay testcase Create test_login, Add a test case :

"""login.py The function under test """
def login(username=None, password=None):
if username is None or password is None:
return {
"code": 400, "msg": " The user name or password is empty " }
if username == " Meng Xiaotian " and password == "123456":
return {
"code": 200, "msg": " Login successful " }
return {
"code": 300, "msg": " Wrong user name or password " }
""" test_login.py The test case """
import unittest
from funcs.login import login
class TestLogin(unittest.TestCase):
def test_login_success(self):
username = " Meng Xiaotian "
password = "123456"
expected = {
"code": 200, "msg": " Login successful " }
actual = login(username, password)
self.assertEqual(expected, actual)

As shown in the figure above , The execution result is a test case , Time consuming 0.003s, The test passed . It means that the process has been completed .

2.8 Executable files

stay run.py Add execution code , And prepare test report generation

import unittest
from unittestreport import TestRunner
from datetime import datetime
suite = unittest.defaultTestLoader.discover("testcase")
# current time 
data_str = str(datetime.now().strftime("%Y-%m-%d__%H-%M-%S"))
# Test report name 
reports_name = data_str + " Project framework demonstration test report .html"
runner = TestRunner(suite,
tester=" Meng Xiaotian ",
report_dir="reports",
filename=reports_name)
runner.run()

2.9 Test report

File output to reports:

The first half shows a basic data summary , Total number of use cases 、 Success, failure 、 Specific value of the number of use cases such as errors , But this is not the actual combat stage , Therefore, the test case has only 1 Use cases for demonstration

There will be a chart in the middle , Present the above data in the form of a chart

At the bottom is the details , Which class can I view 、 Which method passes or fails , Details available , It also supports the filtering of results :

2.10 Path processing

We also need to use path processing in the project , Sometimes we need to read the corresponding path to get the file or data we want , Then we need to use os Path module , There are not many explanations here , You can have a brief understanding of , In the subsequent practical stage, we will focus on .

import os
# Get current file path 
current_path = os.path.abspath(__file__)
# obtain config Folder path 
config_dir = os.path.dirname(current_path)
# Project root 
root_dir = os.path.dirname(config_dir)
# data Catalog 
data_dir = os.path.join(root_dir, "data")
# xlsx File directory 
case_path = os.path.join(data_dir, "cases.xlsx")

2.11 A summary of knowledge

""" Framework implementation : First step : framework design 、 modular The second step : stay cases Write automated test cases inside The third step : stay run.py Collect test cases , Generate test reports Explanation of subsequent practical stage : Step four : Encapsulate common test tools , Public code Step five : Invoking in use cases log Variable to increase the log Step six : Realization excel Data driven """


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