pytest框架介绍

1、什么是pytest

pytest是一个基于Python的测试框架,用于编写和执行测试代码。
pytest应用在自动化测试场合、单元自动化测试、API自动化测试、web/app自动化测试等领域。
可以使用pytest来编写代码来测试API、数据库、UI等。

1.1 pytest的特点和优点

1.pytest是免费和开源的
2.pytest有活跃的社区和维护组织
3.pytest的语法简单灵活,容易上手
4.支持参数化,也就是支持数据驱动
5.支持测试用例的skip和xfail处理
6.pytest可以自动检测测试文件和测试功能
7.pytest允许我们运行整个测试套件的一部分
8.能够支持简单的单元测试和复杂的功能测试
【pytest可以与selenium/appnium等一切进行UI自动化测试】
【pytest可以与Requests一起进行接口自动化测试】
9.可以很好地和Jenkins集成
10.具有很多第三方插件,并且可以自动化扩展
11.pytest-allure可以生成完美的HTML测试报告
12.可以并行运行多个测试,从而减少测试套件的测试时间(pytest-xdist)
13.与以前的测试框架兼容,可执行由Unittest、Nose所写的测试脚本

2、pytest的环境准备

pytest是一个基于python的框架,需要安装在python上。

2.1 pytest安装

安装最新版本的pytest

pip install pytest

3、pytest的setup与teardown框架结构

pytest提供了相对自由和层次丰富的setup与teardown框架结构。

setup() —— 用于测试前的准备工作
teardown() —— 用于测试结束后的清理工作

pytest支持5个层次的setupteardown,包括:session会话级、module模块级、function函数级、class类级、method方法级

  1. 模块级setup_module/teatrdown_module):在模块文件开始和结束只执行一次(不在类中)
  2. 函数级setup_function/teatrdown_function):每个非类函数测试用例开始前和结束后都会执行一次(不在类中)
  3. 方法级setup_method/teatrdown_method):每个类中的测试用例方法开始和结束前都会执行一次(在类中)
  4. 类级setup_class/teatrdown_class):每个类的前后运行一次(在类中)
  5. 兼容类/函数方法setup/teardown):兼容在类中,在每个测试用例方法前后都会执行一次
import pytest

# 模块中的方法
def setup_module(module):
    """在模块中的所有测试函数执行之前运行一次"""
    print("\n--- 设置:在模块测试开始前执行 ---")

def teardown_module(module):
    """在模块中的所有测试函数执行完毕后运行一次"""
    print("\n--- 清理:在模块测试结束后执行 ---")

# 模块中的测试用例
def test_example1():
    print("运行测试用例 1")
    assert True

def test_example2():
    print("运行测试用例 2")
    assert True

# 函数级,不在类中
def setup_function(function):
    # setup 操作
    print(f"\n设置测试环境: {function.__name__}")

def teardown_function(function):
    # teardown 操作
    print(f"\n清理测试环境: {function.__name__}")

def test_case_1():
    # 测试用例代码
    print("执行测试用例 1")
    assert True

def test_case_2():
    # 测试用例代码
    print("执行测试用例 2")
    assert True

类级(setup_class/teatrdown_class)示例:

import pytest
class TestMyClass:

    @classmethod
    def setup_class(cls):
        """该方法将在所有测试开始之前被调用一次"""
        print('setup_class: 在所有测试开始前执行')

    @classmethod
    def teardown_class(cls):
        """该方法将在所有测试结束后被调用一次"""
        print('teardown_class: 在所有测试结束后执行')

    def setup_method(self, method):
        """每个测试方法执行前都会调用此方法"""
        print(f'setup_method: {method.__name__}')

    def teardown_method(self, method):
        """每个测试方法执行后都会调用此方法"""
        print(f'teardown_method: {method.__name__}')

    def test_example1(self):
        print('test_example1: 执行测试用例1')
        assert 1 == 1

    def test_example2(self):
        print('test_example2: 执行测试用例2')
        assert True


if __name__ == "__main__":
    import pytest
    pytest.main()

4、pytest执行查找原则

使用pytest执行测试时候,了解如何执行特定的测试,对于高效开发和维护测试套件至关重要。

在命令行中,使用pytest命令来运行测试。

pytest test_01.py
pytest tests/

使用-k选项过滤测试
如果只想运行包含特定名称或标记的测试,可以使用-k选项:

pytest -k test_name

使用-m选项根据标记运行测试
pytest允许使用标记(marker)来标记特定的测试或测试集合,可以使用-m选项来运行这些标记的测试:

pytest -m slow

5、测试类及测试方法命名原则

5.1 测试文件命名

测试文件与被测的模块或类芳在同一个目录下,并且文件名以test_开头。例如:test_app.py

5.2 测试类命名

使用类来组织你的测试(特别是在使用一些特定的框架如unittest时),类名通常以Test开头。

class TestMyModule:
    def test_something(self):
        assert True

5.3 测试方法命名

函数名:对于基于函数的测试,函数名应该以test_开头。例如:

def test_functionality():
    assert True

方法名:如果你使用类来组织你的测试,则方法名也应该以test_开头。例如:

class TestClass:
    def test_method(self):
        assert True
### Pytest Framework Detailed Introduction and Overview Pytest is an advanced feature-rich library that makes it easy to write simple and scalable test cases for database applications or web services[^1]. The simplicity of writing unit tests using pytest represents just one aspect; indeed, software testing encompasses multiple dimensions such as integration testing, acceptance testing, and regression testing. #### Key Features of Pytest - **Simplicity**: Writing tests becomes straightforward without requiring boilerplate code. - **Scalability**: Supports both small-scale projects and large systems by providing tools like fixtures which allow setup/teardown operations before running individual tests or groups thereof. - **Extensibility via Plugins**: A rich ecosystem exists around pytest through plugins extending its core functionality. For instance, `pytest-django` integrates seamlessly into Django-based workflows while others support specific databases or reporting formats. ```python import pytest def add(a, b): return a + b @pytest.mark.parametrize( 'a,b,output', [ (2, 3, 5), (-1, 1, 0), (7, -8, -1) ] ) def test_addition_functionality(a, b, output): assert add(a, b) == output ``` This example demonstrates how parametrization allows executing the same function against different inputs efficiently within pytest's framework structure. #### Beyond Unit Tests While starting with basic units provides foundational skills necessary when learning about automated checks in programming languages like Python—it barely scratches surface-level capabilities offered today. Exploring further reveals more sophisticated forms beyond mere verification at method level alone: - Integration Testing ensures components work together correctly after being combined. - Acceptance Testing focuses on validating end-to-end scenarios from user perspective ensuring requirements met satisfactorily. - Regression Testing guarantees changes do not break existing functionalities unexpectedly during development cycles. To deepen understanding regarding these topics specifically tailored towards pythonic implementations consider exploring resources dedicated entirely toward mastering this domain.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值