Debian Codegraph @

docs_sphinx/developer/guidelines/testing.rst

raw
1 Testing
2 =======
3
4 Brian uses the `pytest package <https://docs.pytest.org/>`__
5 for its testing framework.
6
7 Running the test suite
8 ----------------------
9 The pytest tool automatically finds tests in the code. However, to deal with the
10 different code generation targets, and correctly set up tests for standalone mode, it is
11 recommended to use Brian's builtin test function that calls pytest appropriately::
12
13 >>> import brian2
14 >>> brian2.test() # doctest: +SKIP
15
16 By default, this runs the test suite for all available (runtime) code generation
17 targets. If you only want to test a specific target, provide it as an argument::
18
19 >>> brian2.test('numpy') # doctest: +SKIP
20
21 If you want to test several targets, use a list of targets::
22
23 >>> brian2.test(['cython']) # doctest: +SKIP
24
25
26 In addition to the tests specific to a code generation target, the test suite
27 will also run a set of independent tests (e.g. parsing of equations, unit
28 system, utility functions, etc.). To exclude these tests, set the
29 ``test_codegen_independent`` argument to ``False``. Not all available tests are
30 run by default, tests that take a long time are excluded. To include these, set
31 ``long_tests`` to ``True``.
32
33 To run the C++ standalone tests, you have to set the ``test_standalone``
34 argument to the name of a standalone device. If you provide an empty argument
35 for the runtime code generation targets, you will only run the standalone
36 tests::
37
38 >>> brian2.test([], test_standalone='cpp_standalone') # doctest: +SKIP
39
40
41 Writing tests
42 -------------
43 Generally speaking, we aim for a 100% code coverage by the test suite. Less
44 coverage means that some code paths are never executed so there's no way of
45 knowing whether a code change broke something in that path.
46
47 Unit tests
48 ~~~~~~~~~~
49 The most basic tests are unit tests, tests that test one kind of functionality or
50 feature. To write a new unit test, add a function called ``test_...`` to one of
51 the ``test_...`` files in the ``brian2.tests`` package. Test files should
52 roughly correspond to packages, test functions should roughly correspond to
53 tests for one function/method/feature. In the test functions, use assertions
54 that will raise an ``AssertionError`` when they are violated, e.g.::
55
56 G = NeuronGroup(42, model='dv/dt = -v / (10*ms) : 1')
57 assert len(G) == 42
58
59 When comparing arrays, use the `array_equal` function from
60 `numpy.testing.utils` which takes care of comparing types, shapes and content
61 and gives a nicer error message in case the assertion fails. Never make tests
62 depend on external factors like random numbers -- tests should always give the
63 same result when run on the same codebase. You should not only test the
64 expected outcome for the correct use of functions and classes but also that
65 errors are raised when expected. For that you can use pytest's ``raises``
66 function with which you can define a block of code that should raise an exception of
67 a certain type::
68
69 with pytest.raises(DimensionMismatchError):
70 3*volt + 5*second
71
72 You can also check whether expected warnings are raised, see the documentation of the
73 :doc:`logging mechanism <logging>` for details
74
75 For simple functions, doctests (see below) are a great alternative to writing
76 classical unit tests.
77
78 By default, all tests are executed for all selected runtime code generation
79 targets (see `Running the test suite`_ above). This is not useful for all tests,
80 some basic tests that for example test equation syntax or the use of physical
81 units do not depend on code generation and need therefore not to be repeated. To
82 execute such tests only once, they can be annotated with a
83 ``codegen_independent`` marker, using the `~pytest.mark`
84 decorator::
85
86 import pytest
87 from brian2 import NeuronGroup
88
89 @pytest.mark.codegen_independent
90 def test_simple():
91 # Test that the length of a NeuronGroup is correct
92 group = NeuronGroup(5, '')
93 assert len(group) == 5
94
95 Tests that are not "codegen-independent" are by default only executed for the
96 runtimes device, i.e. not for the ``cpp_standalone`` device, for example.
97 However, many of those tests follow a common pattern that is compatible with
98 standalone devices as well: they set up a network, run it, and check the state
99 of the network afterwards. Such tests can be marked as
100 ``standalone_compatible``, using the `~pytest.mark` decorator in
101 the same way as for ``codegen_independent`` tests.::
102
103 import pytest
104 from numpy.testing.utils import assert_equal
105 from brian2 import *
106
107 @pytest.mark.standalone_compatible
108 def test_simple_run():
109 # Check that parameter values of a neuron don't change after a run
110 group = NeuronGroup(5, 'v : volt')
111 group.v = 'i*mV'
112 run(1*ms)
113 assert_equal(group.v[:], np.arange(5)*mV)
114
115 Tests that have more than a single run function but are otherwise compatible
116 with standalone mode (e.g. they don't need access to the number of synapses or
117 results of the simulation before the end of the simulation), can be marked as
118 ``standalone_compatible`` and ``multiple_runs``. They then have to use an
119 explicit ``device.build(...)`` call of the form shown below::
120
121 import pytest
122 from numpy.testing.utils import assert_equal
123 from brian2 import *
124
125 @pytest.mark.standalone_compatible
126 @pytest.mark.multiple_runs
127 def test_multiple_runs():
128 # Check that multiple runs advance the clock as expected
129 group = NeuronGroup(5, 'v : volt')
130 mon = StateMonitor(group, 'v', record=True)
131 run(1 * ms)
132 run(1 * ms)
133 device.build(direct_call=False, **device.build_options)
134 assert_equal(defaultclock.t, 2 * ms)
135 assert_equal(mon.t[0], 0 * ms)
136 assert_equal(mon.t[-1], 2 * ms - defaultclock.dt)
137
138
139 Tests can also be written specifically for a standalone device (they then have
140 to include the `~brian2.devices.device.set_device` call and possibly the
141 `~brian2.devices.device.Device.build` call explicitly). In this case tests
142 have to be annotated with the name of the device (e.g. ``'cpp_standalone'``)
143 and with ``'standalone_only'`` to exclude this test from the runtime tests.
144 Such code would look like this for a single `run` call, i.e. using the automatic
145 "build on run" feature::
146
147 import pytest
148 from brian2 import *
149
150 @pytest.mark.cpp_standalone
151 @pytest.mark.standalone_only
152 def test_cpp_standalone():
153 set_device('cpp_standalone', directory=None)
154 # set up simulation
155 # run simulation
156 run(...)
157 # check simulation results
158
159
160 If the code uses more than one `run` statement, it needs an explicit
161 `~brian2.devices.device.Device.build` call::
162
163 import pytest
164 from brian2 import *
165
166 @pytest.mark.cpp_standalone
167 @pytest.mark.standalone_only
168 def test_cpp_standalone():
169 set_device('cpp_standalone', build_on_run=False)
170 # set up simulation
171 # run simulation
172 run(...)
173 # do something
174 # run again
175 run(...)
176 device.build(directory=None)
177 # check simulation results
178
179
180 Summary
181 ^^^^^^^
182 +------------------------------------------+------------------------+-------------------------------------------------------------+
183 | ``@pytest.mark`` marker | Executed for devices | explicit use of `device` |
184 +==========================================+========================+=============================================================+
185 | ``codegen_independent`` | independent of devices | *none* |
186 +------------------------------------------+------------------------+-------------------------------------------------------------+
187 | *none* | Runtime targets | *none* |
188 +------------------------------------------+------------------------+-------------------------------------------------------------+
189 | ``standalone_compatible`` | Runtime and standalone | *none* |
190 +------------------------------------------+------------------------+-------------------------------------------------------------+
191 | ``standalone_compatible, multiple_runs`` | Runtime and standalone | ``device.build(direct_call=False, **device.build_options)`` |
192 +------------------------------------------+------------------------+-------------------------------------------------------------+
193 | ``cpp_standalone, standalone_only`` | C++ standalone device | ``set_device('cpp_standalone')`` |
194 | | | ``...`` |
195 | | | ``device.build(directory=None)`` |
196 +------------------------------------------+------------------------+-------------------------------------------------------------+
197 | ``my_device, standalone_only`` | "My device" | ``set_device('my_device')`` |
198 | | | ``...`` |
199 | | | ``device.build(directory=None)`` |
200 +------------------------------------------+------------------------+-------------------------------------------------------------+
201
202 Doctests
203 ~~~~~~~~
204 Doctests are executable documentation. In the ``Examples`` block of a class or
205 function documentation, simply write code copied from an interactive Python
206 session (to do this from ipython, use ``%doctestmode``), e.g.::
207
208 >>> from brian2.utils.stringtools import word_substitute
209 >>> expr = 'a*_b+c5+8+f(A)'
210 >>> print(word_substitute(expr, {'a':'banana', 'f':'func'}))
211 banana*_b+c5+8+func(A)
212
213 During testing, the actual output will be compared to the expected output and
214 an error will be raised if they don't match. Note that this comparison is
215 strict, e.g. trailing whitespace is not ignored. There are various ways of
216 working around some problems that arise because of this expected exactness (e.g.
217 the stacktrace of a raised exception will never be identical because it contains
218 file names), see the `doctest documentation`_ for details.
219
220 Doctests can (and should) not only be used in docstrings, but also in the
221 hand-written documentation, making sure that the examples actually work. To
222 turn a code example into a doc test, use the ``.. doctest::`` directive, see
223 :doc:`/user/equations` for examples written as doctests. For all doctests,
224 everything that is available after ``from brian2 import *`` can be used
225 directly. For everything else, add import statements to the doctest code or --
226 if you do not want the import statements to appear in the document -- add them
227 in a ``.. testsetup::`` block. See the documentation for
228 `Sphinx's doctest extension`_ for more details.
229
230 Doctests are a great way of testing things as they not only make sure that the
231 code does what it is supposed to do but also that the documentation is up to
232 date!
233
234 .. _`doctest documentation`: https://docs.python.org/2/library/doctest.html
235 .. _`Sphinx's doctest extension`: http://www.sphinx-doc.org/en/stable/ext/doctest.html
236
237
238 Correctness tests
239 ~~~~~~~~~~~~~~~~~
240 [These do not exist yet for brian2]. Unit tests test a specific function or
241 feature in isolation. In addition, we want to have tests where a complex piece
242 of code (e.g. a complete simulation) is tested. Even if it is sometimes
243 impossible to really check whether the result is correct (e.g. in the case of
244 the spiking activity of a complex network), a useful check is also whether the
245 result is *consistent*. For example, the spiking activity should be the same
246 when using code generation for Python or C++. Or, a network could be pickled
247 before running and then the result of the run could be compared to a second run
248 that starts from the unpickled network.