Debian Codegraph @

doc/en/historical-notes.rst

raw
1 Historical Notes
2 ================
3
4 This page lists features or behavior from previous versions of pytest which have changed over the years. They are
5 kept here as a historical note so users looking at old code can find documentation related to them.
6
7
8 .. _marker-revamp:
9
10 Marker revamp and iteration
11 ---------------------------
12
13 .. versionchanged:: 3.6
14
15 pytest's marker implementation traditionally worked by simply updating the ``__dict__`` attribute of functions to cumulatively add markers. As a result, markers would unintentionally be passed along class hierarchies in surprising ways. Further, the API for retrieving them was inconsistent, as markers from parameterization would be stored differently than markers applied using the ``@pytest.mark`` decorator and markers added via ``node.add_marker``.
16
17 This state of things made it technically next to impossible to use data from markers correctly without having a deep understanding of the internals, leading to subtle and hard to understand bugs in more advanced usages.
18
19 Depending on how a marker got declared/changed one would get either a ``MarkerInfo`` which might contain markers from sibling classes,
20 ``MarkDecorators`` when marks came from parameterization or from a ``node.add_marker`` call, discarding prior marks. Also ``MarkerInfo`` acts like a single mark, when it in fact represents a merged view on multiple marks with the same name.
21
22 On top of that markers were not accessible in the same way for modules, classes, and functions/methods.
23 In fact, markers were only accessible in functions, even if they were declared on classes/modules.
24
25 A new API to access markers has been introduced in pytest 3.6 in order to solve the problems with
26 the initial design, providing the :func:`_pytest.nodes.Node.iter_markers` method to iterate over
27 markers in a consistent manner and reworking the internals, which solved a great deal of problems
28 with the initial design.
29
30
31 .. _update marker code:
32
33 Updating code
34 ~~~~~~~~~~~~~
35
36 The old ``Node.get_marker(name)`` function is considered deprecated because it returns an internal ``MarkerInfo`` object
37 which contains the merged name, ``*args`` and ``**kwargs`` of all the markers which apply to that node.
38
39 In general there are two scenarios on how markers should be handled:
40
41 1. Marks overwrite each other. Order matters but you only want to think of your mark as a single item. E.g.
42 ``log_level('info')`` at a module level can be overwritten by ``log_level('debug')`` for a specific test.
43
44 In this case, use ``Node.get_closest_marker(name)``:
45
46 .. code-block:: python
47
48 # replace this:
49 marker = item.get_marker("log_level")
50 if marker:
51 level = marker.args[0]
52
53 # by this:
54 marker = item.get_closest_marker("log_level")
55 if marker:
56 level = marker.args[0]
57
58 2. Marks compose in an additive manner. E.g. ``skipif(condition)`` marks mean you just want to evaluate all of them,
59 order doesn't even matter. You probably want to think of your marks as a set here.
60
61 In this case iterate over each mark and handle their ``*args`` and ``**kwargs`` individually.
62
63 .. code-block:: python
64
65 # replace this
66 skipif = item.get_marker("skipif")
67 if skipif:
68 for condition in skipif.args:
69 # eval condition
70 ...
71
72 # by this:
73 for skipif in item.iter_markers("skipif"):
74 condition = skipif.args[0]
75 # eval condition
76
77
78 If you are unsure or have any questions, please consider opening
79 :issue:`an issue <new>`.
80
81 Related issues
82 ~~~~~~~~~~~~~~
83
84 Here is a non-exhaustive list of issues fixed by the new implementation:
85
86 * Marks don't pick up nested classes (:issue:`199`).
87
88 * Markers stain on all related classes (:issue:`568`).
89
90 * Combining marks - args and kwargs calculation (:issue:`2897`).
91
92 * ``request.node.get_marker('name')`` returns ``None`` for markers applied in classes (:issue:`902`).
93
94 * Marks applied in parametrize are stored as markdecorator (:issue:`2400`).
95
96 * Fix marker interaction in a backward incompatible way (:issue:`1670`).
97
98 * Refactor marks to get rid of the current "marks transfer" mechanism (:issue:`2363`).
99
100 * Introduce FunctionDefinition node, use it in generate_tests (:issue:`2522`).
101
102 * Remove named marker attributes and collect markers in items (:issue:`891`).
103
104 * skipif mark from parametrize hides module level skipif mark (:issue:`1540`).
105
106 * skipif + parametrize not skipping tests (:issue:`1296`).
107
108 * Marker transfer incompatible with inheritance (:issue:`535`).
109
110 More details can be found in the :pr:`original PR <3317>`.
111
112 .. note::
113
114 in a future major release of pytest we will introduce class based markers,
115 at which point markers will no longer be limited to instances of :py:class:`~pytest.Mark`.
116
117
118 cache plugin integrated into the core
119 -------------------------------------
120
121
122
123 The functionality of the :ref:`core cache <cache>` plugin was previously distributed
124 as a third party plugin named ``pytest-cache``. The core plugin
125 is compatible regarding command line options and API usage except that you
126 can only store/receive data between test runs that is json-serializable.
127
128 .. _historical funcargs and pytest.funcargs:
129
130 funcargs and ``pytest_funcarg__``
131 ---------------------------------
132
133
134
135 In versions prior to 2.3 there was no ``@pytest.fixture`` marker
136 and you had to use a magic ``pytest_funcarg__NAME`` prefix
137 for the fixture factory. This remains and will remain supported
138 but is not anymore advertised as the primary means of declaring fixture
139 functions.
140
141
142 ``@pytest.yield_fixture`` decorator
143 -----------------------------------
144
145
146
147 Prior to version 2.10, in order to use a ``yield`` statement to execute teardown code one
148 had to mark a fixture using the ``yield_fixture`` marker. From 2.10 onward, normal
149 fixtures can use ``yield`` directly so the ``yield_fixture`` decorator is no longer needed
150 and considered deprecated.
151
152
153 ``[pytest]`` header in ``setup.cfg``
154 ------------------------------------
155
156
157
158 Prior to 3.0, the supported section name was ``[pytest]``. Due to how
159 this may collide with some distutils commands, the recommended
160 section name for ``setup.cfg`` files is now ``[tool:pytest]``.
161
162 Note that for ``pytest.ini`` and ``tox.ini`` files the section
163 name is ``[pytest]``.
164
165
166 Applying marks to ``@pytest.mark.parametrize`` parameters
167 ---------------------------------------------------------
168
169
170
171 Prior to version 3.1 the supported mechanism for marking values
172 used the syntax:
173
174 .. code-block:: python
175
176 import pytest
177
178
179 @pytest.mark.parametrize(
180 "test_input,expected", [("3+5", 8), ("2+4", 6), pytest.mark.xfail(("6*9", 42))]
181 )
182 def test_eval(test_input, expected):
183 assert eval(test_input) == expected
184
185
186 This was an initial hack to support the feature but soon was demonstrated to be incomplete,
187 broken for passing functions or applying multiple marks with the same name but different parameters.
188
189 The old syntax is planned to be removed in pytest-4.0.
190
191
192 ``@pytest.mark.parametrize`` argument names as a tuple
193 ------------------------------------------------------
194
195
196
197 In versions prior to 2.4 one needed to specify the argument
198 names as a tuple. This remains valid but the simpler ``"name1,name2,..."``
199 comma-separated-string syntax is now advertised first because
200 it's easier to write and produces less line noise.
201
202
203 setup: is now an "autouse fixture"
204 ----------------------------------
205
206
207
208 During development prior to the pytest-2.3 release the name
209 ``pytest.setup`` was used but before the release it was renamed
210 and moved to become part of the general fixture mechanism,
211 namely :ref:`autouse fixtures`
212
213
214 .. _string conditions:
215
216 Conditions as strings instead of booleans
217 -----------------------------------------
218
219
220
221 Prior to pytest-2.4 the only way to specify skipif/xfail conditions was
222 to use strings:
223
224 .. code-block:: python
225
226 import sys
227
228
229 @pytest.mark.skipif("sys.version_info >= (3,3)")
230 def test_function(): ...
231
232 During test function setup the skipif condition is evaluated by calling
233 ``eval('sys.version_info >= (3,0)', namespace)``. The namespace contains
234 all the module globals, and ``os`` and ``sys`` as a minimum.
235
236 Since pytest-2.4 :ref:`boolean conditions <condition booleans>` are considered preferable
237 because markers can then be freely imported between test modules.
238 With strings you need to import not only the marker but all variables
239 used by the marker, which violates encapsulation.
240
241 The reason for specifying the condition as a string was that ``pytest`` can
242 report a summary of skip conditions based purely on the condition string.
243 With conditions as booleans you are required to specify a ``reason`` string.
244
245 Note that string conditions will remain fully supported and you are free
246 to use them if you have no need for cross-importing markers.
247
248 The evaluation of a condition string in ``pytest.mark.skipif(conditionstring)``
249 or ``pytest.mark.xfail(conditionstring)`` takes place in a namespace
250 dictionary which is constructed as follows:
251
252 * the namespace is initialized by putting the ``sys`` and ``os`` modules
253 and the pytest ``config`` object into it.
254
255 * updated with the module globals of the test function for which the
256 expression is applied.
257
258 The pytest ``config`` object allows you to skip based on a test
259 configuration value which you might have added:
260
261 .. code-block:: python
262
263 @pytest.mark.skipif("not config.getvalue('db')")
264 def test_function(): ...
265
266 The equivalent with "boolean conditions" using ``request.config`` is:
267
268 .. code-block:: python
269
270 @pytest.fixture(autouse=True)
271 def skip_if_no_db(request):
272 if not request.config.getoption("--db", default=False):
273 pytest.skip("--db was not specified")
274
275
276 def test_function():
277 pass
278
279 .. note::
280
281 ``pytest.config`` was removed in pytest 5.0. Use ``request.config``
282 (via the ``request`` fixture) or the ``pytestconfig`` fixture instead.
283 See :ref:`pytest.config global deprecated` for details.
284
285 ``pytest.set_trace()``
286 ----------------------
287
288
289
290 Previous to version 2.4 to set a break point in code one needed to use ``pytest.set_trace()``:
291
292 .. code-block:: python
293
294 import pytest
295
296
297 def test_function():
298 ...
299 pytest.set_trace() # invoke PDB debugger and tracing
300
301
302 This is no longer needed and one can use the native ``import pdb;pdb.set_trace()`` call directly.
303
304 For more details see :ref:`breakpoints`.
305
306 "compat" properties
307 -------------------
308
309
310
311 Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances has long
312 been documented as deprecated, but started to emit warnings from pytest ``3.9`` and onward.
313
314 Users should just ``import pytest`` and access those objects using the ``pytest`` module.