Debian Codegraph @

docs/source/reference-testing.rst

raw
1 Testing made easier with ``trio.testing``
2 =========================================
3
4 .. module:: trio.testing
5
6 The :mod:`trio.testing` module provides various utilities to make it
7 easier to test Trio code. Unlike the other submodules in the
8 :mod:`trio` namespace, :mod:`trio.testing` is *not* automatically
9 imported when you do ``import trio``; you must ``import trio.testing``
10 explicitly.
11
12
13 Test harness integration
14 ------------------------
15
16 .. decorator:: trio_test
17
18
19 .. _testing-time:
20
21 Time and timeouts
22 -----------------
23
24 :class:`trio.testing.MockClock` is a :class:`~trio.abc.Clock` with a
25 few tricks up its sleeve to help you efficiently test code involving
26 timeouts:
27
28 * By default, it starts at time 0, and clock time only advances when
29 you explicitly call :meth:`~MockClock.jump`. This provides an
30 extremely controllable clock for testing.
31
32 * You can set :attr:`~MockClock.rate` to 1.0 if you want it to start
33 running in real time like a regular clock. You can stop and start
34 the clock within a test. You can set :attr:`~MockClock.rate` to 10.0
35 to make clock time pass at 10x real speed (so e.g. ``await
36 trio.sleep(10)`` returns after 1 second).
37
38 * But even more interestingly, you can set
39 :attr:`~MockClock.autojump_threshold` to zero or a small value, and
40 then it will watch the execution of the run loop, and any time
41 things have settled down and everyone's waiting for a timeout, it
42 jumps the clock forward to that timeout. In many cases this allows
43 natural-looking code involving timeouts to be automatically run at
44 near full CPU utilization with no changes. (Thanks to `fluxcapacitor
45 <https://github.com/majek/fluxcapacitor>`__ for this awesome idea.)
46
47 * And of course these can be mixed and matched at will.
48
49 Regardless of these shenanigans, from "inside" Trio the passage of time
50 still seems normal so long as you restrict yourself to Trio's time
51 functions (see :ref:`time-and-clocks`). Below is an example
52 demonstrating two different ways of making time pass quickly. Notice
53 how in both cases, the two tasks keep a consistent view of reality and
54 events happen in the expected order, despite being wildly divorced
55 from real time:
56
57 .. literalinclude:: reference-testing/across-realtime.py
58
59 Output:
60
61 .. literalinclude:: reference-testing/across-realtime.out
62 :language: none
63
64 .. autoclass:: MockClock
65 :members:
66
67
68 Inter-task ordering
69 -------------------
70
71 .. autoclass:: Sequencer
72
73 .. autofunction:: wait_all_tasks_blocked
74
75 .. autofunction:: wait_all_threads_completed
76
77 .. autofunction:: active_thread_count
78
79
80 .. _testing-streams:
81
82 Streams
83 -------
84
85 Connecting to an in-process socket server
86 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
87
88 .. autofunction:: open_stream_to_socket_listener
89
90
91 .. _virtual-streams:
92
93 Virtual, controllable streams
94 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
95
96 One particularly challenging problem when testing network protocols is
97 making sure that your implementation can handle data whose flow gets
98 broken up in weird ways and arrives with weird timings: localhost
99 connections tend to be much better behaved than real networks, so if
100 you only test on localhost then you might get bitten later. To help
101 you out, Trio provides some fully in-memory implementations of the
102 stream interfaces (see :ref:`abstract-stream-api`), that let you write
103 all kinds of interestingly evil tests.
104
105 There are a few pieces here, so here's how they fit together:
106
107 :func:`memory_stream_pair` gives you a pair of connected,
108 bidirectional streams. It's like :func:`socket.socketpair`, but
109 without any involvement from that pesky operating system and its
110 networking stack.
111
112 To build a bidirectional stream, :func:`memory_stream_pair` uses
113 two unidirectional streams. It gets these by calling
114 :func:`memory_stream_one_way_pair`.
115
116 :func:`memory_stream_one_way_pair`, in turn, is implemented using the
117 low-ish level classes :class:`MemorySendStream` and
118 :class:`MemoryReceiveStream`. These are implementations of (you
119 guessed it) :class:`trio.abc.SendStream` and
120 :class:`trio.abc.ReceiveStream` that on their own, aren't attached to
121 anything – "sending" and "receiving" just put data into and get data
122 out of a private internal buffer that each object owns. They also have
123 some interesting hooks you can set, that let you customize the
124 behavior of their methods. This is where you can insert the evil, if
125 you want it. :func:`memory_stream_one_way_pair` takes advantage of
126 these hooks in a relatively boring way: it just sets it up so that
127 when you call ``send_all``, or when you close the send stream, then it
128 automatically triggers a call to :func:`memory_stream_pump`, which is
129 a convenience function that takes data out of a
130 :class:`MemorySendStream`\´s buffer and puts it into a
131 :class:`MemoryReceiveStream`\´s buffer. But that's just the default –
132 you can replace this with whatever arbitrary behavior you want.
133
134 Trio also provides some specialized functions for testing completely
135 **un**\buffered streams: :func:`lockstep_stream_one_way_pair` and
136 :func:`lockstep_stream_pair`. These aren't customizable, but they do
137 exhibit an extreme kind of behavior that's good at catching out edge
138 cases in protocol implementations.
139
140
141 API details
142 ~~~~~~~~~~~
143
144 .. autoclass:: MemorySendStream
145 :members:
146
147 .. autoclass:: MemoryReceiveStream
148 :members:
149
150 .. autofunction:: memory_stream_pump
151
152 .. autofunction:: memory_stream_one_way_pair
153
154 .. autofunction:: memory_stream_pair
155
156 .. autofunction:: lockstep_stream_one_way_pair
157
158 .. autofunction:: lockstep_stream_pair
159
160
161 .. _testing-custom-streams:
162
163 Testing custom stream implementations
164 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
165
166 Trio also provides some functions to help you test your custom stream
167 implementations:
168
169 .. autofunction:: check_one_way_stream
170
171 .. autofunction:: check_two_way_stream
172
173 .. autofunction:: check_half_closeable_stream
174
175
176 .. _virtual-network-hooks:
177
178 Virtual networking for testing
179 ------------------------------
180
181 In the previous section you learned how to use virtual in-memory
182 streams to test protocols that are written against Trio's
183 :class:`~trio.abc.Stream` abstraction. But what if you have more
184 complicated networking code – the kind of code that makes connections
185 to multiple hosts, or opens a listening socket, or sends UDP packets?
186
187 Trio doesn't itself provide a virtual in-memory network implementation
188 for testing – but :mod:`trio.socket` module does provide the hooks you
189 need to write your own! And if you're interested in helping implement
190 a reusable virtual network for testing, then `please get in touch
191 <https://github.com/python-trio/trio/issues/170>`__.
192
193 Note that these APIs are actually in :mod:`trio.socket` and
194 :mod:`trio.abc`, but we document them here because they're primarily
195 intended for testing.
196
197 .. currentmodule:: trio.socket
198
199 .. autofunction:: trio.socket.set_custom_hostname_resolver
200
201 .. currentmodule:: trio.abc
202
203 .. autoclass:: trio.abc.HostnameResolver
204 :members:
205
206 .. currentmodule:: trio.socket
207
208 .. autofunction:: trio.socket.set_custom_socket_factory
209
210 .. currentmodule:: trio.abc
211
212 .. autoclass:: trio.abc.SocketFactory
213 :members:
214
215 .. currentmodule:: trio.testing
216
217
218 Testing checkpoints
219 --------------------
220
221 .. autofunction:: assert_checkpoints
222 :with:
223
224 .. autofunction:: assert_no_checkpoints
225 :with:
226
227
228 ExceptionGroup helpers
229 ----------------------
230
231 .. autoclass:: RaisesGroup
232 :members:
233
234 .. autoattribute:: fail_reason
235
236 .. autoclass:: Matcher
237 :members:
238
239 .. autoattribute:: fail_reason
240
241 .. autoclass:: trio.testing._raises_group._ExceptionInfo
242 :members: