Learning Pytest

如何编写pytest测试样例

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 __init__ 方法
  • 测试函数以test_开头
  • 断言使用基本的assert即可
 $ pip3 install -U pytest
 $ pip3 install pytest-html
 $ pip3 install pytest-xdist
 $ pytest --version

 $ pytest
 $ pytest test_failure.py 

 $ pytest -q
 $ pytest -v

 $ pytest -k greate
 $ pytest -m others -v

 $ pytest -n 3
 $ pytest test_failure.py -v --maxfail=1
 $ pytest test_failure.py -v --maxfail=2
 $ pytest test_failure.py -v --maxfail=3

 $ pytest --junitxml="result.xml"
 $ pytest --html="report.html"

Refer: https://www.tutorialspoint.com/pytest/pytest_quick_guide.htm

Pytest - Introduction

Pytest is a python based testing framework, which is used to write and execute test codes. In the present days of REST services, pytest is mainly used for API testing even though we can use pytest to write simple to complex tests, i.e., we can write codes to test API, database, UI, etc.

Advantages of Pytest

The advantages of Pytest are as follows −

  • Pytest can run multiple tests in parallel, which reduces the execution time of the test suite.

  • Pytest has its own way to detect the test file and test functions automatically, if not mentioned explicitly.

  • Pytest allows us to skip a subset of the tests during execution.

  • Pytest allows us to run a subset of the entire test suite.

  • Pytest is free and open source.

  • Because of its simple syntax, pytest is very easy to start with.

In this tutorial, we will explain the pytest fundamentals with sample programs.

Identifying Test files and Test Functions

Running pytest without mentioning a filename will run all files of format test_*.py or *_test.py in the current directory and subdirectories. Pytest automatically identifies those files as test files. We can make pytest run other filenames by explicitly mentioning them.

Pytest requires the test function names to start with test. Function names which are not of format test* are not considered as test functions by pytest. We cannot explicitly make pytest consider any function not starting with test as a test function.

We will understand the execution of tests in our subsequent chapters.

Pytest - Summary

In this pytest tutorial, we covered the following areas −

  • Installing pytest..
  • Identifying test files and test functions.
  • Executing all test files using pytest –v.
  • Executing specific file usimng pytest -v.
  • Execute tests by substring matching pytest -k -v.
  • Execute tests based on markers pytest -m -v.
  • Creating fixtures using @pytest.fixture.
  • conftest.py allows accessing fixtures from multiple files.
  • Parametrizing tests using @pytest.mark.parametrize.
  • Xfailing tests using @pytest.mark.xfail.
  • Skipping tests using @pytest.mark.skip.
  • Stop test execution on n failures using pytest --maxfail = .
  • Running tests in parallel using pytest -n .
  • Generating results xml using pytest -v --junitxml = "result.xml".

你可能感兴趣的:(Learning,入门指南)