The whole process of building the interface automation testing framework

Ideas:
    1. Basic directory construction
        report: static output directory (report or log)
        
        data: static input directory (can store Excel data, some data to be read)
        
        utils: utility method layer (stored here is the public method of the project , Generally, you can use it directly when you get other projects, such as: read data in Excel, connect to the database,)
        
        apis: interface request layer (the methods encapsulated here are generally related to the project, such as: send post request, Send get request, login interface, registration interface, payment interface, add shopping cart interface)
        
        testcases: use case directory (used to store the use cases involved in the project, use cases include single interface use cases and associated interface use cases, when managing directories, It can also be managed through the directory hierarchy)
        
        conftest: The fixtures are stored here, which only take effect for the directory where the file is located. If it is only a single directory use case, it can be created under the root directory. If it is divided into hierarchical directory structure use cases, then for
                 
                 To meet the use case of the current directory, you can create a conftest in this directory to store fixtures, which are the root of the pytest framework pytest.ini: is the
        
        configuration file of pytest, which can be used to store some running configuration items, such as: -v - s; or configure the         log output channel;
        
    the specific configuration of this file can be learned from Baidu
        
conftest---"pytest.ini---"testcases
        
        ②The above is equivalent to a pyramid structure, from left to right is the process from bottom to top
        
        ③The essence of the pyramid is that (the upper part depends on the bottom, and the bottom does not depend on the upper part), for example, (use cases in testcases need to call apis The interface request method in the directory, and apis will not actively call testcases), so
        
            in the work, if we modify a certain file, we need to look up to see who called this file, and modify it accordingly

##########################utils中的db.py的封装
import pymysql

#
# # 1. 连接数据库
# conn = pymysql.connect(
#     host='服务器地址',
#     port=3306,
#     user='用户名',
#     password='密码',
#     db='数据库名'
# )
# # 2. 建立游标
# cur = conn.cursor(pymysql.cursors.DictCursor)  # 没有s 有括号
#
# # 3. 执行sql
# # 3.1 执行查询
# cur.execute("SELECT * FROM cardInfo WHERE cardNumber='hzc_00011';")
# conn.commit()
# # 获取结果
# result = cur.fetchall()
# # result = cur.fetchone() # 取一条少一条
# # cur.fetchmany(3)
# print(result)
#
# # 3.2 执行修改
# # cur.execute("DELETE FROM cardInfo WHERE cardNumber='hzc_00011';")
# # conn.commit()
#
# # 4. 关闭
# cur.close()
# conn.close()


class DB(object):
    def __init__(self):
        self.conn = pymysql.connect(
            host='服务器地址',
            port=3306,
            user='用户名',
            password='密码',
            db='数据库名',
            autocommit=True
        )
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)    #添加此配置项,默认commit了,即建立游标

    def do_sql(self, sql):
        print('执行sql', sql)
        self.cur.execute(sql)    #执行sql语句
        # self.conn.commit()    
        return self.cur.fetchall()    #返回查询到的所有结果


class FuelCardDB(DB):    #继承DB
    """执行具体的sql语句"""
    def del_card(self, card_number):
        """执行删除语句"""
        self.do_sql(f"DELETE FROM cardInfo WHERE cardNumber='{card_number}'")

    def check_card(self, card_number):
        """执行查询语句"""
        result = self.do_sql(f"SELECT * FROM cardInfo WHERE cardNumber='{card_number}';")
        if result:
            return True
        return False

    def add_card(self, card_number):
        """执行添加语句"""
        result = self.check_card(card_number)
        if not result:
            self.do_sql(f"INSERT INTO cardInfo (cardNumber) VALUES ('{card_number}');")

######################### API file encapsulation

Idea: This file can encapsulate different request methods and different request address interfaces into a class, and then call whichever one is used in the use case layer. The following example is to add fuel card
items

import requests

DATA_SOURCE_ID = "bHRz"


class Api(object):
    def __init__(self, base_url):
        self.url = base_url + '/gasStation/process'
        self.session = requests.session()


    def add_fuelcard(self, card_number):
        json_data = {"dataSourceId": DATA_SOURCE_ID, "methodId": "00A", "CardInfo": {"cardNumber": card_number}}
        res = self.session.post(self.url, json=json_data)
        print(res.text)
        return res


    def bind_card(self, user_name, id_type, id_number, card_number):
        json_data = {
            "dataSourceId": DATA_SOURCE_ID,
            "methodId": "01A",
            "CardUser": {
                "userName": user_name,
                "idType": id_type,
                "idNumber": id_number
            },
            "CardInfo": {
                "cardNumber": card_number
            }
        }

        res = self.session.post(self.url, json=json_data)
        print(res.text)
        return res


    def query_card(self, user_id, card_number):
        #dataSourceId=bHRjczEx&userId=1039&cardNumber=1111111111&methodId=02A
        params = {
            "dataSourceId": DATA_SOURCE_ID,
            "methodId": "02A",
            "userId": user_id,
            "cardNumber": card_number
        }
        res = self.session.get(self.url, params=params)
        print(res.text)
        return res

Idea: This file mainly encapsulates the fixtures method, that is, in order to simplify the steps of the use case layer, the operation prerequisite steps and process steps can be completed under this file. There is a base_url under this file, which is the installed plug-in. The installation method
is pip install pytest-base-url

import pytest
from utils.db import FuelCardDB
from apis.fuelcard_api import Api


@pytest.fixture(scope='session')
def db():
   #实例化一个对象
    return FuelCardDB()


@pytest.fixture(scope='session')
def api(base_url):
  #实例化一个对象,并将配置文件中的base_url传给Api层的方法
    return Api(base_url)

@pytest.fixture
def del_card(db):

    def _del_card(card_number):
        db.del_card(card_number)
        yield
        db.del_card(card_number)

    return _del_card

##########################pytest.ini file encapsulation

Thought: As explained above, this file is the configuration file of the pytest framework, that is, the file manipulation will be executed by default when running the use case. Pay attention to the expression format, base_url is used in both the conftest file and the api file, which is the base_url here, and the purpose is to serve as a
server After the address is changed, you don’t need to go to the interface layer to modify the server address one by one, just modify the address here, but
if the request address of the interface changes, you have to modify it one by one. After all, different request addresses are encapsulated for different requests. Methods

[pytest]
addopts = -s --html=reports/report.html --self-contained-html
testpaths = testcases
base_url = http://***.***.***.***:***

#######################Summarize

①The main framework of the interface has basically come out. When we need other methods, we can add them accordingly. For example, the method of reading excel table data can be packaged in the utils directory

②If you need a public method, you can go to Baidu to check the modules written by others. To be honest, writing it yourself for a long time is not as practical as others’ packaged ones. Our goal is to use others’ packaged methods and it’s OK.

③If it involves your own business modules, you have to package them yourself. For example, as mentioned above, api files and conftest files are all related to business

④ For junior automated testers, the most important thing is not to write the framework, but to use the framework written by others to design and write use cases

⑤Basic process of a use case: test environment preparation, test data preparation, sending data, obtaining data response results, setting assertions, environment cleanup

Guess you like

Origin blog.csdn.net/xiao1542/article/details/130273605