温馨提示×

python的pytest用法是什么

小亿
85
2024-12-05 10:52:36
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

pytest 是一个流行的 Python 测试框架,用于编写和执行各种类型的测试,包括单元测试、集成测试和功能测试。以下是 pytest 的一些基本用法:

  1. 安装 pytest

    首先,确保你已经安装了 pytest。如果没有,可以使用以下命令安装:

    pip install pytest
    
  2. 编写测试用例

    在你的项目中创建一个名为 test_*.py*_test.py 的文件,并在其中编写测试用例。测试用例应该以 test_ 开头,并使用 assert 语句进行断言。例如:

    # test_example.py
    
    def test_addition():
        assert 1 + 1 == 2
    
    def test_subtraction():
        assert 3 - 2 == 1
    
  3. 运行测试用例

    在命令行中,导航到包含测试文件的目录,然后运行以下命令:

    pytest
    

    pytest 会自动发现并运行所有以 test_ 开头的文件中的测试用例。

  4. 使用参数化测试

    pytest 支持参数化测试,允许你使用不同的输入数据运行相同的测试逻辑。例如:

    # test_example.py
    
    import pytest
    
    @pytest.mark.parametrize("input1, input2, expected_output", [
        (2, 2, 4),
        (3, 3, 9),
        (0, 0, 0)
    ])
    def test_power(input1, input2, expected_output):
        assert input1 ** input2 == expected_output
    
  5. 使用 fixtures

    pytest 的 fixtures 功能允许你创建可重用的测试环境设置和清理代码。例如:

    # conftest.py
    
    import pytest
    
    @pytest.fixture
    def example_fixture():
        return "example data"
    
    # test_example.py
    
    def test_example_case(example_fixture):
        assert example_fixture == "example data"
    
  6. 使用 mock 和 patch

    pytest 支持使用 mockpatch 装饰器来模拟函数和类。例如:

    # test_example.py
    
    from unittest.mock import Mock
    import pytest
    
    @pytest.fixture
    def mock_function():
        with pytest.MonkeyPatch() as mp:
            mock = Mock()
            mp.setattr("your_module.your_function", mock)
            yield mock
    
    def test_example_case(mock_function):
        your_module.your_function()
        mock_function.assert_called_once()
    

这只是 pytest 的一些基本用法。你还可以查阅 pytest 官方文档 以了解更多高级功能和用法。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python pytest最佳实践是什么

0