Skip to content

Commit 6bd32f5

Browse files
authored
Merge pull request #11 from nicoddemus/whats-new-30
What's new in pytest 3.0
2 parents fd55aa8 + 89dcd6e commit 6bd32f5

File tree

1 file changed

+224
-0
lines changed

1 file changed

+224
-0
lines changed
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
Title: What's new in pytest 3.0
2+
Date: 2016-07-12 12:00
3+
Tags: whatsnew
4+
Authors: nicoddemus
5+
Status: draft
6+
Summary: Summary of new the features in pytest 3.0, compared to 2.9.
7+
8+
This blog post provides a short overview of some of the major features and changes in pytest 3.0. See the [CHANGELOG](http://doc.pytest.org/en/latest/changelog.html) for the complete list.
9+
10+
# Additional command alias: `pytest`
11+
12+
pytest came into existence as part of the [py](https://readthedocs.org/projects/pylib/) library, providing a tool called `py.test`.
13+
14+
Even after pytest was moved to a separate project, the `py.test` name for the command-line tool was kept to preserve backward compatibility with existing scripts and tools.
15+
16+
In pytest-3.0 the command-line tool is now called `pytest`, which is easier to type and prevents some common misunderstandings when tools with the same name are installed in the system.
17+
18+
Note that `py.test` still works.
19+
20+
# `approx()`: function for comparing floating-point numbers
21+
22+
The `approx` function makes it easy to perform floating-point comparisons using a syntax that's as intuitive and close to pytest's philosophy:
23+
24+
:::python
25+
from pytest import approx
26+
27+
def test_similar():
28+
v = 0.1
29+
assert (v + 0.2) == approx(0.3)
30+
31+
# `yield` statements in `@pytest.fixture`
32+
33+
Fixtures marked with `@pytest.fixture` can now use `yield` statements to provide values for test functions exactly like fixtures marked with `@pytest.yield_fixture` decorator:
34+
35+
:::python
36+
import smtplib
37+
import pytest
38+
39+
@pytest.fixture(scope="module")
40+
def smtp():
41+
smtp = smtplib.SMTP("smtp.gmail.com")
42+
yield smtp
43+
smtp.close()
44+
45+
This makes it easier to change an existing fixture that uses `return` to use `yield` syntax if teardown code is needed later. Also, many users consider this style more clearer and natural than the previous method of registering a finalizer function using `request.addfinalizer` because the flow of the test is more explicit. Consider:
46+
47+
@pytest.fixture(scope="module")
48+
def smtp(request):
49+
smtp = smtplib.SMTP("smtp.gmail.com")
50+
request.addfinalizer(smtp.close)
51+
return smtp
52+
53+
This change renders `@pytest.yield_fixture` deprecated and makes `@pytest.fixture` with `yield` statements the recommended way to write fixtures which require teardown code.
54+
55+
Note that registering finalizers in `request` is still supported and there's no intention of removing it in future pytest versions.
56+
57+
# `doctest_namespace` fixture
58+
59+
The `doctest_namespace` fixture can be used to inject items into the
60+
namespace in which doctests run. It is intended to be used by
61+
auto-use fixtures to provide names to doctests.
62+
63+
`doctest_namespace` is a standard `dict` object:
64+
65+
:::python
66+
# content of conftest.py
67+
import numpy
68+
@pytest.fixture(autouse=True)
69+
def add_np(doctest_namespace):
70+
doctest_namespace['np'] = numpy
71+
72+
Doctests below the `conftest.py` file in the directory hierarchy can now use the `numpy` module directly:
73+
74+
:::python
75+
# content of numpy.py
76+
def arange():
77+
"""
78+
>>> a = np.arange(10)
79+
>>> len(a)
80+
10
81+
"""
82+
pass
83+
84+
# Fixture `name` parameter
85+
86+
Fixtures now support a `name` parameter which allow them to be accessed by a different name than the function which defines it:
87+
88+
:::python
89+
@pytest.fixture(name='value')
90+
def fixture_value():
91+
return 10
92+
93+
def test_foo(value):
94+
assert value == 10
95+
96+
This solves the problem where the function argument shadows the argument name, which annoys pylint and might cause bugs if one forgets to pull a fixture into a test function.
97+
98+
# Disable capture within a test
99+
100+
`capsys` and `capfd` fixtures now support a `disabled` context-manager method which can be used to disable output capture temporarily within a test or fixture:
101+
102+
:::python
103+
def test_disabling_capturing(capsys):
104+
print('this output is captured')
105+
with capsys.disabled():
106+
print('output not captured, going directly to sys.stdout')
107+
print('this output is also captured')
108+
109+
# `pytest.raises`: regular expressions and custom messages
110+
111+
The `ExceptionInfo.match` method can be used to check exception messages using regular expressions, similar to `TestCase.assertRaisesRegexp` method
112+
from `unittest`:
113+
114+
:::python
115+
import pytest
116+
117+
def myfunc():
118+
raise ValueError("Exception 123 raised")
119+
120+
def test_match():
121+
with pytest.raises(ValueError) as excinfo:
122+
myfunc()
123+
excinfo.match(r'.* 123 .*')
124+
125+
The regexp parameter is matched with the `re.search` function.
126+
127+
Also, the context manager form accepts a `message` keyword parameter to raise a custom message when the expected exception does not occur:
128+
129+
:::python
130+
def check_input(val):
131+
if input == "b":
132+
raise KeyError
133+
134+
@pytest.mark.parametrize('val', ["a", "b", "c"])
135+
def test_inputs(val):
136+
with pytest.raises(KeyError, message="Key error not raised for {}".format(val)):
137+
check_input(val)
138+
139+
# New hooks
140+
141+
pytest-3.0 adds new hooks, useful both for plugin authors and local `conftest.py` plugins:
142+
143+
* `pytest_fixture_setup(fixturedef, request)`: executes the fixture setup;
144+
* `pytest_fixture_post_finalizer(fixturedef)`: called after the fixture's finalizer and has access to the fixture's result cache;
145+
* `pytest_make_parametrize_id(config, val)`: allow plugins to provide user-friendly strings for custom types to be used by `@pytest.mark.parametrize` calls;
146+
147+
Complete documentation for all pytest hooks can be found in the [hooks documentation](doc.pytest.org/en/latest/writing_plugins.html).
148+
149+
# Parametrize changes
150+
151+
Parametrize ids can now be set to `None`, in which case the automatically generated id will be used:
152+
153+
:::python
154+
import pytest
155+
@pytest.mark.parametrize(("a,b"), [(1,1), (1,1), (1,2)],
156+
ids=["basic", None, "advanced"])
157+
def test_function(a, b):
158+
assert a == b
159+
160+
This will result in the following tests:
161+
162+
* `test_function[basic]`
163+
* `test_function[1-1]`
164+
* `test_function[advanced]`
165+
166+
# New command line options
167+
168+
* `--fixtures-per-test`:
169+
Shows which fixtures are being used for each selected test item. Features doc strings of fixtures by default. Can also show where fixtures are defined if combined with `-v`.
170+
171+
* `--setup-show`:
172+
Performs normal test execution and additionally shows the setup and teardown of fixtures.
173+
174+
* `--setup-plan`:
175+
Performs normal collection and reports the potential setups and teardowns, but does not execute fixtures and tests.
176+
177+
* `--setup-only`:
178+
Performs normal collection, executes setup and teardown of fixtures and reports them.
179+
180+
* `--override-ini`/`-o`:
181+
Overrides values from the configuration file (`pytest.ini`). For example, `"-o xfail_strict=True"` will make all `xfail` markers act as `strict`, failing the test suite if they exit with `XPASS` status.
182+
183+
* `--pdbcls`:
184+
Allow passing a custom debugger class that should be used together with the `--pdb` option. Syntax is in the form `<module>:<class:`, for example `--pdbcls=IPython.core.debugger:Pdb`.
185+
186+
* `--doctest-report`:
187+
Changes the diff output format for doctests, can be one of: `none`, `udiff`, `cdiff`, `ndiff` or `only_first_failure`.
188+
189+
190+
# Assert reinterpretation is gone
191+
192+
Assertion reinterpretation was the preferred method to display better assertion meessages before assertion rewriting was implemented. Assertion rewriting is safer because there is no risk of introducing subtle errors because of assertions with side-effects. The `--assert=reinterp` option has also been removed.
193+
194+
See this [excellent blog post](http://pybites.blogspot.com.br/2011/07/behind-scenes-of-pytests-new-assertion.html) by Benjamin Peterson for a great overview of the assertion-rewriting mechanism.
195+
196+
In addition to this change, assertion rewriting is now also applied automatically in `conftest.py` files and plugins installed using `setuptools`.
197+
198+
# Feature Deprecation
199+
200+
The pytest team took the opportunity to discuss how to handle feature deprecation during the [pytest 2016 sprint]({filename}pytest-development-sprint.md), intending to minimize impact on the users as well as slowly fade-out some outdated features. It was decided:
201+
202+
## Internal pytest-warnings now are displayed by default
203+
204+
Not showing them by default is confusing to users, as most people don't know how to display them in the first place. Also, it will help wider adoption of new ways of using pytest's features.
205+
206+
## Deadline for deprecated features: new major version
207+
208+
Following [semantic versioning](http://semver.org/), the pytest team will add deprecation warnings to features which are considered obsolete because there are better alternatives or usage is low while maintenance burden on the team is high. Deprecated features will only be removed on the next **major** release, for example pytest-4.0, giving users and plugin authors ample time to update.
209+
210+
## Deprecated features
211+
212+
The following features have been considered officially deprecated in pytest-3.0, emitting pytest-warnings when used and scheduled for removal in 4.0:
213+
214+
* `yield-based` tests; use `@pytest.mark.parametrize` instead;
215+
* `pytest_funcarg__` prefix to declare fixtures; use `@pytest.fixture` decorator instead;
216+
* `--resultlog`: this option was rarely used and there are more modern alternatives;
217+
218+
# Small improvements and bug-fixes
219+
220+
As usual, this release includes a lot of small improvements and bug fixes. Make sure to checkout the full [CHANGELOG](http://doc.pytest.org/en/latest/changelog.html) for the complete list.
221+
222+
223+
224+

0 commit comments

Comments
 (0)