1<section xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="sec-writing-nixos-tests">
2 <title>Writing Tests</title>
3 <para>
4 A NixOS test is a Nix expression that has the following structure:
5 </para>
6 <programlisting language="bash">
7import ./make-test-python.nix {
8
9 # Either the configuration of a single machine:
10 machine =
11 { config, pkgs, ... }:
12 { configuration…
13 };
14
15 # Or a set of machines:
16 nodes =
17 { machine1 =
18 { config, pkgs, ... }: { … };
19 machine2 =
20 { config, pkgs, ... }: { … };
21 …
22 };
23
24 testScript =
25 ''
26 Python code…
27 '';
28}
29</programlisting>
30 <para>
31 The attribute <literal>testScript</literal> is a bit of Python code
32 that executes the test (described below). During the test, it will
33 start one or more virtual machines, the configuration of which is
34 described by the attribute <literal>machine</literal> (if you need
35 only one machine in your test) or by the attribute
36 <literal>nodes</literal> (if you need multiple machines). For
37 instance,
38 <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/login.nix"><literal>login.nix</literal></link>
39 only needs a single machine to test whether users can log in on the
40 virtual console, whether device ownership is correctly maintained
41 when switching between consoles, and so on. On the other hand,
42 <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/nfs/simple.nix"><literal>nfs/simple.nix</literal></link>,
43 which tests NFS client and server functionality in the Linux kernel
44 (including whether locks are maintained across server crashes),
45 requires three machines: a server and two clients.
46 </para>
47 <para>
48 There are a few special NixOS configuration options for test VMs:
49 </para>
50 <variablelist>
51 <varlistentry>
52 <term>
53 <literal>virtualisation.memorySize</literal>
54 </term>
55 <listitem>
56 <para>
57 The memory of the VM in megabytes.
58 </para>
59 </listitem>
60 </varlistentry>
61 <varlistentry>
62 <term>
63 <literal>virtualisation.vlans</literal>
64 </term>
65 <listitem>
66 <para>
67 The virtual networks to which the VM is connected. See
68 <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/nat.nix"><literal>nat.nix</literal></link>
69 for an example.
70 </para>
71 </listitem>
72 </varlistentry>
73 <varlistentry>
74 <term>
75 <literal>virtualisation.writableStore</literal>
76 </term>
77 <listitem>
78 <para>
79 By default, the Nix store in the VM is not writable. If you
80 enable this option, a writable union file system is mounted on
81 top of the Nix store to make it appear writable. This is
82 necessary for tests that run Nix operations that modify the
83 store.
84 </para>
85 </listitem>
86 </varlistentry>
87 </variablelist>
88 <para>
89 For more options, see the module
90 <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/virtualisation/qemu-vm.nix"><literal>qemu-vm.nix</literal></link>.
91 </para>
92 <para>
93 The test script is a sequence of Python statements that perform
94 various actions, such as starting VMs, executing commands in the
95 VMs, and so on. Each virtual machine is represented as an object
96 stored in the variable <literal>name</literal> if this is also the
97 identifier of the machine in the declarative config. If you didn't
98 specify multiple machines using the <literal>nodes</literal>
99 attribute, it is just <literal>machine</literal>. The following
100 example starts the machine, waits until it has finished booting,
101 then executes a command and checks that the output is more-or-less
102 correct:
103 </para>
104 <programlisting language="python">
105machine.start()
106machine.wait_for_unit("default.target")
107if not "Linux" in machine.succeed("uname"):
108 raise Exception("Wrong OS")
109</programlisting>
110 <para>
111 The first line is actually unnecessary; machines are implicitly
112 started when you first execute an action on them (such as
113 <literal>wait_for_unit</literal> or <literal>succeed</literal>). If
114 you have multiple machines, you can speed up the test by starting
115 them in parallel:
116 </para>
117 <programlisting language="python">
118start_all()
119</programlisting>
120 <para>
121 The following methods are available on machine objects:
122 </para>
123 <variablelist>
124 <varlistentry>
125 <term>
126 <literal>start</literal>
127 </term>
128 <listitem>
129 <para>
130 Start the virtual machine. This method is asynchronous — it
131 does not wait for the machine to finish booting.
132 </para>
133 </listitem>
134 </varlistentry>
135 <varlistentry>
136 <term>
137 <literal>shutdown</literal>
138 </term>
139 <listitem>
140 <para>
141 Shut down the machine, waiting for the VM to exit.
142 </para>
143 </listitem>
144 </varlistentry>
145 <varlistentry>
146 <term>
147 <literal>crash</literal>
148 </term>
149 <listitem>
150 <para>
151 Simulate a sudden power failure, by telling the VM to exit
152 immediately.
153 </para>
154 </listitem>
155 </varlistentry>
156 <varlistentry>
157 <term>
158 <literal>block</literal>
159 </term>
160 <listitem>
161 <para>
162 Simulate unplugging the Ethernet cable that connects the
163 machine to the other machines.
164 </para>
165 </listitem>
166 </varlistentry>
167 <varlistentry>
168 <term>
169 <literal>unblock</literal>
170 </term>
171 <listitem>
172 <para>
173 Undo the effect of <literal>block</literal>.
174 </para>
175 </listitem>
176 </varlistentry>
177 <varlistentry>
178 <term>
179 <literal>screenshot</literal>
180 </term>
181 <listitem>
182 <para>
183 Take a picture of the display of the virtual machine, in PNG
184 format. The screenshot is linked from the HTML log.
185 </para>
186 </listitem>
187 </varlistentry>
188 <varlistentry>
189 <term>
190 <literal>get_screen_text_variants</literal>
191 </term>
192 <listitem>
193 <para>
194 Return a list of different interpretations of what is
195 currently visible on the machine's screen using optical
196 character recognition. The number and order of the
197 interpretations is not specified and is subject to change, but
198 if no exception is raised at least one will be returned.
199 </para>
200 <note>
201 <para>
202 This requires passing <literal>enableOCR</literal> to the
203 test attribute set.
204 </para>
205 </note>
206 </listitem>
207 </varlistentry>
208 <varlistentry>
209 <term>
210 <literal>get_screen_text</literal>
211 </term>
212 <listitem>
213 <para>
214 Return a textual representation of what is currently visible
215 on the machine's screen using optical character recognition.
216 </para>
217 <note>
218 <para>
219 This requires passing <literal>enableOCR</literal> to the
220 test attribute set.
221 </para>
222 </note>
223 </listitem>
224 </varlistentry>
225 <varlistentry>
226 <term>
227 <literal>send_monitor_command</literal>
228 </term>
229 <listitem>
230 <para>
231 Send a command to the QEMU monitor. This is rarely used, but
232 allows doing stuff such as attaching virtual USB disks to a
233 running machine.
234 </para>
235 </listitem>
236 </varlistentry>
237 <varlistentry>
238 <term>
239 <literal>send_key</literal>
240 </term>
241 <listitem>
242 <para>
243 Simulate pressing keys on the virtual keyboard, e.g.,
244 <literal>send_key("ctrl-alt-delete")</literal>.
245 </para>
246 </listitem>
247 </varlistentry>
248 <varlistentry>
249 <term>
250 <literal>send_chars</literal>
251 </term>
252 <listitem>
253 <para>
254 Simulate typing a sequence of characters on the virtual
255 keyboard, e.g.,
256 <literal>send_chars("foobar\n")</literal> will type
257 the string <literal>foobar</literal> followed by the Enter
258 key.
259 </para>
260 </listitem>
261 </varlistentry>
262 <varlistentry>
263 <term>
264 <literal>execute</literal>
265 </term>
266 <listitem>
267 <para>
268 Execute a shell command, returning a list
269 <literal>(status, stdout)</literal>. If the command detaches,
270 it must close stdout, as <literal>execute</literal> will wait
271 for this to consume all output reliably. This can be achieved
272 by redirecting stdout to stderr <literal>>&2</literal>,
273 to <literal>/dev/console</literal>,
274 <literal>/dev/null</literal> or a file. Examples of detaching
275 commands are <literal>sleep 365d &</literal>, where the
276 shell forks a new process that can write to stdout and
277 <literal>xclip -i</literal>, where the
278 <literal>xclip</literal> command itself forks without closing
279 stdout. Takes an optional parameter
280 <literal>check_return</literal> that defaults to
281 <literal>True</literal>. Setting this parameter to
282 <literal>False</literal> will not check for the return code
283 and return -1 instead. This can be used for commands that shut
284 down the VM and would therefore break the pipe that would be
285 used for retrieving the return code.
286 </para>
287 </listitem>
288 </varlistentry>
289 <varlistentry>
290 <term>
291 <literal>succeed</literal>
292 </term>
293 <listitem>
294 <para>
295 Execute a shell command, raising an exception if the exit
296 status is not zero, otherwise returning the standard output.
297 Commands are run with <literal>set -euo pipefail</literal>
298 set:
299 </para>
300 <itemizedlist>
301 <listitem>
302 <para>
303 If several commands are separated by <literal>;</literal>
304 and one fails, the command as a whole will fail.
305 </para>
306 </listitem>
307 <listitem>
308 <para>
309 For pipelines, the last non-zero exit status will be
310 returned (if there is one, zero will be returned
311 otherwise).
312 </para>
313 </listitem>
314 <listitem>
315 <para>
316 Dereferencing unset variables fail the command.
317 </para>
318 </listitem>
319 <listitem>
320 <para>
321 It will wait for stdout to be closed. See
322 <literal>execute</literal> for the implications.
323 </para>
324 </listitem>
325 </itemizedlist>
326 </listitem>
327 </varlistentry>
328 <varlistentry>
329 <term>
330 <literal>fail</literal>
331 </term>
332 <listitem>
333 <para>
334 Like <literal>succeed</literal>, but raising an exception if
335 the command returns a zero status.
336 </para>
337 </listitem>
338 </varlistentry>
339 <varlistentry>
340 <term>
341 <literal>wait_until_succeeds</literal>
342 </term>
343 <listitem>
344 <para>
345 Repeat a shell command with 1-second intervals until it
346 succeeds.
347 </para>
348 </listitem>
349 </varlistentry>
350 <varlistentry>
351 <term>
352 <literal>wait_until_fails</literal>
353 </term>
354 <listitem>
355 <para>
356 Repeat a shell command with 1-second intervals until it fails.
357 </para>
358 </listitem>
359 </varlistentry>
360 <varlistentry>
361 <term>
362 <literal>wait_for_unit</literal>
363 </term>
364 <listitem>
365 <para>
366 Wait until the specified systemd unit has reached the
367 <quote>active</quote> state.
368 </para>
369 </listitem>
370 </varlistentry>
371 <varlistentry>
372 <term>
373 <literal>wait_for_file</literal>
374 </term>
375 <listitem>
376 <para>
377 Wait until the specified file exists.
378 </para>
379 </listitem>
380 </varlistentry>
381 <varlistentry>
382 <term>
383 <literal>wait_for_open_port</literal>
384 </term>
385 <listitem>
386 <para>
387 Wait until a process is listening on the given TCP port (on
388 <literal>localhost</literal>, at least).
389 </para>
390 </listitem>
391 </varlistentry>
392 <varlistentry>
393 <term>
394 <literal>wait_for_closed_port</literal>
395 </term>
396 <listitem>
397 <para>
398 Wait until nobody is listening on the given TCP port.
399 </para>
400 </listitem>
401 </varlistentry>
402 <varlistentry>
403 <term>
404 <literal>wait_for_x</literal>
405 </term>
406 <listitem>
407 <para>
408 Wait until the X11 server is accepting connections.
409 </para>
410 </listitem>
411 </varlistentry>
412 <varlistentry>
413 <term>
414 <literal>wait_for_text</literal>
415 </term>
416 <listitem>
417 <para>
418 Wait until the supplied regular expressions matches the
419 textual contents of the screen by using optical character
420 recognition (see <literal>get_screen_text</literal> and
421 <literal>get_screen_text_variants</literal>).
422 </para>
423 <note>
424 <para>
425 This requires passing <literal>enableOCR</literal> to the
426 test attribute set.
427 </para>
428 </note>
429 </listitem>
430 </varlistentry>
431 <varlistentry>
432 <term>
433 <literal>wait_for_console_text</literal>
434 </term>
435 <listitem>
436 <para>
437 Wait until the supplied regular expressions match a line of
438 the serial console output. This method is useful when OCR is
439 not possibile or accurate enough.
440 </para>
441 </listitem>
442 </varlistentry>
443 <varlistentry>
444 <term>
445 <literal>wait_for_window</literal>
446 </term>
447 <listitem>
448 <para>
449 Wait until an X11 window has appeared whose name matches the
450 given regular expression, e.g.,
451 <literal>wait_for_window("Terminal")</literal>.
452 </para>
453 </listitem>
454 </varlistentry>
455 <varlistentry>
456 <term>
457 <literal>copy_from_host</literal>
458 </term>
459 <listitem>
460 <para>
461 Copies a file from host to machine, e.g.,
462 <literal>copy_from_host("myfile", "/etc/my/important/file")</literal>.
463 </para>
464 <para>
465 The first argument is the file on the host. The file needs to
466 be accessible while building the nix derivation. The second
467 argument is the location of the file on the machine.
468 </para>
469 </listitem>
470 </varlistentry>
471 <varlistentry>
472 <term>
473 <literal>systemctl</literal>
474 </term>
475 <listitem>
476 <para>
477 Runs <literal>systemctl</literal> commands with optional
478 support for <literal>systemctl --user</literal>
479 </para>
480 <programlisting language="python">
481machine.systemctl("list-jobs --no-pager") # runs `systemctl list-jobs --no-pager`
482machine.systemctl("list-jobs --no-pager", "any-user") # spawns a shell for `any-user` and runs `systemctl --user list-jobs --no-pager`
483</programlisting>
484 </listitem>
485 </varlistentry>
486 <varlistentry>
487 <term>
488 <literal>shell_interact</literal>
489 </term>
490 <listitem>
491 <para>
492 Allows you to directly interact with the guest shell. This
493 should only be used during test development, not in production
494 tests. Killing the interactive session with
495 <literal>Ctrl-d</literal> or <literal>Ctrl-c</literal> also
496 ends the guest session.
497 </para>
498 </listitem>
499 </varlistentry>
500 </variablelist>
501 <para>
502 To test user units declared by
503 <literal>systemd.user.services</literal> the optional
504 <literal>user</literal> argument can be used:
505 </para>
506 <programlisting language="python">
507machine.start()
508machine.wait_for_x()
509machine.wait_for_unit("xautolock.service", "x-session-user")
510</programlisting>
511 <para>
512 This applies to <literal>systemctl</literal>,
513 <literal>get_unit_info</literal>, <literal>wait_for_unit</literal>,
514 <literal>start_job</literal> and <literal>stop_job</literal>.
515 </para>
516 <para>
517 For faster dev cycles it's also possible to disable the code-linters
518 (this shouldn't be commited though):
519 </para>
520 <programlisting language="bash">
521import ./make-test-python.nix {
522 skipLint = true;
523 machine =
524 { config, pkgs, ... }:
525 { configuration…
526 };
527
528 testScript =
529 ''
530 Python code…
531 '';
532}
533</programlisting>
534 <para>
535 This will produce a Nix warning at evaluation time. To fully disable
536 the linter, wrap the test script in comment directives to disable
537 the Black linter directly (again, don't commit this within the
538 Nixpkgs repository):
539 </para>
540 <programlisting language="bash">
541 testScript =
542 ''
543 # fmt: off
544 Python code…
545 # fmt: on
546 '';
547</programlisting>
548</section>