Python自动化测试框架-pytest

Python自动化测试框架-pytest

源码: https://github.com/pytest-dev/pytest
文档: https://docs.pytest.org/en/8.2.x/

安装: pip install pytest
查看版本: pytest -V

简单样例

# content of test_sample.py
def inc(x):
    return x + 1

def test_answer():
    assert inc(3) == 5

命令行执行pytest可以看到执行结果

命名规范

  • 测试模块: 文件以test_开头
  • 测试类: 以Test开头
  • 测试方法: 函数以test开头
# content of test_class.py
class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, "check")

执行方式

# 帮助命令
pytest -h

# 测试单个文件
pytest test_mod.py

# 测试文件夹下的用例
pytest testing/

# 执行关键字表达式
# 执行 TestMyClass.test_something, 不执行 TestMyClass.test_method_simple
pytest -k 'MyClass and not method'

# 查看用例的print输出
pytest -s

常用功能

1.数据驱动测试

准备多组数据,在一条用例中测试

# content of test_expectation.py
import pytest

@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

从文件中读取数据,如test_data.csv文件

input,expected
1,True
-2,False
3,True
0,False
import pytest
import csv


def load_csv_data(file_path):
    with open(file_path, 'r') as f:
        reader = csv.reader(f)
        next(reader)  # 跳过标题行
        return [(int(row[0]), row[1] == 'True') for row in reader]


@pytest.mark.parametrize("number,expected", load_csv_data('test_data.csv'))
def test_is_positive(number, expected):
    assert (number > 0) == expected

2.fixture装饰器

在pytest中,@pytest.fixture用于将一个函数标记为一个fixture。
Fixture是一种可以为测试函数提供可重复使用的初始化代码或者资源的机制。避免在每个测试函数中重复编写相同的初始化或清理代码,提高了代码的可维护性和可重复性.

import pytest

# 定义一个简单的fixture,返回一个值
@pytest.fixture
def setup():
    print("\nSetup for test")
    yield 10  # yield之后的代码作为清理操作
    print("\nTeardown after test")

# 使用fixture
def test_fixture_example(setup):
    assert setup == 10

3.生成测试报告

可以使用pytest-html插件来生成包含详细信息的html报告

# 安装pytest-html
pip install pytest-html

# 运行并生成测试报告,文件保存在当前路径下
pytest --html=report.html

生成JUnit/XML格式的报告,通常用于与持续集成系统(如Jenkins)集成,使测试结果能够被轻松地解析和显示。

pytest --junitxml=report.xml

参考文档: https://blog.csdn.net/qadnkz/article/details/136333732

posted @ 2024-06-15 23:23  rustling  阅读(10)  评论(0编辑  收藏  举报