Pytest Learning Tutorial_Basic Knowledge (1)

Preface

pytest is a framework for writing and executing Python unit tests. It provides rich functionality and flexibility, making writing and running tests easy and efficient.

  Some of the main features and explanations of pytest are as follows:

  • Automatically discover tests : pytest will automatically find files, classes, and functions starting with "test_" and identify them as test cases. This avoids manually writing complex test suites.
  • Parameterized tests : pytest supports using the @pytest.mark.parametrize decorator to define parameterized tests. By passing different parameters to the test function, you can easily perform multiple tests and check the results of different input combinations.
  • Assertion support : pytest provides a rich and flexible assertion library to verify whether the expected results are consistent with the actual results. These assertion functions can handle various data types and comparison logic, making writing assertion statements simpler and more intuitive.
  • Fixture : Fixture is a powerful feature of pytest, used to prepare the environment before testing and clean up after testing. Fixtures help you create and manage shared test resources such as database connections, temporary files, and more.
  • Plug-in system : pytest has an extensible plug-in system, and various plug-ins can be added as needed to extend its functionality. These plug-ins can be used to generate test reports, integrate other testing tools, modify the test execution process, etc.

In summary, pytest is a powerful and easy-to-use Python unit testing framework that provides rich features and flexible configuration options, allowing developers to efficiently conduct test-driven development and ensure code quality and reliability.

1. Installation

1. pytest installation

安装命令: pip install -U pytest
查看版本: pytest --version

2. pytest extension plug-in

pip install pytest-cov
pip install pytest-html
pip install pytest-xdist
pip install pytest-repeat
pip install pytest-mock
pip install pytest-selenium
pip install pytest-timeout
pip install pytest-django
pip install pytest-flask
pip install pytest-bdd
pip install pytest-datadir
pip install pytest-ordering
pip install pytest-rerunfailures
pip install pytest-base-url
pip install allure-pytest
pip install pytest-randomly
pip install pytest-asyncio
  • pytest-cov: Generate a test coverage report, showing the parts of the code covered by tests
  • pytest-html: Generate beautiful HTML reports to display test results in a visual form
  • pytest-xdist: Execute tests in parallel on multiple processes or hosts to improve test speed
  • pytest-repeat: Repeat test cases to detect stability and sporadic errors
  • pytest-mock: Easily mock and assert using Mock objects
  • pytest-selenium: Run tests in Selenium for automated end-to-end testing of web applications
  • pytest-timeout: Set the timeout for test running to avoid blocking caused by long-term running
  • pytest-django: Provides support and enhancements for testing Django projects
  • pytest-flask: Provides support and enhancements for testing Flask applications
  • pytest-bdd: Use behavior-driven development (BDD) method to write tests, combined with Gherkin syntax
  • pytest-datadir: access the test data directory while the test is running
  • pytest-ordering: Control the execution order of test functions
  • pytest-rerunfailures: Rerun failed test cases to handle sporadic failures
  • pytest-base-url: Set the base URL for reference in tests of web applications
  • allure-pytest: Generate Allure reports, providing detailed and interactive test results
  • pytest-randomly: Randomizes the execution order of test cases to help discover uncertainty issues
  • pytest-asyncio: supports asynchronous testing and is used to write tests based on asyncio-based asynchronous code

2. Use case design principles

  • File name requirements: Usually pytest will automatically discover files starting with test_ or ending with _test as test files, but it can also be customized through configuration. For example test_example.py or example_test.py both comply with the naming convention.

  • Functions starting with test_: pytest will recognize functions starting with test_ as test cases, these functions should contain the specific behavior or functionality you want to test. For example, def test_addition(): is a test case function starting with test_.

  • Classes starting with Test and methods starting with test_: Another common convention in pytest is that classes starting with Test are used to organize related test cases, and methods starting with test_ in the class are recognized as independent test cases. Note that these methods cannot contain __init__ methods.

  • Use assert for assertion: In pytest, it is recommended to use assert statement for assertion. For example, assert add(2, 3) == 5 can be used to assert whether the result of the add() function is as expected.

3. Code examples

1. Test functions and test classes

# content of test_sample.py
# 测试函数
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 4
# 可以看到pytest自动地运行了test_answer函数,同时提示测试通过,因为func函数的返回值是4


# 测试类,把多条用例放到一个类中
class TestClass:
    def func(self, x):
        return x + 1

    def test_B(self):
        assert self.func(3) == 6, '结果不符合预期'

    def test_A(self):
        assert self.func(3) == 5
# 可以看到,pytest自动地运行了test_B和test_A函数,同时都提示测试失败,\
# 因为TestClass类中的func方法的返回值是4,而不是6和5,所以assert语句报错

Insert image description here

2. Exception handling

# content of test_sample.py
import pytest


def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b


def test_divide():
    with pytest.raises(ZeroDivisionError) as exc_info:
        divide(10, 0)

    assert str(exc_info.value) == "Cannot divide by zero"

In the above example, the divide function is used to perform the division operation. If the divisor b is zero, a ZeroDivisionError exception is thrown. In the test function test_divide, we use the pytest.raises context manager to capture the exception and assert whether its exception information is as expected.

When the pytest command is run to execute the test, it will detect that the divide function raised a ZeroDivisionError exception, and the assertion passes. This indicates that the exception handling mechanism is working properly.

4. Commonly used assertion methods

assert x == y:判断x是否等于y
assert x != y:判断x是否不等于y
assert x > y:判断x是否大于y
assert x < y:判断x是否小于y
assert x >= y:判断x是否大于等于y
assert x <= y:判断x是否小于等于y
assert x 判断x为真
assert not x 判断x不为真
assert item in collection:判断item是否在collection中
assert item not in collection:判断item是否不在collection中

5. Execute orders

1. Pytest execution command

pytest: 运行所有以test_*.py或*_test.py命名的文件中的测试函数。
pytest test_sample.py: 运行指定的test_sample.py文件中的测试函数。
pytest testing/: 运行指定目录下所有以test_*.py命名的文件中的测试函数。
pytest -k "test_B": 按关键字匹配运行包含test_B关键字的测试函数。
pytest test_sample.py::test_B: 运行指定的test_sample.py文件中的test_B函数。
pytest test_sample.py::TestClass::test_B: 运行指定的test_sample.py文件中的TestClass测试类中的test_B方法。

2. Other execution commands

pytest -q: 使用-q/--quiet标志可以使输出保持简短。
pytest -v: 显示每个测试用例的执行结果。
pytest -s: 用于显示测试函数中的print()函数输出。
pytest -x: 第一次遇到错误后停止测试。
pytest --maxfail=2: 遇到两次错误后停止测试。
pytest -rs: -rs选项可以显示测试报告的摘要,包括已跳过的测试、错误和失败的数量以及原因。

6. Directory structure organization

When using Pytest for unit testing, you can organize your test cases according to the following directory structure:

project/
├── src/
│   ├── module1.py
│   └── module2.py
└── tests/
    ├── test_module1.py
    └── test_module2.py
  • project/ is your project root directory
  • The src/ directory stores your source code files
  • module1.py and module2.py are the source code files of the module or function you want to test
  • tests/ directory stores test case files
  • test_module1.py and test_module2.py are
    test case files used to test module1.py and module2.py

You can create more test case files in the tests/ directory as needed, and each file can contain multiple test functions. In the test case file, you can use various assertions and decorators provided by Pytest to write test logic.

Please note that this is just an example of a common organizational structure that you can adapt and extend to suit your project needs.

Guess you like

Origin blog.csdn.net/qq_45664055/article/details/131959799