~ubuntu-branches/ubuntu/trusty/twisted/trusty-proposed

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
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
<title>Twisted Documentation: Writing tests for Twisted code using Trial</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
  </head>

  <body bgcolor="white">
    <h1 class="title">Writing tests for Twisted code using Trial</h1>
    <div class="toc"><ol><li><a href="#auto0">Trial basics</a></li><li><a href="#auto1">Trial directories</a></li><li><a href="#auto2">Twisted-specific quirks: reactor, Deferreds, callLater</a></li><ul><li><a href="#auto3">Leave the Reactor as you found it</a></li><li><a href="#auto4">Using Timers to Detect Failing Tests</a></li><li><a href="#auto5">Interacting with warnings in tests</a></li><li><a href="#auto6">Parallel test</a></li></ul></ol></div>
    <div class="content">

<span/>

<h2>Trial basics<a name="auto0"/></h2>

<p><strong>Trial</strong> is Twisted's testing framework.  It provides a
library for writing test cases and utility functions for working with the
Twisted environment in your tests, and a command-line utility for running your
tests. Trial is built on the Python standard library's <code>unittest</code>
module.</p>

<p>To run all the Twisted tests, do:</p>

<pre class="shell" xml:space="preserve">
$ trial twisted
</pre>

<p>Refer to the Trial man page for other command-line options.</p>

<h2>Trial directories<a name="auto1"/></h2>

<p>You might notice a new <code class="shell">_trial_temp</code> folder in the
current working directory after Trial completes the tests. This folder is the
working directory for the Trial process. It can be used by unit tests and 
allows them to write whatever data they like to disk, and not worry
about polluting the current working directory.</p>

<p>Folders named <code class="shell">_trial_temp-&lt;counter&gt;</code> are
created if two instances of Trial are run in parallel from the same directory,
so as to avoid giving two different test-runs the same temporary directory.</p>

<p>The <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.python.lockfile.html" title="twisted.python.lockfile">twisted.python.lockfile</a></code> utility is used to lock
the <code class="shell">_trial_temp</code> directories. On Linux, this results
in symlinks to pids. On Windows, directories are created with a single file with
a pid as the contents. These lock files will be cleaned up if Trial exits normally
and otherwise they will be left behind. They should be cleaned up the next time
Trial tries to use the directory they lock, but it's also safe to delete them
manually if desired.</p>

<h2>Twisted-specific quirks: reactor, Deferreds, callLater<a name="auto2"/></h2>

<p>The standard Python <code>unittest</code> framework, from which Trial is
derived, is ideal for testing code with a fairly linear flow of control.
Twisted is an asynchronous networking framework which provides a clean,
sensible way to establish functions that are run in response to events (like
timers and incoming data), which creates a highly non-linear flow of control.
Trial has a few extensions which help to test this kind of code. This section
provides some hints on how to use these extensions and how to best structure
your tests.</p>

<h3>Leave the Reactor as you found it<a name="auto3"/></h3>

<p>Trial runs the entire test suite (over four thousand tests) in a single
process, with a single reactor. Therefore it is important that your test
leave the reactor in the same state as it found it. Leftover timers may
expire during somebody else's unsuspecting test. Leftover connection attempts
may complete (and fail) during a later test. These lead to intermittent
failures that wander from test to test and are very time-consuming to track
down.</p>

<p>If your test leaves event sources in the reactor, Trial will fail the test.
The <code>tearDown</code> method is a good place to put cleanup code: it is
always run regardless of whether your test passes or fails (like a <code>finally</code>
clause in a try-except-finally construct). Exceptions in <code>tearDown</code>
are flagged as errors and flunk the test. 
 <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.trial.unittest.TestCase.addCleanup.html" title="twisted.trial.unittest.TestCase.addCleanup">TestCase.addCleanup</a></code> is
another useful tool for cleaning up.  With it, you can register callables to
clean up resources as the test allocates them.  Generally, code should be
written so that only resources allocated in the tests need to be cleaned up in
the tests.  Resources which are allocated internally by the implementation
should be cleaned up by the implementation.</p>

<p>If your code uses Deferreds or depends on the reactor running, you can
return a Deferred from your test method, setUp, or tearDown and Trial will
do the right thing. That is, it will run the reactor for you until the
Deferred has triggered and its callbacks have been run. Don't use 
 <code>reactor.run()</code>, <code>reactor.stop()</code>, <code>reactor.crash()</code> or <code>reactor.iterate()</code> in your tests.</p>

<p>Calls to <code>reactor.callLater</code> create <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.internet.interfaces.IDelayedCall.html" title="twisted.internet.interfaces.IDelayedCall">IDelayedCall</a></code>s.  These need to be run
or cancelled during a test, otherwise they will outlive the test.  This would
be bad, because they could interfere with a later test, causing confusing
failures in unrelated tests!  For this reason, Trial checks the reactor to make
sure there are no leftover <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.internet.interfaces.IDelayedCall.html" title="twisted.internet.interfaces.IDelayedCall">IDelayedCall</a></code>s in the reactor after a
test, and will fail the test if there are.  The cleanest and simplest way to
make sure this all works is to return a Deferred from your test.</p>

<p>Similarly, sockets created during a test should be closed by the end of the
test.  This applies to both listening ports and client connections.  So, calls
to <code>reactor.listenTCP</code> (and <code>listenUNIX</code>, and so on)
return <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.internet.interfaces.IListeningPort.html" title="twisted.internet.interfaces.IListeningPort">IListeningPort</a></code>s, and these should be
cleaned up before a test ends by calling their <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.internet.interfaces.IListeningPort.stopListening.html" title="twisted.internet.interfaces.IListeningPort.stopListening">stopListening</a></code> method.
Calls to <code>reactor.connectTCP</code> return <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.internet.interfaces.IConnector.html" title="twisted.internet.interfaces.IConnector">IConnector</a></code>s, which should be cleaned
up by calling their <code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.internet.interfaces.IConnector.disconnect.html" title="twisted.internet.interfaces.IConnector.disconnect">disconnect</a></code> method.  Trial
will warn about unclosed sockets.</p>

<p>The golden rule is: If your tests call a function which returns a Deferred,
your test should return a Deferred.</p>

<h3>Using Timers to Detect Failing Tests<a name="auto4"/></h3>

<p>It is common for tests to establish some kind of fail-safe timeout that
will terminate the test in case something unexpected has happened and none of
the normal test-failure paths are followed. This timeout puts an upper bound
on the time that a test can consume, and prevents the entire test suite from
stalling because of a single test. This is especially important for the
Twisted test suite, because it is run automatically by the buildbot whenever
changes are committed to the Subversion repository.</p>

<p>The way to do this in Trial is to set the <code>.timeout</code> attribute
on your unit test method.  Set the attribute to the number of seconds you wish
to elapse before the test raises a timeout error.  Trial has a default timeout
which will be applied even if the <code>timeout</code> attribute is not set.
The Trial default timeout is usually sufficient and should be overridden only
in unusual cases.</p>

<h3>Interacting with warnings in tests<a name="auto5"/></h3>

<p>Trial includes specific support for interacting with Python's 
 <code>warnings</code> module.  This support allows warning-emitting code to
be written test-driven, just as any other code would be.  It also improves
the way in which warnings reporting when a test suite is running.</p>

<p><code class="API"><a href="http://twistedmatrix.com/documents/13.2.0/api/twisted.trial.unittest.TestCase.flushWarnings.html" title="twisted.trial.unittest.TestCase.flushWarnings">TestCase.flushWarnings</a></code>
allows tests to be written which make assertions about what warnings have
been emitted during a particular test method. In order to test a warning with 
 <code>flushWarnings</code>, write a test which first invokes the code which
will emit a warning and then calls <code>flushWarnings</code> and makes
assertions about the result.  For example:</p>

<pre class="python"><p class="py-linenumber">1
2
3
4
</p><span class="py-src-keyword">class</span> <span class="py-src-identifier">SomeWarningsTests</span>(<span class="py-src-parameter">TestCase</span>):
    <span class="py-src-keyword">def</span> <span class="py-src-identifier">test_warning</span>(<span class="py-src-parameter">self</span>):
        <span class="py-src-variable">warnings</span>.<span class="py-src-variable">warn</span>(<span class="py-src-string">&quot;foo is bad&quot;</span>)
        <span class="py-src-variable">self</span>.<span class="py-src-variable">assertEqual</span>(<span class="py-src-variable">len</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">flushWarnings</span>()), <span class="py-src-number">1</span>)
</pre>

<p>Warnings emitted in tests which are not flushed will be included by the
default reporter in its output after the result of the test.  If Python's
warnings filter system (see <a href="http://docs.python.org/using/cmdline.html#cmdoption-unittest-discover-W" shape="rect">the
-W command option to Python</a>) is configured to treat a warning as an error,
then unflushed warnings will causes tests to fail and will be included in
the summary section of the default reporter.  Note that unlike usual
operation, when <code>warnings.warn</code> is called as part of a test
method, it will not raise an exception when warnings have been configured as
errors.  However, if called outside of a test method (for example, at module
scope in a test module or a module imported by a test module) then it 
 <em>will</em> raise an exception.</p>

<h3>Parallel test<a name="auto6"/></h3>

<p>In many situations, your unit tests may run faster if they are allowed to
run in parallel, such that blocking I/O calls allow other tests to continue.
Trial, like unittest, supports the -j parameter.  Run <code>trial -j 3</code>
to run 3 test runners at the same time.</p>

<p>This requires care in your test creation.  Obviously, you need to ensure that
your code is otherwise content to work in a parallel fashion while working within
Twisted... and if you are using weird global variables in places, parallel tests
might reveal this.</p>

<p>However, if you have a test that fires up a schema on an external database
in the <code>setUp</code> function, does some operations on it in the test, and
then deletes that schema in the tearDown function, your tests will behave in an
unpredictable fashion as they tromp upon each other if they have their own
schema.  And this won't actually indicate a real error in your code, merely a
testing-specific race-condition.</p>

  </div>

    <p><a href="index.html">Index</a></p>
    <span class="version">Version: 13.2.0</span>
  </body>
</html>