pytest数据驱动及conftest文件及装饰器使用(一)

简介: pytest数据驱动及conftest文件及装饰器使用

一:数据驱动

file_operate.py文件

# coding=utf-8
"""
    @Project :pachong-master 
    @File    :file_operate.py
    @Author  :gaojs
    @Date    :2022/7/1 23:00
    @Blogs   : https://www.gaojs.com.cn
"""
import openpyxl as xl
import yaml
def read_excel(filepath, sheet_name):
    """
    读取数据,将其转换成所需格式
    :return:
    """
    # 得到整个excel文档对象
    wb = xl.load_workbook(filepath)
    # 获取某个sheet工作表数据
    sheet_data = wb[sheet_name]
    # 定义空列表,用来存储多行数据,每行数据都是一个列表
    data = []
    # 得到总行数
    lines_count = sheet_data.max_row
    # 得到总列数
    cols_count = sheet_data.max_column
    for li in range(2, lines_count+1):
        line = []
        for co in range(1, cols_count+1):
            cell = sheet_data.cell(li, co).value
            if cell is None:
                cell = ''
            line.append(cell)
        data.append(line)
    return data
def write_excel(filepath, sheet_name, row, col, text):
    """
    写入内容
    :return:
    """
    wb = xl.load_workbook(filepath)
    sheet_data = wb[sheet_name]
    # 写入数据
    sheet_data.cell(row=row, column=col, value=text)
    wb.save(filepath)
def read_yaml(filepath):
    """
    读取yaml文件
    :return:
    """
    with open(filepath, mode='r', encoding='utf-8') as fin:
        content = yaml.load(fin, Loader=yaml.FullLoader)
        return content
def write_yaml(filepath, text):
    """
    写入文件内容
    :return:
    """
    with open(filepath, mode='w', encoding='utf-8') as fin:
        yaml.dump(text, fin, Dumper=yaml.Dumper)
if __name__ == '__main__':
    # print(read_excel('./test_data.xlsx', '数据驱动数据'))
    # write_excel('./test_data.xlsx', '数据驱动数据', row=6, col=6, text='gaojianshuai')
    print(read_yaml('./test_data.yml').get('数据驱动数据'))
    write_yaml('./test_data1.yml', {'userName': 'gaojs', 'password': '1234'})

test_data.yml文件

# 数据驱动接口数据
数据驱动数据:
  - ['admin', 1234, 200, 0, 'success']
  - ['', 1234, 200, 1, '参数为空']
  - ['admin', '', 200, 1, '参数为空']

二、pytest记录

conftest.py文件

# coding=utf-8
"""
    @Project :pachong-master 
    @File    :conftest.py
    @Author  :gaojs
    @Date    :2022/6/30 21:47
    @Blogs   : https://www.gaojs.com.cn
"""
from typing import List
import pytest
import requests
from 码同学.requests_study.cookie_study import login
@pytest.fixture(scope='session', autouse=True)
def login_and_logout():
    print('在conftest.py中定义fixture,自动执行')
    login(userName='admin', password='1234')
    print('在档次执行测试中只执行一次,因为作用域是session')
    yield
    print('在当前执行测试只执行一次后置动作,因为作用域是session')
# 重写pytest的一个hook函数,处理pycharm插件界面显示的执行结果乱码
def pytest_collection_modifyitems(items:List["item"]):
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode-escape")
        item._nodeid = item._nodeid.encode("utf-8").decode("unicode-escape")
@pytest.fixture(scope='module', autouse=True)
def VPN0():
    print('在conftest.py中定义fixture,自动执行')
    login(userName='admin', password='1234')
    print('在当前每个用例执行一次,因为作用域是module')
    yield
    print('在当前每个用例执行后执行一次,因为作用域是module')

pytest.ini

不能有中文

[pytest]
addopts = -sv -n auto --dist=loadfile
testpaths = ./
python_files = test*.py
python_classes = Test*
python_functions = test_*

test_param_caresian.py

# coding=utf-8
"""
    @Project :pachong-master 
    @File    :test_param_login.py
    @Author  :gaojs
    @Date    :2022/6/30 22:44
    @Blogs   : https://www.gaojs.com.cn
"""
import pytest
import requests
# 第一步:将测试数据转换成python中列表套列表的格式
from 码同学.requests_study.cookie_study import login
from 码同学.requests_study.put_api_study import post_update_phone_info
# 第二:使用pytest装饰器,将其传递给测试用例函数
brand = ['Apple', 'xiaomi', 'sanxing']
color = ['red', 'yellow', 'black']
memorySize = ['256G', '128G', '64G', '512G']
cpuCore=['8核', '4核', '16核']
expect_status_code = [200]
expect_code = ['0']
expect_message = ['更新成功']
@pytest.mark.parametrize('brand', brand)
@pytest.mark.parametrize('color', color)
@pytest.mark.parametrize('memorySize', memorySize)
@pytest.mark.parametrize('cpuCore', cpuCore)
@pytest.mark.parametrize('expect_status_code', expect_status_code)
@pytest.mark.parametrize('expect_code', expect_code)
@pytest.mark.parametrize('expect_message', expect_message)
def test_put(brand, color, memorySize, cpuCore, expect_status_code, expect_code, expect_message):
    """
    笛卡尔积参数化
    :return:
    """
    resp = post_update_phone_info(brand=brand, color=color, memorySize=memorySize, cpuCore=cpuCore)
    status_code = resp.status_code
    assert status_code == expect_status_code
    # 断言code
    resp_json = resp.json()
    code = resp_json['code']
    assert code == expect_code
    # message断言
    result = resp_json['message']
    assert result == expect_message
# 异常组合不适合笛卡尔积,只能对有效值多个值进行使用

test_param_login.py

# coding=utf-8
"""
    @Project :pachong-master 
    @File    :test_param_login.py
    @Author  :gaojs
    @Date    :2022/6/30 22:44
    @Blogs   : https://www.gaojs.com.cn
"""
import pytest
import requests
from ..datadriver.file_operate import read_yaml, read_excel
# 第一步:将测试数据转换成python中列表套列表的格式
from 码同学.requests_study.cookie_study import login
# 第一种数据给定:指定在文件中
# test_data = [
#     ['admin', '1234', 200, '0', 'success'],
#     ['', '1234', 200, '1', '参数为空'],
#     ['admin', '', 200, '1', '参数为空']
# ]
# 第二种,通过调用file_operate文件中的方法读取excel数据
# test_data = read_excel(r'E:\爬虫\pachong-master\码同学\datadriver\test_data.xlsx', '数据驱动数据')
test_data = read_yaml(r'E:\爬虫\pachong-master\码同学\datadriver\test_data.yml').get('数据驱动数据')
print(test_data)
@pytest.mark.parametrize('userName, password, expect_status_code, expect_code, expect_message', test_data)
def test_login_param(userName, password, expect_status_code, expect_code, expect_message):
    """
    数据驱动:登录测试
    :return:
    """
    resp = login(userName=userName, password=password)
    status_code = resp.status_code
    assert status_code == expect_status_code
    # 断言code
    resp_json = resp.json()
    code = resp_json['code']
    assert code == expect_code
    # message断言
    result = resp_json['message']
    assert result == expect_message

test_by_func.py

# coding=utf-8
"""
    @Project :pachong-master 
    @File    :test_by_func.py
    @Author  :gaojs
    @Date    :2022/6/30 21:55
    @Blogs   : https://www.gaojs.com.cn
"""
# 以函数形式编写测试用例
# 测试用例
from 码同学.requests_study.cookie_study import login
def test_login():
    """
    登录测试用例
    :return:
    """
    resp = login(userName='admin', password='1234')
    status_code = resp.status_code
    assert status_code == 200
    # 业务断言,
    resp_json = resp.json()
    # print(resp_json)
    code = resp_json['code']
    assert code == '0'
    result = resp_json['message']
    assert result == 'success'
def test_login_userisnull():
    """
    登录测试用例
    :return:
    """
    resp = login(userName='', password='1234')
    status_code = resp.status_code
    assert status_code == 200
    # 业务断言,
    resp_json = resp.json()
    print(resp_json)
    code = resp_json['code']
    assert code == '1'
    result = resp_json['message']
    assert result == '参数为空'
# 运行代码方式
"""
1.运行单个用例
pytest .\码同学\pytest_study\test_by_class.py::TestLogin::test_login_userisnull
2.运行整个类下 的所有用例
pytest -sv .\码同学\pytest_study\test_by_class.py
3.右键执行所有用例:光标放在所有第一个方法顶部
4.右键执行某一个用例:贯标放在对应的函数上
"""

test_by_class.py

# coding=utf-8
"""
    @Project :pachong-master 
    @File    :test_by_class.py
    @Author  :gaojs
    @Date    :2022/6/30 21:55
    @Blogs   : https://www.gaojs.com.cn
"""
# 以类形式编写测试用例
# 测试用例
from 码同学.requests_study.cookie_study import login
class TestLogin:
    # 测试用例1
    def test_login(self):
        """
        登录测试用例
        :return:
        """
        resp = login(userName='admin', password='1234')
        status_code = resp.status_code
        assert status_code == 200
        # 业务断言,
        resp_json = resp.json()
        # print(resp_json)
        code = resp_json['code']
        assert code == '0'
        result = resp_json['message']
        assert result == 'success'
    # 测试用例2
    def test_login_userisnull(self):
        """
        登录测试用例
        :return:
        """
        resp = login(userName='', password='1234')
        status_code = resp.status_code
        assert status_code == 200
        # 业务断言,
        resp_json = resp.json()
        print(resp_json)
        code = resp_json['code']
        assert code == '1'
        result = resp_json['message']
        assert result == '参数为空'
# 运行代码方式
"""
1.运行单个用例
pytest .\码同学\pytest_study\test_by_class.py::TestLogin::test_login_userisnull
2.运行整个类下 的所有用例
pytest -sv .\码同学\pytest_study\test_by_class.py
3.右键执行所有用例
"""
相关文章
|
8天前
pytest命令行传递参数excelpath实现数据驱动
pytest命令行传递参数excelpath实现数据驱动
52 0
|
8天前
|
测试技术 Python
pytest中的fixture和conftest.py
pytest中的fixture和conftest.py
|
8月前
|
测试技术 数据库连接 Python
conftest.py是什么?该怎么用?
conftest.py是什么?该怎么用?
113 0
06-pytest-fixture的三种调用方式
06-pytest-fixture的三种调用方式
|
10月前
|
测试技术
34-pytest-Hooks函数之获取用例执行结果
34-pytest-Hooks函数之获取用例执行结果
|
10月前
|
测试技术 Python
05-pytest-通过confest.py共享fixture
05-pytest-通过confest.py共享fixture
|
12月前
|
测试技术
pytest conftest.py和fixture的配合使用
pytest conftest.py和fixture的配合使用
|
12月前
|
测试技术 Python
pytest fixture装饰器
pytest fixture装饰器
|
测试技术
pytest学习和使用9-fixture中conftest.py如何使用?
pytest学习和使用9-fixture中conftest.py如何使用?
104 0
pytest学习和使用9-fixture中conftest.py如何使用?

热门文章

最新文章