Debian Codegraph @

doc/en/getting-started.rst

raw
1 .. _get-started:
2
3 Get Started
4 ===================================
5
6 .. _`getstarted`:
7 .. _`installation`:
8
9 Install ``pytest``
10 ----------------------------------------
11
12 1. Run the following command in your command line:
13
14 .. code-block:: bash
15
16 pip install -U pytest
17
18 2. Check that you installed the correct version:
19
20 .. code-block:: bash
21
22 $ pytest --version
23 pytest 9.1.1
24
25 .. _`simpletest`:
26
27 Create your first test
28 ----------------------------------------------------------
29
30 Create a new file called ``test_sample.py``, containing a function, and a test:
31
32 .. code-block:: python
33
34 # content of test_sample.py
35 def func(x):
36 return x + 1
37
38
39 def test_answer():
40 assert func(3) == 5
41
42 The test
43
44 .. code-block:: pytest
45
46 $ pytest
47 =========================== test session starts ============================
48 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
49 rootdir: /home/sweet/project
50 collected 1 item
51
52 test_sample.py F [100%]
53
54 ================================= FAILURES =================================
55 _______________________________ test_answer ________________________________
56
57 def test_answer():
58 > assert func(3) == 5
59 E assert 4 == 5
60 E + where 4 = func(3)
61
62 test_sample.py:6: AssertionError
63 ========================= short test summary info ==========================
64 FAILED test_sample.py::test_answer - assert 4 == 5
65 ============================ 1 failed in 0.12s =============================
66
67 The ``[100%]`` refers to the overall progress of running all test cases. After it finishes, pytest then shows a failure report because ``func(3)`` does not return ``5``.
68
69 .. note::
70
71 You can use the ``assert`` statement to verify test expectations. pytest’s :ref:`Advanced assertion introspection <python:assert>` will intelligently report intermediate values of the assert expression so you can avoid the many names :ref:`of JUnit legacy methods <testcase-objects>`.
72
73 Run multiple tests
74 ----------------------------------------------------------
75
76 ``pytest`` will run all files of the form ``test_*.py`` or ``*_test.py`` in the current directory and its subdirectories. More generally, it follows :ref:`standard test discovery rules <test discovery>`.
77
78
79 Assert that a certain exception is raised
80 --------------------------------------------------------------
81
82 Use the :ref:`raises <assertraises>` helper to assert that some code raises an exception:
83
84 .. code-block:: python
85
86 # content of test_sysexit.py
87 import pytest
88
89
90 def f():
91 raise SystemExit(1)
92
93
94 def test_mytest():
95 with pytest.raises(SystemExit):
96 f()
97
98 Execute the test function with “quiet” reporting mode:
99
100 .. code-block:: pytest
101
102 $ pytest -q test_sysexit.py
103 . [100%]
104 1 passed in 0.12s
105
106 .. note::
107
108 The ``-q/--quiet`` flag keeps the output brief in this and following examples.
109
110 See :ref:`assertraises` for specifying more details about the expected exception.
111
112 Group multiple tests in a class
113 --------------------------------------------------------------
114
115 .. regendoc:wipe
116
117 Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test:
118
119 .. code-block:: python
120
121 # content of test_class.py
122 class TestClass:
123 def test_one(self):
124 x = "this"
125 assert "h" in x
126
127 def test_two(self):
128 x = "hello"
129 assert hasattr(x, "check")
130
131 ``pytest`` discovers all tests following its :ref:`Conventions for Python test discovery <test discovery>`, so it finds both ``test_`` prefixed functions. There is no need to subclass anything, but make sure to prefix your class with ``Test`` otherwise the class will be skipped. We can simply run the module by passing its filename:
132
133 .. code-block:: pytest
134
135 $ pytest -q test_class.py
136 .F [100%]
137 ================================= FAILURES =================================
138 ____________________________ TestClass.test_two ____________________________
139
140 self = <test_class.TestClass object at 0xdeadbeef0001>
141
142 def test_two(self):
143 x = "hello"
144 > assert hasattr(x, "check")
145 E AssertionError: assert False
146 E + where False = hasattr('hello', 'check')
147
148 test_class.py:8: AssertionError
149 ========================= short test summary info ==========================
150 FAILED test_class.py::TestClass::test_two - AssertionError: assert False
151 1 failed, 1 passed in 0.12s
152
153 The first test passed and the second failed. You can easily see the intermediate values in the assertion to help you understand the reason for the failure.
154
155 Grouping tests in classes can be beneficial for the following reasons:
156
157 * Test organization
158 * Sharing fixtures for tests only in that particular class
159 * Applying marks at the class level and having them implicitly apply to all tests
160
161 Something to be aware of when grouping tests inside classes is that each test has a unique instance of the class.
162 Having each test share the same class instance would be very detrimental to test isolation and would promote poor test practices.
163 This is outlined below:
164
165 .. regendoc:wipe
166
167 .. code-block:: python
168
169 # content of test_class_demo.py
170 class TestClassDemoInstance:
171 value = 0
172
173 def test_one(self):
174 self.value = 1
175 assert self.value == 1
176
177 def test_two(self):
178 assert self.value == 1
179
180
181 .. code-block:: pytest
182
183 $ pytest -k TestClassDemoInstance -q
184 .F [100%]
185 ================================= FAILURES =================================
186 ______________________ TestClassDemoInstance.test_two ______________________
187
188 self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>
189
190 def test_two(self):
191 > assert self.value == 1
192 E assert 0 == 1
193 E + where 0 = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>.value
194
195 test_class_demo.py:9: AssertionError
196 ========================= short test summary info ==========================
197 FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0 == 1
198 1 failed, 1 passed in 0.12s
199
200 Note that attributes added at class level are *class attributes*, so they will be shared between tests.
201
202 Compare floating-point values with pytest.approx
203 --------------------------------------------------------------
204
205 ``pytest`` also provides a number of utilities to make writing tests easier.
206 For example, you can use :func:`pytest.approx` to compare floating-point
207 values that may have small rounding errors:
208
209 .. code-block:: python
210
211 # content of test_approx.py
212 import pytest
213
214
215 def test_sum():
216 assert (0.1 + 0.2) == pytest.approx(0.3)
217
218 This avoids the need for manual tolerance checks or using
219 ``math.isclose`` and works with scalars, lists, and NumPy arrays.
220
221
222 Request a unique temporary directory for functional tests
223 --------------------------------------------------------------
224
225 ``pytest`` provides :std:doc:`Builtin fixtures/function arguments <builtin>` to request arbitrary resources, like a unique temporary directory:
226
227 .. code-block:: python
228
229 # content of test_tmp_path.py
230 def test_needsfiles(tmp_path):
231 print(tmp_path)
232 assert 0
233
234 List the name ``tmp_path`` in the test function signature and ``pytest`` will lookup and call a fixture factory to create the resource before performing the test function call. Before the test runs, ``pytest`` creates a unique-per-test-invocation temporary directory:
235
236 .. code-block:: pytest
237
238 $ pytest -q test_tmp_path.py
239 F [100%]
240 ================================= FAILURES =================================
241 _____________________________ test_needsfiles ______________________________
242
243 tmp_path = PosixPath('PYTEST_TMPDIR/test_needsfiles0')
244
245 def test_needsfiles(tmp_path):
246 print(tmp_path)
247 > assert 0
248 E assert 0
249
250 test_tmp_path.py:3: AssertionError
251 --------------------------- Captured stdout call ---------------------------
252 PYTEST_TMPDIR/test_needsfiles0
253 ========================= short test summary info ==========================
254 FAILED test_tmp_path.py::test_needsfiles - assert 0
255 1 failed in 0.12s
256
257 More info on temporary directory handling is available at :ref:`Temporary directories and files <tmp_path handling>`.
258
259 Find out what kind of builtin :ref:`pytest fixtures <fixtures>` exist with the command:
260
261 .. code-block:: bash
262
263 pytest --fixtures # shows builtin and custom fixtures
264
265 Note that this command omits fixtures with leading ``_`` unless the :option:`-v` option is added.
266
267 Continue reading
268 -------------------------------------
269
270 Check out additional pytest resources to help you customize tests for your unique workflow:
271
272 * ":ref:`usage`" for command line invocation examples
273 * ":ref:`existingtestsuite`" for working with preexisting tests
274 * ":ref:`mark`" for information on the ``pytest.mark`` mechanism
275 * ":ref:`fixtures`" for providing a functional baseline to your tests
276 * ":ref:`plugins`" for managing and writing plugins
277 * ":ref:`goodpractices`" for virtualenv and test layouts