Pytest PDF
Pytest PDF
Release 2.7.1
CONTENTS
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
3
4
7
11
16
17
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
21
21
25
28
32
46
47
51
53
54
56
59
60
61
66
66
69
70
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
73
73
74
74
74
75
75
76
76
76
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
77
79
5.1
5.2
5.3
5.4
5.5
5.6
5.7
5.8
5.9
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
79
79
80
80
81
81
81
82
82
85
89
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
93
93
103
115
122
131
133
135
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
141
141
142
142
142
142
142
143
144
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
145
145
146
146
146
147
147
147
12 Release announcements
12.1 pytest-2.7.1: bug fixes . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2 pytest-2.7.0: fixes, features, speed improvements . . . . . . . . . . . . .
12.3 pytest-2.6.3: fixes and little improvements . . . . . . . . . . . . . . . . .
12.4 Changes 2.6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.5 pytest-2.6.2: few fixes and cx_freeze support . . . . . . . . . . . . . . .
12.6 pytest-2.6.1: fixes and new xfail feature . . . . . . . . . . . . . . . . . .
12.7 Changes 2.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8 pytest-2.6.0: shorter tracebacks, new warning system, test runner compat
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
149
149
150
151
151
151
152
152
153
ii
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
12.9
12.10
12.11
12.12
12.13
12.14
12.15
12.16
12.17
12.18
12.19
12.20
12.21
12.22
12.23
12.24
12.25
12.26
12.27
12.28
12.29
12.30
12.31
12.32
pytest-2.5.2: fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . .
pytest-2.5.1: fixes and new home page styling . . . . . . . . . . . . . .
pytest-2.5.0: now down to ZERO reported bugs! . . . . . . . . . . . .
pytest-2.4.2: colorama on windows, plugin/tmpdir fixes . . . . . . . .
pytest-2.4.1: fixing three regressions compared to 2.3.5 . . . . . . . . .
pytest-2.4.0: new fixture features/hooks and bug fixes . . . . . . . . .
pytest-2.3.5: bug fixes and little improvements . . . . . . . . . . . . .
pytest-2.3.4: stabilization, more flexible selection via -k expr . . . .
pytest-2.3.3: integration fixes, py24 suport, */** shown in traceback .
pytest-2.3.2: some fixes and more traceback-printing speed . . . . . . .
pytest-2.3.1: fix regression with factory functions . . . . . . . . . . . .
pytest-2.3: improved fixtures / better unittest integration . . . . . . . .
pytest-2.2.4: bug fixes, better junitxml/unittest/python3 compat . . . .
pytest-2.2.2: bug fixes . . . . . . . . . . . . . . . . . . . . . . . . . .
pytest-2.2.1: bug fixes, perfect teardowns . . . . . . . . . . . . . . . .
py.test 2.2.0: test marking++, parametrization++ and duration profiling
py.test 2.1.3: just some more fixes . . . . . . . . . . . . . . . . . . . .
py.test 2.1.2: bug fixes and fixes for jython . . . . . . . . . . . . . . .
py.test 2.1.1: assertion fixes and improved junitxml output . . . . . . .
py.test 2.1.0: perfected assertions and bug fixes . . . . . . . . . . . . .
py.test 2.0.3: bug fixes and speed ups . . . . . . . . . . . . . . . . . .
py.test 2.0.2: bug fixes, improved xfail/skip expressions, speed ups . . .
py.test 2.0.1: bug fixes . . . . . . . . . . . . . . . . . . . . . . . . . .
py.test 2.0.0: asserts++, unittest++, reporting++, config++, docs++ . .
13 Changelog history
13.1 2.7.1 (compared to 2.7.0) .
13.2 2.7.0 (compared to 2.6.4) .
13.3 2.6.4 . . . . . . . . . . .
13.4 2.6.3 . . . . . . . . . . .
13.5 2.6.2 . . . . . . . . . . .
13.6 2.6.1 . . . . . . . . . . .
13.7 2.6 . . . . . . . . . . . .
13.8 2.5.2 . . . . . . . . . . .
13.9 2.5.1 . . . . . . . . . . .
13.10 2.5.0 . . . . . . . . . . .
13.11 v2.4.2 . . . . . . . . . . .
13.12 v2.4.1 . . . . . . . . . . .
13.13 v2.4 . . . . . . . . . . . .
13.14 v2.3.5 . . . . . . . . . . .
13.15 v2.3.4 . . . . . . . . . . .
13.16 v2.3.3 . . . . . . . . . . .
13.17 v2.3.2 . . . . . . . . . . .
13.18 v2.3.1 . . . . . . . . . . .
13.19 v2.3.0 . . . . . . . . . . .
13.20 v2.2.4 . . . . . . . . . . .
13.21 v2.2.3 . . . . . . . . . . .
13.22 v2.2.2 . . . . . . . . . . .
13.23 v2.2.1 . . . . . . . . . . .
13.24 v2.2.0 . . . . . . . . . . .
13.25 v2.1.3 . . . . . . . . . . .
13.26 v2.1.2 . . . . . . . . . . .
13.27 v2.1.1 . . . . . . . . . . .
13.28 v2.1.0 . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
155
156
156
158
159
159
162
163
164
165
166
166
168
169
169
170
172
172
173
173
174
175
176
177
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
181
181
181
182
183
183
183
184
185
185
186
187
188
188
190
191
191
192
192
192
194
194
194
194
195
195
196
196
196
iii
13.29
13.30
13.31
13.32
13.33
13.34
13.35
13.36
13.37
13.38
13.39
13.40
13.41
13.42
13.43
13.44
13.45
13.46
13.47
13.48
13.49
13.50
13.51
Index
iv
v2.0.3 . .
v2.0.2 . .
v2.0.1 . .
v2.0.0 . .
v1.3.4 . .
v1.3.3 . .
v1.3.2 . .
v1.3.1 . .
v1.3.0 . .
v1.2.0 . .
v1.1.1 . .
v1.1.0 . .
v1.0.2 . .
v1.0.2 . .
v1.0.1 . .
v1.0.0 . .
v1.0.0b9
v1.0.0b8
v1.0.0b7
v1.0.0b3
v1.0.0b1
v0.9.2 . .
v0.9.1 . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
197
197
197
198
199
199
200
201
202
203
203
204
205
206
206
206
206
207
207
208
208
208
209
211
CONTENTS
CONTENTS
CHAPTER
ONE
1.2.1 Installation
Installation options:
pip install -U pytest # or
easy_install -U pytest
$ py.test --version
This is pytest version 2.7.1, imported from /tmp/sandbox/pytest/.tox/regen/lib/python3.4/site-package
test_sample.py F
================================= FAILURES =================================
_______________________________ test_answer ________________________________
>
E
E
def test_answer():
assert func(3) == 5
assert 4 == 5
+ where 4 = func(3)
test_sample.py:5: AssertionError
========================= 1 failed in 0.01 seconds =========================
pytest found the test_answer function by following standard test discovery rules, basically detecting the
test_ prefixes. We got a failure report because our little func(3) call did not return 5.
Note: You can simply use the assert statement for asserting test expectations. pytests Advanced assertion introspection will intelligently report intermediate values of the assert expression freeing you from the need to learn the
many names of JUnit legacy methods.
Todo
For further ways to assert exceptions see the raises
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
The two tests are found because of the standard Conventions for Python test discovery. There is no need to subclass
anything. We can simply run the module by passing its filename:
$ py.test -q test_class.py
.F
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________
self = <test_class.TestClass object at 0x7fbf54cf5668>
>
E
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
assert hasattr('hello', 'check')
test_class.py:8: AssertionError
1 failed, 1 passed in 0.01 seconds
The first test passed, the second failed. Again we can easily see the intermediate values used in the assertion, helping
us to understand the reason for the failure.
We list the name tmpdir in the test function signature and pytest will lookup and call a fixture factory to create
the resource before performing the test function call. Lets just run it:
$ py.test -q test_tmpdir.py
F
================================= FAILURES =================================
_____________________________ test_needsfiles ______________________________
tmpdir = local('/tmp/pytest-18/test_needsfiles0')
>
E
def test_needsfiles(tmpdir):
print (tmpdir)
assert 0
assert 0
test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call --------------------------/tmp/pytest-18/test_needsfiles0
1 failed in 0.05 seconds
Before the test runs, a unique-per-test-invocation temporary directory was created. More info at Temporary directories
and files.
You can find out what kind of builtin pytest fixtures: explicit, modular, scalable exist by typing:
py.test --fixtures
This is equivalent to invoking the command line script py.test [...] directly.
Import pkg and use its filesystem location to find and run tests:
py.test --pyargs pkg # run all tests found below directory of pypkg
--tb=long
--tb=native
--tb=short
--tb=line
#
#
#
#
This will invoke the Python debugger on every failure. Often you might only want to do this for the first failing test to
understand a certain failure situation:
py.test -x --pdb
# drop to PDB on first failure, then end test session
py.test --pdb --maxfail=3 # drop to PDB for first three failures
Note that on any failure the exception information is stored on sys.last_value, sys.last_type and
sys.last_traceback. In interactive use, this allows one to drop into postmortem debugging with any debug
tool. One can also manually access the exception information, for example:
>> import sys
>> sys.last_traceback.tb_lineno
42
>> sys.last_value
AssertionError('assert result == "ok"',)
Prior to pytest version 2.0.0 you could only enter PDB tracing if you disabled capturing on the command line via
py.test -s. In later versions, pytest automatically disables its output capture when you enter PDB tracing:
Output capture in other tests is not affected.
Any prior test output that has already been captured and will be processed as such.
Any later output produced within the same test will not be captured and will instead get sent directly to
sys.stdout. Note that this holds true even for test output occuring after you exit the interactive PDB tracing
session and continue with the regular test run.
Since pytest version 2.4.0 you can also use the native Python import pdb;pdb.set_trace() call to enter PDB
tracing without having to use the pytest.set_trace() wrapper or explicitly disable pytests output capturing
via py.test -s.
py.test --resultlog=path
and look at the content at the path location. Such files are used e.g. by the PyPy-test web page to show test results
over several revisions.
This will submit test run information to a remote Paste service and provide a URL for each failure. You may select
tests as usual or add for example -x if you only want to send one particular failure.
Creating a URL for a whole test session log:
py.test --pastebin=all
this acts as if you would call py.test from the command line. It will not raise SystemExit but return the exitcode
instead. You can pass in options and arguments:
pytest.main(['-x', 'mytestdir'])
or pass in a string:
pytest.main("-x mytestdir")
Running it will show that MyPlugin was added and its hook was invoked:
10
$ python myinvoke.py
*** test run reporting finishing
source bin/activate
# on unix
scripts/activate
# on Windows
Due to the activate step above the pip will come from the virtualenv directory and install any package into the
isolated virtual environment.
inlining test directories into your application package, useful if you have direct relation between (unit-)test and
application modules and want to distribute your tests along with your application:
setup.py
# your distutils/setuptools Python package metadata
mypkg/
__init__.py
appmodule.py
...
test/
test_app.py
...
11
pip install -e .
avoid __init__.py files in your test directories. This way your tests can run easily against an installed version
of mypkg, independently from the installed package if it contains the tests or not.
With inlined tests you might put __init__.py into test directories and make them installable as part of
your application. Using the py.test --pyargs mypkg invocation pytest will discover where mypkg is
installed and collect tests from there. With the external test you can still distribute tests but they will not be
installed or become importable.
Typically you can run tests by pointing to test directories or modules:
py.test tests/test_app.py
py.test mypkg/test/test_app.py
py.test mypkg
py.test
...
#
#
#
#
for
for
run
run
Because of the above editable install mode you can change your source code (both tests and the app) and
rerun tests at will. Once you are done with your work, you can use tox to make sure that the package is really correct
and tests pass in all required configurations.
Note: You can use Python3 namespace packages (PEP420) for your application but pytest will still perform test
package name discovery based on the presence of __init__.py files. If you use one of the two recommended file
system layouts above but leave away the __init__.py files from your directories it should just work on Python3.3
and above. From inlined tests, however, you will need to use absolute imports for getting at your application code.
Note: If pytest finds a a/b/test_module.py test file while recursing into the filesystem it determines the import
name as follows:
determine basedir: this is the first upward (towards the root) directory not containing an __init__.py.
If e.g. both a and b contain an __init__.py file then the parent directory of a will become the basedir.
perform sys.path.insert(0, basedir) to make the test module importable under the fully qualified
import name.
import a.b.test_module where the path is determined by converting path separators / into . characters. This means you must follow the convention of having directory and file names map directly to the import
names.
The reason for this somewhat evolved importing technique is that in larger projects multiple test modules might import
from each other and thus deriving a canonical import name helps to avoid surprises such as a test modules getting
imported twice.
12
This generates a runtests.py script which is a fully functional basic pytest script, running unchanged under
Python2 and Python3. You can tell people to download the script and then e.g. run it like this:
python runtests.py
and make this script part of your distribution and then add this to your setup.py file:
from distutils.core import setup, Command
# you can also import from setuptools
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import subprocess
import sys
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
setup(
#...,
cmdclass = {'test': PyTest},
#...,
)
this will execute your tests using runtests.py. As this is a standalone version of pytest no prior installation
whatsoever is required for calling the test command. You can also pass additional arguments to the subprocess-calls
such as your test directory or other options.
13
import sys
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
setup(
#...,
tests_require=['pytest'],
cmdclass = {'test': PyTest},
)
this will download pytest if needed and then run your tests as you would expect it to. You can pass a single string
of arguments using the --pytest-args or -a command-line option. For example:
python setup.py test -a "--durations=5"
14
Within Python modules, pytest also discovers tests using the standard unittest.TestCase subclassing technique.
15
16
17
18
may feel more natural. Moreover, funcargs are ideal for writing advanced test support code (like e.g. the monkeypatch, the tmpdir or capture funcargs) because the support code can register setup/teardown functions in a managed
class/module/function scope.
Can I yield multiple values from a fixture function function?
There are two conceptual reasons why yielding from a factory function is not possible:
If multiple factories yielded values there would be no natural place to determine the combination policy - in
real-world examples some combinations often should not run.
Calling factories for obtaining test function arguments is part of setting up and running a test. At that point it is
not possible to add new test calls to the test collection anymore.
However, with pytest-2.3 you can use the Fixtures as Function arguments decorator and specify params so that all
tests depending on the factory-created resource will run multiple times with different parameters.
You can also use the pytest_generate_tests hook to implement the parametrization scheme of your choice.
19
20
CHAPTER
TWO
21
22
23
keywords
keywords/markers dictionary for the underlying node.
session
pytest session object.
addfinalizer(finalizer)
add finalizer/teardown function to be called after the last test within the requesting test context finished
execution.
applymarker(marker)
Apply a marker to a single test function invocation. This method is useful if you dont want to have a
keyword/marker on all function invocations.
Parameters marker a _pytest.mark.MarkDecorator object created by a call to
pytest.mark.NAME(...).
raiseerror(msg)
raise a FixtureLookupError with the given message.
cached_setup(setup, teardown=None, scope=module, extrakey=None)
(deprecated) Return a testing resource managed by setup & teardown calls. scope and extrakey
determine when the teardown function will be called so that subsequent calls to setup would recreate
the resource. With pytest-2.3 you often do not need cached_setup() as you can directly declare a
scope on a fixture function and register a finalizer through request.addfinalizer().
Parameters
teardown function receiving a previously setup resource.
setup a no-argument function creating a resource.
scope a string value out of function, class, module or session indicating the
caching lifecycle of the resource.
extrakey added to internal caching key of (funcargname, scope).
getfuncargvalue(argname)
Dynamically retrieve a named fixture function argument.
As of pytest-2.3, it is easier and usually better to access other fixture values by stating it as an input
argument in the fixture function. If you only can decide about using another fixture at test setup time, you
may use this function to retrieve it inside a fixture function body.
24
This will display command line and configuration file settings which were registered by installed plugins.
25
look for pytest.ini, tox.ini and setup.cfg files in the ancestor directory and upwards. If one is
matched, it becomes the ini-file and its directory becomes the rootdir. An existing pytest.ini file will always
be considered a match whereas tox.ini and setup.cfg will only match if they contain a [pytest]
section.
if no ini-file was found, look for setup.py upwards from the common ancestor directory to determine the
rootdir.
if no ini-file and no setup.py was found, use the already determined common ancestor as root directory.
This allows to work with pytest in structures that are not part of a package and dont have any particular ini-file
configuration.
Note that options from multiple ini-files candidates are never merged, the first one wins (pytest.ini always wins
even if it does not contain a [pytest] section).
The config object will subsequently carry these attributes:
config.rootdir: the determined root directory, guaranteed to exist.
config.inifile: the determined ini-file, may be None.
The rootdir is used a reference directory for constructing test addresses (nodeids) and can be used also by plugins
for storing per-testrun information.
Example:
py.test path/to/testdir path/other/
will determine the common ancestor as path and then check for ini-files as follows:
# first look for pytest.ini files
path/pytest.ini
path/setup.cfg # must also contain [pytest] section to match
path/tox.ini
# must also contain [pytest] section to match
pytest.ini
... # all the way down to the root
# now look for setup.py
path/setup.py
setup.py
... # all the way down to the root
Alternatively, you can set a PYTEST_ADDOPTS environment variable to add command line options while the environment is in use:
export PYTEST_ADDOPTS="-rsxX -q"
From now on, running pytest will add the specified options.
26
matches
matches
matches
matches
everything
any single character
any character in seq
any char not in seq
Default patterns are .*, CVS, _darcs, {arch}, *.egg. Setting a norecursedirs
replaces the default. Here is an example of how to avoid certain directories:
# content of setup.cfg
[pytest]
norecursedirs = .svn _build tmp*
This would tell pytest to not look into typical subversion or sphinx-build directories or into any tmp prefixed
directory.
python_files
One or more Glob-style file patterns determining which python files are considered as test modules.
python_classes
One or more name prefixes or glob-style patterns determining which classes are considered for test collection.
Here is an example of how to collect tests from classes that end in Suite:
# content of pytest.ini
[pytest]
python_classes = *Suite
Note that unittest.TestCase derived classes are always collected regardless of this option, as
unittests own collection framework is used to collect those tests.
python_functions
One or more name prefixes or glob-patterns determining which test functions and methods are considered tests.
Here is an example of how to collect test functions and methods that end in _test:
# content of pytest.ini
[pytest]
python_functions = *_test
27
Note that this has no effect on methods that live on a unittest .TestCase derived class, as unittests
own collection framework is used to collect those tests.
See Changing naming conventions for more detailed examples.
doctest_optionflags
One or more doctest flag names from the standard doctest module. See how py.test handles doctests.
to assert that your function returns a certain value. If this assertion fails you will see the return value of the function
call:
$ py.test test_assert1.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-87, inifile:
collected 1 items
test_assert1.py F
================================= FAILURES =================================
______________________________ test_function _______________________________
>
E
E
def test_function():
assert f() == 4
assert 3 == 4
+ where 3 = f()
test_assert1.py:5: AssertionError
========================= 1 failed in 0.01 seconds =========================
pytest has support for showing the values of the most common subexpressions including calls, attributes, comparisons, and binary and unary operators. (See Demo of Python failure reports with pytest). This allows you to use the
idiomatic python constructs without boilerplate code while not losing introspection information.
However, if you specify a message with the assertion like this:
assert a % 2 == 0, "value was odd, should be even"
then no assertion introspection takes places at all and the message will be simply shown in the traceback.
See Advanced assertion introspection for more information on assertion introspection.
28
and if you need to have access to the actual exception info you may use:
def test_recursion_depth():
with pytest.raises(RuntimeError) as excinfo:
def f():
f()
f()
assert 'maximum recursion' in str(excinfo.value)
excinfo is a py.code.ExceptionInfo instance, which is a wrapper around the actual exception raised. The main
attributes of interest are .type, .value and .traceback.
If you want to write test code that works on Python 2.4 as well, you may also use two other ways to test for an expected
exception:
pytest.raises(ExpectedException, func, *args, **kwargs)
pytest.raises(ExpectedException, "func(*args, **kwargs)")
both of which execute the specified function with args and kwargs and asserts that the given ExpectedException
is raised. The reporter will provide you with helpful output in case of failures such as no exception or wrong exception.
Note that it is also possible to specify a raises argument to pytest.mark.xfail, which checks that the test is
failing in a more specific way than just having any exception raised:
@pytest.mark.xfail(raises=IndexError)
def test_f():
f()
Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail with a check function is probably better for something like
documenting unfixed bugs (where the test describes what should happen) or bugs in dependencies.
29
>
E
E
E
E
E
E
def test_set_comparison():
set1 = set("1308")
set2 = set("8035")
assert set1 == set2
assert set(['0', '1', '3', '8']) == set(['0', '3', '5', '8'])
Extra items in the left set:
'1'
Extra items in the right set:
'5'
Use -v to get the full diff
test_assert2.py:5: AssertionError
========================= 1 failed in 0.01 seconds =========================
30
def test_compare():
f1 = Foo(1)
f2 = Foo(2)
assert f1 == f2
you can run the test module and get the custom output defined in the conftest file:
$ py.test -q test_foocompare.py
F
================================= FAILURES =================================
_______________________________ test_compare _______________________________
>
E
E
def test_compare():
f1 = Foo(1)
f2 = Foo(2)
assert f1 == f2
assert Comparing Foo instances:
vals: 1 != 2
test_foocompare.py:8: AssertionError
1 failed in 0.01 seconds
If this assertion fails then the re-evaluation will probably succeed! This is because f.read() will return an empty
string when it is called the second time during the re-evaluation. However, it is easy to rewrite the assertion and avoid
any trouble:
31
content = f.read()
assert content != '...'
Here, the test_ehlo needs the smtp fixture value. pytest will discover and call the @pytest.fixture marked
smtp fixture function. Running the test looks like this:
32
$ py.test test_smtpsimple.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-98, inifile:
collected 1 items
test_smtpsimple.py F
================================= FAILURES =================================
________________________________ test_ehlo _________________________________
smtp = <smtplib.SMTP object at 0x7f9d45764c88>
>
E
def test_ehlo(smtp):
response, msg = smtp.ehlo()
assert response == 250
assert 0 # for demo purposes
assert 0
test_smtpsimple.py:11: AssertionError
========================= 1 failed in 1.07 seconds =========================
In the failure traceback we see that the test function was called with a smtp argument, the smtplib.SMTP()
instance created by the fixture function. The test function fails on our deliberate assert 0. Here is the exact
protocol used by pytest to call the test function this way:
1. pytest finds the test_ehlo because of the test_ prefix. The test function needs a function argument named
smtp. A matching fixture function is discovered by looking for a fixture-marked function named smtp.
2. smtp() is called to create an instance.
3. test_ehlo(<SMTP instance>) is called and fails in the last line of the test function.
Note that if you misspell a function argument or want to use one that isnt available, youll see an error with a list of
available function arguments.
Note: You can always issue:
py.test --fixtures test_simplefactory.py
33
The name of the fixture again is smtp and you can access its result by listing the name smtp as an input parameter in
any test or fixture function (in or below the directory where conftest.py is located):
# content of test_module.py
def test_ehlo(smtp):
response = smtp.ehlo()
assert response[0] == 250
assert "merlinux" in response[1]
assert 0 # for demo purposes
def test_noop(smtp):
response = smtp.noop()
assert response[0] == 250
assert 0 # for demo purposes
We deliberately insert failing assert 0 statements in order to inspect what is going on and can now run the tests:
$ py.test test_module.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-98, inifile:
collected 2 items
test_module.py FF
================================= FAILURES =================================
________________________________ test_ehlo _________________________________
smtp = <smtplib.SMTP object at 0x7fb558b12240>
>
E
def test_ehlo(smtp):
response = smtp.ehlo()
assert response[0] == 250
assert "merlinux" in response[1]
TypeError: Type str doesn't support the buffer API
test_module.py:5: TypeError
________________________________ test_noop _________________________________
smtp = <smtplib.SMTP object at 0x7fb558b12240>
def test_noop(smtp):
34
>
E
response = smtp.noop()
assert response[0] == 250
assert 0 # for demo purposes
assert 0
test_module.py:11: AssertionError
========================= 2 failed in 0.82 seconds =========================
You see the two assert 0 failing and more importantly you can also see that the same (module-scoped) smtp
object was passed into the two test functions because pytest shows the incoming argument values in the traceback. As
a result, the two test functions using smtp run as quick as a single one because they reuse the same instance.
If you decide that you rather want to have a session-scoped smtp instance, you can simply declare it:
@pytest.fixture(scope="session")
def smtp(...):
# the returned fixture value will be shared for
# all tests needing it
The fin function will execute when the last test using the fixture in the module has finished execution.
Lets execute it:
$ py.test -s -q --tb=no
FFteardown smtp
2 failed in 1.44 seconds
We see that the smtp instance is finalized after the two tests finished execution. Note that if we decorated our fixture
function with scope=function then fixture setup and cleanup would occur around each single test. In either
case the test module itself does not need to change or know about these details of fixture setup.
35
# content of conftest.py
import pytest
import smtplib
@pytest.fixture(scope="module")
def smtp(request):
server = getattr(request.module, "smtpserver", "merlinux.eu")
smtp = smtplib.SMTP(server)
def fin():
print ("finalizing %s (%s)" % (smtp, server))
smtp.close()
return smtp
We use the request.module attribute to optionally obtain an smtpserver attribute from the test module. If we
just execute again, nothing much has changed:
$ py.test -s -q --tb=no
FF
2 failed in 0.62 seconds
Lets quickly create another test module that actually sets the server URL in its module namespace:
# content of test_anothersmtp.py
smtpserver = "mail.python.org"
def test_showhelo(smtp):
assert 0, smtp.helo()
Running it:
$ py.test -qq --tb=short test_anothersmtp.py
F
================================= FAILURES =================================
______________________________ test_showhelo _______________________________
test_anothersmtp.py:5: in test_showhelo
assert 0, smtp.helo()
E
AssertionError: (250, b'mail.python.org')
E
assert 0
voila! The smtp fixture function picked up our mail server name from the module namespace.
36
@pytest.fixture(scope="module",
params=["merlinux.eu", "mail.python.org"])
def smtp(request):
smtp = smtplib.SMTP(request.param)
def fin():
print ("finalizing %s" % smtp)
smtp.close()
request.addfinalizer(fin)
return smtp
The main change is the declaration of params with @pytest.fixture, a list of values for each of which the
fixture function will execute and can access a value via request.param. No test function code needs to change.
So lets just do another run:
$ py.test -q test_module.py
FFFF
================================= FAILURES =================================
__________________________ test_ehlo[merlinux.eu] __________________________
smtp = <smtplib.SMTP object at 0x7f4eecf92080>
>
E
def test_ehlo(smtp):
response = smtp.ehlo()
assert response[0] == 250
assert "merlinux" in response[1]
TypeError: Type str doesn't support the buffer API
test_module.py:5: TypeError
__________________________ test_noop[merlinux.eu] __________________________
smtp = <smtplib.SMTP object at 0x7f4eecf92080>
>
E
def test_noop(smtp):
response = smtp.noop()
assert response[0] == 250
assert 0 # for demo purposes
assert 0
test_module.py:11: AssertionError
________________________ test_ehlo[mail.python.org] ________________________
smtp = <smtplib.SMTP object at 0x7f4eecf92048>
>
E
def test_ehlo(smtp):
response = smtp.ehlo()
assert response[0] == 250
assert "merlinux" in response[1]
TypeError: Type str doesn't support the buffer API
test_module.py:5: TypeError
-------------------------- Captured stdout setup --------------------------finalizing <smtplib.SMTP object at 0x7f4eecf92080>
________________________ test_noop[mail.python.org] ________________________
smtp = <smtplib.SMTP object at 0x7f4eecf92048>
def test_noop(smtp):
response = smtp.noop()
37
>
E
test_module.py:11: AssertionError
4 failed in 1.75 seconds
We see that our two test functions each ran twice, against the different smtp instances. Note also, that with the
mail.python.org connection the second test fails in test_ehlo because a different server string is expected
than what arrived.
pytest will build a string that is the test ID for each fixture value in a parametrized fixture, e.g.
test_ehlo[merlinux.eu] and test_ehlo[mail.python.org] in the above examples. These IDs can
be used with -k to select specific cases to run, and they will also identify the specific case when one is failing.
Running pytest with --collect-only will show the generated IDs.
Numbers, strings, booleans and None will have their usual string representation used in the test ID. For other objects,
pytest will make a string based on the argument name. It is possible to customise the string used in a test ID for a
certain fixture value by using the ids keyword argument:
import pytest
@pytest.fixture(params=[0, 1], ids=["spam", "ham"])
def a(request):
return request.param
def test_a(a):
pass
def idfn(fixture_value):
if fixture_value == 0:
return "eggs"
else:
return None
@pytest.fixture(params=[0, 1], ids=idfn)
def b(request):
return request.param
def test_b(b):
pass
The above shows how ids can be either a list of strings to use or a function which will be called with the fixture value
and then has to return a string to use. In the latter case if the function return None then pytests auto-generated ID will
be used.
Running the above tests results in the following test IDs being used:
$ py.test --collect-only
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-98, inifile:
collected 6 items
<Module 'test_anothersmtp.py'>
<Function 'test_showhelo[merlinux.eu]'>
<Function 'test_showhelo[mail.python.org]'>
<Module 'test_module.py'>
<Function 'test_ehlo[merlinux.eu]'>
<Function 'test_noop[merlinux.eu]'>
38
<Function 'test_ehlo[mail.python.org]'>
<Function 'test_noop[mail.python.org]'>
=============================
Here we declare an app fixture which receives the previously defined smtp fixture and instantiates an App object
with it. Lets run it:
$ py.test -v test_appsetup.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 -- /tmp/sandbox/pytest/.tox/regen/bin/pyt
rootdir: /tmp/doc-exec-98, inifile:
collecting ... collected 2 items
test_appsetup.py::test_smtp_exists[merlinux.eu] PASSED
test_appsetup.py::test_smtp_exists[mail.python.org] PASSED
========================= 2 passed in 1.09 seconds =========================
Due to the parametrization of smtp the test will run twice with two different App instances and respective smtp
servers. There is no need for the app fixture to be aware of the smtp parametrization as pytest will fully analyse the
fixture dependency graph.
Note, that the app fixture has a scope of module and uses a module-scoped smtp fixture. The example would still
work if smtp was cached on a session scope: it is fine for fixtures to use broader scoped fixtures but not the
other way round: A session-scoped fixture could not use a module-scoped one in a meaningful way.
39
The following example uses two parametrized funcargs, one of which is scoped on a per-module basis, and all the
functions perform print calls to show the setup/teardown flow:
# content of test_module.py
import pytest
@pytest.fixture(scope="module", params=["mod1", "mod2"])
def modarg(request):
param = request.param
print ("create", param)
def fin():
print ("fin %s" % param)
return param
@pytest.fixture(scope="function", params=[1,2])
def otherarg(request):
return request.param
def test_0(otherarg):
print (" test0", otherarg)
def test_1(modarg):
print (" test1", modarg)
def test_2(otherarg, modarg):
print (" test2", otherarg, modarg)
Lets run the tests in verbose mode and with looking at the print-output:
$ py.test -v -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 -- /tmp/sandbox/pytest/.tox/regen/bin/pyt
rootdir: /tmp/doc-exec-98, inifile:
collecting ... collected 8 items
test_module.py::test_0[1]
test0 1
PASSED
test_module.py::test_0[2]
test0 2
PASSED
test_module.py::test_1[mod1] create mod1
test1 mod1
PASSED
test_module.py::test_2[1-mod1]
test2 1
PASSED
test_module.py::test_2[2-mod1]
test2 2
PASSED
test_module.py::test_1[mod2] create mod2
test1 mod2
PASSED
test_module.py::test_2[1-mod2]
test2 1
PASSED
test_module.py::test_2[2-mod2]
test2 2
PASSED
mod1
mod1
mod2
mod2
You can see that the parametrized module-scoped modarg resource caused an ordering of test execution that lead
to the fewest possible active resources. The finalizer for the mod1 parametrized resource was executed before the
mod2 resource was setup.
40
Due to the usefixtures marker, the cleandir fixture will be required for the execution of each test method, just
as if you specified a cleandir function argument to each of them. Lets run it to verify our fixture is activated and the
tests pass:
$ py.test -q
..
2 passed in 0.01 seconds
and you may specify fixture usage at the test module level, using a generic feature of the mark mechanism:
pytestmark = pytest.mark.usefixtures("cleandir")
Lastly you can put fixtures required by all tests in your project into an ini-file:
# content of pytest.ini
[pytest]
usefixtures = cleandir
41
The class-level transact fixture is marked with autouse=true which implies that all test methods in the class will
use this fixture without a need to state it in the test function signature or with a class-level usefixtures decorator.
If we run it, we get two passing tests:
$ py.test -q
..
2 passed in 0.01 seconds
42
# content of conftest.py
@pytest.fixture()
def transact(self, request, db):
db.begin()
request.addfinalizer(db.rollback)
All test methods in this TestClass will use the transaction fixture while other test classes or functions in the module
will not use it unless they also add a transact reference.
43
def username(username):
return 'overridden-' + username
test_something.py
# content of tests/subfolder/test_something.py
def test_username(username):
assert username == 'overridden-username'
As you can see, a fixture with the same name can be overridden for certain test folder level. Note that the base or
super fixture can be accessed from the overriding fixture easily - used in the example above.
Override a fixture on a test module level
Given the tests file structure is:
tests/
__init__.py
conftest.py
# content of tests/conftest.py
@pytest.fixture
def username():
return 'username'
test_something.py
# content of tests/test_something.py
import pytest
@pytest.fixture
def username(username):
return 'overridden-' + username
def test_username(username):
assert username == 'overridden-username'
test_something_else.py
# content of tests/test_something_else.py
import pytest
@pytest.fixture
def username(username):
return 'overridden-else-' + username
def test_username(username):
assert username == 'overridden-else-username'
In the example above, a fixture with the same name can be overridden for certain test module.
Override a fixture with direct test parametrization
Given the tests file structure is:
tests/
__init__.py
conftest.py
# content of tests/conftest.py
44
import pytest
@pytest.fixture
def username():
return 'username'
@pytest.fixture
def other_username(username):
return 'other-' + username
test_something.py
# content of tests/test_something.py
import pytest
@pytest.mark.parametrize('username', ['directly-overridden-username'])
def test_username(username):
assert username == 'directly-overridden-username'
@pytest.mark.parametrize('username', ['directly-overridden-username-other'])
def test_username_other(other_username):
assert username == 'other-directly-overridden-username-other'
In the example above, a fixture value is overridden by the test parameter value. Note that the value of the fixture can
be overridden this way even if the test doesnt use it directly (doesnt mention it in the function prototype).
Override a parametrized fixture with non-parametrized one and vice versa
Given the tests file structure is:
tests/
__init__.py
conftest.py
# content of tests/conftest.py
import pytest
@pytest.fixture(params=['one', 'two', 'three'])
def parametrized_username(request):
return request.param
@pytest.fixture
def non_parametrized_username(request):
return 'username'
test_something.py
# content of tests/test_something.py
import pytest
@pytest.fixture
def parametrized_username():
return 'overridden-username'
@pytest.fixture(params=['one', 'two', 'three'])
def non_parametrized_username(request):
return request.param
def test_username(parametrized_username):
45
In the example above, a parametrized fixture is overridden with a non-parametrized version, and a non-parametrized
fixture is overridden with a parametrized version for certain test module. The same applies for the test folder level
obviously.
In contrast to finalization through registering callbacks, our fixture function used a yield statement to provide the
lines of the /etc/passwd file. The code after the yield statement serves as the teardown code, avoiding the
indirection of registering a teardown callback function.
Lets run it with output capturing disabled:
$ py.test -q -s test_yield.py
setup before yield
test called
46
We can also seamlessly use the new syntax with with statements. Lets simplify the above passwd fixture:
# content of test_yield2.py
import pytest
@pytest.yield_fixture
def passwd():
with open("/etc/passwd") as f:
yield f.readlines()
def test_has_lines(passwd):
assert len(passwd) >= 1
The file f will be closed after the test finished execution because the Python file object supports finalization when
the with statement ends.
Note that the new syntax is fully integrated with using scope, params and other fixture features. Changing existing
fixture functions to use yield is thus straight forward.
47
Here, the @parametrize decorator defines three different (input,expected) tuples so that the test_eval
function will run three times using them in turn:
$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-109, inifile:
collected 3 items
test_expectation.py ..F
================================= FAILURES =================================
____________________________ test_eval[6*9-42] _____________________________
input = '6*9', expected = 42
>
E
E
@pytest.mark.parametrize("input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_eval(input, expected):
assert eval(input) == expected
assert 54 == 42
+ where 54 = eval('6*9')
test_expectation.py:8: AssertionError
==================== 1 failed, 2 passed in 0.02 seconds ====================
As designed in this example, only one pair of input/output values fails the simple test function. And as usual with test
function arguments, you can see the input and output values in the traceback.
Note that you could also use the parametrize marker on a class or a module (see Marking test functions with attributes)
which would invoke several functions with the argument sets.
48
It is also possible to mark individual test instances within parametrize, for example with the builtin mark.xfail:
# content of test_expectation.py
import pytest
@pytest.mark.parametrize("input,expected", [
("3+5", 8),
("2+4", 6),
pytest.mark.xfail(("6*9", 42)),
])
def test_eval(input, expected):
assert eval(input) == expected
The one parameter set which caused a failure previously now shows up as an xfailed (expected to fail) test.
Note: In versions prior to 2.4 one needed to specify the argument names as a tuple. This remains valid but the
simpler "name1,name2,..." comma-separated-string syntax is now advertised first because its easier to write
and produces less line noise.
Now we add a conftest.py file containing the addition of a command line option and the parametrization of our
test function:
# content of conftest.py
def pytest_addoption(parser):
parser.addoption("--stringinput", action="append", default=[],
help="list of stringinputs to pass to test functions")
def pytest_generate_tests(metafunc):
if 'stringinput' in metafunc.fixturenames:
49
metafunc.parametrize("stringinput",
metafunc.config.option.stringinput)
If we now pass two stringinput values, our test will run twice:
$ py.test -q --stringinput="hello" --stringinput="world" test_strings.py
..
2 passed in 0.01 seconds
Lets also run with a stringinput that will lead to a failing test:
$ py.test -q --stringinput="!" test_strings.py
F
================================= FAILURES =================================
___________________________ test_valid_string[!] ___________________________
stringinput = '!'
>
E
E
def test_valid_string(stringinput):
assert stringinput.isalpha()
assert <built-in method isalpha of str object at 0x7f6e2145e768>()
+ where <built-in method isalpha of str object at 0x7f6e2145e768> = '!'.isalpha
test_strings.py:3: AssertionError
1 failed in 0.01 seconds
For further examples, you might want to look at more parametrization examples.
50
Parameters
argnames a comma-separated string denoting one or more argument names, or a
list/tuple of argument strings.
argvalues The list of argvalues determines how often a test is invoked with different
argument values. If only one argname was specified argvalues is a list of simple values. If
N argnames were specified, argvalues must be a list of N-tuples, where each tuple-element
specifies a value for its respective argname.
indirect if True each argvalue corresponding to an argname will be passed as request.param to its respective argname fixture function so that it can perform more expensive
setups during the setup phase of a test rather than at collection time.
ids list of string ids, or a callable. If strings, each is corresponding to the argvalues so
that they are part of the test id. If callable, it should take one argument (a single argvalue)
and return a string or return None. If None, the automatically generated id for that argument
will be used. If no ids are provided they will be generated automatically from the argvalues.
scope if specified it denotes the scope of the parameters. The scope is used for grouping tests by parameter instances. It will also override any fixture-function defined scope,
allowing to set a dynamic scope using test context or configuration.
Metafunc.addcall(funcargs=None, id=_notexists, param=_notexists)
(deprecated, use parametrize) Add a new call to the underlying test function during the collection phase of a test
run. Note that request.addcall() is called during the test collection phase prior and independently to actual test
execution. You should only use addcall() if you need to specify multiple arguments of a test function.
Parameters
funcargs argument keyword dictionary used when invoking the test function.
id used for reporting and identification purposes. If you dont supply an id an automatic
unique id will be generated.
param a parameter which will be exposed to a later fixture function invocation through
the request.param attribute.
51
def setup_module(module):
""" setup any state specific to the execution of the given module."""
def teardown_module(module):
""" teardown any state that was previously setup with a setup_module
method.
"""
If you would rather define test functions directly at module level you can also use the following functions to implement
fixtures:
def setup_function(function):
""" setup any state tied to the execution of the given function.
Invoked for every test function in the module.
"""
def teardown_function(function):
""" teardown any state that was previously setup with a setup_function
call.
"""
Note that it is possible for setup/teardown pairs to be invoked multiple times per testing process.
52
and running this module will show you precisely the output of the failing function and hide the other one:
$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-90, inifile:
collected 2 items
test_module.py .F
================================= FAILURES =================================
________________________________ test_func2 ________________________________
53
>
E
def test_func2():
assert False
assert False
test_module.py:9: AssertionError
-------------------------- Captured stdout setup --------------------------setting up <function test_func2 at 0x7fa678d6eb70>
==================== 1 failed, 1 passed in 0.01 seconds ====================
The readouterr() call snapshots the output so far - and capturing will be continued. After the test function finishes
the original streams will be restored. Using capsys this way frees your test from having to care about setting/resetting
output streams and also interacts well with pytests own per-test capturing.
If you want to capture on filedescriptor level you can use the capfd function argument which offers the exact same
interface but allows to also capture output from libraries or subprocesses that directly write to operating system level
output streams (FD1 and FD2).
use
the
# content of test_module.py
import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')
def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
54
x = getssh()
assert x == '/abc/.ssh'
Here our test function monkeypatches os.path.expanduser and then calls into an function that calls it. After the
test function finishes the os.path.expanduser modification will be undone.
This autouse fixture will be executed for each test function and it will delete the method
request.session.Session.request so that any attempts within tests to create http requests will fail.
55
56
or use the package in develop/in-place mode with a checkout of the pytest-xdist repository
python setup.py develop
Especially for longer running tests or tests requiring a lot of I/O this can lead to considerable speed ups.
Running tests in a Python subprocess
To instantiate a Python-2.4 subprocess and send tests to it, you may type:
py.test -d --tx popen//python=python2.4
This will start a subprocess which is run with the python2.4 Python interpreter, found in your system binary lookup
path.
If you prefix the tx option value like this:
py.test -d --tx 3*popen//python=python2.4
then three subprocesses would be created and the tests will be distributed to three subprocesses and run simultanously.
Running tests in looponfailing mode
For refactoring a project with a medium or large test suite you can use the looponfailing mode. Simply add the --f
option:
py.test -f
and pytest will run your tests. Assuming you have failures it will then wait for file changes and re-run the failing
test set. File changes are detected by looking at looponfailingroots root directories and all of their contents
(recursively). If the default for this value does not work for you you can change it in your project by setting a
configuration option:
# content of a pytest.ini, setup.cfg or tox.ini file
[pytest]
looponfailroots = mypkg testdir
This would lead to only looking for file changes in the respective directories, specified relatively to the ini-files
directory.
Sending tests to remote SSH accounts
Suppose you have a package mypkg which contains some tests that you can successfully run locally. And you also
have a ssh-reachable machine myhost. Then you can ad-hoc distribute your tests by typing:
py.test -d --tx ssh=myhostpopen --rsyncdir mypkg mypkg
57
This will synchronize your mypkg package directory with a remote ssh account and then collect and run your tests at
the remote side.
You can specify multiple --rsyncdir directories to be sent to the remote side.
Sending tests to remote Socket Servers
Download the single-module socketserver.py Python program and run it like this:
python socketserver.py
It will tell you that it starts listening on the default port. You can now on your home machine specify this new socket
host with something like this:
py.test -d --tx socket=192.168.1.102:8888 --rsyncdir mypkg mypkg
If you specify a windows host, an OSX host and a Linux environment this command will send each tests to all platforms
- and report back failures from all platforms at once. The specifications strings use the xspec syntax.
Specifying test exec environments in an ini file
pytest (since version 2.0) supports ini-style configuration. For example, you could make running with three subprocesses your default:
[pytest]
addopts = -n3
These directory specifications are relative to the directory where the configuration file was found.
58
Running this would result in a passed test except for the last assert 0 line which we use to look at values:
$ py.test test_tmpdir.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-118, inifile:
collected 1 items
test_tmpdir.py F
================================= FAILURES =================================
_____________________________ test_create_file _____________________________
tmpdir = local('/tmp/pytest-19/test_create_file0')
>
E
def test_create_file(tmpdir):
p = tmpdir.mkdir("sub").join("hello.txt")
p.write("content")
assert p.read() == "content"
assert len(tmpdir.listdir()) == 1
assert 0
assert 0
test_tmpdir.py:7: AssertionError
========================= 1 failed in 0.04 seconds =========================
When distributing tests on the local machine, pytest takes care to configure a basetemp directory for the sub processes such that all temporary data lands below a single per-test run basetemp directory.
59
60
name = None
name of attribute
args = None
positional argument list, empty if none specified
kwargs = None
keyword argument dictionary, empty if nothing specified
add(args, kwargs)
add a MarkInfo with the given args and kwargs.
2.13 Skip and xfail: dealing with tests that can not succeed
If you have test functions that cannot be run on certain platforms or that you expect to fail you can mark them
accordingly or you may call helper functions during execution of setup or test functions.
A skip means that you expect your test to pass unless the environment (e.g. wrong Python interpreter, missing dependency) prevents it to run. And xfail means that your test can run but you expect it to fail because there is an
implementation problem.
pytest counts and lists skip and xfail tests separately. Detailed information about skipped/xfailed tests is not shown
by default to avoid cluttering the output. You can use the -r option to see details corresponding to the short letters
shown in the test progress:
py.test -rxs
During test function setup the condition (sys.version_info >= (3,3)) is checked. If it evaluates to True, the test
function will be skipped with the specified reason. Note that pytest enforces specifying a reason in order to report
meaningful skip reasons (e.g. when using -rs). If the condition is a string, it will be evaluated as python expression.
You can share skipif markers between modules. Consider this test module:
# content of test_mymodule.py
import mymodule
minversion = pytest.mark.skipif(mymodule.__versioninfo__ < (1,1),
reason="at least mymodule-1.1 required")
@minversion
def test_function():
...
2.13. Skip and xfail: dealing with tests that can not succeed
61
# test_myothermodule.py
from test_mymodule import minversion
@minversion
def test_anotherfunction():
...
For larger test suites its usually a good idea to have one file where you define the markers which you then consistently
apply throughout your test suite.
Alternatively, the pre pytest-2.4 way to specify condition strings instead of booleans will remain fully supported in
future versions of pytest. It couldnt be easily used for importing markers between test modules so its no longer
advertised as the primary method.
If the condition is true, this marker will produce a skip result for each of the test methods.
If your code targets python2.5 where class-decorators are not available, you can set the pytestmark attribute of a
class:
class TestPosixCalls:
pytestmark = pytest.mark.skipif(sys.platform == 'win32',
reason="requires Windows")
def test_function(self):
"will not be setup or run under 'win32' platform"
As with the class-decorator, the pytestmark special name tells pytest to apply it to each test function in the class.
If you want to skip all test functions of a module, you must use the pytestmark name on the global level:
# test_module.py
pytestmark = pytest.mark.skipif(...)
If multiple skipif decorators are applied to a test function, it will be skipped if any of the skip conditions is true.
This test will be run but no traceback will be reported when it fails. Instead terminal reporting will list it in the
expected to fail or unexpectedly passing sections.
62
you can force the running and reporting of an xfail marked test as if it werent marked at all.
As with skipif you can also mark your expectation of a failure on a particular platform:
@pytest.mark.xfail(sys.version_info >= (3,3),
reason="python3.3 api changes")
def test_function():
...
If you want to be more specific as to why the test is failing, you can specify a single exception, or a list of exceptions,
in the raises argument. Then the test will be reported as a regular failure if it fails with an exception not mentioned
in raises.
You can furthermore prevent the running of an xfail test or specify a reason such as a bug ID or similar. Here is a
simple test file with the several usages:
import pytest
xfail = pytest.mark.xfail
@xfail
def test_hello():
assert 0
@xfail(run=False)
def test_hello2():
assert 0
@xfail("hasattr(os, 'sep')")
def test_hello3():
assert 0
@xfail(reason="bug 110")
def test_hello4():
assert 0
@xfail('pytest.__version__[0] != "17"')
def test_hello5():
assert 0
def test_hello6():
pytest.xfail("reason")
@xfail(raises=IndexError)
def test_hello7():
x = []
x[1] = 1
2.13. Skip and xfail: dealing with tests that can not succeed
63
If docutils cannot be imported here, this will lead to a skip outcome of the test. You can also skip based on the
version number of a library:
64
The version will be read from the specified modules __version__ attribute.
During test function setup the skipif condition is evaluated by calling eval(sys.version_info >=
(3,0), namespace). The namespace contains all the module globals, and os and sys as a minimum.
Since pytest-2.4 condition booleans are considered preferable because markers can then be freely imported between
test modules. With strings you need to import not only the marker but all variables everything used by the marker,
which violates encapsulation.
The reason for specifying the condition as a string was that pytest can report a summary of skip conditions based
purely on the condition string. With conditions as booleans you are required to specify a reason string.
Note that string conditions will remain fully supported and you are free to use them if you have no need for crossimporting markers.
The evaluation of a condition string in pytest.mark.skipif(conditionstring) or
pytest.mark.xfail(conditionstring) takes place in a namespace dictionary which is constructed
as follows:
the namespace is initialized by putting the sys and os modules and the pytest config object into it.
updated with the module globals of the test function for which the expression is applied.
The pytest config object allows you to skip based on a test configuration value which you might have added:
@pytest.mark.skipif("not config.getvalue('db')")
def test_function(...):
...
Note:
You cannot use pytest.config.getvalue() in code imported before py.tests argument parsing takes place. For example, conftest.py files are imported before command line parsing and thus
config.getvalue() will not execute correctly.
2.13. Skip and xfail: dealing with tests that can not succeed
65
2.15.1 Usage
After Installation type:
py.test
and you should be able to run your unittest-style tests if they are contained in test_* modules. If that works for
you then you can make use of most pytest features, for example --pdb debugging in failures, using plain assertstatements, more informative tracebacks, stdout-capturing or distributing tests to multiple CPUs via the -nNUM option
if you installed the pytest-xdist plugin. Please refer to the general pytest documentation for many more
examples.
66
This defines a fixture function db_class which - if used - is called once for each test class and which sets the classlevel db attribute to a DummyDB instance. The fixture function achieves this by receiving a special request object
which gives access to the requesting test context such as the cls attribute, denoting the class from which the fixture is
used. This architecture de-couples fixture writing from actual test code and allows re-use of the fixture by a minimal
reference, the fixture name. So lets write an actual unittest.TestCase class using our fixture definition:
# content of test_unittest_db.py
import unittest
import pytest
@pytest.mark.usefixtures("db_class")
class MyTest(unittest.TestCase):
def test_method1(self):
assert hasattr(self, "db")
assert 0, self.db
# fail for demo purposes
def test_method2(self):
assert 0, self.db
# fail for demo purposes
The @pytest.mark.usefixtures("db_class") class-decorator makes sure that the pytest fixture function
db_class is called once per class. Due to the deliberately failing assert statements, we can take a look at the
self.db values in the traceback:
$ py.test test_unittest_db.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-119, inifile:
collected 2 items
test_unittest_db.py FF
================================= FAILURES =================================
___________________________ MyTest.test_method1 ____________________________
self = <test_unittest_db.MyTest testMethod=test_method1>
def test_method1(self):
assert hasattr(self, "db")
67
>
E
E
assert 0, self.db
# fail for demo purposes
AssertionError: <conftest.db_class.<locals>.DummyDB object at 0x7f97382031d0>
assert 0
test_unittest_db.py:9: AssertionError
___________________________ MyTest.test_method2 ____________________________
self = <test_unittest_db.MyTest testMethod=test_method2>
>
E
E
def test_method2(self):
assert 0, self.db
# fail for demo purposes
AssertionError: <conftest.db_class.<locals>.DummyDB object at 0x7f97382031d0>
assert 0
test_unittest_db.py:12: AssertionError
========================= 2 failed in 0.04 seconds =========================
This default pytest traceback shows that the two test methods share the same self.db instance which was our
intention when writing the class-scoped fixture function above.
Due to the autouse flag the initdir fixture function will be used for all methods of the class where it is defined. This is a shortcut for using a @pytest.mark.usefixtures("initdir") marker on the class like in
the previous example.
Running this test module ...:
$ py.test -q test_unittest_cleandir.py
.
1 passed in 0.25 seconds
... gives us one passed test because the initdir fixture function was executed ahead of the test_method.
Note:
68
While pytest supports receiving fixtures via test function arguments for non-unittest test methods,
Chapter 2. pytest reference documentation
unittest.TestCase methods cannot directly receive fixture function arguments as implementing that is likely to
inflict on the ability to run general unittest.TestCase test suites. Maybe optional support would be possible, though.
If unittest finally grows a plugin system that should help as well. In the meanwhile, the above usefixtures and
autouse examples should help to mix in pytest fixtures into unittest suites. And of course you can also start to
selectively leave away the unittest.TestCase subclassing, use plain asserts and get the unlimited pytest feature
set.
2.16.1 Usage
After Installation type:
python setup.py develop # make sure tests can import our package
py.test # instead of 'nosetests'
and you should be able to run your nose style tests and make use of pytests capabilities.
69
on the command line. You can also trigger running of doctests from docstrings in all python modules (including
regular python test modules):
py.test --doctest-modules
You can make these changes permanent in your project by putting them into a pytest.ini file like this:
# content of pytest.ini
[pytest]
addopts = --doctest-modules
then you can just invoke py.test without command line options:
$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-96, inifile: pytest.ini
collected 1 items
mymodule.py .
========================= 1 passed in 0.06 seconds =========================
Also, using fixtures from classes, modules or projects and autouse fixtures (xUnit setup on steroids) fixtures are supported when executing text doctest files.
70
The standard doctest module provides some setting flags to configure the strictness of doctest tests. In py.test You
can enable those flags those flags using the configuration file. To make pytest ignore trailing whitespaces and ignore
lengthy exception stack traces you can just write:
# content of pytest.ini
[pytest]
doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
71
72
CHAPTER
THREE
pytest implements all aspects of configuration, collection, running and reporting by calling well specified hooks.
Virtually any Python module can be registered as a plugin. It can implement any number of hook functions (usually
two or three) which all have a pytest_ prefix, making hook functions easy to distinguish and find. There are three
basic location types:
builtin plugins: loaded from pytests internal _pytest directory.
external plugins: modules discovered through setuptools entry points
conftest.py plugins: modules auto-discovered in test directories
Note: If you have conftest.py files which do not reside in a python package directory (i.e. one containing an
__init__.py) then import conftest can be ambiguous because there might be other conftest.py files as well
on your PYTHONPATH or sys.path. It is thus good practise for projects to either put conftest.py under a
package scope or to never import anything from a conftest.py file.
73
If a plugin is installed, pytest automatically finds and integrates it, there is no need to activate it. We have a page
listing all 3rd party plugins and their status against the latest py.test version and here is a little annotated list for some
popular plugins:
pytest-django: write tests for django apps, using pytest integration.
pytest-twisted: write tests for twisted apps, starting a reactor and processing deferreds from test functions.
pytest-capturelog: to capture and assert about messages from the logging module
pytest-cov: coverage reporting, compatible with distributed testing
pytest-xdist: to distribute tests to CPUs and remote hosts, to run in boxed mode which allows to survive segmentation faults, to run in looponfailing mode, automatically re-running failing tests on file changes, see also
xdist: pytest distributed testing plugin
pytest-instafail: to report failures while the test run is happening.
pytest-bdd and pytest-konira to write tests using behaviour-driven testing.
pytest-timeout: to timeout tests based on function marks or global definitions.
pytest-cache: to interactively re-run failing tests and help other plugins to store test run information across
invocations.
pytest-pep8: a --pep8 option to enable PEP8 compliance checking.
oejskit: a plugin to run javascript unittests in life browsers
To see a complete list of all plugins with their latest testing status against different py.test and Python versions, please
visit plugincompat.
You may also discover more plugins through a pytest- pypi.python.org search.
74
the pytest11 entrypoint to discover its plugins and you can thus make your plugin available by defining it in your
setuptools-invocation:
# sample ./setup.py file
from setuptools import setup
setup(
name="myproject",
packages = ['myproject']
# the following makes a plugin available to pytest
entry_points = {
'pytest11': [
'name_of_plugin = myproject.pluginmodule',
]
},
)
If a package is installed this way, pytest will load myproject.pluginmodule as a plugin which can define
well specified hooks.
When the test module or conftest plugin is loaded the specified plugins will be loaded as well. You can also use dotted
path like this:
pytest_plugins = "myapp.testsupport.myplugin"
75
If you want to look at the names of existing plugins, use the --traceconfig option.
and will get an extended test header which shows activated plugins and their names. It will also print local plugins aka
conftest.py files when they are loaded.
This means that any subsequent try to activate/load the named plugin will it already existing. See Finding out which
plugins are active for how to obtain the name of a plugin.
76
CHAPTER
FOUR
You can find the source code for the following plugins in the pytest repository.
_pytest.assertion
_pytest.capture
_pytest.config
_pytest.doctest
_pytest.genscript
_pytest.helpconfig
_pytest.junitxml
_pytest.mark
_pytest.monkeypatch
_pytest.nose
_pytest.pastebin
_pytest.pdb
_pytest.pytester
_pytest.python
_pytest.recwarn
_pytest.resultlog
_pytest.runner
_pytest.main
_pytest.skipping
_pytest.terminal
_pytest.tmpdir
_pytest.unittest
77
78
CHAPTER
FIVE
79
pytest_configure(config)
called after command line options have been parsed and all plugins and initial conftest files been loaded.
pytest_unconfigure(config)
called before test process is exited.
object
for
the
given
pytest.Item
and
For deeper understanding you may look at the default implementation of these hooks in _pytest.runner and
maybe also in _pytest.pdb which interacts with _pytest.capture and its input/output capturing in order to
immediately drop into interactive debugging when a test failure occurs.
The _pytest.terminal reported specifically uses the reporting hook to print information about a test run.
80
pytest_collect_file(path, parent)
return collection Node or None for the given path. Any new node needs to have the specified parent as a
parent.
For influencing the collection of objects in Python modules you can use the following hook:
pytest_pycollect_makeitem(collector, name, obj)
return custom item/collector for a python object in a module, or None.
pytest_generate_tests(metafunc)
generate (multiple) parametrized calls to a test function.
After collection is complete, you can modify the order of items, delete or otherwise amend the test items:
pytest_collection_modifyitems(session, config, items)
called after collection has been performed, may filter or re-order the items in-place.
81
pytest_addhooks(pluginmanager)
called at plugin load time to allow adding new hooks via a call to pluginmanager.registerhooks(module).
Hooks are usually declared as do-nothing functions that contain only documentation describing when the hook will be
called and what return values are expected.
For an example, see newhooks.py from xdist: pytest distributed testing plugin.
This has the added benefit of allowing you to conditionally install hooks depending on which plugins are installed.
82
Note that hook wrappers dont return results themselves, they merely perform tracing or other side effects around the
actual hook implementations. If the result of the underlying hook is a mutable object, they may modify that result,
however.
83
84
CHAPTER
SIX
class Config
access to configuration values, pluginmanager and plugin hooks.
option = None
access to command line option as attributes. (deprecated), use getoption() instead
pluginmanager = None
a pluginmanager instance
warn(code, message)
generate a warning for this test session.
classmethod fromdictargs(option_dict, args)
constructor useable for subprocesses.
addinivalue_line(name, line)
add a line to an ini-file option. The option must have been declared but might not yet be set in which case
the line becomes the the first line in its value.
getini(name)
return configuration value from an ini file. If the specified name hasnt been registered through a prior
parser.addini call (usually from a plugin), a ValueError is raised.
getoption(name, default=<NOTSET>, skip=False)
return command line option value.
Parameters
name name of the option. You may also specify the literal --OPT option instead of the
dest option name.
default default value if no option of that name exists.
skip if True raise pytest.skip if option does not exists or has a None value.
getvalue(name, path=None)
(deprecated, use getoption())
getvalueorskip(name, path=None)
(deprecated, use getoption(skip=True))
class Parser
Parser for command line arguments and ini-file values.
getgroup(name, description=, after=None)
get (or create) a named option Group.
Name name of the option group.
85
86
add_marker(marker)
dynamically add a marker object to the node.
marker can be a string or pytest.mark.* instance.
get_marker(name)
get a marker object from this node or None if the node doesnt have a marker with that name.
listextrakeywords()
Return a set of all extra keywords in self and any parents.
addfinalizer(fin)
register a function to be called when this node is finalized.
This method can only be called when this node is active in a setup chain, for example during self.setup().
getparent(cls)
get the next parent node (including ourself) which is an instance of the given class
class Collector
Bases: _pytest.main.Node
Collector instances create children through collect() and thus iteratively build a tree.
exception CollectError
Bases: exceptions.Exception
an error during collection, contains a custom message.
Collector.collect()
returns a list of children (items and collectors) for this collection node.
Collector.repr_failure(excinfo)
represent a collection failure.
class Item
Bases: _pytest.main.Node
a basic test invocation item. Note that for a single function there might be multiple test invocation items.
class Module
Bases: _pytest.main.File, _pytest.python.PyCollector
Collector for test classes and functions.
class Class
Bases: _pytest.python.PyCollector
Collector for test methods.
class Function
Bases:
_pytest.python.FunctionMixin,
_pytest.python.FuncargnamesCompatAttr
_pytest.main.Item,
a Function Item is responsible for setting up and executing a Python test function.
function
underlying python function object
runtest()
execute the underlying test function.
class CallInfo
Result/Exception info a function invocation.
87
when = None
context of invocation: one of setup, call, teardown, memocollect
excinfo = None
None or ExceptionInfo object.
class TestReport
Basic test report object (also used for setup and teardown calls if they fail).
nodeid = None
normalized collection node id
location = None
a (filesystempath, lineno, domaininfo) tuple indicating the actual location of a test item - it might be
different from the collected one e.g. if a method is inherited from a different module.
keywords = None
a name -> value dictionary containing all keywords and markers associated with a test invocation.
outcome = None
test outcome, always one of passed, failed, skipped.
longrepr = None
None or a failure representation.
when = None
one of setup, call, teardown to indicate runtest phase.
sections = None
list of (secname, data) extra information which needs to marshallable
duration = None
time it took to run just the test
class CallOutcome
Outcome of a function call, either an exception or a proper result. Calling the get_result method will return
the result or reraise the exception raised when the function was called.
88
CHAPTER
SEVEN
The table below contains a listing of plugins found in PyPI and their status when tested using py.test 2.7.0 and python
2.7 and 3.3.
A complete listing can also be found at plugincompat, which contains tests status against other py.test releases.
Name
Py27
Py34
Home
Summary
pytest-allure-adaptor
pytest-ansible
UNKNOWN
pytest-autochecklog
pytest-bdd
pytest-beakerlib
link
pytest-beds
pytest-bench
pytest-benchmark
pytest-blockage
pytest-bpdb
pytest-browsermob-proxy
pytest-bugzilla
pytest-cache
pytest-cagoule
pytest-capturelog
pytest-catchlog
pytest-circleci
pytest-cloud
pytest-codecheckers
pytest plugin to add source code sanity checks (pep8 and friends)
89
Py27
Py34
Home
Summary
pytest-colordots
pytest-config
Base configurations and utilities for developing your Python project test
pytest-contextfixture
pytest-couchdbkit
pytest-cov
py.test plugin for coverage reporting with support for both centralised an
pytest-cpp
pytest-dbfixtures
pytest-dbus-notification
pytest-describe
pytest-diffeo
pytest-django
link
pytest-django-haystack
pytest-django-lite
pytest-django-sqlcount
pytest-echo
link
py.test plugin for reporting the number of SQLs executed per django test
pytest plugin with mechanisms for echoing environment variables, packa
pytest-env
pytest-eradicate
pytest-figleaf
pytest-fixture-tools
pytest-flakes
pytest-flask
pytest-greendots
pytest-growl
?
?
pytest-httpbin
pytest-httpretty
pytest-incremental
pytest-instafail
pytest-ipdb
pytest-ipynb
Use pytests runner to discover and execute tests as cells of IPython note
90
Py27
Py34
Home
Summary
pytest-jira
pytest-knows
A pytest plugin that can automaticly skip test case based on dependence
pytest-konira
pytest-localserver
pytest-marker-bugzilla
pytest-markfiltration
UNKNOWN
pytest-marks
UNKNOWN
pytest-mock
Thin-wrapper around the mock package for easier use with py.test
pytest-monkeyplus
pytest-mozwebqa
pytest-multihost
link
pytest-oerp
pytest-oot
link
pytest-optional
pytest-ordering
pytest-osxnotify
pytest-paste-config
pytest-pep257
?
?
pytest-pep8
pytest-pipeline
pytest-poo
pytest-poo-fail
pytest-pycharm
pytest-pydev
pytest-pyq
link
pytest-pythonpath
pytest-qt
pytest-quickcheck
pytest-rage
91
Py27
Py34
Home
Summary
pytest-raisesregexp
pytest-random
pytest-readme
pytest-regtest
link
pytest-remove-stale-bytecode
pytest-rerunfailures
pytest-runfailed
pytest-runner
pytest-services
pytest-sftpserver
pytest-smartcov
pytest-sourceorder
link
pytest-spec
pytest-splinter
pytest-stepwise
pytest-sugar
py.test is a plugin for py.test that changes the default look and feel of py.
pytest-timeout
pytest-tornado
pytest-translations
pytest-twisted
pytest-unmarked
pytest-watch
pytest-xdist
pytest-xprocess
pytest-yamlwsgi
pytest-zap
(Updated on 2015-02-28)
92
CHAPTER
EIGHT
Here is a (growing) list of examples. Contact us if you need more examples or have questions. Also take a look at
the comprehensive documentation which contains many example snippets as well. Also, pytest on stackoverflow.com
often comes with example answers.
For basic examples, see
Installation and Getting Started for basic introductory examples
Asserting with the assert statement for basic assertion examples
pytest fixtures: explicit, modular, scalable for basic fixture/setup examples
Parametrizing fixtures and test functions for basic test function parametrization
Support for unittest.TestCase / Integration of fixtures for basic unittest integration
Running tests written for nose for basic nosetests integration
The following examples aim at various use cases you might encounter.
>
E
failure_demo.py:15: AssertionError
_________________________ TestFailing.test_simple __________________________
93
failure_demo.py:28: AssertionError
____________________ TestFailing.test_simple_multiline _____________________
self = <failure_demo.TestFailing object at 0x7f65f1c812b0>
>
def test_simple_multiline(self):
otherfunc_multi(
42,
6*9)
failure_demo.py:33:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
a = 42, b = 54
>
E
def otherfunc_multi(a,b):
assert (a ==
b)
assert 42 == 54
failure_demo.py:11: AssertionError
___________________________ TestFailing.test_not ___________________________
self = <failure_demo.TestFailing object at 0x7f65f1c9df98>
>
E
E
def test_not(self):
def f():
return 42
assert not f()
assert not 42
+ where 42 = <function TestFailing.test_not.<locals>.f at 0x7f65f2323598>()
failure_demo.py:38: AssertionError
_________________ TestSpecialisedExplanations.test_eq_text _________________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c67710>
>
E
E
E
def test_eq_text(self):
assert 'spam' == 'eggs'
assert 'spam' == 'eggs'
- spam
+ eggs
failure_demo.py:42: AssertionError
_____________ TestSpecialisedExplanations.test_eq_similar_text _____________
94
>
E
E
E
E
E
def test_eq_similar_text(self):
assert 'foo 1 bar' == 'foo 2 bar'
assert 'foo 1 bar' == 'foo 2 bar'
- foo 1 bar
?
^
+ foo 2 bar
?
^
failure_demo.py:45: AssertionError
____________ TestSpecialisedExplanations.test_eq_multiline_text ____________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1cc4d30>
>
E
E
E
E
E
def test_eq_multiline_text(self):
assert 'foo\nspam\nbar' == 'foo\neggs\nbar'
assert 'foo\nspam\nbar' == 'foo\neggs\nbar'
foo
- spam
+ eggs
bar
failure_demo.py:48: AssertionError
______________ TestSpecialisedExplanations.test_eq_long_text _______________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1cce588>
>
E
E
E
E
E
E
E
def test_eq_long_text(self):
a = '1'*100 + 'a' + '2'*100
b = '1'*100 + 'b' + '2'*100
assert a == b
assert '111111111111...2222222222222' == '1111111111111...2222222222222'
Skipping 90 identical leading characters in diff, use -v to show
Skipping 91 identical trailing characters in diff, use -v to show
- 1111111111a222222222
?
^
+ 1111111111b222222222
?
^
failure_demo.py:53: AssertionError
_________ TestSpecialisedExplanations.test_eq_long_text_multiline __________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c81cc0>
>
E
E
E
E
E
E
E
E
E
def test_eq_long_text_multiline(self):
a = '1\n'*100 + 'a' + '2\n'*100
b = '1\n'*100 + 'b' + '2\n'*100
assert a == b
assert '1\n1\n1\n1\n...n2\n2\n2\n2\n' == '1\n1\n1\n1\n1...n2\n2\n2\n2\n'
Skipping 190 identical leading characters in diff, use -v to show
Skipping 191 identical trailing characters in diff, use -v to show
1
1
1
1
1
- a2
95
E
E
E
E
E
+ b2
2
2
2
2
failure_demo.py:58: AssertionError
_________________ TestSpecialisedExplanations.test_eq_list _________________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1ca2cc0>
>
E
E
E
def test_eq_list(self):
assert [0, 1, 2] == [0, 1, 3]
assert [0, 1, 2] == [0, 1, 3]
At index 2 diff: 2 != 3
Use -v to get the full diff
failure_demo.py:61: AssertionError
______________ TestSpecialisedExplanations.test_eq_list_long _______________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c29358>
>
E
E
E
def test_eq_list_long(self):
a = [0]*100 + [1] + [3]*100
b = [0]*100 + [2] + [3]*100
assert a == b
assert [0, 0, 0, 0, 0, 0, ...] == [0, 0, 0, 0, 0, 0, ...]
At index 100 diff: 1 != 2
Use -v to get the full diff
failure_demo.py:66: AssertionError
_________________ TestSpecialisedExplanations.test_eq_dict _________________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c9b588>
>
E
E
E
E
E
E
E
E
E
def test_eq_dict(self):
assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}
assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}
Omitting 1 identical items, use -v to show
Differing items:
{'b': 1} != {'b': 2}
Left contains more items:
{'c': 0}
Right contains more items:
{'d': 0}
Use -v to get the full diff
failure_demo.py:69: AssertionError
_________________ TestSpecialisedExplanations.test_eq_set __________________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c7fdd8>
>
E
E
E
E
96
def test_eq_set(self):
assert set([0, 10, 11, 12]) == set([0, 20, 21])
assert set([0, 10, 11, 12]) == set([0, 20, 21])
Extra items in the left set:
10
11
E
E
E
E
E
12
Extra items in the right set:
20
21
Use -v to get the full diff
failure_demo.py:72: AssertionError
_____________ TestSpecialisedExplanations.test_eq_longer_list ______________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c347f0>
>
E
E
E
def test_eq_longer_list(self):
assert [1,2] == [1,2,3]
assert [1, 2] == [1, 2, 3]
Right contains more items, first extra item: 3
Use -v to get the full diff
failure_demo.py:75: AssertionError
_________________ TestSpecialisedExplanations.test_in_list _________________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f2313668>
>
E
def test_in_list(self):
assert 1 in [0, 2, 3, 4, 5]
assert 1 in [0, 2, 3, 4, 5]
failure_demo.py:78: AssertionError
__________ TestSpecialisedExplanations.test_not_in_text_multiline __________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1cceb38>
>
E
E
E
E
E
E
E
E
E
def test_not_in_text_multiline(self):
text = 'some multiline\ntext\nwhich\nincludes foo\nand a\ntail'
assert 'foo' not in text
assert 'foo' not in 'some multiline\ntext\nw...ncludes foo\nand a\ntail'
'foo' is contained here:
some multiline
text
which
includes foo
?
+++
and a
tail
failure_demo.py:82: AssertionError
___________ TestSpecialisedExplanations.test_not_in_text_single ____________
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1c27438>
>
E
E
E
E
def test_not_in_text_single(self):
text = 'single foo line'
assert 'foo' not in text
assert 'foo' not in 'single foo line'
'foo' is contained here:
single foo line
?
+++
failure_demo.py:86: AssertionError
97
>
E
E
E
E
def test_not_in_text_single_long(self):
text = 'head ' * 50 + 'foo ' + 'tail ' * 20
assert 'foo' not in text
assert 'foo' not in 'head head head head hea...ail tail tail tail tail '
'foo' is contained here:
head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
?
+++
failure_demo.py:90: AssertionError
______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______
self = <failure_demo.TestSpecialisedExplanations object at 0x7f65f1ce16d8>
>
E
E
E
E
def test_not_in_text_single_long_term(self):
text = 'head ' * 50 + 'f'*70 + 'tail ' * 20
assert 'f'*70 not in text
assert 'fffffffffff...ffffffffffff' not in 'head head he...l tail tail '
'ffffffffffffffffff...fffffffffffffffffff' is contained here:
head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail
?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
failure_demo.py:94: AssertionError
______________________________ test_attribute ______________________________
>
E
E
def test_attribute():
class Foo(object):
b = 1
i = Foo()
assert i.b == 2
assert 1 == 2
+ where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0x7f65f1c814e0>.b
failure_demo.py:101: AssertionError
_________________________ test_attribute_instance __________________________
>
E
E
E
def test_attribute_instance():
class Foo(object):
b = 1
assert Foo().b == 2
assert 1 == 2
+ where 1 = <failure_demo.test_attribute_instance.<locals>.Foo object at 0x7f65f1c7f7f0>.b
+
where <failure_demo.test_attribute_instance.<locals>.Foo object at 0x7f65f1c7f7f0> = <c
failure_demo.py:107: AssertionError
__________________________ test_attribute_failure __________________________
>
98
def test_attribute_failure():
class Foo(object):
def _get_b(self):
raise Exception('Failed to get attrib')
b = property(_get_b)
i = Foo()
assert i.b == 2
failure_demo.py:116:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <failure_demo.test_attribute_failure.<locals>.Foo object at 0x7f65f1c97dd8>
>
E
def _get_b(self):
raise Exception('Failed to get attrib')
Exception: Failed to get attrib
failure_demo.py:113: Exception
_________________________ test_attribute_multiple __________________________
>
E
E
E
E
E
def test_attribute_multiple():
class Foo(object):
b = 1
class Bar(object):
b = 2
assert Foo().b == Bar().b
assert 1 == 2
+ where 1 = <failure_demo.test_attribute_multiple.<locals>.Foo object at 0x7f65f1c9b630>.b
+
where <failure_demo.test_attribute_multiple.<locals>.Foo object at 0x7f65f1c9b630> = <c
+ and
2 = <failure_demo.test_attribute_multiple.<locals>.Bar object at 0x7f65f1c9b2b0>.b
+
where <failure_demo.test_attribute_multiple.<locals>.Bar object at 0x7f65f1c9b2b0> = <c
failure_demo.py:124: AssertionError
__________________________ TestRaises.test_raises __________________________
self = <failure_demo.TestRaises object at 0x7f65f1c3eba8>
>
def test_raises(self):
s = 'qwe'
raises(TypeError, "int(s)")
failure_demo.py:133:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
E
int(s)
ValueError: invalid literal for int() with base 10: 'qwe'
>
E
def test_raises_doesnt(self):
raises(IOError, "int('3')")
Failed: DID NOT RAISE
failure_demo.py:136: Failed
__________________________ TestRaises.test_raise ___________________________
self = <failure_demo.TestRaises object at 0x7f65f1cceeb8>
>
E
def test_raise(self):
raise ValueError("demo error")
ValueError: demo error
failure_demo.py:139: ValueError
99
>
E
def test_tupleerror(self):
a,b = [1]
ValueError: need more than 1 value to unpack
failure_demo.py:142: ValueError
______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______
self = <failure_demo.TestRaises object at 0x7f65f1ca2240>
>
E
def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
l = [1,2,3]
print ("l is %r" % l)
a,b = l.pop()
TypeError: 'int' object is not iterable
failure_demo.py:147: TypeError
--------------------------- Captured stdout call --------------------------l is [1, 2, 3]
________________________ TestRaises.test_some_error ________________________
self = <failure_demo.TestRaises object at 0x7f65f1cb36a0>
>
E
def test_some_error(self):
if namenotexi:
NameError: name 'namenotexi' is not defined
failure_demo.py:150: NameError
____________________ test_dynamic_compile_shows_nicely _____________________
>
def test_dynamic_compile_shows_nicely():
src = 'def foo():\n assert 1 == 0\n'
name = 'abc-123'
module = py.std.imp.new_module(name)
code = py.code.compile(src, name, 'exec')
py.builtin.exec_(code, module.__dict__)
py.std.sys.modules[name] = module
module.foo()
failure_demo.py:165:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
E
def foo():
assert 1 == 0
assert 1 == 0
100
>
return 43
somefunc(f(), g())
failure_demo.py:175:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
failure_demo.py:8: in somefunc
otherfunc(x,y)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
a = 44, b = 43
>
E
def otherfunc(a,b):
assert a==b
assert 44 == 43
failure_demo.py:5: AssertionError
___________________ TestMoreErrors.test_z1_unpack_error ____________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1c9d940>
>
E
def test_z1_unpack_error(self):
l = []
a,b = l
ValueError: need more than 0 values to unpack
failure_demo.py:179: ValueError
____________________ TestMoreErrors.test_z2_type_error _____________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1c7f208>
>
E
def test_z2_type_error(self):
l = 3
a,b = l
TypeError: 'int' object is not iterable
failure_demo.py:183: TypeError
______________________ TestMoreErrors.test_startswith ______________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1cc40b8>
>
E
E
def test_startswith(self):
s = "123"
g = "456"
assert s.startswith(g)
assert <built-in method startswith of str object at 0x7f65f1ce14c8>('456')
+ where <built-in method startswith of str object at 0x7f65f1ce14c8> = '123'.startswith
failure_demo.py:188: AssertionError
__________________ TestMoreErrors.test_startswith_nested ___________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1c81b00>
>
def test_startswith_nested(self):
def f():
return "123"
def g():
return "456"
assert f().startswith(g())
101
E
E
E
E
failure_demo.py:195: AssertionError
_____________________ TestMoreErrors.test_global_func ______________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1c97240>
>
E
E
def test_global_func(self):
assert isinstance(globf(42), float)
assert isinstance(43, float)
+ where 43 = globf(42)
failure_demo.py:198: AssertionError
_______________________ TestMoreErrors.test_instance _______________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1ce1080>
>
E
E
def test_instance(self):
self.x = 6*7
assert self.x != 42
assert 42 != 42
+ where 42 = <failure_demo.TestMoreErrors object at 0x7f65f1ce1080>.x
failure_demo.py:202: AssertionError
_______________________ TestMoreErrors.test_compare ________________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1c3e828>
>
E
E
def test_compare(self):
assert globf(10) < 5
assert 11 < 5
+ where 11 = globf(10)
failure_demo.py:205: AssertionError
_____________________ TestMoreErrors.test_try_finally ______________________
self = <failure_demo.TestMoreErrors object at 0x7f65f1c67828>
>
E
def test_try_finally(self):
x = 1
try:
assert x == 0
assert 1 == 0
failure_demo.py:210: AssertionError
___________________ TestCustomAssertMsg.test_single_line ___________________
self = <failure_demo.TestCustomAssertMsg object at 0x7f65f1c29860>
>
E
102
def test_single_line(self):
class A:
a = 1
b = 2
assert A.a == b, "A.a appears not to be b"
AssertionError: A.a appears not to be b
E
E
assert 1 == 2
+ where 1 = <class 'failure_demo.TestCustomAssertMsg.test_single_line.<locals>.A'>.a
failure_demo.py:221: AssertionError
____________________ TestCustomAssertMsg.test_multiline ____________________
self = <failure_demo.TestCustomAssertMsg object at 0x7f65f1c676a0>
>
E
E
E
E
E
def test_multiline(self):
class A:
a = 1
b = 2
assert A.a == b, "A.a appears not to be b\n" \
"or does not appear to be b\none of those"
AssertionError: A.a appears not to be b
or does not appear to be b
one of those
assert 1 == 2
+ where 1 = <class 'failure_demo.TestCustomAssertMsg.test_multiline.<locals>.A'>.a
failure_demo.py:227: AssertionError
___________________ TestCustomAssertMsg.test_custom_repr ___________________
self = <failure_demo.TestCustomAssertMsg object at 0x7f65f1ccebe0>
>
E
E
E
E
E
E
def test_custom_repr(self):
class JSON:
a = 1
def __repr__(self):
return "This is JSON\n{\n 'foo': 'bar'\n}"
a = JSON()
b = 2
assert a.a == b, a
AssertionError: This is JSON
{
'foo': 'bar'
}
assert 1 == 2
+ where 1 = This is JSON\n{\n 'foo': 'bar'\n}.a
failure_demo.py:237: AssertionError
======================== 42 failed in 0.35 seconds =========================
103
For this to work we need to add a command line option and provide the cmdopt through a fixture function:
# content of conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption("--cmdopt", action="store", default="type1",
help="my option: type1 or type2")
@pytest.fixture
def cmdopt(request):
return request.config.getoption("--cmdopt")
>
E
def test_answer(cmdopt):
if cmdopt == "type1":
print ("first")
elif cmdopt == "type2":
print ("second")
assert 0 # to see what was printed
assert 0
test_sample.py:6: AssertionError
--------------------------- Captured stdout call --------------------------first
1 failed in 0.01 seconds
>
E
def test_answer(cmdopt):
if cmdopt == "type1":
print ("first")
elif cmdopt == "type2":
print ("second")
assert 0 # to see what was printed
assert 0
test_sample.py:6: AssertionError
--------------------------- Captured stdout call --------------------------second
1 failed in 0.01 seconds
You can see that the command line option arrived in our test. This completes the basic pattern. However, one often
104
rather wants to process command line options outside of the test and rather pass in different or more complex objects.
If you have the xdist plugin installed you will now always perform test runs using a number of subprocesses close to
your CPU. Running in an empty directory with the above conftest.py:
$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-162, inifile:
collected 0 items
=============================
105
$ py.test -rs
# "-rs" means report details on the little 's'
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-162, inifile:
collected 2 items
test_module.py .s
========================= short test summary info ==========================
SKIP [1] /tmp/doc-exec-162/conftest.py:9: need --runslow option to run
=================== 1 passed, 1 skipped in 0.01 seconds ====================
The __tracebackhide__ setting influences pytest showing of tracebacks: the checkconfig function will
not be shown unless the --fulltrace command line option is specified. Lets run our little function:
$ py.test -q test_checkconfig.py
F
================================= FAILURES =================================
______________________________ test_something ______________________________
>
E
def test_something():
checkconfig(42)
Failed: not configured: 42
test_checkconfig.py:8: Failed
1 failed in 0.02 seconds
106
accordingly in your application. Its also a good idea to use your own application module rather than sys for handling
flag.
You can also return a list of strings which will be considered as several lines of information. You can of course also
make the amount of reporting information on e.g. the value of config.option.verbose so that you present
more information appropriately:
# content of conftest.py
def pytest_report_header(config):
if config.option.verbose > 0:
return ["info1: did you know that ...", "did you?"]
107
These two hook implementations work together to abort incremental-marked tests in a class. Here is a test module
example:
# content of test_step.py
import pytest
@pytest.mark.incremental
class TestUserHandling:
def test_login(self):
pass
def test_modification(self):
assert 0
def test_deletion(self):
pass
def test_normal():
pass
If we run this:
$ py.test -rx
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-162, inifile:
collected 4 items
test_step.py .Fx.
================================= FAILURES =================================
____________________ TestUserHandling.test_modification ____________________
self = <test_step.TestUserHandling object at 0x7ff60bbb83c8>
>
E
def test_modification(self):
assert 0
assert 0
test_step.py:9: AssertionError
========================= short test summary info ==========================
XFAIL test_step.py::TestUserHandling::()::test_deletion
109
Well see that test_deletion was not executed because test_modification failed. It is reported as an
expected failure.
and then a module in a sister directory which will not see the db fixture:
# content of b/test_error.py
def test_root(db): # no db here, will error out
pass
110
>
E
def test_modification(self):
assert 0
assert 0
test_step.py:9: AssertionError
_________________________________ test_a1 __________________________________
db = <conftest.DB object at 0x7f8ecdc11470>
>
E
E
def test_a1(db):
assert 0, db # to show value
AssertionError: <conftest.DB object at 0x7f8ecdc11470>
assert 0
a/test_db.py:2: AssertionError
_________________________________ test_a2 __________________________________
db = <conftest.DB object at 0x7f8ecdc11470>
>
E
E
def test_a2(db):
assert 0, db # to show value
AssertionError: <conftest.DB object at 0x7f8ecdc11470>
assert 0
a/test_db2.py:2: AssertionError
========== 3 failed, 2 passed, 1 xfailed, 1 error in 0.05 seconds ==========
The two test modules in the a directory see the same db fixture instance while the one test in the sister-directory b
doesnt see it. We could of course also define a db fixture in that sister directorys conftest.py file. Note that
each fixture is only instantiated if there is a test actually needing it (unless you use autouse fixture which are always
executed ahead of the first test executing).
111
@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
# execute all other hooks to obtain the report object
rep = __multicall__.execute()
# we only look at actual failing test calls, not setup/teardown
if rep.when == "call" and rep.failed:
mode = "a" if os.path.exists("failures") else "w"
with open("failures", mode) as f:
# let's also access a fixture for the fun of it
if "tmpdir" in item.funcargs:
extra = " (%s)" % item.funcargs["tmpdir"]
else:
extra = ""
f.write(rep.nodeid + extra + "\n")
return rep
>
E
def test_fail1(tmpdir):
assert 0
assert 0
test_module.py:2: AssertionError
________________________________ test_fail2 ________________________________
>
E
def test_fail2():
assert 0
assert 0
test_module.py:4: AssertionError
========================= 2 failed in 0.02 seconds =========================
you will have a failures file which contains the failing test ids:
$ cat failures
test_module.py::test_fail1 (/tmp/pytest-22/test_fail10)
112
test_module.py::test_fail2
@pytest.fixture
def something(request):
def fin():
# request.node is an "item" because we use the default
# "function" scope
if request.node.rep_setup.failed:
print ("setting up a test failed!", request.node.nodeid)
elif request.node.rep_setup.passed:
if request.node.rep_call.failed:
print ("executing test failed", request.node.nodeid)
request.addfinalizer(fin)
113
$ py.test -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-162, inifile:
collected 3 items
test_module.py Esetting up a test failed! test_module.py::test_setup_fails
Fexecuting test failed test_module.py::test_call_fails
F
================================== ERRORS ==================================
____________________ ERROR at setup of test_setup_fails ____________________
>
E
@pytest.fixture
def other():
assert 0
assert 0
test_module.py:6: AssertionError
================================= FAILURES =================================
_____________________________ test_call_fails ______________________________
something = None
>
E
def test_call_fails(something):
assert 0
assert 0
test_module.py:12: AssertionError
________________________________ test_fail2 ________________________________
>
E
def test_fail2():
assert 0
assert 0
test_module.py:15: AssertionError
==================== 2 failed, 1 error in 0.02 seconds =====================
Youll see that the fixture finalizers could use the precise reporting information.
114
executables=[Executable("app_main.py")],
options={"build_exe":
{
'includes': pytest.freeze_includes()}
},
# ... other options
)
If you dont want to ship a different executable just in order to run your tests, you can make your program check for a
certain flag and pass control over to pytest instead. For example:
# contents of app_main.py
import sys
if len(sys.argv) > 1 and sys.argv[1] == '--pytest':
import pytest
sys.exit(pytest.main(sys.argv[2:]))
else:
# normal application execution: at this point argv can be parsed
# by your argument-parsing library of choice as usual
...
This makes it convenient to execute your tests from within your frozen application, using standard py.test
command-line options:
$ ./app_main --pytest --verbose --tb=long --junit-xml=results.xml test-suite/
/bin/sh: 1: ./app_main: not found
115
else:
end = 2
metafunc.parametrize("param1", range(end))
We run only two computations, so we see two dots. lets run the full monty:
$ py.test -q --all
....F
================================= FAILURES =================================
_____________________________ test_compute[4] ______________________________
param1 = 4
>
E
def test_compute(param1):
assert param1 < 4
assert 4 < 4
test_compute.py:3: AssertionError
1 failed, 4 passed in 0.02 seconds
As expected when running the full range of param1 values well get an error on the last one.
@pytest.mark.parametrize("a,b,expected", testdata)
def test_timedistance_v0(a, b, expected):
diff = a - b
assert diff == expected
116
def idfn(val):
if isinstance(val, (datetime,)):
# note this wouldn't show any hours/minutes/seconds
return val.strftime('%Y%m%d')
117
If you just collect tests youll also nicely see advanced and basic as variants for the test function:
$ py.test --collect-only test_scenarios.py
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-159, inifile:
collected 4 items
<Module 'test_scenarios.py'>
<Class 'TestSampleWithScenarios'>
<Instance '()'>
<Function 'test_demo1[basic]'>
<Function 'test_demo2[basic]'>
<Function 'test_demo1[advanced]'>
<Function 'test_demo2[advanced]'>
=============================
Note that we told metafunc.parametrize() that your scenario values should be considered class-scoped. With
pytest-2.3 this leads to a resource-based ordering.
We can now add a test configuration that generates two invocations of the test_db_initialized function and
also implements a factory that creates a database object for the actual test invocations:
# content of conftest.py
import pytest
def pytest_generate_tests(metafunc):
if 'db' in metafunc.fixturenames:
metafunc.parametrize("db", ['d1', 'd2'], indirect=True)
class DB1:
"one database object"
118
class DB2:
"alternative database object"
@pytest.fixture
def db(request):
if request.param == "d1":
return DB1()
elif request.param == "d2":
return DB2()
else:
raise ValueError("invalid internal test config")
>
E
def test_db_initialized(db):
# a dummy test
if db.__class__.__name__ == "DB2":
pytest.fail("deliberately failing for demo purposes")
Failed: deliberately failing for demo purposes
test_backends.py:6: Failed
1 failed, 1 passed in 0.01 seconds
The first invocation with db == "DB1" passed while the second with db == "DB2" failed. Our db fixture function has instantiated each of the DB values during the setup phase while the pytest_generate_tests generated
two according calls to the test_db_initialized during the collection phase.
119
argnames = list(funcarglist[0])
metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]
for funcargs in funcarglist])
class TestClass:
# a map specifying multiple argument sets for a test method
params = {
'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ],
'test_zerodivision': [dict(a=1, b=0), ],
}
def test_equals(self, a, b):
assert a == b
def test_zerodivision(self, a, b):
pytest.raises(ZeroDivisionError, "a/b")
Our test generator looks up a class-level definition which specifies which argument sets to use for each test function.
Lets run it:
$ py.test -q
F..
================================= FAILURES =================================
________________________ TestClass.test_equals[2-1] ________________________
self = <test_parametrize.TestClass object at 0x7f878094f630>, a = 1, b = 2
def test_equals(self, a, b):
assert a == b
assert 1 == 2
>
E
test_parametrize.py:18: AssertionError
1 failed, 2 passed in 0.02 seconds
120
@pytest.fixture(params=pythonlist)
def python2(request, python1):
return Python(request.param, python1.picklefile)
class Python:
def __init__(self, version, picklefile):
self.pythonpath = py.path.local.sysfind(version)
if not self.pythonpath:
pytest.skip("%r not found" %(version,))
self.picklefile = picklefile
def dumps(self, obj):
dumpfile = self.picklefile.dirpath("dump.py")
dumpfile.write(py.code.Source("""
import pickle
f = open(%r, 'wb')
s = pickle.dump(%r, f, protocol=2)
f.close()
""" % (str(self.picklefile), obj)))
py.process.cmdexec("%s %s" %(self.pythonpath, dumpfile))
def load_and_is_true(self, expression):
loadfile = self.picklefile.dirpath("load.py")
loadfile.write(py.code.Source("""
import pickle
f = open(%r, 'rb')
obj = pickle.load(f)
f.close()
res = eval(%r)
if not res:
raise SystemExit(1)
""" % (str(self.picklefile), expression)))
print (loadfile)
py.process.cmdexec("%s %s" %(self.pythonpath, loadfile))
@pytest.mark.parametrize("obj", [42, {}, {1:3},])
def test_basic_objects(python1, python2, obj):
python1.dumps(obj)
python2.load_and_is_true("obj == %s" % obj)
Running it results in some skips if we dont have all the python interpreters installed and otherwise runs all combinations (5 interpreters times 5 interpreters times 3 objects to serialize/deserialize):
. $ py.test -rs -q multipython.py
...........................
27 passed in 4.14 seconds
121
@pytest.fixture(scope="session")
def basemod(request):
return pytest.importorskip("base")
@pytest.fixture(scope="session", params=["opt1", "opt2"])
def optmod(request):
return pytest.importorskip(request.param)
Youll see that we dont have a opt2 module and thus the second test run of our test_func1 was skipped. A few
notes:
the fixture functions in the conftest.py file are session-scoped because we dont need to import more
than once
if you have multiple test functions and a skipped import, you will see the [1] count increasing in the report
you can put @pytest.mark.parametrize style parametrization on the test functions to parametrize input/output
values as well.
122
$ py.test -v -m webtest
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 -- /tmp/sandbox/pytest/.tox/regen/bin/pyt
rootdir: /tmp/doc-exec-157, inifile:
collecting ... collected 4 items
test_server.py::test_send_http PASSED
=================== 3 tests deselected by "-m 'webtest'" ===================
================== 1 passed, 3 deselected in 0.01 seconds ==================
$ py.test -v test_server.py::TestClass::test_method
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 -- /tmp/sandbox/pytest/.tox/regen/bin/pyt
rootdir: /tmp/doc-exec-157, inifile:
collecting ... collected 5 items
123
test_server.py::TestClass::test_method PASSED
========================= 1 passed in 0.01 seconds =========================
$ py.test -v test_server.py::TestClass
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 -- /tmp/sandbox/pytest/.tox/regen/bin/pyt
rootdir: /tmp/doc-exec-157, inifile:
collecting ... collected 4 items
test_server.py::TestClass::test_method PASSED
========================= 1 passed in 0.01 seconds =========================
Note: Node IDs are of the form module.py::class::method or module.py::function. Node IDs
control which tests are collected, so module.py::class will select all test methods on the class. Nodes are also
created for each parameter of a parametrized fixture or test, so selecting a parametrized test must include the parameter
value, e.g. module.py::function[param].
Node IDs for failing tests are displayed in the test summary info when running py.test with the -rf option. You can
also construct Node IDs from the output of py.test --collectonly.
And you can also run all tests except the ones that match the keyword:
124
Note: If you are using expressions such as X and Y then both X and Y need to be simple non-keyword names. For
example, pass or from will result in SyntaxErrors because -k evaluates the expression.
However, if the -k argument is a simple string, no such restrictions apply. Also -k not STRING has no restrictions. You can also specify numbers like -k 1.3 to match tests which are parametrized with the float 1.3.
You can ask which markers exist for your test suite - the list includes our just defined webtest markers:
$ py.test --markers
@pytest.mark.webtest: mark a test as a webtest.
@pytest.mark.skipif(condition): skip the given test function if eval(condition) results in a True val
125
@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to
@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to
For an example on how to add and work with markers from a plugin, see Custom marker and command line option to
control test runs.
Note: It is recommended to explicitely register markers so that:
there is one place in your test suite defining your markers
asking for existing markers via py.test --markers gives good output
typos in function markers are treated as an error if you use the --strict option. Future versions of pytest
are probably going to start treating non-registered markers as errors at some point.
This is equivalent to directly applying the decorator to the two test functions.
To remain backward-compatible with Python 2.4 you can also set a pytestmark attribute on a TestClass like this:
import pytest
class TestClass:
pytestmark = pytest.mark.webtest
in which case it will be applied to all functions and methods defined in the module.
126
import pytest
@pytest.mark.foo
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.mark.bar((1, 3)),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
In this example the mark foo will apply to each of the three tests, whereas the bar mark is only applied to the
second test. Skip and xfail marks can also be applied in this way, see Skip/xfail with parametrize.
Note: If the data you are parametrizing happen to be single callables, you need to be careful when marking these
items. pytest.mark.xfail(my_func) wont work because its also the signature of a function being decorated. To resolve
this ambiguity, you need to pass a reason argument: pytest.mark.xfail(func_bar, reason=Issue#7).
8.4.7 Custom marker and command line option to control test runs
Plugins can provide custom markers and implement specific behaviour based on it. This is a self-contained example
which adds a command line option and a parametrized test function marker to run tests specifies via named environments:
# content of conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption("-E", action="store", metavar="NAME",
help="only run tests matching the environment NAME.")
def pytest_configure(config):
# register an additional marker
config.addinivalue_line("markers",
"env(name): mark test to run only on named environment")
def pytest_runtest_setup(item):
envmarker = item.get_marker("env")
if envmarker is not None:
envname = envmarker.args[0]
if envname != item.config.getoption("-E"):
pytest.skip("test requires env %r" % envname)
and an example invocations specifying a different environment than what the test needs:
$ py.test -E stage2
=========================== test session starts ============================
127
@pytest.mark.skipif(condition): skip the given test function if eval(condition) results in a True val
@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to
@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to
Here we have the marker glob applied three times to the same test function. From a conftest file we can read it like
this:
# content of conftest.py
import sys
128
def pytest_runtest_setup(item):
g = item.get_marker("glob")
if g is not None:
for info in g:
print ("glob args=%s kwargs=%s" %(info.args, info.kwargs))
sys.stdout.flush()
Lets run this without capturing output and see what we get:
$ py.test -q -s
glob args=('function',) kwargs={'x': 3}
glob args=('class',) kwargs={'x': 2}
glob args=('module',) kwargs={'x': 1}
.
1 passed in 0.01 seconds
then tests will be skipped if they were specified for a different platform. Lets do a little test file to show how this looks
like:
# content of test_plat.py
import pytest
@pytest.mark.osx
def test_if_apple_is_evil():
pass
@pytest.mark.linux2
def test_if_linux_works():
pass
@pytest.mark.win32
def test_if_win32_crashes():
pass
def test_runs_everywhere():
pass
129
then you will see two test skipped and two executed tests as expected:
$ py.test -rs # this option reports skip reasons
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-157, inifile:
collected 4 items
test_plat.py sss.
========================= short test summary info ==========================
SKIP [3] /tmp/doc-exec-157/conftest.py:12: cannot run on platform linux
=================== 1 passed, 3 skipped in 0.01 seconds ====================
Note that if you specify a platform via the marker-command line option like this:
$ py.test -m linux2
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-157, inifile:
collected 4 items
test_plat.py s
=================== 3 tests deselected by "-m 'linux2'" ====================
================= 1 skipped, 3 deselected in 0.01 seconds ==================
then the unmarked-tests will not be run. It is thus a way to restrict the run to the specific tests.
130
131
import pytest
@pytest.fixture(scope="session", autouse=True)
def callattr_ahead_of_alltests(request):
print ("callattr_ahead_of_alltests called")
seen = set([None])
session = request.node
for item in session.items:
cls = item.getparent(pytest.Class)
if cls not in seen:
if hasattr(cls.obj, "callme"):
cls.obj.callme()
seen.add(cls)
test classes may now define a callme method which will be called ahead of running any tests:
# content of test_module.py
class TestHello:
@classmethod
def callme(cls):
print ("callme called!")
def test_method1(self):
print ("test_method1 called")
def test_method2(self):
print ("test_method1 called")
class TestOther:
@classmethod
def callme(cls):
print ("callme other called")
def test_other(self):
print ("test other")
# works with unittest as well ...
import unittest
class SomeTest(unittest.TestCase):
@classmethod
def callme(self):
print ("SomeTest callme called")
def test_unit1(self):
print ("test_unit1 method called")
132
This would tell pytest to not recurse into typical subversion or sphinx-build directories or into any tmp prefixed
directory.
This would make pytest look for tests in files that match the check_* .py glob-pattern, Check prefixes in
classes, and functions and methods that match *_check. For example, if we have:
# content of check_myapp.py
class CheckMyApp:
def simple_check(self):
pass
def complex_check(self):
pass
Note: the python_functions and python_classes options has no effect for unittest.TestCase test
discovery because pytest delegates detection of test case methods to unittest code.
133
which would run the respective test module. Like with other options, through an ini-file and the addopts option you
can make this change more permanently:
# content of pytest.ini
[pytest]
addopts = --pyargs
Now a simple invocation of py.test NAME will check if NAME exists as an importable package/module and
otherwise treat it as a filesystem path.
However, many projects will have a setup.py which they dont want to be imported. Moreover, there may files only
importable by a specific python version. For such cases you can dynamically define files to be ignored by listing them
in a conftest.py file:
# content of conftest.py
import sys
collect_ignore = ["setup.py"]
if sys.version_info[0] > 2:
collect_ignore.append("pkg/module_py2.py")
134
# content of pkg/module_py2.py
def test_only_on_python2():
try:
assert 0
except Exception, e:
pass
then a pytest run on python2 will find the one test when run with a python2 interpreters and will leave out the setup.py
file:
$ py.test --collect-only
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-160, inifile: pytest.ini
collected 0 items
=============================
If you run with a Python3 interpreter the moduled added through the conftest.py file will not be considered for test
collection.
135
if name != value:
raise YamlException(self, name, value)
def repr_failure(self, excinfo):
""" called when self.runtest() raises an exception. """
if isinstance(excinfo.value, YamlException):
return "\n".join([
"usecase execution failed",
"
spec failed: %r: %r" % excinfo.value.args[1:3],
"
no further details known at this point."
])
def reportinfo(self):
return self.fspath, 0, "usecase: %s" % self.name
class YamlException(Exception):
""" custom exception for error reporting. """
and if you installed PyYAML or a compatible YAML-parser you can now execute the test specification:
nonpython $ py.test test_simple.yml
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/sandbox/pytest/doc/en, inifile: pytest.ini
collected 2 items
test_simple.yml .F
================================= FAILURES =================================
______________________________ usecase: hello ______________________________
usecase execution failed
spec failed: 'some': 'other'
no further details known at this point.
==================== 1 failed, 1 passed in 0.19 seconds ====================
You get one dot for the passing sub1: sub1 check and one failure. Obviously in the above conftest.py youll
want to implement a more interesting interpretation of the yaml-values. You can easily write your own domain specific
testing language this way.
Note: repr_failure(excinfo) is called for representing test failures. If you create custom collection nodes
you can return an error representation string of your choice. It will be reported as a (red) string.
reportinfo() is used for representing the test location and is also consulted when reporting in verbose mode:
nonpython $ py.test -v
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 -- /tmp/sandbox/pytest/.tox/regen/bin/pyt
rootdir: /tmp/sandbox/pytest/doc/en, inifile: pytest.ini
136
While developing your custom test collection and execution its also interesting to just look at the collection tree:
nonpython $ py.test --collect-only
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/sandbox/pytest/doc/en, inifile: pytest.ini
collected 2 items
<YamlFile 'example/nonpython/test_simple.yml'>
<YamlItem 'ok'>
<YamlItem 'hello'>
=============================
137
138
CHAPTER
NINE
139
140
CHAPTER
TEN
Contributions are highly welcomed and appreciated. Every little help counts, so do not hesitate!
Contribution links
Contribution getting started
Submit a plugin, co-develop pytest
Report bugs
Submit feedback for developers
Fix bugs
Implement features
Write documentation
Preparing Pull Requests on Bitbucket
Using git with bitbucket/hg
141
142
hg
cd
hg
hg
hg
clone ssh://[email protected]/YOUR_BITBUCKET_USERNAME/pytest
pytest
up pytest-2.7
# if you want to fix a bug for the pytest-2.7 series
up default
# if you want to add a feature bound for the next minor release
branch your-branch-name # your feature/bugfix branch
If
you
need
some
help
with
http://mercurial.selenic.com/wiki/QuickStart
Mercurial,
follow
this
quick
start
guide:
This command will run tests via the tox tool against Python 2.7 and 3.4 and also perform flakes coding-style
checks. runtox.py is a thin wrapper around tox which installs from a development package index where
newer (not yet released to pypi) versions of dependencies (especially py) might be present.
To run tests on py27 and pass options (e.g. enter pdb on failure) to pytest you can do:
$ python runtox.py -e py27 -- --pdb
5. Commit and push once your tests pass and you are happy with your change(s):
$ hg commit -m"<commit message>"
$ hg push -b .
143
source: YOUR_BITBUCKET_USERNAME/pytest
branch: your-branch-name
target: pytest-dev/pytest
branch: default
# if it's a feature
branch: pytest-VERSION # if it's a bugfix
144
CHAPTER
ELEVEN
Target audience: Reading this document requires basic knowledge of python testing, xUnit setup methods and the
(previous) basic pytest funcarg mechanism, see http://pytest.org/2.2.4/funcargs.html If you are new to pytest, then you
can simply ignore this section and read the other sections.
145
This factory implementation does not need to call cached_setup() anymore because it will only be invoked once
per session. Moreover, the request.addfinalizer() registers a finalizer according to the specified resource
scope on which the factory function is operating.
Here the factory will be invoked twice (with the respective mysql and pg values set as request.param attributes) and and all of the tests requiring db will run twice as well. The mysql and pg values will also be used
for reporting the test-invocation variants.
This new way of parametrizing funcarg factories should in many cases allow to re-use already written factories because effectively request.param was already used when test functions/classes were parametrized via
parametrize(indirect=True)() calls.
Of course its perfectly fine to combine parametrization and scoping:
@pytest.fixture(scope="session", params=["mysql", "pg"])
def db(request):
if request.param == "mysql":
db = MySQL()
elif request.param == "pg":
db = PG()
request.addfinalizer(db.destroy) # destroy when session is finished
return db
This would execute all tests requiring the per-session db resource twice, receiving the values created by the two
respective invocations to the factory function.
146
@pytest.fixture()
def db(request):
...
The name under which the funcarg resource can be requested is db.
You can still use the old non-decorator way of specifying funcarg factories aka:
def pytest_funcarg__db(request):
...
But it is then not possible to define scoping and parametrization. It is thus recommended to use the factory decorator.
147
if you used parametrization and funcarg factories which made use of request.cached_setup() it is
recommeneded to invest a few minutes and simplify your fixture function code to use the Fixtures as Function
arguments decorator instead. This will also allow to take advantage of the automatic per-resource grouping of
tests.
148
CHAPTER
TWELVE
RELEASE ANNOUNCEMENTS
149
See
fix issue650: new option --docttest-ignore-import-errors which will turn import errors in doctests
into skips. Thanks Charles Cloud for the complete PR.
fix issue655: work around different ways that cause python2/3 to leak sys.exc_info into fixtures/tests causing
failures in 3rd party code
fix issue615: assertion re-writing did not correctly escape % signs when formatting boolean operations, which
tripped over mixing booleans with modulo operators. Thanks to Tom Viner for the report, triaging and fix.
implement issue351: add ability to specify parametrize ids as a callable to generate custom test ids. Thanks
Brianna Laugher for the idea and implementation.
introduce and document new hookwrapper mechanism useful for plugins which want to wrap the execution
of certain hooks for their purposes. This supersedes the undocumented __multicall__ protocol which
pytest itself and some external plugins use. Note that pytest-2.8 is scheduled to drop supporting the old
__multicall__ and only support the hookwrapper protocol.
majorly speed up invocation of plugin hooks
use hookwrapper mechanism in builtin pytest plugins.
add a doctest ini option for doctest flags, thanks Holger Peters.
150
add note to docs that if you want to mark a parameter and the parameter is a callable, you also need to pass in a
reason to disambiguate it from the decorator case. Thanks Tom Viner.
python_classes and python_functions options now support glob-patterns for test discovery, as discussed in
issue600. Thanks Ldiary Translations.
allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).
fix issue463: raise specific error for parameterize misspelling (pfctdayelise).
On failure, the sys.last_value, sys.last_type and sys.last_traceback are set, so that a user
can inspect the error via postmortem debugging (almarklein).
151
http://pytest.org
As usual, you can upgrade from pypi via:
pip install -U pytest
12.5.1 2.6.2
Added function pytest.freeze_includes(), which makes it easy to embed pytest into executables using tools like
cx_freeze. See docs for examples and rationale. Thanks Bruno Oliveira.
Improve assertion rewriting cache invalidation precision.
fixed issue561: adapt autouse fixture example for python3.
fixed issue453: assertion rewriting issue with __repr__ containing n{, n} and n~.
fix issue560: correctly display code if an else: or finally: is followed by statements on the same line.
Fix example in monkeypatch documentation, thanks t-8ch.
fix issue572: correct tmpdir doc example for python3.
Do not mark as universal wheel because Python 2.6 is different from other builds due to the extra argparse
dependency. Fixes issue566. Thanks sontek.
152
fix issue437 where assertion rewriting could cause pytest-xdist slaves to collect different tests. Thanks Bruno
Oliveira.
fix issue555: add errors attribute to capture-streams to satisfy some distutils and possibly other code accessing
sys.stdout.errors.
fix issue547 capsys/capfd also work when output capturing (-s) is disabled.
address issue170: allow pytest.mark.xfail(...) to specify expected exceptions via an optional raises=EXC
argument where EXC can be a single exception or a tuple of exception classes. Thanks David Mohr for the
complete PR.
fix integration of pytest with unittest.mock.patch decorator when it uses the new argument. Thanks Nicolas
Delaby for test and PR.
fix issue with detecting conftest files if the arguments contain :: node id specifications (copy pasted from -v
output)
fix issue544 by only removing @NUM at the end of :: separated parts and if the part has an .py extension
dont use py.std import helper, rather import things directly. Thanks Bruno Oliveira.
12.8 pytest-2.6.0: shorter tracebacks, new warning system, test runner compat
pytest is a mature Python testing tool with more than a 1000 tests against itself, passing on many different interpreters
and platforms.
The 2.6.0 release should be drop-in backward compatible to 2.5.2 and fixes a number of bugs and brings some new
features, mainly:
shorter tracebacks by default: only the first (test function) entry and the last (failure location) entry are shown,
the ones between only in short format. Use --tb=long to get back the old behaviour of showing long
entries everywhere.
a new warning system which reports oddities during collection and execution. For example, ignoring collecting
Test* classes with an __init__ now produces a warning.
various improvements to nose/mock/unittest integration
Note also that 2.6.0 departs with the zero reported bugs policy because it has been too hard to keep up with it,
unfortunately. Instead we are for now rather bound to work on upvoted issues in the https://bitbucket.org/pytestdev/pytest/issues?status=new&status=open&sort=-votes issue tracker.
See docs at:
http://pytest.org
As usual, you can upgrade from pypi via:
pip install -U pytest
12.8. pytest-2.6.0: shorter tracebacks, new warning system, test runner compat
153
12.8.1 2.6.0
fix issue537: Avoid importing old assertion reinterpretation code by default. Thanks Benjamin Peterson.
fix issue364: shorten and enhance tracebacks representation by default. The new tb=auto option (default)
will only display long tracebacks for the first and last entry. You can get the old behaviour of printing all entries
as long entries with tb=long. Also short entries by default are now printed very similarly to tb=native
ones.
fix issue514: teach assertion reinterpretation about private class attributes Thanks Benjamin Peterson.
change -v output to include full node IDs of tests. Users can copy a node ID from a test run, including line
number, and use it as a positional argument in order to run only a single test.
fix issue 475: fail early and comprehensible if calling pytest.raises with wrong exception type.
fix issue516: tell in getting-started about current dependencies.
cleanup setup.py a bit and specify supported versions. Thanks Jurko Gospodnetic for the PR.
change XPASS colour to yellow rather then red when tests are run with -v.
fix issue473: work around mock putting an unbound method into a class dict when double-patching.
fix issue498: if a fixture finalizer fails, make sure that the fixture is still invalidated.
fix issue453: the result of the pytest_assertrepr_compare hook now gets its newlines escaped so that format_exception does not blow up.
internal new warning system: pytest will now produce warnings when it detects oddities in your test collection or
execution. Warnings are ultimately sent to a new pytest_logwarning hook which is currently only implemented
by the terminal plugin which displays warnings in the summary line and shows more details when -rw (report
on warnings) is specified.
change skips into warnings for test classes with an __init__ and callables in test modules which look like a test
but are not functions.
fix issue436: improved finding of initial conftest files from command line arguments by using the result of
parse_known_args rather than the previous flaky heuristics. Thanks Marc Abramowitz for tests and initial fixing
approaches in this area.
fix issue #479: properly handle nose/unittest(2) SkipTest exceptions during collection/loading of test modules.
Thanks to Marc Schlaich for the complete PR.
fix issue490: include pytest_load_initial_conftests in documentation and improve docstring.
fix issue472: clarify that pytest.config.getvalue() cannot work if its triggered ahead of command
line parsing.
merge PR123: improved integration with mock.patch decorator on tests.
fix issue412: messing with stdout/stderr FD-level streams is now captured without crashes.
fix issue483: trial/py33 works now properly. Thanks Daniel Grana for PR.
improve example for pytest integration with python setup.py test which now has a generic -a or pytestargs option where you can pass additional options as a quoted string. Thanks Trevor Bekolay.
simplified internal capturing mechanism and made it more robust against tests or setups changing FD1/FD2,
also better integrated now with pytest.pdb() in single tests.
improvements to pytests own test-suite leakage detection, courtesy of PRs from Marc Abramowitz
fix issue492: avoid leak in test_writeorg. Thanks Marc Abramowitz.
fix issue493: dont run tests in doc directory with python setup.py test (use tox -e doctesting for that)
154
fix issue486: better reporting and handling of early conftest loading failures
some cleanup and simplification of internal conftest handling.
work a bit harder to break reference cycles when catching exceptions. Thanks Jurko Gospodnetic.
fix issue443: fix skip examples to use proper comparison. Thanks Alex Groenholm.
support nose-style __test__ attribute on modules, classes and functions, including unittest-style Classes. If
set to False, the test will not be collected.
fix issue512: show <notset> for arguments which might not be set in monkeypatch plugin. Improves output
in documentation.
avoid importing py.test (an old alias module for pytest)
12.9.1 2.5.2
fix issue409 better interoperate with cx_freeze by not trying to import from collections.abc which causes
problems for py27/cx_freeze. Thanks Wolfgang L. for reporting and tracking it down.
fixed docs and code to use pytest instead of py.test almost everywhere. Thanks Jurko Gospodnetic for the
complete PR.
fix issue425: mention at end of py.test -h that markers and fixtures work according to specified test path (or
current dir)
fix issue413: exceptions with unicode attributes are now printed correctly also on python2 and with pytest-xdist
runs. (the fix requires py-1.4.20)
copy, cleanup and integrate py.io capture from pylib 1.4.20.dev2 (rev 13d9af95547e)
address issue416: clarify docs as to conftest.py loading semantics
fix issue429: comparing byte strings with non-ascii chars in assert expressions now work better. Thanks Floris
Bruynooghe.
make capfd/capsys.capture private, its unused and shouldnt be exposed
155
have fun and a nice remaining bug-free time of the year :) holger krekel
12.10.1 2.5.1
merge new documentation styling PR from Tobias Bieniek.
fix issue403: allow parametrize of multiple same-name functions within a collection node. Thanks Andreas
Kloeckner and Alex Gaynor for reporting and analysis.
Allow parameterized fixtures to specify the ID of the parameters by adding an ids argument to pytest.fixture()
and pytest.yield_fixture(). Thanks Floris Bruynooghe.
fix issue404 by always using the binary xml escape in the junitxml plugin. Thanks Ronny Pfannschmidt.
fix issue407: fix addoption docstring to point to argparse instead of optparse. Thanks Daniel D. Wright.
156
Particular thanks for helping with this release go to Anatoly Bubenkoff, Floris Bruynooghe, Marc Abramowitz, Ralph
Schmitt, Ronny Pfannschmidt, Donald Stufft, James Lan, Rob Dennis, Jason R. Coombs, Mathieu Agopian, Virgil
Dupras, Bruno Oliveira, Alex Gaynor and others.
have fun, holger krekel
12.11.1 2.5.0
dropped python2.5 from automated release testing of pytest itself which means its probably going to break soon
(but still works with this release we believe).
simplified and fixed implementation for calling finalizers when parametrized fixtures or function arguments are
involved. finalization is now performed lazily at setup time instead of in the teardown phase. While this
might sound odd at first, it helps to ensure that we are correctly handling setup/teardown even in complex code.
User-level code should not be affected unless its implementing the pytest_runtest_teardown hook and expecting
certain fixture instances are torn down within (very unlikely and would have been unreliable anyway).
PR90: add color=yes|no|auto option to force terminal coloring mode (auto is default). Thanks Marc
Abramowitz.
fix issue319 - correctly show unicode in assertion errors. Many thanks to Floris Bruynooghe for the complete
PR. Also means we depend on py>=1.4.19 now.
fix issue396 - correctly sort and finalize class-scoped parametrized tests independently from number of methods
on the class.
refix issue323 in a better way parametrization should now never cause Runtime Recursion errors because
the underlying algorithm for re-ordering tests per-scope/per-fixture is not recursive anymore (it was tail-call
recursive before which could lead to problems for more than >966 non-function scoped parameters).
fix issue290 - there is preliminary support now for parametrizing with repeated same values (sometimes useful
to to test if calling a second time works as with the first time).
close issue240 - document precisely how pytest module importing works, discuss the two common test directory
layouts, and how it interacts with PEP420-namespace packages.
fix issue246 fix finalizer order to be LIFO on independent fixtures depending on a parametrized higher-thanfunction scoped fixture. (was quite some effort so please bear with the complexity of this sentence :) Thanks
Ralph Schmitt for the precise failure example.
fix issue244 by implementing special index for parameters to only use indices for paramentrized test ids
fix issue287 by running all finalizers but saving the exception from the first failing finalizer and re-raising it
so teardown will still have failed. We reraise the first failing exception because it might be the cause for other
finalizers to fail.
fix ordering when mock.patch or other standard decorator-wrappings are used with test methods. This fixues
issue346 and should help with random xdist collection failures. Thanks to Ronny Pfannschmidt and Donald
Stufft for helping to isolate it.
fix issue357 - special case -k expressions to allow for filtering with simple strings that are not valid python
expressions. Examples: -k 1.3 matches all tests parametrized with 1.3. -k None filters all tests that have
None in their name and conversely -k not None. Previously these examples would raise syntax errors.
fix issue384 by removing the trial support code since the unittest compat enhancements allow trial to handle it
on its own
dont hide an ImportError when importing a plugin produces one. fixes issue375.
157
fix issue275 - allow usefixtures and autouse fixtures for running doctest text files.
fix issue380 by making resultlog only rely on longrepr instead of the reprcrash attribute which only exists
sometimes.
address issue122: allow @pytest.fixture(params=iterator) by exploding into a list early on.
fix pexpect-3.0 compatibility for pytests own tests. (fixes issue386)
allow nested parametrize-value markers, thanks James Lan for the PR.
fix unicode handling with new monkeypatch.setattr(import_path, value) API. Thanks Rob Dennis. Fixes issue371.
fix unicode handling with junitxml, fixes issue368.
In assertion rewriting mode on Python 2, fix the detection of coding cookies. See issue #330.
make runxfail turn imperative pytest.xfail calls into no ops (it already did neutralize pytest.mark.xfail markers)
refine pytest / pkg_resources interactions: The AssertionRewritingHook PEP302 compliant loader now registers
itself with setuptools/pkg_resources properly so that the pkg_resources.resource_stream method works properly.
Fixes issue366. Thanks for the investigations and full PR to Jason R. Coombs.
pytestconfig fixture is now session-scoped as it is the same object during the whole test run. Fixes issue370.
avoid one surprising case of marker malfunction/confusion:
@pytest.mark.some(lambda arg: ...)
def test_function():
would not work correctly because pytest assumes @pytest.mark.some gets a function to be decorated already.
We now at least detect if this arg is an lambda and thus the example will work. Thanks Alex Gaynor for bringing
it up.
xfail a test on pypy that checks wrong encoding/ascii (pypy does not error out). fixes issue385.
internally make varnames() deal with classess __init__, although its not needed by pytest itself atm. Also fix
caching. Fixes issue376.
fix issue221 - handle importing of namespace-package with no __init__.py properly.
refactor internal FixtureRequest handling to avoid monkeypatching. One of the positive user-facing effects is
that the request object can now be used in closures.
fixed version comparison in pytest.importskip(modname, minverstring)
fix issue377 by clarifying in the nose-compat docs that pytest does not duplicate the unittest-API into the plain
namespace.
fix verbose reporting for @mockd test functions
158
avoid tmpdir fixture to create too long filenames especially when parametrization is used (issue354)
fix pytest-pep8 and pytest-flakes / pytest interactions (collection names in mark plugin was assuming an item
always has a function which is not true for those plugins etc.) Thanks Andi Zeidler.
introduce node.get_marker/node.add_marker API for plugins like pytest-pep8 and pytest-flakes to avoid the
messy details of the node.keywords pseudo-dicts. Adapted docs.
remove attempt to dup stdout at startup as its icky. the normal capturing should catch enough possibilities of
tests messing up standard FDs.
add pluginmanager.do_configure(config) as a link to config.do_configure() for plugin-compatibility
as usual, docs at http://pytest.org and upgrades via:
pip install -U pytest
for example:
better unittest/nose compatibility: all teardown methods are now only called if the corresponding setup method
succeeded.
159
Many thanks to all who helped, including Floris Bruynooghe, Brianna Laugher, Andreas Pelme, Anthon van
der Neut, Anatoly Bubenkoff, Vladimir Keleshev, Mathieu Agopian, Ronny Pfannschmidt, Christian Theunert
and many others.
may passing tests be with you,
holger krekel
160
fix issue181: pdb now also works on collect errors (and on internal errors) . This was implemented by a slight
internal refactoring and the introduction of a new hook pytest_exception_interact hook (see next
item).
fix issue341:
introduce new experimental hook for IDEs/terminals
pytest_exception_interact(node, call, report).
to
intercept
debugging:
new monkeypatch.setattr() variant to provide a shorter invocation for patching out classes/functions from modules:
monkeypatch.setattr(requests.get, myfunc)
will replace the get function of the requests module with myfunc.
fix issue322: tearDownClass is not run if setUpClass failed. Thanks Mathieu Agopian for the initial fix. Also
make all of pytest/nose finalizer mimick the same generic behaviour: if a setupX exists and fails, dont run
teardownX. This internally introduces a new method node.addfinalizer() helper which can only be called
during the setup phase of a node.
simplify pytest.mark.parametrize() signature: allow to pass a CSV-separated string to specify argnames. For
example: pytest.mark.parametrize("input,expected", [(1,2), (2,3)]) works as well
as the previous: pytest.mark.parametrize(("input", "expected"), ...).
add support for setUpModule/tearDownModule detection, thanks Brian Okken.
integrate tab-completion on options through use of argcomplete. Thanks Anthon van der Neut for the PR.
change option names to be hyphen-separated long options but keep the old spelling backward compatible. py.test
-h will only show the hyphenated version, for example collect-only but collectonly will remain valid as
well (for backward-compat reasons). Many thanks to Anthon van der Neut for the implementation and to Hynek
Schlawack for pushing us.
fix issue 308 - allow to mark/xfail/skip individual parameter sets when parametrizing. Thanks Brianna Laugher.
call new experimental pytest_load_initial_conftests hook to allow 3rd party plugins to do something before a
conftest is loaded.
Bug fixes:
fix issue358 - capturing options are now parsed more properly by using a new parser.parse_known_args method.
pytest now uses argparse instead of optparse (thanks Anthon) which means that argparse is added as a dependency if installing into python2.6 environments or below.
fix issue333: fix a case of bad unittest/pytest hook interaction.
PR27: correctly handle nose.SkipTest during collection. Thanks Antonio Cuni, Ronny Pfannschmidt.
fix issue355: junitxml puts name=pytest attribute to testsuite tag.
fix issue336: autouse fixture in plugins should work again.
fix issue279: improve object comparisons on assertion failure for standard datatypes and recognise collections.abc. Thanks to Brianna Laugher and Mathieu Agopian.
fix issue317: assertion rewriter support for the is_package method
fix issue335: document py.code.ExceptionInfo() object returned from pytest.raises(), thanks Mathieu Agopian.
remove implicit distribute_setup support from setup.py.
fix issue305: ignore any problems when writing pyc files.
SO-17664702: call fixture finalizers even if the fixture function partially failed (finalizers would not always be
called before)
161
fix issue320 - fix class scope for fixtures when mixed with module-level functions. Thanks Anatloy Bubenkoff.
you can specify -q or -qq to get different levels of quieter reporting (thanks Katarzyna Jachim)
fix issue300 - Fix order of conftest loading when starting py.test in a subdirectory.
fix issue323 - sorting of many module-scoped arg parametrizations
make sessionfinish hooks execute with the same cwd-context as at session start (helps fix plugin behaviour
which write output files with relative path such as pytest-cov)
fix issue316 - properly reference collection hooks in docs
fix issue 306 - cleanup of -k/-m options to only match markers/test names/keywords respectively. Thanks Wouter
van Ackooy.
improved doctest counting for doctests in python modules files without any doctest items will not show up
anymore and doctest examples are counted as separate test items. thanks Danilo Bellini.
fix issue245 by depending on the released py-1.4.14 which fixes py.io.dupfile to work with files with no mode.
Thanks Jason R. Coombs.
fix junitxml generation when test output contains control characters, addressing issue267, thanks Jaap
Broekhuizen
fix issue338: honor tb style for setup/teardown errors as well. Thanks Maho.
fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.
better parametrize error messages, thanks Brianna Laugher
pytest_terminal_summary(terminalreporter) hooks can now use .section(title) and .line(msg) methods to
print extra information at the end of a test run.
162
163
yielded test functions will now have autouse-fixtures active but cannot accept fixtures as funcargs
- its anyway recommended to rather use the post-2.0 parametrize features instead of yield, see:
http://pytest.org/latest/example/parametrize.html
fix autouse-issue where autouse-fixtures would not be discovered if defined in a a/conftest.py file and tests in
a/tests/test_some.py
fix issue226 - LIFO ordering for fixture teardowns
fix issue224 - invocations with >256 char arguments now work
fix issue91 - add/discuss package/directory level setups in example
fixes related to autouse discovery and calling
Thanks in particular to Thomas Waldmann for spotting and reporting issues.
See
http://pytest.org/
for general information. To install or upgrade pytest:
pip install -U pytest # or easy_install -U pytest
best, holger krekel
164
fix issue148 - @unittest.skip on classes is now recognized and avoids calling setUpClass/tearDownClass, thanks
Pavel Repin
fix issue209 - reintroduce python2.4 support by depending on newer pylib which re-introduced statement-finding
for pre-AST interpreters
nose support: only call setup if its a callable, thanks Andrew Taumoefolau
fix issue219 - add py2.4-3.3 classifiers to TROVE list
in tracebacks ,* arg values are now shown next to normal arguments (thanks Manuel Jacob)
fix issue217 - support mock.patch with pytests fixtures - note that you need either mock-1.0.1 or the python3.3
builtin unittest.mock.
fix issue127 - improve documentation for pytest_addoption() and add a config.getoption(name) helper
function for consistency.
165
166
If you are interested in the precise reasoning (including examples) of the pytest-2.3 fixture evolution, please consult
http://pytest.org/latest/funcarg_compare.html
For general info on installation and getting started:
http://pytest.org/latest/getting-started.html
Docs and PDF access as usual at:
http://pytest.org
and more details for those already in the knowing of pytest can be found in the CHANGELOG below.
Particular thanks for this release go to Floris Bruynooghe, Alex Okrushko Carl Meyer, Ronny Pfannschmidt, Benjamin
Peterson and Alex Gaynor for helping to get the new features right and well integrated. Ronny and Floris also helped
to fix a number of bugs and yet more people helped by providing bug reports.
have fun, holger krekel
167
make request.keywords and node.keywords writable. All descendant collection nodes will see keyword values.
Keywords are dictionaries containing markers and other info.
fix issue 178: xml binary escapes are now wrapped in py.xml.raw
fix issue 176: correctly catch the builtin AssertionError even when we replaced AssertionError with a subclass
on the python level
factory discovery no longer fails with magic global callables that provide no sane __code__ object (mock.call
for example)
fix issue 182: testdir.inprocess_run now considers passed plugins
fix issue 188: ensure sys.exc_info is clear on python2 before calling into a test
fix issue 191: add unittest TestCase runTest method support
fix issue 156: monkeypatch correctly handles class level descriptors
reporting refinements:
pytest_report_header now receives a startdir so that you can use startdir.bestrelpath(yourpath) to show
nice relative path
allow plugins to implement both pytest_report_header and pytest_sessionstart (sessionstart is invoked
first).
dont show deselected reason line if there is none
py.test -vv will show all of assert comparisations instead of truncating
168
fix issue #143: call unconfigure/sessionfinish always when configure/sessionstart where called
fix issue #144: better mangle test ids to junitxml classnames
upgrade distribute_setup.py to 0.6.27
169
170
http://pytest.org/
If you want to install or upgrade pytest you might just type:
pip install -U pytest # or
easy_install -U pytest
Thanks to Ronny Pfannschmidt, David Burns, Jeff Donner, Daniel Nouri, Alfredo Deza and all who gave feedback or
sent bug reports.
best, holger krekel
171
Thanks to the bug reporters and to Ronny Pfannschmidt, Benjamin Peterson and Floris Bruynooghe who implemented
the fixes.
best, holger krekel
172
173
See http://pytest.org/assert.html#advanced-assertion-introspection for detailed information. The work has been partly
sponsored by my company, merlinux GmbH.
For further details on bug fixes and smaller enhancements see below.
If you want to install or upgrade pytest, just type one of:
pip install -U pytest # or
easy_install -U pytest
There also is a bugfix release 1.6 of pytest-xdist, the plugin that enables seemless distributed and looponfail testing
for Python.
best, holger krekel
174
Many thanks to all issue reporters and people asking questions or complaining, particularly Jurko for his insistence,
Laura, Victor and Brianna for helping with improving and Ronny for his general advise.
best, holger krekel
This will not run the test function if the modules version string does not start with a 1. Note that specifying
a string instead of a boolean expressions allows py.test to report meaningful information when summarizing a
test run as to what conditions lead to skipping (or xfail-ing) tests.
fix issue28 - setup_method and pytest_generate_tests work together The setup_method fixture method now gets
called also for test function invocations generated from the pytest_generate_tests hook.
fix issue27 - collectonly and keyword-selection (-k) now work together Also, if you do py.test collectonly
-q you now get a flat list of test ids that you can use to paste to the py.test commandline in order to execute a
particular test.
12.30. py.test 2.0.2: bug fixes, improved xfail/skip expressions, speed ups
175
fix issue25 avoid reported problems with pdb and python3.2/encodings output
fix issue23 - tmpdir argument now works on Python3.2 and WindowsXP Starting with Python3.2 os.symlink
may be supported. By requiring a newer py lib version the py.path.local() implementation acknowledges this.
fixed typos in the docs (thanks Victor Garcia, Brianna Laugher) and particular thanks to Laura Creighton who
also revieved parts of the documentation.
fix slighly wrong output of verbose progress reporting for classes (thanks Amaury)
more precise (avoiding of) deprecation warnings for node.Class|Function accesses
avoid std unittest assertion helper code in tracebacks (thanks Ronny)
Many thanks to all issue reporters and people asking questions or complaining. Particular thanks to Floris Bruynooghe
and Ronny Pfannschmidt for their great coding contributions and many others for feedback and help.
best, holger krekel
176
fix issue9: setup/teardown functions for an xfail-marked test will report as xfail if they fail but report as normally passing (not xpassing) if they succeed. This only is true for direct setup/teardown invocations because
teardown_class/ teardown_module cannot closely relate to a single test.
fix issue14: no logging errors at process exit
refinements to collecting output on non-ttys
refine internal plugin registration and traceconfig output
introduce a mechanism to prevent/unregister
http://pytest.org/latest/plugins.html#cmdunregister
plugins
from
the
command
line,
see
Many thanks to all issue reporters and people asking questions or complaining. Particular thanks to Floris Bruynooghe
and Ronny Pfannschmidt for their great coding contributions and many others for feedback and help.
best, holger krekel
177
[pytest]
norecursedirs = .hg data*
addopts = -x --pyargs
see http://pytest.org/2.0.0/customize.html
improved standard unittest support. In general py.test should now better be able to run custom unittest.TestCases
like twisted trial or Django based TestCases. Also you can now run the tests of an installed unittest package
with py.test:
py.test --pyargs unittest
new -q option which decreases verbosity and prints a more nose/unittest-style dot output.
many many more detailed improvements details
12.32.2 Fixes
fix issue126 - introduce py.test.set_trace() to trace execution via PDB during the running of tests even if capturing
is ongoing.
fix issue124 - make reporting more resilient against tests opening files on filedescriptor 1 (stdout).
fix issue109 - sibling conftest.py files will not be loaded. (and Directory collectors cannot be customized anymore from a Directorys conftest.py - this needs to happen at least one level up).
fix issue88 (finding custom test nodes from command line arg)
fix issue93 stdout/stderr is captured while importing conftest.py
fix bug: unittest collected functions now also can have pytestmark applied at class/module level
178
removed the disabled attribute in test classes. Use the skipping and pytestmark mechanism to skip or
xfail a test class.
py.test.collect.Directory does not exist anymore and it is not possible to provide an own Directory object. If
you have used this and dont know what to do, get in contact. Well figure something out.
Note that pytest_collect_directory() is still called but any return value will be ignored. This allows to keep old
code working that performed for example py.test.skip() in collect() to prevent recursion into directory trees if
a certain dependency or command line option is missing.
see Changelog history for more detailed changes.
179
180
CHAPTER
THIRTEEN
CHANGELOG HISTORY
See
181
fix issue650: new option --docttest-ignore-import-errors which will turn import errors in doctests
into skips. Thanks Charles Cloud for the complete PR.
fix issue655: work around different ways that cause python2/3 to leak sys.exc_info into fixtures/tests causing
failures in 3rd party code
fix issue615: assertion re-writing did not correctly escape % signs when formatting boolean operations, which
tripped over mixing booleans with modulo operators. Thanks to Tom Viner for the report, triaging and fix.
implement issue351: add ability to specify parametrize ids as a callable to generate custom test ids. Thanks
Brianna Laugher for the idea and implementation.
introduce and document new hookwrapper mechanism useful for plugins which want to wrap the execution
of certain hooks for their purposes. This supersedes the undocumented __multicall__ protocol which
pytest itself and some external plugins use. Note that pytest-2.8 is scheduled to drop supporting the old
__multicall__ and only support the hookwrapper protocol.
majorly speed up invocation of plugin hooks
use hookwrapper mechanism in builtin pytest plugins.
add a doctest ini option for doctest flags, thanks Holger Peters.
add note to docs that if you want to mark a parameter and the parameter is a callable, you also need to pass in a
reason to disambiguate it from the decorator case. Thanks Tom Viner.
python_classes and python_functions options now support glob-patterns for test discovery, as discussed in
issue600. Thanks Ldiary Translations.
allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).
fix issue463: raise specific error for parameterize misspelling (pfctdayelise).
On failure, the sys.last_value, sys.last_type and sys.last_traceback are set, so that a user
can inspect the error via postmortem debugging (almarklein).
13.3 2.6.4
Improve assertion failure reporting on iterables, by using ndiff and pprint.
removed outdated japanese docs from source tree.
docs for pytest_addhooks hook. Thanks Bruno Oliveira.
updated plugin index docs. Thanks Bruno Oliveira.
fix issue557: with -k we only allow the old style - for negation at the beginning of strings and even that is
deprecated. Use not instead. This should allow to pick parametrized tests where - appeared in the parameter.
fix issue604: Escape % character in the assertion message.
fix issue620: add explanation in the genscript target about what the binary blob means. Thanks Dinu Gherman.
fix issue614: fixed pastebin support.
fix issue620: add explanation in the genscript target about what the binary blob means. Thanks Dinu Gherman.
fix issue614: fixed pastebin support.
182
13.4 2.6.3
fix issue575: xunit-xml was reporting collection errors as failures instead of errors, thanks Oleg Sinyavskiy.
fix issue582: fix setuptools example, thanks Laszlo Papp and Ronny Pfannschmidt.
Fix infinite recursion bug when pickling capture.EncodedFile, thanks Uwe Schmitt.
fix issue589: fix bad interaction with numpy and others when showing exceptions. Check for precise maximum
recursion depth exceed exception instead of presuming any RuntimeError is that one (implemented in py dep).
Thanks Charles Cloud for analysing the issue.
fix conftest related fixture visibility issue: when running with a CWD outside a test package pytest would get
fixture discovery wrong. Thanks to Wolfgang Schnerring for figuring out a reproducable example.
Introduce pytest_enter_pdb hook (needed e.g. by pytest_timeout to cancel the timeout when interactively entering pdb). Thanks Wolfgang Schnerring.
check xfail/skip also with non-python function test items. Thanks Floris Bruynooghe.
13.5 2.6.2
Added function pytest.freeze_includes(), which makes it easy to embed pytest into executables using tools like
cx_freeze. See docs for examples and rationale. Thanks Bruno Oliveira.
Improve assertion rewriting cache invalidation precision.
fixed issue561: adapt autouse fixture example for python3.
fixed issue453: assertion rewriting issue with __repr__ containing n{, n} and n~.
fix issue560: correctly display code if an else: or finally: is followed by statements on the same line.
Fix example in monkeypatch documentation, thanks t-8ch.
fix issue572: correct tmpdir doc example for python3.
Do not mark as universal wheel because Python 2.6 is different from other builds due to the extra argparse
dependency. Fixes issue566. Thanks sontek.
Implement issue549: user-provided assertion messages now no longer replace the py.test introspection message
but are shown in addition to them.
13.6 2.6.1
No longer show line numbers in the verbose output, the output is now purely the nodeid. The line number is
still shown in failure reports. Thanks Floris Bruynooghe.
fix issue437 where assertion rewriting could cause pytest-xdist slaves to collect different tests. Thanks Bruno
Oliveira.
fix issue555: add errors attribute to capture-streams to satisfy some distutils and possibly other code accessing
sys.stdout.errors.
fix issue547 capsys/capfd also work when output capturing (-s) is disabled.
address issue170: allow pytest.mark.xfail(...) to specify expected exceptions via an optional raises=EXC
argument where EXC can be a single exception or a tuple of exception classes. Thanks David Mohr for the
complete PR.
13.4. 2.6.3
183
fix integration of pytest with unittest.mock.patch decorator when it uses the new argument. Thanks Nicolas
Delaby for test and PR.
fix issue with detecting conftest files if the arguments contain :: node id specifications (copy pasted from -v
output)
fix issue544 by only removing @NUM at the end of :: separated parts and if the part has an .py extension
dont use py.std import helper, rather import things directly. Thanks Bruno Oliveira.
13.7 2.6
Cache exceptions from fixtures according to their scope (issue 467).
fix issue537: Avoid importing old assertion reinterpretation code by default.
fix issue364: shorten and enhance tracebacks representation by default. The new tb=auto option (default)
will only display long tracebacks for the first and last entry. You can get the old behaviour of printing all entries
as long entries with tb=long. Also short entries by default are now printed very similarly to tb=native
ones.
fix issue514: teach assertion reinterpretation about private class attributes
change -v output to include full node IDs of tests. Users can copy a node ID from a test run, including line
number, and use it as a positional argument in order to run only a single test.
fix issue 475: fail early and comprehensible if calling pytest.raises with wrong exception type.
fix issue516: tell in getting-started about current dependencies.
cleanup setup.py a bit and specify supported versions. Thanks Jurko Gospodnetic for the PR.
change XPASS colour to yellow rather then red when tests are run with -v.
fix issue473: work around mock putting an unbound method into a class dict when double-patching.
fix issue498: if a fixture finalizer fails, make sure that the fixture is still invalidated.
fix issue453: the result of the pytest_assertrepr_compare hook now gets its newlines escaped so that format_exception does not blow up.
internal new warning system: pytest will now produce warnings when it detects oddities in your test collection or
execution. Warnings are ultimately sent to a new pytest_logwarning hook which is currently only implemented
by the terminal plugin which displays warnings in the summary line and shows more details when -rw (report
on warnings) is specified.
change skips into warnings for test classes with an __init__ and callables in test modules which look like a test
but are not functions.
fix issue436: improved finding of initial conftest files from command line arguments by using the result of
parse_known_args rather than the previous flaky heuristics. Thanks Marc Abramowitz for tests and initial fixing
approaches in this area.
fix issue #479: properly handle nose/unittest(2) SkipTest exceptions during collection/loading of test modules.
Thanks to Marc Schlaich for the complete PR.
fix issue490: include pytest_load_initial_conftests in documentation and improve docstring.
fix issue472: clarify that pytest.config.getvalue() cannot work if its triggered ahead of command
line parsing.
merge PR123: improved integration with mock.patch decorator on tests.
184
fix issue412: messing with stdout/stderr FD-level streams is now captured without crashes.
fix issue483: trial/py33 works now properly. Thanks Daniel Grana for PR.
improve example for pytest integration with python setup.py test which now has a generic -a or pytestargs option where you can pass additional options as a quoted string. Thanks Trevor Bekolay.
simplified internal capturing mechanism and made it more robust against tests or setups changing FD1/FD2,
also better integrated now with pytest.pdb() in single tests.
improvements to pytests own test-suite leakage detection, courtesy of PRs from Marc Abramowitz
fix issue492: avoid leak in test_writeorg. Thanks Marc Abramowitz.
fix issue493: dont run tests in doc directory with python setup.py test (use tox -e doctesting for that)
fix issue486: better reporting and handling of early conftest loading failures
some cleanup and simplification of internal conftest handling.
work a bit harder to break reference cycles when catching exceptions. Thanks Jurko Gospodnetic.
fix issue443: fix skip examples to use proper comparison. Thanks Alex Groenholm.
support nose-style __test__ attribute on modules, classes and functions, including unittest-style Classes. If
set to False, the test will not be collected.
fix issue512: show <notset> for arguments which might not be set in monkeypatch plugin. Improves output
in documentation.
13.8 2.5.2
fix issue409 better interoperate with cx_freeze by not trying to import from collections.abc which causes
problems for py27/cx_freeze. Thanks Wolfgang L. for reporting and tracking it down.
fixed docs and code to use pytest instead of py.test almost everywhere. Thanks Jurko Gospodnetic for the
complete PR.
fix issue425: mention at end of py.test -h that markers and fixtures work according to specified test path (or
current dir)
fix issue413: exceptions with unicode attributes are now printed correctly also on python2 and with pytest-xdist
runs. (the fix requires py-1.4.20)
copy, cleanup and integrate py.io capture from pylib 1.4.20.dev2 (rev 13d9af95547e)
address issue416: clarify docs as to conftest.py loading semantics
fix issue429: comparing byte strings with non-ascii chars in assert expressions now work better. Thanks Floris
Bruynooghe.
make capfd/capsys.capture private, its unused and shouldnt be exposed
13.9 2.5.1
merge new documentation styling PR from Tobias Bieniek.
fix issue403: allow parametrize of multiple same-name functions within a collection node. Thanks Andreas
Kloeckner and Alex Gaynor for reporting and analysis.
13.8. 2.5.2
185
Allow parameterized fixtures to specify the ID of the parameters by adding an ids argument to pytest.fixture()
and pytest.yield_fixture(). Thanks Floris Bruynooghe.
fix issue404 by always using the binary xml escape in the junitxml plugin. Thanks Ronny Pfannschmidt.
fix issue407: fix addoption docstring to point to argparse instead of optparse. Thanks Daniel D. Wright.
13.10 2.5.0
dropped python2.5 from automated release testing of pytest itself which means its probably going to break soon
(but still works with this release we believe).
simplified and fixed implementation for calling finalizers when parametrized fixtures or function arguments are
involved. finalization is now performed lazily at setup time instead of in the teardown phase. While this
might sound odd at first, it helps to ensure that we are correctly handling setup/teardown even in complex code.
User-level code should not be affected unless its implementing the pytest_runtest_teardown hook and expecting
certain fixture instances are torn down within (very unlikely and would have been unreliable anyway).
PR90: add color=yes|no|auto option to force terminal coloring mode (auto is default). Thanks Marc
Abramowitz.
fix issue319 - correctly show unicode in assertion errors. Many thanks to Floris Bruynooghe for the complete
PR. Also means we depend on py>=1.4.19 now.
fix issue396 - correctly sort and finalize class-scoped parametrized tests independently from number of methods
on the class.
refix issue323 in a better way parametrization should now never cause Runtime Recursion errors because
the underlying algorithm for re-ordering tests per-scope/per-fixture is not recursive anymore (it was tail-call
recursive before which could lead to problems for more than >966 non-function scoped parameters).
fix issue290 - there is preliminary support now for parametrizing with repeated same values (sometimes useful
to to test if calling a second time works as with the first time).
close issue240 - document precisely how pytest module importing works, discuss the two common test directory
layouts, and how it interacts with PEP420-namespace packages.
fix issue246 fix finalizer order to be LIFO on independent fixtures depending on a parametrized higher-thanfunction scoped fixture. (was quite some effort so please bear with the complexity of this sentence :) Thanks
Ralph Schmitt for the precise failure example.
fix issue244 by implementing special index for parameters to only use indices for paramentrized test ids
fix issue287 by running all finalizers but saving the exception from the first failing finalizer and re-raising it
so teardown will still have failed. We reraise the first failing exception because it might be the cause for other
finalizers to fail.
fix ordering when mock.patch or other standard decorator-wrappings are used with test methods. This fixues
issue346 and should help with random xdist collection failures. Thanks to Ronny Pfannschmidt and Donald
Stufft for helping to isolate it.
fix issue357 - special case -k expressions to allow for filtering with simple strings that are not valid python
expressions. Examples: -k 1.3 matches all tests parametrized with 1.3. -k None filters all tests that have
None in their name and conversely -k not None. Previously these examples would raise syntax errors.
fix issue384 by removing the trial support code since the unittest compat enhancements allow trial to handle it
on its own
dont hide an ImportError when importing a plugin produces one. fixes issue375.
fix issue275 - allow usefixtures and autouse fixtures for running doctest text files.
186
fix issue380 by making resultlog only rely on longrepr instead of the reprcrash attribute which only exists
sometimes.
address issue122: allow @pytest.fixture(params=iterator) by exploding into a list early on.
fix pexpect-3.0 compatibility for pytests own tests. (fixes issue386)
allow nested parametrize-value markers, thanks James Lan for the PR.
fix unicode handling with new monkeypatch.setattr(import_path, value) API. Thanks Rob Dennis. Fixes issue371.
fix unicode handling with junitxml, fixes issue368.
In assertion rewriting mode on Python 2, fix the detection of coding cookies. See issue #330.
make runxfail turn imperative pytest.xfail calls into no ops (it already did neutralize pytest.mark.xfail markers)
refine pytest / pkg_resources interactions: The AssertionRewritingHook PEP302 compliant loader now registers
itself with setuptools/pkg_resources properly so that the pkg_resources.resource_stream method works properly.
Fixes issue366. Thanks for the investigations and full PR to Jason R. Coombs.
pytestconfig fixture is now session-scoped as it is the same object during the whole test run. Fixes issue370.
avoid one surprising case of marker malfunction/confusion:
@pytest.mark.some(lambda arg: ...)
def test_function():
would not work correctly because pytest assumes @pytest.mark.some gets a function to be decorated already.
We now at least detect if this arg is an lambda and thus the example will work. Thanks Alex Gaynor for bringing
it up.
xfail a test on pypy that checks wrong encoding/ascii (pypy does not error out). fixes issue385.
internally make varnames() deal with classess __init__, although its not needed by pytest itself atm. Also fix
caching. Fixes issue376.
fix issue221 - handle importing of namespace-package with no __init__.py properly.
refactor internal FixtureRequest handling to avoid monkeypatching. One of the positive user-facing effects is
that the request object can now be used in closures.
fixed version comparison in pytest.importskip(modname, minverstring)
fix issue377 by clarifying in the nose-compat docs that pytest does not duplicate the unittest-API into the plain
namespace.
fix verbose reporting for @mockd test functions
13.11 v2.4.2
on Windows require colorama and a newer py lib so that py.io.TerminalWriter() now uses colorama instead of
its own ctypes hacks. (fixes issue365) thanks Paul Moore for bringing it up.
fix -k matching of tests where repr and attr and other names would cause wrong matches because of an
internal implementation quirk (dont ask) which is now properly implemented. fixes issue345.
avoid tmpdir fixture to create too long filenames especially when parametrization is used (issue354)
fix pytest-pep8 and pytest-flakes / pytest interactions (collection names in mark plugin was assuming an item
always has a function which is not true for those plugins etc.) Thanks Andi Zeidler.
13.11. v2.4.2
187
introduce node.get_marker/node.add_marker API for plugins like pytest-pep8 and pytest-flakes to avoid the
messy details of the node.keywords pseudo-dicts. Adapted docs.
remove attempt to dup stdout at startup as its icky. the normal capturing should catch enough possibilities of
tests messing up standard FDs.
add pluginmanager.do_configure(config) as a link to config.do_configure() for plugin-compatibility
13.12 v2.4.1
When using parser.addoption() unicode arguments to the type keyword should also be converted to the respective types. thanks Floris Bruynooghe, @dnozay. (fixes issue360 and issue362)
fix dotted filename completion when using argcomplete thanks Anthon van der Neuth. (fixes issue361)
fix regression when a 1-tuple (arg,) is used for specifying parametrization (the values of the parametrization
were passed nested in a tuple). Thanks Donald Stufft.
merge doc typo fixes, thanks Andy Dirnberger
13.13 v2.4
known incompatibilities:
if calling genscript from python2.7 or above, you only get a standalone script which works on python2.7 or
above. Use Python2.6 to also get a python2.5 compatible version.
all xunit-style teardown methods (nose-style, pytest-style, unittest-style) will not be called if the corresponding
setup method failed, see issue322 below.
the pytest_plugin_unregister hook wasnt ever properly called and there is no known implementation of the hook
- so it got removed.
pytest.fixture-decorated functions cannot be generators (i.e. use yield) anymore. This change might be reversed in 2.4.1 if it causes unforeseen real-life issues. However, you can always write and return an inner
function/generator and change the fixture consumer to iterate over the returned generator. This change was done
in lieu of the new pytest.yield_fixture decorator, see below.
new features:
experimentally introduce a new pytest.yield_fixture decorator which accepts exactly the same parameters as pytest.fixture but mandates a yield statement instead of a return statement from fixture
functions. This allows direct integration with with-style context managers in fixture functions and generally
avoids registering of finalization callbacks in favour of treating the after-yield as teardown code. Thanks
Andreas Pelme, Vladimir Keleshev, Floris Bruynooghe, Ronny Pfannschmidt and many others for discussions.
allow boolean expression directly with skipif/xfail if a reason is also specified. Rework skipping documentation to recommend condition as booleans because it prevents surprises when importing markers between
modules. Specifying conditions as strings will remain fully supported.
reporting: color the last line red or green depending if failures/errors occurred or everything passed. thanks
Christian Theunert.
make import pdb ; pdb.set_trace() work natively wrt capturing (no -s needed anymore), making
pytest.set_trace() a mere shortcut.
188
fix issue181: pdb now also works on collect errors (and on internal errors) . This was implemented by a slight
internal refactoring and the introduction of a new hook pytest_exception_interact hook (see next
item).
fix issue341:
introduce new experimental hook for IDEs/terminals
pytest_exception_interact(node, call, report).
to
intercept
debugging:
new monkeypatch.setattr() variant to provide a shorter invocation for patching out classes/functions from modules:
monkeypatch.setattr(requests.get, myfunc)
will replace the get function of the requests module with myfunc.
fix issue322: tearDownClass is not run if setUpClass failed. Thanks Mathieu Agopian for the initial fix. Also
make all of pytest/nose finalizer mimick the same generic behaviour: if a setupX exists and fails, dont run
teardownX. This internally introduces a new method node.addfinalizer() helper which can only be called
during the setup phase of a node.
simplify pytest.mark.parametrize() signature: allow to pass a CSV-separated string to specify argnames. For
example: pytest.mark.parametrize("input,expected", [(1,2), (2,3)]) works as well
as the previous: pytest.mark.parametrize(("input", "expected"), ...).
add support for setUpModule/tearDownModule detection, thanks Brian Okken.
integrate tab-completion on options through use of argcomplete. Thanks Anthon van der Neut for the PR.
change option names to be hyphen-separated long options but keep the old spelling backward compatible. py.test
-h will only show the hyphenated version, for example collect-only but collectonly will remain valid as
well (for backward-compat reasons). Many thanks to Anthon van der Neut for the implementation and to Hynek
Schlawack for pushing us.
fix issue 308 - allow to mark/xfail/skip individual parameter sets when parametrizing. Thanks Brianna Laugher.
call new experimental pytest_load_initial_conftests hook to allow 3rd party plugins to do something before a
conftest is loaded.
Bug fixes:
fix issue358 - capturing options are now parsed more properly by using a new parser.parse_known_args method.
pytest now uses argparse instead of optparse (thanks Anthon) which means that argparse is added as a dependency if installing into python2.6 environments or below.
fix issue333: fix a case of bad unittest/pytest hook interaction.
PR27: correctly handle nose.SkipTest during collection. Thanks Antonio Cuni, Ronny Pfannschmidt.
fix issue355: junitxml puts name=pytest attribute to testsuite tag.
fix issue336: autouse fixture in plugins should work again.
fix issue279: improve object comparisons on assertion failure for standard datatypes and recognise collections.abc. Thanks to Brianna Laugher and Mathieu Agopian.
fix issue317: assertion rewriter support for the is_package method
fix issue335: document py.code.ExceptionInfo() object returned from pytest.raises(), thanks Mathieu Agopian.
remove implicit distribute_setup support from setup.py.
fix issue305: ignore any problems when writing pyc files.
SO-17664702: call fixture finalizers even if the fixture function partially failed (finalizers would not always be
called before)
13.13. v2.4
189
fix issue320 - fix class scope for fixtures when mixed with module-level functions. Thanks Anatloy Bubenkoff.
you can specify -q or -qq to get different levels of quieter reporting (thanks Katarzyna Jachim)
fix issue300 - Fix order of conftest loading when starting py.test in a subdirectory.
fix issue323 - sorting of many module-scoped arg parametrizations
make sessionfinish hooks execute with the same cwd-context as at session start (helps fix plugin behaviour
which write output files with relative path such as pytest-cov)
fix issue316 - properly reference collection hooks in docs
fix issue 306 - cleanup of -k/-m options to only match markers/test names/keywords respectively. Thanks Wouter
van Ackooy.
improved doctest counting for doctests in python modules files without any doctest items will not show up
anymore and doctest examples are counted as separate test items. thanks Danilo Bellini.
fix issue245 by depending on the released py-1.4.14 which fixes py.io.dupfile to work with files with no mode.
Thanks Jason R. Coombs.
fix junitxml generation when test output contains control characters, addressing issue267, thanks Jaap
Broekhuizen
fix issue338: honor tb style for setup/teardown errors as well. Thanks Maho.
fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.
better parametrize error messages, thanks Brianna Laugher
pytest_terminal_summary(terminalreporter) hooks can now use .section(title) and .line(msg) methods to
print extra information at the end of a test run.
13.14 v2.3.5
fix issue169: respect tb=style with setup/teardown errors as well.
never consider a fixture function for test function collection
allow re-running of test items / helps to fix pytest-reruntests plugin and also help to keep less fixture/resource
references alive
put captured stdout/stderr into junitxml output even for passing tests (thanks Adam Goucher)
Issue 265 - integrate nose setup/teardown with setupstate so it doesnt try to teardown if it did not setup
issue 271 - dont write junitxml on slave nodes
Issue 274 - dont try to show full doctest example when doctest does not know the example location
issue 280 - disable assertion rewriting on buggy CPython 2.6.0
inject getfixture() helper to retrieve fixtures from doctests, thanks Andreas Zeidler
issue 259 - when assertion rewriting, be consistent with the default source encoding of ASCII on Python 2
issue 251 - report a skip instead of ignoring classes with init
issue250 unicode/str mixes in parametrization names and values now works
issue257, assertion-triggered compilation of source ending in a comment line doesnt blow up in python2.5
(fixed through py>=1.4.13.dev6)
fix genscript option to generate standalone scripts that also work with python3.3 (importer ordering)
190
13.15 v2.3.4
yielded test functions will now have autouse-fixtures active but cannot accept fixtures as funcargs
- its anyway recommended to rather use the post-2.0 parametrize features instead of yield, see:
http://pytest.org/latest/example/parametrize.html
fix autouse-issue where autouse-fixtures would not be discovered if defined in a a/conftest.py file and tests in
a/tests/test_some.py
fix issue226 - LIFO ordering for fixture teardowns
fix issue224 - invocations with >256 char arguments now work
fix issue91 - add/discuss package/directory level setups in example
allow to dynamically define markers via item.keywords[...]=assignment integrating with -m option
make -k accept an expressions the same as with -m so that one can write: -k name1 or name2 etc. This is
a slight incompatibility if you used special syntax like TestClass.test_method which you now need to write as
-k TestClass and test_method to match a certain method in a certain test class.
13.16 v2.3.3
fix issue214 - parse modules that contain special objects like e. g. flasks request object which blows up on
getattr access if no request is active. thanks Thomas Waldmann.
fix issue213 - allow to parametrize with values like numpy arrays that do not support an __eq__ operator
fix issue215 - split test_python.org into multiple files
fix issue148 - @unittest.skip on classes is now recognized and avoids calling setUpClass/tearDownClass, thanks
Pavel Repin
fix issue209 - reintroduce python2.4 support by depending on newer pylib which re-introduced statement-finding
for pre-AST interpreters
nose support: only call setup if its a callable, thanks Andrew Taumoefolau
13.15. v2.3.4
191
13.17 v2.3.2
fix issue208 and fix issue29 use new py version to avoid long pauses when printing tracebacks in long modules
fix issue205 - conftests in subdirs customizing pytest_pycollect_makemodule and pytest_pycollect_makeitem
now work properly
fix teardown-ordering for parametrized setups
fix issue127 - better documentation for pytest_addoption and related objects.
fix unittest behaviour: TestCase.runtest only called if there are test methods defined
improve trial support: dont collect its empty unittest.TestCase.runTest() method
python setup.py test now works with pytest itself
fix/improve internal/packaging related bits:
exception message check of test_nose.py now passes on python33 as well
issue206 - fix test_assertrewrite.py to work when a global PYTHONDONTWRITEBYTECODE=1 is
present
add tox.ini to pytest distribution so that ignore-dirs and others config bits are properly distributed for
maintainers who run pytest-own tests
13.18 v2.3.1
fix issue202 - fix regression: using self from fixture functions now works as expected (its the same self
instance that a test method which uses the fixture sees)
skip pexpect using tests (test_pdb.py mostly) on freebsd* systems due to pexpect not supporting it properly
(hanging)
link to web pages from markers output which provides help for pytest.mark.* usage.
13.19 v2.3.0
fix issue202 - better automatic names for parametrized test functions
fix issue139 - introduce @pytest.fixture which allows direct scoping and parametrization of funcarg factories.
fix issue198 - conftest fixtures were not found on windows32 in some circumstances with nested directory
structures due to path manipulation issues
fix issue193 skip test functions with were parametrized with empty parameter sets
192
fix python3.3 compat, mostly reporting bits that previously depended on dict ordering
introduce re-ordering of tests by resource and parametrization setup which takes precedence to the usual fileordering
fix issue185 monkeypatching time.time does not cause pytest to fail
fix issue172 duplicate call of pytest.fixture decoratored setup_module functions
fix junitxml=path construction so that if tests change the current working directory and the path is a relative path
it is constructed correctly from the original current working dir.
fix python setup.py test example to cause a proper errno return
fix issue165 - fix broken doc links and mention stackoverflow for FAQ
catch unicode-issues when writing failure representations to terminal to prevent the whole session from crashing
fix xfail/skip confusion:
a skip-mark or an imperative pytest.skip will now take precedence
before xfail-markers because we cant determine xfail/xpass status in case of a skip.
see
also: http://stackoverflow.com/questions/11105828/in-py-test-when-i-explicitly-skip-a-test-that-is-marked-asxfail-how-can-i-get
always report installed 3rd party plugins in the header of a test run
fix issue160: a failing setup of an xfail-marked tests should be reported as xfail (not xpass)
fix issue128: show captured output when capsys/capfd are used
fix issue179: propperly show the dependency chain of factories
pluginmanager.register(...) now raises ValueError if the plugin has been already registered or the name is taken
fix issue159: improve http://pytest.org/latest/faq.html especially with respect to the magic history, also mention pytest-django, trial and unittest integration.
make request.keywords and node.keywords writable. All descendant collection nodes will see keyword values.
Keywords are dictionaries containing markers and other info.
fix issue 178: xml binary escapes are now wrapped in py.xml.raw
fix issue 176: correctly catch the builtin AssertionError even when we replaced AssertionError with a subclass
on the python level
factory discovery no longer fails with magic global callables that provide no sane __code__ object (mock.call
for example)
fix issue 182: testdir.inprocess_run now considers passed plugins
fix issue 188: ensure sys.exc_info is clear on python2 before calling into a test
fix issue 191: add unittest TestCase runTest method support
fix issue 156: monkeypatch correctly handles class level descriptors
reporting refinements:
pytest_report_header now receives a startdir so that you can use startdir.bestrelpath(yourpath) to show
nice relative path
allow plugins to implement both pytest_report_header and pytest_sessionstart (sessionstart is invoked
first).
dont show deselected reason line if there is none
py.test -vv will show all of assert comparisations instead of truncating
13.19. v2.3.0
193
13.20 v2.2.4
fix error message for rewritten assertions involving the % operator
fix issue 126: correctly match all invalid xml characters for junitxml binary escape
fix issue with unittest: now @unittest.expectedFailure markers should be processed correctly (you can also use
@pytest.mark markers)
document integration with the extended distribute/setuptools test commands
fix issue 140: propperly get the real functions of bound classmethods for setup/teardown_class
fix issue #141: switch from the deceased paste.pocoo.org to bpaste.net
fix issue #143: call unconfigure/sessionfinish always when configure/sessionstart where called
fix issue #144: better mangle test ids to junitxml classnames
upgrade distribute_setup.py to 0.6.27
13.21 v2.2.3
fix uploaded package to only include neccesary files
13.22 v2.2.2
fix issue101: wrong args to unittest.TestCase test function now produce better output
fix issue102: report more useful errors and hints for when a test directory was renamed and some
pyc/__pycache__ remain
fix issue106: allow parametrize to be applied multiple times e.g. from module, class and at function level.
fix issue107: actually perform session scope finalization
dont check in parametrize if indirect parameters are funcarg names
add chdir method to monkeypatch funcarg
fix crash resulting from calling monkeypatch undo a second time
fix issue115: make collectonly robust against early failure (missing files/directories)
-qq collectonly now shows only files and the number of tests in them
-q collectonly now shows test ids
allow adding of attributes to test reports such that it also works with distributed testing (no upgrade of pytestxdist needed)
13.23 v2.2.1
fix issue99 (in pytest and py) internallerrors with resultlog now produce better output - fixed by normalizing
pytest_internalerror input arguments.
fix issue97 / traceback issues (in pytest and py) improve traceback output in conjunction with jinja2 and cython
which hack tracebacks
194
fix issue93 (in pytest and pytest-xdist) avoid delayed teardowns: the final test in a test node will now run
its teardown directly instead of waiting for the end of the session. Thanks Dave Hunt for the good reporting
and feedback. The pytest_runtest_protocol as well as the pytest_runtest_teardown hooks now have nextitem
available which will be None indicating the end of the test run.
fix collection crash due to unknown-source collected items, thanks to Ralf Schmitt (fixed by depending on a
more recent pylib)
13.24 v2.2.0
fix issue90: introduce eager tearing down of test items so that teardown function are called earlier.
add an all-powerful metafunc.parametrize function which allows to parametrize test function arguments in multiple steps and therefore from indepdenent plugins and palces.
add a @pytest.mark.parametrize helper which allows to easily call a test function with different argument values
Add examples to the parametrize example page, including a quick port of Test scenarios and the new
parametrize function and decorator.
introduce registration for pytest.mark.* helpers via ini-files or through plugin hooks. Also introduce a strict
option which will treat unregistered markers as errors allowing to avoid typos and maintain a well described set
of markers for your test suite. See exaples at http://pytest.org/latest/mark.html and its links.
issue50: introduce -m marker option to select tests based on markers (this is a stricter and more predictable
version of -k in that -m only matches complete markers and has more obvious rules for and/or semantics.
new feature to help optimizing the speed of your tests: durations=N option for displaying N slowest test calls
and setup/teardown methods.
fix issue87: pastebin now works with python3
fix issue89: pdb with unexpected exceptions in doctest work more sensibly
fix and cleanup pytests own test suite to not leak FDs
fix issue83: link to generated funcarg list
fix issue74: pyarg module names are now checked against imp.find_module false positives
fix compatibility with twisted/trial-11.1.0 use cases
simplify Node.listchain
simplify junitxml output code by relying on py.xml
add support for skip properties on unittest classes and functions
13.25 v2.1.3
fix issue79: assertion rewriting failed on some comparisons in boolops
correctly handle zero length arguments (a la pytest )
fix issue67 / junitxml now contains correct test durations, thanks ronny
fix issue75 / skipping test failure on jython
fix issue77 / Allow assertrepr_compare hook to apply to a subset of tests
13.24. v2.2.0
195
13.26 v2.1.2
fix assertion rewriting on files with windows newlines on some Python versions
refine test discovery by package/module name (pyargs), thanks Florian Mayer
fix issue69 / assertion rewriting fixed on some boolean operations
fix issue68 / packages now work with assertion rewriting
fix issue66: use different assertion rewriting caches when the -O option is passed
dont try assertion rewriting on Jython, use reinterp
13.27 v2.1.1
fix issue64 / pytest.set_trace now works within pytest_generate_tests hooks
fix issue60 / fix error conditions involving the creation of __pycache__
fix issue63 / assertion rewriting on inserts involving strings containing %
fix assertion rewriting on calls with a ** arg
dont cache rewritten modules if bytecode generation is disabled
fix assertion rewriting in read-only directories
fix issue59: provide system-out/err tags for junitxml output
fix issue61: assertion rewriting on boolean operations with 3 or more operands
you can now build a man page with cd doc ; make man
13.28 v2.1.0
fix issue53 call nosestyle setup functions with correct ordering
fix issue58 and issue59: new assertion code fixes
merge Benjamins assertionrewrite branch: now assertions for test modules on python 2.6 and above are done
by rewriting the AST and saving the pyc file before the test module is imported. see doc/assert.txt for more info.
fix issue43: improve doctests with better traceback reporting on unexpected exceptions
fix issue47: timing output in junitxml for test cases is now correct
fix issue48: typo in MarkInfo repr leading to exception
fix issue49: avoid confusing error when initizaliation partially fails
fix issue44: env/username expansion for junitxml file path
show releaselevel information in test runs for pypy
reworked doc pages for better navigation and PDF generation
report KeyboardInterrupt even if interrupted during session startup
fix issue 35 - provide PDF doc version and download link from index page
196
13.29 v2.0.3
fix issue38: nicer tracebacks on calls to hooks, particularly early configure/sessionstart ones
fix missing skip reason/meta information in junitxml files, reported via http://lists.idyll.org/pipermail/testing-inpython/2011-March/003928.html
fix issue34: avoid collection failure with test prefixed classes deriving from object.
dont require zlib (and other libs) for genscript plugin without genscript actually being used.
speed up skips (by not doing a full traceback represenation internally)
fix issue37: avoid invalid characters in junitxmls output
13.30 v2.0.2
tackle issue32 - speed up test runs of very quick test functions by reducing the relative overhead
fix issue30 - extended xfail/skipif handling and improved reporting. If you have a syntax error in your skip/xfail
expressions you now get nice error reports.
Also you can now access module globals from xfail/skipif expressions so that this for example works now:
import pytest
import mymodule
@pytest.mark.skipif("mymodule.__version__[0] == "1")
def test_function():
pass
This will not run the test function if the modules version string does not start with a 1. Note that specifying
a string instead of a boolean expressions allows py.test to report meaningful information when summarizing a
test run as to what conditions lead to skipping (or xfail-ing) tests.
fix issue28 - setup_method and pytest_generate_tests work together The setup_method fixture method now gets
called also for test function invocations generated from the pytest_generate_tests hook.
fix issue27 - collectonly and keyword-selection (-k) now work together Also, if you do py.test collectonly
-q you now get a flat list of test ids that you can use to paste to the py.test commandline in order to execute a
particular test.
fix issue25 avoid reported problems with pdb and python3.2/encodings output
fix issue23 - tmpdir argument now works on Python3.2 and WindowsXP Starting with Python3.2 os.symlink
may be supported. By requiring a newer py lib version the py.path.local() implementation acknowledges this.
fixed typos in the docs (thanks Victor Garcia, Brianna Laugher) and particular thanks to Laura Creighton who
also revieved parts of the documentation.
fix slighly wrong output of verbose progress reporting for classes (thanks Amaury)
more precise (avoiding of) deprecation warnings for node.Class|Function accesses
avoid std unittest assertion helper code in tracebacks (thanks Ronny)
13.31 v2.0.1
refine and unify initial capturing so that it works nicely even if the logging module is used on an early-loaded
conftest.py file or plugin.
13.29. v2.0.3
197
allow to omit () in test ids to allow for uniform test ids as produced by Alfredos nice pytest.vim plugin.
fix issue12 - show plugin versions with version and traceconfig and also document how to add extra
information to reporting test header
fix issue17 (import-* reporting issue on python3) by requiring py>1.4.0 (1.4.1 is going to include it)
fix issue10 (numpy arrays truth checking) by refining assertion interpretation in py lib
fix issue15: make nose compatibility tests compatible with python3 (now that nose-1.0 supports python3)
remove somewhat surprising same-conftest detection because it ignores conftest.py when they appear in several subdirs.
improve assertions (not in), thanks Floris Bruynooghe
improve behaviour/warnings when running on top of python -OO (assertions and docstrings are turned off,
leading to potential false positives)
introduce a pytest_cmdline_processargs(args) hook to allow dynamic computation of command line arguments.
This fixes a regression because py.test prior to 2.0 allowed to set command line options from conftest.py files
which so far pytest-2.0 only allowed from ini-files now.
fix issue7: assert failures in doctest modules. unexpected failures in doctests will not generally show nicer, i.e.
within the doctest failing context.
fix issue9: setup/teardown functions for an xfail-marked test will report as xfail if they fail but report as normally passing (not xpassing) if they succeed. This only is true for direct setup/teardown invocations because
teardown_class/ teardown_module cannot closely relate to a single test.
fix issue14: no logging errors at process exit
refinements to collecting output on non-ttys
refine internal plugin registration and traceconfig output
introduce a mechanism to prevent/unregister
http://pytest.org/plugins.html#cmdunregister
plugins
from
the
command
line,
see
13.32 v2.0.0
pytest-2.0 is now its own package and depends on pylib-2.0
new ability: python -m pytest / python -m pytest.main ability
new python invcation: pytest.main(args, plugins) to load some custom plugins early.
try harder to run unittest test suites in a more compatible manner by deferring setup/teardown semantics to the
unittest package. also work harder to run twisted/trial and Django tests which should now basically work by
default.
introduce a new way to set config options via ini-style files, by default setup.cfg and tox.ini files are searched.
The old ways (certain environment variables, dynamic conftest.py reading is removed).
add a new -q option which decreases verbosity and prints a more nose/unittest-style dot output.
fix issue135 - marks now work with unittest test cases as well
198
fix issue126 - introduce py.test.set_trace() to trace execution via PDB during the running of tests even if capturing
is ongoing.
fix issue123 - new python -m py.test invocation for py.test (requires Python 2.5 or above)
fix issue124 - make reporting more resilient against tests opening files on filedescriptor 1 (stdout).
fix issue109 - sibling conftest.py files will not be loaded. (and Directory collectors cannot be customized anymore from a Directorys conftest.py - this needs to happen at least one level up).
introduce (customizable) assertion failure representations and enhance output on assertion failures for comparisons and other cases (Floris Bruynooghe)
nose-plugin: pass through type-signature failures in setup/teardown functions instead of not calling them (Ed
Singleton)
remove py.test.collect.Directory (follows from a major refactoring and simplification of the collection process)
majorly reduce py.test core code, shift function/python testing to own plugin
fix issue88 (finding custom test nodes from command line arg)
refine tmpdir creation, will now create basenames better associated with test names (thanks Ronny)
xpass (unexpected pass) tests dont cause exitcode!=0
fix issue131 / issue60 - importing doctests in __init__ files used as namespace packages
fix issue93 stdout/stderr is captured while importing conftest.py
fix bug: unittest collected functions now also can have pytestmark applied at class/module level
add ability to use class level for cached_setup helper
fix strangeness: mark.* objects are now immutable, create new instances
13.33 v1.3.4
fix issue111: improve install documentation for windows
fix issue119: fix custom collectability of __init__.py as a module
fix issue116: doctestmodules work with __init__.py files as well
fix issue115: unify internal exception passthrough/catching/GeneratorExit
fix issue118: new tb=native for presenting cpython-standard exceptions
13.34 v1.3.3
fix issue113: assertion representation problem with triple-quoted strings (and possibly other cases)
make conftest loading detect that a conftest file with the same content was already loaded, avoids surprises
in nested directory structures which can be produced e.g. by Hudson. It probably removes the need to use
confcutdir in most cases.
fix terminal coloring for win32 (thanks Michael Foord for reporting)
fix weirdness: make terminal width detection work on stdout instead of stdin (thanks Armin Ronacher for
reporting)
remove trailing whitespace in all py/text distribution files
13.33. v1.3.4
199
13.35 v1.3.2
13.35.1 New features
fix issue103: introduce py.test.raises as context manager, examples:
with py.test.raises(ZeroDivisionError):
x = 0
1 / x
with py.test.raises(RuntimeError) as excinfo:
call_something()
# you may do extra checks on excinfo.value|type|traceback here
improved error reporting on collection and import errors. This makes use of a more general mechanism, namely
that for custom test item/collect nodes node.repr_failure(excinfo) is now uniformly called so that
you can override it to return a string error representation of your choice which is going to be reported as a (red)
string.
introduce junitprefix=STR option to prepend a prefix to all reports in the junitxml file.
200
13.36 v1.3.1
13.36.1 New features
issue91: introduce new py.test.xfail(reason) helper to imperatively mark a test as expected to fail. Can be used
from within setup and test functions. This is useful especially for parametrized tests when certain configurations
are expected-to-fail. In this case the declarative approach with the @py.test.mark.xfail cannot be used as it
would mark all configurations as xfail.
issue102: introduce new maxfail=NUM option to stop test runs after NUM failures. This is a generalization of
the -x or exitfirst option which is now equivalent to maxfail=1. Both -x and maxfail will now also
print a line near the end indicating the Interruption.
issue89: allow py.test.mark decorators to be used on classes (class decorators were introduced with python2.6)
and also allow to have multiple markers applied at class/module level by specifying a list.
improve and refine letter reporting in the progress bar: . pass f failed test s skipped tests (reminder: use for
dependency/platform mismatch only) x xfailed test (test that was expected to fail) X xpassed test (test that was
expected to fail but passed)
You can use any combination of fsxX with the -r extended reporting option. The xfail/xpass results will show
up as skipped tests in the junitxml output - which also fixes issue99.
make py.test.cmdline.main() return the exitstatus instead of raising SystemExit and also allow it to be called
multiple times. This of course requires that your application and tests are properly teared down and dont have
global state.
13.36. v1.3.1
201
improve support for raises and other dynamically compiled code by manipulating pythons linecache.cache
instead of the previous rather hacky way of creating custom code objects. This makes it seemlessly work on
Jython and PyPy where it previously didnt.
fix issue96: make capturing more resilient against Control-C interruptions (involved somewhat substantial refactoring to the underlying capturing functionality to avoid race conditions).
fix chaining of conditional skipif/xfail decorators - so it works now as expected to use multiple
@py.test.mark.skipif(condition) decorators, including specific reporting which of the conditions lead to skipping.
fix issue95: late-import zlib so that its not required for general py.test startup.
fix issue94: make reporting more robust against bogus source code (and internally be more careful when presenting unexpected byte sequences)
13.37 v1.3.0
deprecate report option in favour of a new shorter and easier to remember -r option: it takes a string argument
consisting of any combination of xfsX characters. They relate to the single chars you see during the dotted
progress printing and will print an extra line per test at the end of the test run. This extra line indicates the exact
position or test ID that you directly paste to the py.test cmdline in order to re-run a particular test.
allow external plugins to register new hooks via the new pytest_addhooks(pluginmanager) hook. The new
release of the pytest-xdist plugin for distributed and looponfailing testing requires this feature.
add a new pytest_ignore_collect(path, config) hook to allow projects and plugins to define exclusion behaviour
for their directory structure - for example you may define in a conftest.py this method:
def pytest_ignore_collect(path):
return path.check(link=1)
13.38 v1.2.0
refined usage and options for py.cleanup:
py.cleanup
py.cleanup
py.cleanup
py.cleanup
py.cleanup
py.cleanup
add a new option py.test funcargs which shows available funcargs and their help strings (docstrings on their
respective factory function) for a given test path
display a short and concise traceback if a funcarg lookup fails
early-load conftest.py files in non-dot first-level sub directories. allows to conveniently keep and access testrelated options in a test subdir and still add command line options.
fix issue67: new super-short traceback-printing option: tb=line will print a single line for each failing
(python) test indicating its filename, lineno and the failure value
fix issue78: always call python-level teardown functions even if the according setup failed. This includes
refinements for calling setup_module/class functions which will now only be called once instead of the previous
behaviour where theyd be called multiple times if they raise an exception (including a Skipped exception). Any
exception will be re-corded and associated with all tests in the according module/class scope.
fix issue63: assume <40 columns to be a bogus terminal width, default to 80
fix pdb debugging to be in the correct frame on raises-related errors
update apipkg.py to fix an issue where recursive imports might unnecessarily break importing
fix plugin links
13.39 v1.1.1
moved dist/looponfailing from py.test core into a new separately released pytest-xdist plugin.
new junitxml plugin: junitxml=path will generate a junit style xml file which is processable e.g. by the Hudson
CI system.
new option: genscript=path will generate a standalone py.test script which will not need any libraries installed.
thanks to Ralf Schmitt.
new option: ignore will prevent specified path from collection. Can be specified multiple times.
new option: confcutdir=dir will make py.test only consider conftest files that are relative to the specified dir.
new funcarg: pytestconfig is the pytest config object for access to command line args and can now be easily
used in a test.
install py.test and py.which with a -$VERSION suffix to disambiguate between Python3, python2.X, Jython
and PyPy installed versions.
13.38. v1.2.0
203
13.40 v1.1.0
introduce
automatic
plugin
pkg_resources.iter_entry_points
registration
via
pytest11
entrypoints
via
setuptools
204
13.41 v1.0.2
adjust and improve docs
remove py.rest tool and internal namespace - it was never really advertised and can still be used with the old
release if needed. If there is interest it could be revived into its own tool i guess.
fix issue48 and issue59: raise an Error if the module from an imported test file does not seem to come from the
filepath - avoids same-name confusion that has been reported repeatedly
merged Ronnys nose-compatibility hacks: now nose-style setup_module() and setup() functions are supported
introduce generalized py.test.mark function marking
reshuffle / refine command line grouping
deprecate parser.addgroup in favour of getgroup which creates option group
add report command line option that allows to control showing of skipped/xfailed sections
generalized skipping: a new way to mark python functions with skipif or xfail at function, class and modules
level based on platform or sys-module attributes.
extend py.test.mark decorator to allow for positional args
introduce and test py.cleanup -d to remove empty directories
fix issue #59 - robustify unittest test collection
make bpython/help interaction work by adding an __all__ attribute to ApiModule, cleanup initpkg
use MIT license for pylib, add some contributors
remove py.execnet code and substitute all usages with execnet proper
fix issue50 - cached_setup now caches more to expectations for test functions with multiple arguments.
merge Jarkos fixes, issue #45 and #46
add the ability to specify a path for py.lookup to search in
fix a funcarg cached_setup bug probably only occuring in distributed testing and module scope with teardown.
many fixes and changes for making the code base python3 compatible, many thanks to Benjamin Peterson for
helping with this.
consolidate builtins implementation to be compatible with >=2.3, add helpers to ease keeping 2 and 3k compatible code
deprecate py.compat.doctest|subprocess|textwrap|optparse
deprecate py.magic.autopath, remove py/magic directory
move pytest assertion handling to py/code and a pytest_assertion plugin, add no-assert option, deprecate
py.magic namespaces in favour of (less) py.code ones.
consolidate and cleanup py/code classes and files
cleanup py/misc, move tests to bin-for-dist
introduce delattr/delitem/delenv methods to py.tests monkeypatch funcarg
13.41. v1.0.2
205
13.42 v1.0.2
fixing packaging issues, triggered by fedora redhat packaging, also added doc, examples and contrib dirs to the
tarball.
added a documentation link to the new django plugin.
13.43 v1.0.1
added a pytest_nose plugin which handles nose.SkipTest,
setup/teardown and tries to report functions correctly.
nose-style function/method/generator
capturing of unicode writes or encoded strings to sys.stdout/err work better, also terminalwriting was adapted
and somewhat unified between windows and linux.
improved documentation layout and content a lot
added a help-config option to show conftest.py / ENV-var names for all longopt cmdline options, and some
special conftest.py variables. renamed conf_capture conftest setting to option_capture accordingly.
fix issue #27: better reporting on non-collectable items given on commandline (e.g. pyc files)
fix issue #33: added version flag (thanks Benjamin Peterson)
fix issue #32: adding support for incomplete paths to wcpath.status()
Test prefixed classes are not collected by default anymore if they have an __init__ method
monkeypatch setenv() now accepts a prepend parameter
improved reporting of collection error tracebacks
simplified multicall mechanism and plugin architecture, renamed some internal methods and argnames
13.44 v1.0.0
more terse reporting try to show filesystem path relatively to current dir
improve xfail output a bit
13.45 v1.0.0b9
cleanly handle and report final teardown of test setup
fix svn-1.6 compat issue with py.path.svnwc().versioned() (thanks Wouter Vanden Hove)
206
setup/teardown or collection problems now show as ERRORs or with big Es in the progress lines. they are
reported and counted separately.
dist-testing: properly handle test items that get locally collected but cannot be collected on the remote side often due to platform/dependency reasons
simplified py.test.mark API - see keyword plugin documentation
integrate better with logging: capturing now by default captures test functions and their immediate
setup/teardown in a single stream
capsys and capfd funcargs now have a readouterr() and a close() method (underlyingly py.io.StdCapture/FD
objects are used which grew a readouterr() method as well to return snapshots of captured out/err)
make assert-reinterpretation work better with comparisons not returning bools (reported with numpy from thanks
maciej fijalkowski)
reworked per-test output capturing into the pytest_iocapture.py plugin and thus removed capturing code from
config object
item.repr_failure(excinfo) instead of item.repr_failure(excinfo, outerr)
13.46 v1.0.0b8
pytest_unittest-plugin is now enabled by default
introduced pytest_keyboardinterrupt hook and refined pytest_sessionfinish hooked, added tests.
workaround a buggy logging module interaction (closing already closed files). Thanks to Sridhar Ratnakumar
for triggering.
if plugins use py.test.importorskip for importing a dependency only a warning will be issued instead of exiting
the testing process.
many improvements to docs: - refined funcargs doc , use the term factory instead of provider - added a new
talk/tutorial doc page - better download page - better plugin docstrings - added new plugins page and automatic
doc generation script
fixed teardown problem related to partially failing funcarg setups (thanks MrTopf for reporting),
pytest_runtest_teardown is now always invoked even if the pytest_runtest_setup failed.
tweaked doctest output for docstrings in py modules, thanks Radomir.
13.47 v1.0.0b7
renamed py.test.xfail back to py.test.mark.xfail to avoid two ways to decorate for xfail
re-added py.test.mark decorator for setting keywords on functions (it was actually documented so removing it
was not nice)
remove scope-argument from request.addfinalizer() because request.cached_setup has the scope arg.
TOOWTDI.
perform setup finalization before reporting failures
apply modified patches from Andreas Kloeckner to allow test functions to have no func_code (#22) and to make
-k and function keywords work (#20)
apply patch from Daniel Peolzleithner (issue #23)
13.46. v1.0.0b8
207
13.48 v1.0.0b3
plugin classes are removed: one now defines hooks directly in conftest.py or global pytest_*.py files.
added new pytest_namespace(config) hook that allows to inject helpers directly to the py.test.* namespace.
documented and refined many hooks
added new style of generative tests via pytest_generate_tests hook that integrates well with function arguments.
13.49 v1.0.0b1
introduced new funcarg setup method, see doc/test/funcarg.txt
introduced plugin architecuture and many new py.test plugins, see doc/test/plugins.txt
teardown_method is now guaranteed to get called after a test method has run.
new method: py.test.importorskip(mod,minversion) will either import or call py.test.skip()
completely revised internal py.test architecture
new py.process.ForkedFunc object allowing to fork execution of a function to a sub process and getting a result
back.
XXX lots of things missing here XXX
13.50 v0.9.2
refined installation and metadata, created new setup.py, now based on setuptools/ez_setup (thanks to Ralf
Schmitt for his support).
improved the way of making py.* scripts available in windows environments, they are now added to the Scripts
directory as .cmd files.
py.path.svnwc.status() now is more complete and uses xml output from the svn command if available (Guido
Wesdorp)
fix for py.path.svn* to work with svn 1.5 (Chris Lamb)
fix path.relto(otherpath) method on windows to use normcase for checking if a path is relative.
py.tests traceback is better parseable from editors (follows the filenames:LINENO: MSG convention) (thanks
to Osmo Salomaa)
fix to javascript-generation, py.test runbrowser should work more reliably now
removed previously accidentally added py.test.broken and py.test.notimplemented helpers.
there now is a py.__version__ attribute
208
13.51 v0.9.1
This is a fairly complete list of v0.9.1, which can serve as a reference for developers.
allowing + signs in py.path.svn urls [39106]
fixed support for Failed exceptions without excinfo in py.test [39340]
added support for killing processes for Windows (as well as platforms that support os.kill) in py.misc.killproc
[39655]
added setup/teardown for generative tests to py.test [40702]
added detection of FAILED TO LOAD MODULE to py.test [40703, 40738, 40739]
fixed problem with calling .remove() on wcpaths of non-versioned files in py.path [44248]
fixed some import and inheritance issues in py.test [41480, 44648, 44655]
fail to run greenlet tests when pypy is available, but without stackless [45294]
small fixes in rsession tests [45295]
fixed issue with 2.5 type representations in py.test [45483, 45484]
made that internal reporting issues displaying is done atomically in py.test [45518]
made that non-existing files are igored by the py.lookup script [45519]
improved exception name creation in py.test [45535]
made that less threads are used in execnet [merge in 45539]
removed lock required for atomical reporting issue displaying in py.test [45545]
removed globals from execnet [45541, 45547]
refactored cleanup mechanics, made that setDaemon is set to 1 to make atexit get called in 2.5 (py.execnet)
[45548]
fixed bug in joining threads in py.execnets servemain [45549]
refactored py.test.rsession tests to not rely on exact output format anymore [45646]
using repr() on test outcome [45647]
added Reason classes for py.test.skip() [45648, 45649]
killed some unnecessary sanity check in py.test.collect [45655]
avoid using os.tmpfile() in py.io.fdcapture because on Windows its only usable by Administrators [45901]
added support for locking and non-recursive commits to py.path.svnwc [45994]
locking files in py.execnet to prevent CPython from segfaulting [46010]
added export() method to py.path.svnurl
fixed -d -x in py.test [47277]
fixed argument concatenation problem in py.path.svnwc [49423]
restore py.test behaviour that it exits with code 1 when there are failures [49974]
dont fail on html files that dont have an accompanying .txt file [50606]
fixed utestconvert.py < input [50645]
small fix for code indentation in py.code.source [50755]
13.51. v0.9.1
209
210
INDEX
A
add() (MarkInfo method), 61
add_marker() (Node method), 86
addcall() (Metafunc method), 51
addfinalizer() (FixtureRequest method), 24
addfinalizer() (Node method), 87
addini() (Parser method), 86
addinivalue_line() (Config method), 85
addoption() (Parser method), 86
addopts
configuration value, 27
applymarker() (FixtureRequest method), 24
args (MarkInfo attribute), 61
C
cached_setup() (FixtureRequest method), 24
CallInfo (class in _pytest.runner), 87
CallOutcome (class in _pytest.core), 88
chdir() (monkeypatch method), 56
Class (class in _pytest.python), 87
cls (FixtureRequest attribute), 23
collect() (Collector method), 87
Collector (class in _pytest.main), 87
Collector.CollectError, 87
Config (class in _pytest.config), 85
config (FixtureRequest attribute), 23
config (Node attribute), 86
configuration value
addopts, 27
doctest_optionflags, 28
minversion, 27
norecursedirs, 27
python_classes, 27
python_files, 27
python_functions, 27
configuration value, 28
duration (TestReport attribute), 88
E
excinfo (CallInfo attribute), 88
exit() (in module _pytest.runner), 22
extra_keyword_matches (Node attribute), 86
F
fail() (in module _pytest.runner), 22
fixture() (in module _pytest.python), 23
fixturename (FixtureRequest attribute), 23
FixtureRequest (class in _pytest.python), 23
fromdictargs() (_pytest.config.Config class method), 85
fspath (FixtureRequest attribute), 23
fspath (Node attribute), 86
Function (class in _pytest.python), 87
function (FixtureRequest attribute), 23
function (Function attribute), 87
G
get_marker() (Node method), 87
getfuncargvalue() (FixtureRequest method), 24
getgroup() (Parser method), 85
getini() (Config method), 85
getoption() (Config method), 85
getparent() (Node method), 87
getvalue() (Config method), 85
getvalueorskip() (Config method), 85
I
ihook (Node attribute), 86
importorskip() (in module _pytest.runner), 22
instance (FixtureRequest attribute), 23
Item (class in _pytest.main), 87
211
L
listchain() (Node method), 86
listextrakeywords() (Node method), 87
location (TestReport attribute), 88
longrepr (TestReport attribute), 88
M
main() (in module pytest), 21
MarkDecorator (class in _pytest.mark), 60
MarkGenerator (class in _pytest.mark), 60
MarkInfo (class in _pytest.mark), 60
minversion
configuration value, 27
Module (class in _pytest.python), 87
module (FixtureRequest attribute), 23
monkeypatch (class in _pytest.monkeypatch), 55
N
name (MarkInfo attribute), 60
name (Node attribute), 86
Node (class in _pytest.main), 86
node (FixtureRequest attribute), 23
nodeid (Node attribute), 86
nodeid (TestReport attribute), 88
norecursedirs
configuration value, 27
O
option (Config attribute), 85
outcome (TestReport attribute), 88
P
parametrize() (Metafunc method), 50
parent (Node attribute), 86
Parser (class in _pytest.config), 85
pluginmanager (Config attribute), 85
pytest_addhooks() (in module _pytest.hookspec), 81
pytest_addoption() (in module _pytest.hookspec), 79
pytest_assertrepr_compare()
(in
module
_pytest.hookspec), 30
pytest_cmdline_main() (in module _pytest.hookspec), 79
pytest_cmdline_parse() (in module _pytest.hookspec), 79
pytest_cmdline_preparse() (in module _pytest.hookspec),
79
pytest_collect_directory() (in module _pytest.hookspec),
80
pytest_collect_file() (in module _pytest.hookspec), 80
pytest_collection_modifyitems()
(in
module
_pytest.hookspec), 81
pytest_collectreport() (in module _pytest.hookspec), 81
pytest_collectstart() (in module _pytest.hookspec), 81
pytest_configure() (in module _pytest.hookspec), 79
pytest_deselected() (in module _pytest.hookspec), 81
212
pytest_exception_interact()
(in
module
_pytest.hookspec), 81
pytest_generate_tests() (in module _pytest.hookspec), 81
pytest_ignore_collect() (in module _pytest.hookspec), 80
pytest_internalerror() (in module _pytest.hookspec), 81
pytest_itemcollected() (in module _pytest.hookspec), 81
pytest_keyboard_interrupt()
(in
module
_pytest.hookspec), 81
pytest_load_initial_conftests()
(in
module
_pytest.hookspec), 79
pytest_namespace() (in module _pytest.hookspec), 79
pytest_pycollect_makeitem()
(in
module
_pytest.hookspec), 81
pytest_runtest_call() (in module _pytest.hookspec), 80
pytest_runtest_logreport() (in module _pytest.hookspec),
81
pytest_runtest_makereport()
(in
module
_pytest.hookspec), 80
pytest_runtest_protocol() (in module _pytest.hookspec),
80
pytest_runtest_setup() (in module _pytest.hookspec), 80
pytest_runtest_teardown() (in module _pytest.hookspec),
80
pytest_unconfigure() (in module _pytest.hookspec), 80
Python Enhancement Proposals
PEP 8, 4
python_classes
configuration value, 27
python_files
configuration value, 27
python_functions
configuration value, 27
R
raiseerror() (FixtureRequest method), 24
raises() (in module pytest), 21
repr_failure() (Collector method), 87
runtest() (Function method), 87
S
scope (FixtureRequest attribute), 23
sections (TestReport attribute), 88
session (FixtureRequest attribute), 24
session (Node attribute), 86
setattr() (monkeypatch method), 55
setenv() (monkeypatch method), 56
setitem() (monkeypatch method), 56
skip() (in module _pytest.runner), 22
syspath_prepend() (monkeypatch method), 56
T
TestReport (class in _pytest.runner), 88
Index
U
undo() (monkeypatch method), 56
W
warn() (Config method), 85
warn() (Node method), 86
when (CallInfo attribute), 87
when (TestReport attribute), 88
X
xfail() (in module _pytest.skipping), 22
Index
213