Fix spelling in writing/tests.rst
[python-guide.git] / docs / writing / tests.rst
1 Testing Your Code
2 =====================
3
4 Testing your code is very important.
5
6 Getting used to writing the testing code and the running code in parallel is
7 now considered a good habit. Used wisely, this method helps you define more
8 precisely your code's intent and have a more decoupled architecture.
9
10 Some general rules of testing:
11
12 - A testing unit should focus on one tiny bit of functionality and prove it
13   correct.
14
15 - Each test unit must be fully independent. Each of them must be able to run
16   alone, and also within the test suite, regardless of the order they are called.
17   The implication of this rule is that each test must be loaded with a fresh
18   dataset and may have to do some cleanup afterwards. This is usually
19   handled by setUp() and tearDown() methods.
20
21 - Try hard to make tests that run fast. If one single test needs more than a
22   few millisecond to run, development will be slowed down or the tests will not
23   be run as often as desirable. In some cases, test can't be fast because they
24   need a complex data structure to work on, and this data structure must be
25   loaded every time the test runs. Keep these heavier tests in a separate test
26   suite that is run by some scheduled task, and run all other tests as often
27   as needed.
28
29 - Learn your tools and learn how to run a single test or a test case. Then,
30   when developing a function inside a module, run this function's tests very
31   often, ideally automatically when you save the code.
32
33 - Always run the full test suite before a coding session, and run it again
34   after. This will give you more confidence that you did not break anything in
35   the rest of the code.
36
37 - It is a good idea to implement a hook that runs all test before pushing code
38   to a shared repository.
39
40 - If you are in the middle of a development and have to interrupt your work, it
41   is a good idea to write a broken unit test about what you want to develop next.
42   When coming back to work, you will have a pointer to where you were and get
43   faster on tracks.
44
45 - The first step when you are debugging your code is to write a new test
46   pinpointing the bug. While it is not always possible to do, those bug
47   catching test are among the most valuable piece of code in your project.
48
49 - Use long and descriptive names for testing functions. The style guide here is
50   slightly different than that of running code, where short names are often
51   preferred. The reason is testing functions are never called explicitly.
52   ``square()`` or even ``sqr()`` is ok in running code, but in testing code you
53   would has names such as ``test_square_of_number_2()``,
54   ``test_square_negative_number()``. These function names are displayed when a
55   test fail, and should be as descriptive as possible.
56
57 - When something goes wrong or has to be changed, and if your code has a good
58   set of tests, you or other maintainers will rely largely on the testing suite
59   to fix the problem or modify a given behavior. Therefore the testing code will
60   be read as much as or even more than the running code. A unit test whose
61   purpose is unclear is not very helpful is this case.
62
63 - Another use of the testing code is as an introduction to new developers. When
64   someone will have to work on the code base, running and reading the related
65   testing code is often the best they can do. They will or should discover the
66   hot spots, where most difficulties arise, and the corner cases. If they have
67   to add some functionality, the first step should be to add a test and, by this
68   mean, ensure the new functionality is not already a working path that has not
69   been plugged in the interface.
70
71 The Basics
72 ::::::::::
73
74
75 Unittest
76 --------
77
78 Unittest is the batteries-included test module in the Python standard library.
79 Its API will be familiar to anyone who has used any of the JUnit/nUnit/CppUnit
80 series of tools.
81
82 Creating testcases is accomplished by subclassing a TestCase base class
83
84 ::
85
86     import unittest
87
88     def fun(x):
89         return x + 1
90
91     class MyTest(unittest.TestCase):
92         def test(self):
93             self.assertEqual(fun(3), 4)
94
95 As of Python 2.7 unittest also includes its own test discovery mechanisms.
96
97     `unittest in the standard library documentation <http://docs.python.org/library/unittest.html>`_
98
99
100 Doctest
101 -------
102
103 The doctest module searches for pieces of text that look like interactive
104 Python sessions in docstrings, and then executes those sessions to verify that
105 they work exactly as shown.
106
107 Doctests have a different use case than proper unit tests: they are usually
108 less detailed and don't catch special cases or obscure regression bugs. They
109 are useful as an expressive documentation of the main use cases of a module and
110 its components. However, doctests should run automatically each time the full
111 test suite runs.
112
113 A simple doctest in a function:
114
115 ::
116
117     def square(x):
118         """Squares x.
119
120         >>> square(2)
121         4
122         >>> square(-2)
123         4
124         """
125
126         return x * x
127
128     if __name__ == '__main__':
129         import doctest
130         doctest.testmod()
131
132 When running this module from the command line as in ``python module.py``, the
133 doctests will run and complain if anything is not behaving as described in the
134 docstrings.
135
136 Tools
137 :::::
138
139
140 py.test
141 -------
142
143 py.test is a no-boilerplate alternative to Python's standard unittest module.
144
145 ::
146
147     $ pip install pytest
148
149 Despite being a fully-featured and extensible test tool it boasts a simple
150 syntax. Creating a test suite is as easy as writing a module with a couple of
151 functions
152
153 ::
154
155     # content of test_sample.py
156     def func(x):
157         return x + 1
158
159     def test_answer():
160         assert func(3) == 5
161
162 and then running the `py.test` command
163
164 ::
165
166     $ py.test
167     =========================== test session starts ============================
168     platform darwin -- Python 2.7.1 -- pytest-2.2.1
169     collecting ... collected 1 items
170
171     test_sample.py F
172
173     ================================= FAILURES =================================
174     _______________________________ test_answer ________________________________
175
176         def test_answer():
177     >       assert func(3) == 5
178     E       assert 4 == 5
179     E        +  where 4 = func(3)
180
181     test_sample.py:5: AssertionError
182     ========================= 1 failed in 0.02 seconds =========================
183
184 far less work than would be required for the equivalent functionality with the
185 unittest module!
186
187     `py.test <http://pytest.org/latest/>`_
188
189
190 Nose
191 ----
192
193 nose extends unittest to make testing easier.
194
195
196 ::
197
198     $ pip install nose
199
200 nose provides automatic test discovery to save you the hassle of manually
201 creating test suites. It also provides numerous plugins for features such as
202 xUnit-compatible test output, coverage reporting, and test selection.
203
204     `nose <http://readthedocs.org/docs/nose/en/latest/>`_
205
206
207 tox
208 ---
209
210 tox is a tool for automating test environment management and testing against
211 multiple interpreter configurations
212
213 ::
214
215     $ pip install tox
216
217 tox allows you to configure complicated multi-parameter test matrices via a
218 simple ini-style configuration file.
219
220     `tox <http://tox.testrun.org/latest/>`_
221
222 Unittest2
223 ---------
224
225 unittest2 is a backport of Python 2.7's unittest module which has an improved
226 API and better assertions over the one available in previous versions of Python.
227
228 If you're using Python 2.6 or below, you can install it with pip
229
230 ::
231
232     $ pip install unittest2
233
234 You may want to import the module under the name unittest to make porting code
235 to newer versions of the module easier in the future
236
237 ::
238
239     import unittest2 as unittest
240
241     class MyTest(unittest.TestCase):
242         ...
243
244 This way if you ever switch to a newer python version and no longer need the
245 unittest2 module, you can simply change the import in your test module without
246 the need to change any other code.
247
248     `unittest2 <http://pypi.python.org/pypi/unittest2>`_
249
250