Python+requests+pytest+allure封装接口自动化4-EXCEL\YAML测试数据管理

一、测试数据管理类型

为了将数据和代码进行分离,我们可以将测试数据单独存储和管理,至于说你是存csv、excel、yaml、

db,这些方式都可以,

二、excel存储数据封装

excel的操作需要依赖第三方库,这里使用pandas

1. 安装pandas

#windows
pip install openpyxl
pip install pandas
# mac
python3 -m pip install openpyxl
python3 -m pip install pandas

2. 使用pandas读取数据

1、在common目录中新建一个load_file.py的文件,封装excel的构造pytest支持的数据格式[[],[]]

import pandas as pd
import os

import yaml

abs_path = os.path.abspath(__file__)
# 三种方式
project_path = os.path.dirname(abs_path).rstrip('\\common')
# project_path = os.path.dirname(abs_path).replace('\\common','')
# project_path = os.path.dirname(abs_path)[0:len(os.path.dirname(abs_path))-6]

def read_excel(filePath, sheet_name):
    df = pd.read_excel(f'{project_path}{filePath}', sheet_name=sheet_name)
    # 获取EXCEL的行数
    lines_count = df.shape[0]
    # 获取EXCEL的列数
    cols_count = df.shape[1]
    # 需要遍历构造pytest能够识别的数据结构
    # [
    #     ['标题为空', '', '超级管理员', '内容', '1', 200, '操作成功'],
    #     ['正常发帖', '1111', '超级管理员', '内容', '1', 200, '操作成功'],
    #     ['发帖用户为空', '1111', '', '内容', '1', 200, '操作成功'],
    # ]
    result_data = []
    lines_data = []
    for i in range(lines_count):
        lines_data = []
        for j in range(cols_count):
            cell_data = df.iloc[i, j]
            # 把不是str类型的数据都装为int
            if not isinstance(cell_data, str):
                cell_data = int(cell_data)
            print(type(cell_data))
            lines_data.append(cell_data)
        result_data.append(lines_data)
    return result_data

if __name__ == '__main__':
    result = read_excel('/data/community_testdata.xlsx', '发帖数据')
    print(result)

3. 修改发帖测试用例

修改发帖的用例为通过EXCEL去构造Pytest数据

import pytest

from api.portal.portalArticle.create_article_api import CreateArticleApi
from common.file_load import read_excel


class TestCreateArticleApi:
    test_data = read_excel('\data\community_testdata.xlsx', '发帖数据')
    # test_data = [
    #     ['标题为空', '', '超级管理员', '内容', '1', 200, '操作成功'],
    #     ['正常发帖', '1111', '超级管理员', '内容', '1', 200, '操作成功'],
    #     ['发帖用户为空', '1111', '', '内容', '1', 200, '操作成功'],
    # ]

    @pytest.mark.parametrize('casename,title, author, content, createUser,expect_code,expect_message', test_data)
    def test_buy_now_params(self, casename, title, author, content, createUser, expect_code, expect_message):
        createArticleApi = CreateArticleApi(title, author, content, createUser)
        resp = createArticleApi.sendRequest()
        print(resp.text)
        status_code = resp.status_code
        assert status_code == expect_code
        message = resp.json()['msg']
        assert message == expect_message
Python+requests+pytest+allure封装接口自动化4-EXCEL\YAML测试数据管理_第1张图片

三、YAML存储数据封装

  1. 安装PyYAML

# windows
pip install PyYAML
# mac
python3 -m pip install PyYAML

在load_file中封装如下代码

#读取yaml文件的数据
def load_yaml_file(filePath):
    with open(file=f'{project_path}{filePath}', mode='r', encoding='UTF-8') as f:
        yaml_content = yaml.load(f, Loader=yaml.FullLoader)
        return yaml_content

#往yaml文件写数据
def write_yaml(filePath, content):
    with open(file=f'{project_path}{filePath}', mode='w', encoding='UTF-8') as f:
        yaml.dump(content, f, Dumper=yaml.Dumper)
  1. 登录接口改为读取yml文件参数化

1、修改portal_login_api.py,把用户名和密码的参数传进去方法中

from api.base_api import BasePortalApi

# 登录接口集成封装的requests接口类
from common.file_load import load_yaml_file


class PortalLoginApi(BasePortalApi):
    portalToken = ''

    def __init__(self, userName, password):
        # 调用父类的初始化数据函数
        super().__init__()
        # 定义登录接口需要传的参数1
        self.url = f'{self.host}/flogin'
        self.json = {
            "userName": userName,
            "password": password
        }
        self.method = 'post'


if __name__ == '__main__':
    data = load_yaml_file('/config/common.yml')
    userName = data['userName']
    password = data['password']
    portalLoginApi = PortalLoginApi(userName, password)
    resp = portalLoginApi.sendRequest()
    print(resp.json())

2.修改conftest.py,使用封装的yml函数参数化读取

# 自定义一个fixture,来实现portal的token的提取和赋值
@pytest.fixture(scope='session',autouse=True)
def get_portal_token():
    data = load_yaml_file('/config/common.yml')
    userName = data['userName']
    password = data['password']
    portalLoginApi = PortalLoginApi(userName,password)
    resp = portalLoginApi.sendRequest()
    BasePortalApi.portalToken = resp.json()['data']['token']

你可能感兴趣的:(自动化测试,python,pytest,自动化)