File: chapter_testing.tex

package info (click to toggle)
python-biopython 1.78%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 65,756 kB
  • sloc: python: 221,141; xml: 178,777; ansic: 13,369; sql: 1,208; makefile: 131; sh: 70
file content (421 lines) | stat: -rw-r--r-- 14,730 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
\chapter{The Biopython testing framework}
\label{chapter:testing}

Biopython has a regression testing framework (the file
\verb|run_tests.py|) based on
\href{https://docs.python.org/3/library/unittest.html}{unittest},
the standard unit testing framework for Python.  Providing comprehensive
tests for modules is one of the most important aspects of making sure that
the Biopython code is as bug-free as possible before going out.
It also tends to be one of the most undervalued aspects of contributing.
This chapter is designed to make running the Biopython tests and
writing good test code as easy as possible.
Ideally, every module that goes into Biopython
should have a test (and should also have documentation!).
All our developers, and anyone installing Biopython from source,
are strongly encouraged to run the unit tests.

\section{Running the tests}

When you download the Biopython source code, or check it out from
our source code repository, you should find a subdirectory call
\verb|Tests|.  This contains the key script \verb|run_tests.py|,
lots of individual scripts named \verb|test_XXX.py|, and lots of
other subdirectories which contain input files for the test suite.

As part of building and installing Biopython you will typically
run the full test suite at the command line from the Biopython
source top level directory using the following:

\begin{minted}{console}
$ python setup.py test
\end{minted}

This is actually equivalent to going to the \verb|Tests|
subdirectory and running:

\begin{minted}{console}
$ python run_tests.py
\end{minted}

You'll often want to run just some of the tests, and this is done
like this:

\begin{minted}{console}
$ python run_tests.py test_SeqIO.py test_AlignIO.py
\end{minted}

When giving the list of tests, the \verb|.py| extension is optional,
so you can also just type:

\begin{minted}{console}
$ python run_tests.py test_SeqIO test_AlignIO
\end{minted}

To run the docstring tests (see section \ref{sec:doctest}), you can use

\begin{minted}{console}
$ python run_tests.py doctest
\end{minted}

You can also skip any tests which have been setup with an explicit
online component by adding \verb|--offline|, e.g.

\begin{minted}{console}
$ python run_tests.py --offline
\end{minted}

By default, \verb|run_tests.py| runs all tests, including the docstring tests.

If an individual test is failing, you can also try running it
directly, which may give you more information.

Tests based on Python's standard  \verb|unittest| framework will
\verb|import unittest| and then define \verb|unittest.TestCase| classes,
each with one or more sub-tests as methods starting with \verb|test_| which
check some specific aspect of the code.

\subsection{Running the tests using Tox}

Like most Python projects, you can also use
\href{https://tox.readthedocs.org/en/latest/}{Tox} to run the tests on multiple
Python versions, provided they are already installed in your system.

We do not provide the configuration \texttt{tox.ini} file in our code base because
of difficulties pinning down user-specific settings (e.g. executable names of the
Python versions). You may also only be interested in testing Biopython only against
a subset of the Python versions that we support.

If you are interested in using Tox, you could start with the example
\texttt{tox.ini} shown below:

\begin{minted}{text}
[tox]
envlist = pypy,py36,py37

[testenv]
changedir = Tests
commands = {envpython} run_tests.py --offline
deps =
    numpy
    reportlab
\end{minted}

Using the template above, executing \texttt{tox} will test your Biopython
code against PyPy, Python 3.6 and Python3.7. It assumes that those Pythons'
executables are named accordingly: ``python3.7`` for Python 3.7, and so on.


\section{Writing tests}

Let's say you want to write some tests for a module called \verb|Biospam|.
This can be a module you wrote, or an existing module that doesn't have
any tests yet.  In the examples below, we assume that
\verb|Biospam| is a module that does simple math.

Each Biopython test consists of a script containing the test itself, and
optionally a directory with input files used by the test:

\begin{enumerate}
  \item \verb|test_Biospam.py| -- The actual test code for your module.
  \item \verb|Biospam| [optional]-- A directory where any necessary input files
    will be located. If you have any output files that should be manually
    reviewed, output them here (but this is discouraged) to prevent clogging
    up the main Tests directory. In general, use a temporary file/folder.
\end{enumerate}

Any script with a \verb|test_| prefix in the \verb|Tests| directory will be found and run by \verb|run_tests.py|. Below, we show an example test script \verb|test_Biospam.py|. If you put this script in the Biopython \verb|Tests| directory, then \verb|run_tests.py| will find it and execute the tests contained in it:

\begin{minted}{console}
$ python run_tests.py
test_Ace ... ok
test_AlignIO ... ok
test_BioSQL ... ok
test_BioSQL_SeqIO ... ok
test_Biospam ... ok
test_CAPS ... ok
test_Clustalw ... ok
...
----------------------------------------------------------------------
Ran 107 tests in 86.127 seconds
\end{minted}

\subsection{Writing a test using {\texttt unittest}}

The \verb|unittest|-framework has been included with Python since version
2.1, and is documented in the Python Library Reference (which I know you
are keeping under your pillow, as recommended).  There is also
\href{https://docs.python.org/3/library/unittest.html}{online documentaion
for unittest}.
If you are familiar with the \verb|unittest| system (or something similar
like the nose test framework), you shouldn't have any trouble.  You may
find looking at the existing examples within Biopython helpful too.

Here's a minimal \verb|unittest|-style test script for \verb|Biospam|,
which you can copy and paste to get started:

\begin{minted}{python}
import unittest
from Bio import Biospam


class BiospamTestAddition(unittest.TestCase):
    def test_addition1(self):
        result = Biospam.addition(2, 3)
        self.assertEqual(result, 5)

    def test_addition2(self):
        result = Biospam.addition(9, -1)
        self.assertEqual(result, 8)


class BiospamTestDivision(unittest.TestCase):
    def test_division1(self):
        result = Biospam.division(3.0, 2.0)
        self.assertAlmostEqual(result, 1.5)

    def test_division2(self):
        result = Biospam.division(10.0, -2.0)
        self.assertAlmostEqual(result, -5.0)


if __name__ == "__main__":
    runner = unittest.TextTestRunner(verbosity=2)
    unittest.main(testRunner=runner)
\end{minted}

In the division tests, we use \verb|assertAlmostEqual| instead of \verb|assertEqual| to avoid tests failing due to roundoff errors; see the \verb|unittest| chapter in the Python documentation for details and for other functionality available in \verb|unittest| (\href{https://docs.python.org/3/library/unittest.html}{online reference}).

These are the key points of \verb|unittest|-based tests:

\begin{itemize}
  \item Test cases are stored in classes that derive from
    \verb|unittest.TestCase| and cover one basic aspect of your code

  \item You can use methods \verb|setUp| and \verb|tearDown| for any repeated
    code which should be run before and after each test method.  For example,
    the \verb|setUp| method might be used to create an instance of the object
    you are testing, or open a file handle.  The \verb|tearDown| should do any
    ``tidying up'', for example closing the file handle.

  \item The tests are prefixed with \verb|test_| and each test should cover
    one specific part of what you are trying to test. You can have as
    many tests as you want in a class.

  \item At the end of the test script, you can use
\begin{minted}{python}
if __name__ == "__main__":
    runner = unittest.TextTestRunner(verbosity=2)
    unittest.main(testRunner=runner)
\end{minted}
        to execute the tests when the script is run by itself (rather than
        imported from \verb|run_tests.py|).
        If you run this script, then you'll see something like the following:

\begin{minted}{console}
$ python test_BiospamMyModule.py
test_addition1 (__main__.TestAddition) ... ok
test_addition2 (__main__.TestAddition) ... ok
test_division1 (__main__.TestDivision) ... ok
test_division2 (__main__.TestDivision) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.059s

OK
\end{minted}

  \item To indicate more clearly what each test is doing, you can add
        docstrings to each test.  These are shown when running the tests,
        which can be useful information if a test is failing.

\begin{minted}{python}
import unittest
from Bio import Biospam


class BiospamTestAddition(unittest.TestCase):
    def test_addition1(self):
        """An addition test"""
        result = Biospam.addition(2, 3)
        self.assertEqual(result, 5)

    def test_addition2(self):
        """A second addition test"""
        result = Biospam.addition(9, -1)
        self.assertEqual(result, 8)


class BiospamTestDivision(unittest.TestCase):
    def test_division1(self):
        """Now let's check division"""
        result = Biospam.division(3.0, 2.0)
        self.assertAlmostEqual(result, 1.5)

    def test_division2(self):
        """A second division test"""
        result = Biospam.division(10.0, -2.0)
        self.assertAlmostEqual(result, -5.0)


if __name__ == "__main__":
    runner = unittest.TextTestRunner(verbosity=2)
    unittest.main(testRunner=runner)
\end{minted}

        Running the script will now show you:

\begin{minted}{console}
$ python test_BiospamMyModule.py
An addition test ... ok
A second addition test ... ok
Now let's check division ... ok
A second division test ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK
\end{minted}
\end{itemize}

If your module contains docstring tests (see section \ref{sec:doctest}),
you \emph{may} want to include those in the tests to be run. You can do so as
follows by modifying the code under \verb|if __name__ == "__main__":|
to look like this:

\begin{minted}{python}
if __name__ == "__main__":
    unittest_suite = unittest.TestLoader().loadTestsFromName("test_Biospam")
    doctest_suite = doctest.DocTestSuite(Biospam)
    suite = unittest.TestSuite((unittest_suite, doctest_suite))
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    runner.run(suite)
\end{minted}

This is only relevant if you want to run the docstring tests when you
execute \verb|python test_Biospam.py| if it has some complex run-time
dependency checking.

In general instead include the docstring tests by adding them to the
\verb|run_tests.py| as explained below.

\section{Writing doctests}
\label{sec:doctest}

Python modules, classes and functions support built in documentation using
docstrings.  The \href{https://docs.python.org/3/library/doctest.html}{doctest
framework} (included with Python) allows the developer to embed working
examples in the docstrings, and have these examples automatically tested.

Currently only part of Biopython includes doctests. The \verb|run_tests.py|
script takes care of running the doctests. For this purpose, at the top of
the \verb|run_tests.py| script is a manually compiled list of modules to
skip, important where optional external dependencies which may
not be installed (e.g. the Reportlab and NumPy libraries).  So, if you've
added some doctests to the docstrings in a Biopython module, in order to
have them excluded in the Biopython test suite, you must update
\verb|run_tests.py| to include your module. Currently, the relevant part
of \verb|run_tests.py| looks as follows:

\begin{minted}{python}
# Following modules have historic failures. If you fix one of these
# please remove here!
EXCLUDE_DOCTEST_MODULES = [
    "Bio.PDB",
    "Bio.PDB.AbstractPropertyMap",
    "Bio.Phylo.Applications._Fasttree",
    "Bio.Phylo._io",
    "Bio.Phylo.TreeConstruction",
    "Bio.Phylo._utils",
]

# Exclude modules with online activity
# They are not excluded by default, use --offline to exclude them
ONLINE_DOCTEST_MODULES = ["Bio.Entrez", "Bio.ExPASy", "Bio.TogoWS"]

# Silently ignore any doctests for modules requiring numpy!
if numpy is None:
    EXCLUDE_DOCTEST_MODULES.extend(
        [
            "Bio.Affy.CelFile",
            "Bio.Cluster",
            # ...
        ]
    )
\end{minted}

Note that we regard doctests primarily as documentation, so you should
stick to typical usage. Generally complicated examples dealing with error
conditions and the like would be best left to a dedicated unit test.

Note that if you want to write doctests involving file parsing, defining
the file location complicates matters.  Ideally use relative paths assuming
the code will be run from the \verb|Tests| directory, see the
\verb|Bio.SeqIO| doctests for an example of this.

To run the docstring tests only, use
\begin{minted}{console}
$ python run_tests.py doctest
\end{minted}

Note that the doctest system is fragile and care is needed to ensure
your output will match on all the different versions of Python that
Biopython supports (e.g. differences in floating point numbers).

\section{Writing doctests in the Tutorial}
\label{sec:doctest-tutorial}

This Tutorial you are reading has a lot of code snippets, which are
often formatted like a doctest. We have our own system in file
\verb|test_Tutorial.py| to allow tagging code snippets in the
Tutorial source to be run as Python doctests. This works by adding
special \verb|%doctest| comment lines before each Python block,
e.g.

\begin{verbatim}

%doctest
\begin{minted}{pycon}
>>> from Bio.Seq import Seq
>>> s = Seq("ACGT")
>>> len(s)
4
\end{minted}
\end{verbatim}

\noindent Often code examples are not self-contained, but
continue from the previous Python block. Here we use the
magic comment \verb|%cont-doctest| as shown here:

\begin{verbatim}

%cont-doctest
\begin{minted}{pycon}
>>> s == "ACGT"
True
\end{minted}
\end{verbatim}

The special \verb|%doctest| comment line can take a working directory
(relative to the \verb|Doc/| folder) to use if you have any example
data files, e.g. \verb|%doctest examples| will use the
\verb|Doc/examples| folder, while  \verb|%doctest ../Tests/GenBank|
will use the \verb|Tests/GenBank| folder.

After the directory argument, you can specify any Python dependencies
which must be present in order to run the test by adding \verb|lib:XXX|
to indicate \verb|import XXX| must work, e.g.
\verb|%doctest examples lib:numpy|

You can run the Tutorial doctests via:

\begin{minted}{console}
$ python test_Tutorial.py
\end{minted}

or:

\begin{minted}{console}
$ python run_tests.py test_Tutorial.py
\end{minted}