Installation and Getting Started
Python support version: Python 2.6, 2.7, 3.3, 3.4, 3.5, Jython, PyPy-2.3
Supported platforms: Unix/Posix and Windows
PyPI package name: pytest
Dependencies: py,colorama (Windows)
PDF document: Download the latest version of the document
Pytest is a framework that makes it very convenient to create simple and extensible test cases. Test cases are clear and readable without a lot of cumbersome code. In just a few minutes you can run a small unit test or a complex functional test of your application or library.
Install pytest
Execute the following command on the command line
pip install -U pytest
Check installed version of pytest
$ pytest --version
This is pytest version 3.x.y,imported from $PYTHON_PREFIX/lib/python3.6/site-packages/pytest.py
Create your first test case
It only takes 4 lines of code to create a simple test case
# test_sample.py文件内容
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
It's that simple. Now you can execute this test case:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y,pytest-3.x.y,py-1.x.y,pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR,inifile:
collected 1 item
test_sample.py F [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================
Since func(3) is not equal to 5, this test returns a failure result message.
Note:
You can use the assert statement to assert the expected results of your test cases. Pytest's advanced assertion introspection mechanism can intelligently display the intermediate results of assertion expressions to avoid the problem of repeated variable names in methods derived from JUnit.
Execute multiple test cases
The pytest command will execute all test_.py and _test.py files in the current directory and subdirectories . In general, use cases need to follow standard test discovery rules.
Assert that the specified exception was thrown
Use raise to throw the specified exception in the corresponding code:
# test_sysexit.py文件内容
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
Using "silent" mode, execute this test with, for example:
$ pytest -q test_sysexit.py
. [100%]
1 passed in 0.12 seconds
Use classes to organize multiple test cases
Once you need to develop multiple test cases, you may want to use classes to organize them. Using Pytest, it is easy to create a test class that contains multiple test cases:
# test_class.py文件内容
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x,'check')
Pytest can find all use cases that follow the Python test case discovery convention rules, so it can find all functions and methods starting with test_ outside the test class beginning with Test and in the class. The test class no longer needs to inherit any objects. We simply need to run the module by its filename.
$ pytest -q test_class.py
.F [100%]
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________
self = <test_class.TestClass object at 0xdeadbeef>
def test_two(self):
x = "hello"
> assert hasattr(x,'check')
E AssertionError: assert False
E + where False = hasattr('hello','check')
test_class.py:8: AssertionError
1 failed,1 passed in 0.12 seconds
The first use case was executed successfully, and the second use case failed. You can easily understand why it failed by looking at the intermediate values of the variables in the assertion.
Request to use a separate temporary directory in function tests
Pytest provides built-in fixtures method arguments to use arbitrary resources, such as a separate temporary directory:
# test_tmpdir.py文件内容
def test_needsfiles(tmpdir):
print (tmpdir)
assert 0
When the test case function uses tmpdir as a parameter, Pytest will find and call the fixture factory method to create the corresponding resource before the test case function call. Before the tests are run, Pytest creates a separate temporary directory for each test case:
$ pytest -q test_tmpdir.py
F [100%]
================================= FAILURES =================================
_____________________________ test_needsfiles ______________________________
tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')
def test_needsfiles(tmpdir):
print (tmpdir)
> assert 0
E assert 0
test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles0
1 failed in 0.12 seconds
For more information on tmpdir handling, see: Temporary Directories and Files
further reading
Check out other pytest documentation resources to help you build custom test cases and unique workflows:
- "Invoke pyest with pytest -m pytest" - command line invocation example
- "Using pytest with legacy test suite" - use the previous test case
- "Marking test cases with attributes" - pytest.mark related information
- "pytest fixtures: explicit, modular, extensible" - Functional benchmarks for your tests
- "Plugin Authoring" - managing and authoring plugins
- "Good Integration Practices" - Virtual Environments and Test Layering
In the end, many friends have the idea of learning. Here I shared the video tutorial of the test on station B. You can watch it by yourself:
Advanced learning of automated testing:
Zero-based software testing learning:
Public account fan benefits
-
Get a full set of software testing resources for free
-
Software testing interview question brushing applet is free to use
-
Free use of GPT exclusively for testers