git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #71684 from tfc/integration-test-python

nixos: add python testing support

commit22906321fbc0d38372d7ae2657adb2597fc384c1 authorFlorian Klink <flokli@flokli.de> dateTue 5 Nov 2019, 00:06 (7 years ago) parentd34465e40396a7
18 files changed+1369−303
nixos/doc/manual/development/running-nixos-tests-interactively.xml+6−6 nixos/doc/manual/development/writing-nixos-tests.xml+44−43 nixos/lib/test-driver/test-driver.py+758 nixos/lib/testing-python.nix+279 nixos/tests/acme.nix+35−30 nixos/tests/ammonite.nix+3−3 nixos/tests/automysqlbackup.nix+18−14 nixos/tests/bittorrent.nix+36−22 nixos/tests/boot.nix+17−18 nixos/tests/emacs-daemon.nix+13−10 nixos/tests/gitea.nix+16−14 nixos/tests/login.nix+45−59 nixos/tests/make-test-python.nix+9 nixos/tests/postgresql.nix+24−20 nixos/tests/quake3.nix+21−21 nixos/tests/wireguard/default.nix+6−6 nixos/tests/wireguard/generated.nix+30−26 nixos/tests/zfs.nix+9−11
nixos/doc/manual/development/running-nixos-tests-interactively.xml+6−6
@@ -14,14 +14,14 @@
1414starting VDE switch for network 1
1515<prompt>&gt;</prompt>
1616</screen>
17− You can then take any Perl statement, e.g.
17+ You can then take any Python statement, e.g.
1818<screen>
19−<prompt>&gt;</prompt> startAll
20−<prompt>&gt;</prompt> testScript
21−<prompt>&gt;</prompt> $machine->succeed("touch /tmp/foo")
22−<prompt>&gt;</prompt> print($machine->succeed("pwd")) # Show stdout of command
19+<prompt>&gt;</prompt> start_all()
20+<prompt>&gt;</prompt> test_script()
21+<prompt>&gt;</prompt> machine.succeed("touch /tmp/foo")
22+<prompt>&gt;</prompt> print(machine.succeed("pwd")) # Show stdout of command
2323</screen>
24− The function <command>testScript</command> executes the entire test script
24+ The function <command>test_script</command> executes the entire test script
2525 and drops you back into the test driver command line upon its completion.
2626 This allows you to inspect the state of the VMs after the test (e.g. to debug
2727 the test script).
nixos/doc/manual/development/writing-nixos-tests.xml+44−43
@@ -8,7 +8,7 @@
88 <para>
99 A NixOS test is a Nix expression that has the following structure:
1010<programlisting>
11−import ./make-test.nix {
11+import ./make-test-python.nix {
1212
1313 # Either the configuration of a single machine:
1414 machine =
@@ -27,11 +27,11 @@ import ./make-test.nix {
2727
2828 testScript =
2929 ''
30− <replaceable>Perl code…</replaceable>
30+ <replaceable>Python code…</replaceable>
3131 '';
3232}
3333</programlisting>
34− The attribute <literal>testScript</literal> is a bit of Perl code that
34+ The attribute <literal>testScript</literal> is a bit of Python code that
3535 executes the test (described below). During the test, it will start one or
3636 more virtual machines, the configuration of which is described by the
3737 attribute <literal>machine</literal> (if you need only one machine in your
@@ -96,26 +96,27 @@ xlink:href="https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/virtualis
9696 </para>
9797
9898 <para>
99− The test script is a sequence of Perl statements that perform various
99+ The test script is a sequence of Python statements that perform various
100100 actions, such as starting VMs, executing commands in the VMs, and so on. Each
101101 virtual machine is represented as an object stored in the variable
102− <literal>$<replaceable>name</replaceable></literal>, where
103− <replaceable>name</replaceable> is the identifier of the machine (which is
104− just <literal>machine</literal> if you didn’t specify multiple machines
105− using the <literal>nodes</literal> attribute). For instance, the following
106− starts the machine, waits until it has finished booting, then executes a
107− command and checks that the output is more-or-less correct:
102+ <literal><replaceable>name</replaceable></literal> if this is also the
103+ identifier of the machine in the declarative config.
104+ If you didn't specify multiple machines using the <literal>nodes</literal>
105+ attribute, it is just <literal>machine</literal>.
106+ The following example starts the machine, waits until it has finished booting,
107+ then executes a command and checks that the output is more-or-less correct:
108108<programlisting>
109−$machine->start;
110−$machine->waitForUnit("default.target");
111−$machine->succeed("uname") =~ /Linux/ or die;
109+machine.start()
110+machine.wait_for_unit("default.target")
111+if not "Linux" in machine.succeed("uname"):
112+ raise Exception("Wrong OS")
112113</programlisting>
113114 The first line is actually unnecessary; machines are implicitly started when
114− you first execute an action on them (such as <literal>waitForUnit</literal>
115+ you first execute an action on them (such as <literal>wait_for_unit</literal>
115116 or <literal>succeed</literal>). If you have multiple machines, you can speed
116117 up the test by starting them in parallel:
117118<programlisting>
118−startAll;
119+start_all()
119120</programlisting>
120121 </para>
121122
@@ -187,7 +188,7 @@ startAll;
187188 </varlistentry>
188189 <varlistentry>
189190 <term>
190− <methodname>getScreenText</methodname>
191+ <methodname>get_screen_text</methodname>
191192 </term>
192193 <listitem>
193194 <para>
@@ -204,7 +205,7 @@ startAll;
204205 </varlistentry>
205206 <varlistentry>
206207 <term>
207− <methodname>sendMonitorCommand</methodname>
208+ <methodname>send_monitor_command</methodname>
208209 </term>
209210 <listitem>
210211 <para>
@@ -215,23 +216,23 @@ startAll;
215216 </varlistentry>
216217 <varlistentry>
217218 <term>
218− <methodname>sendKeys</methodname>
219+ <methodname>send_keys</methodname>
219220 </term>
220221 <listitem>
221222 <para>
222223 Simulate pressing keys on the virtual keyboard, e.g.,
223− <literal>sendKeys("ctrl-alt-delete")</literal>.
224+ <literal>send_keys("ctrl-alt-delete")</literal>.
224225 </para>
225226 </listitem>
226227 </varlistentry>
227228 <varlistentry>
228229 <term>
229− <methodname>sendChars</methodname>
230+ <methodname>send_chars</methodname>
230231 </term>
231232 <listitem>
232233 <para>
233234 Simulate typing a sequence of characters on the virtual keyboard, e.g.,
234− <literal>sendKeys("foobar\n")</literal> will type the string
235+ <literal>send_keys("foobar\n")</literal> will type the string
235236 <literal>foobar</literal> followed by the Enter key.
236237 </para>
237238 </listitem>
@@ -272,7 +273,7 @@ startAll;
272273 </varlistentry>
273274 <varlistentry>
274275 <term>
275− <methodname>waitUntilSucceeds</methodname>
276+ <methodname>wait_until_succeeds</methodname>
276277 </term>
277278 <listitem>
278279 <para>
@@ -282,7 +283,7 @@ startAll;
282283 </varlistentry>
283284 <varlistentry>
284285 <term>
285− <methodname>waitUntilFails</methodname>
286+ <methodname>wait_until_fails</methodname>
286287 </term>
287288 <listitem>
288289 <para>
@@ -292,7 +293,7 @@ startAll;
292293 </varlistentry>
293294 <varlistentry>
294295 <term>
295− <methodname>waitForUnit</methodname>
296+ <methodname>wait_for_unit</methodname>
296297 </term>
297298 <listitem>
298299 <para>
@@ -302,7 +303,7 @@ startAll;
302303 </varlistentry>
303304 <varlistentry>
304305 <term>
305− <methodname>waitForFile</methodname>
306+ <methodname>wait_for_file</methodname>
306307 </term>
307308 <listitem>
308309 <para>
@@ -312,7 +313,7 @@ startAll;
312313 </varlistentry>
313314 <varlistentry>
314315 <term>
315− <methodname>waitForOpenPort</methodname>
316+ <methodname>wait_for_open_port</methodname>
316317 </term>
317318 <listitem>
318319 <para>
@@ -323,7 +324,7 @@ startAll;
323324 </varlistentry>
324325 <varlistentry>
325326 <term>
326− <methodname>waitForClosedPort</methodname>
327+ <methodname>wait_for_closed_port</methodname>
327328 </term>
328329 <listitem>
329330 <para>
@@ -333,7 +334,7 @@ startAll;
333334 </varlistentry>
334335 <varlistentry>
335336 <term>
336− <methodname>waitForX</methodname>
337+ <methodname>wait_for_x</methodname>
337338 </term>
338339 <listitem>
339340 <para>
@@ -343,13 +344,13 @@ startAll;
343344 </varlistentry>
344345 <varlistentry>
345346 <term>
346− <methodname>waitForText</methodname>
347+ <methodname>wait_for_text</methodname>
347348 </term>
348349 <listitem>
349350 <para>
350351 Wait until the supplied regular expressions matches the textual contents
351352 of the screen by using optical character recognition (see
352− <methodname>getScreenText</methodname>).
353+ <methodname>get_screen_text</methodname>).
353354 </para>
354355 <note>
355356 <para>
@@ -361,23 +362,23 @@ startAll;
361362 </varlistentry>
362363 <varlistentry>
363364 <term>
364− <methodname>waitForWindow</methodname>
365+ <methodname>wait_for_window</methodname>
365366 </term>
366367 <listitem>
367368 <para>
368369 Wait until an X11 window has appeared whose name matches the given
369− regular expression, e.g., <literal>waitForWindow(qr/Terminal/)</literal>.
370+ regular expression, e.g., <literal>wait_for_window("Terminal")</literal>.
370371 </para>
371372 </listitem>
372373 </varlistentry>
373374 <varlistentry>
374375 <term>
375− <methodname>copyFileFromHost</methodname>
376+ <methodname>copy_file_from_host</methodname>
376377 </term>
377378 <listitem>
378379 <para>
379380 Copies a file from host to machine, e.g.,
380− <literal>copyFileFromHost("myfile", "/etc/my/important/file")</literal>.
381+ <literal>copy_file_from_host("myfile", "/etc/my/important/file")</literal>.
381382 </para>
382383 <para>
383384 The first argument is the file on the host. The file needs to be
@@ -397,8 +398,8 @@ startAll;
397398 </para>
398399 <para>
399400<programlisting>
400−$machine->systemctl("list-jobs --no-pager"); // runs `systemctl list-jobs --no-pager`
401−$machine->systemctl("list-jobs --no-pager", "any-user"); // spawns a shell for `any-user` and runs `systemctl --user list-jobs --no-pager`
401+machine.systemctl("list-jobs --no-pager") # runs `systemctl list-jobs --no-pager`
402+machine.systemctl("list-jobs --no-pager", "any-user") # spawns a shell for `any-user` and runs `systemctl --user list-jobs --no-pager`
402403</programlisting>
403404 </para>
404405 </listitem>
@@ -408,14 +409,14 @@ $machine->systemctl("list-jobs --no-pager", "any-user"); // spawns a shell for `
408409
409410 <para>
410411 To test user units declared by <literal>systemd.user.services</literal> the
411− optional <literal>$user</literal> argument can be used:
412+ optional <literal>user</literal> argument can be used:
412413<programlisting>
413−$machine->start;
414−$machine->waitForX;
415−$machine->waitForUnit("xautolock.service", "x-session-user");
414+machine.start()
415+machine.wait_for_x()
416+machine.wait_for_unit("xautolock.service", "x-session-user")
416417</programlisting>
417− This applies to <literal>systemctl</literal>, <literal>getUnitInfo</literal>,
418− <literal>waitForUnit</literal>, <literal>startJob</literal> and
419− <literal>stopJob</literal>.
418+ This applies to <literal>systemctl</literal>, <literal>get_unit_info</literal>,
419+ <literal>wait_for_unit</literal>, <literal>start_job</literal> and
420+ <literal>stop_job</literal>.
420421 </para>
421422</section>
nixos/lib/test-driver/test-driver.pynew file+758
@@ -0,0 +1,758 @@
1+#! /somewhere/python3
2+
3+from contextlib import contextmanager
4+from xml.sax.saxutils import XMLGenerator
5+import _thread
6+import atexit
7+import os
8+import pty
9+import queue
10+import re
11+import shutil
12+import socket
13+import subprocess
14+import sys
15+import tempfile
16+import time
17+import unicodedata
18+import ptpython.repl
19+
20+CHAR_TO_KEY = {
21+ "A": "shift-a",
22+ "N": "shift-n",
23+ "-": "0x0C",
24+ "_": "shift-0x0C",
25+ "B": "shift-b",
26+ "O": "shift-o",
27+ "=": "0x0D",
28+ "+": "shift-0x0D",
29+ "C": "shift-c",
30+ "P": "shift-p",
31+ "[": "0x1A",
32+ "{": "shift-0x1A",
33+ "D": "shift-d",
34+ "Q": "shift-q",
35+ "]": "0x1B",
36+ "}": "shift-0x1B",
37+ "E": "shift-e",
38+ "R": "shift-r",
39+ ";": "0x27",
40+ ":": "shift-0x27",
41+ "F": "shift-f",
42+ "S": "shift-s",
43+ "'": "0x28",
44+ '"': "shift-0x28",
45+ "G": "shift-g",
46+ "T": "shift-t",
47+ "`": "0x29",
48+ "~": "shift-0x29",
49+ "H": "shift-h",
50+ "U": "shift-u",
51+ "\\": "0x2B",
52+ "|": "shift-0x2B",
53+ "I": "shift-i",
54+ "V": "shift-v",
55+ ",": "0x33",
56+ "<": "shift-0x33",
57+ "J": "shift-j",
58+ "W": "shift-w",
59+ ".": "0x34",
60+ ">": "shift-0x34",
61+ "K": "shift-k",
62+ "X": "shift-x",
63+ "/": "0x35",
64+ "?": "shift-0x35",
65+ "L": "shift-l",
66+ "Y": "shift-y",
67+ " ": "spc",
68+ "M": "shift-m",
69+ "Z": "shift-z",
70+ "\n": "ret",
71+ "!": "shift-0x02",
72+ "@": "shift-0x03",
73+ "#": "shift-0x04",
74+ "$": "shift-0x05",
75+ "%": "shift-0x06",
76+ "^": "shift-0x07",
77+ "&": "shift-0x08",
78+ "*": "shift-0x09",
79+ "(": "shift-0x0A",
80+ ")": "shift-0x0B",
81+}
82+
83+
84+def eprint(*args, **kwargs):
85+ print(*args, file=sys.stderr, **kwargs)
86+
87+
88+def create_vlan(vlan_nr):
89+ global log
90+ log.log("starting VDE switch for network {}".format(vlan_nr))
91+ vde_socket = os.path.abspath("./vde{}.ctl".format(vlan_nr))
92+ pty_master, pty_slave = pty.openpty()
93+ vde_process = subprocess.Popen(
94+ ["vde_switch", "-s", vde_socket, "--dirmode", "0777"],
95+ bufsize=1,
96+ stdin=pty_slave,
97+ stdout=subprocess.PIPE,
98+ stderr=subprocess.PIPE,
99+ shell=False,
100+ )
101+ fd = os.fdopen(pty_master, "w")
102+ fd.write("version\n")
103+ # TODO: perl version checks if this can be read from
104+ # an if not, dies. we could hang here forever. Fix it.
105+ vde_process.stdout.readline()
106+ if not os.path.exists(os.path.join(vde_socket, "ctl")):
107+ raise Exception("cannot start vde_switch")
108+
109+ return (vlan_nr, vde_socket, vde_process, fd)
110+
111+
112+def retry(fn):
113+ """Call the given function repeatedly, with 1 second intervals,
114+ until it returns True or a timeout is reached.
115+ """
116+
117+ for _ in range(900):
118+ if fn(False):
119+ return
120+ time.sleep(1)
121+
122+ if not fn(True):
123+ raise Exception("action timed out")
124+
125+
126+class Logger:
127+ def __init__(self):
128+ self.logfile = os.environ.get("LOGFILE", "/dev/null")
129+ self.logfile_handle = open(self.logfile, "wb")
130+ self.xml = XMLGenerator(self.logfile_handle, encoding="utf-8")
131+ self.queue = queue.Queue(1000)
132+
133+ self.xml.startDocument()
134+ self.xml.startElement("logfile", attrs={})
135+
136+ def close(self):
137+ self.xml.endElement("logfile")
138+ self.xml.endDocument()
139+ self.logfile_handle.close()
140+
141+ def sanitise(self, message):
142+ return "".join(ch for ch in message if unicodedata.category(ch)[0] != "C")
143+
144+ def maybe_prefix(self, message, attributes):
145+ if "machine" in attributes:
146+ return "{}: {}".format(attributes["machine"], message)
147+ return message
148+
149+ def log_line(self, message, attributes):
150+ self.xml.startElement("line", attributes)
151+ self.xml.characters(message)
152+ self.xml.endElement("line")
153+
154+ def log(self, message, attributes={}):
155+ eprint(self.maybe_prefix(message, attributes))
156+ self.drain_log_queue()
157+ self.log_line(message, attributes)
158+
159+ def enqueue(self, message):
160+ self.queue.put(message)
161+
162+ def drain_log_queue(self):
163+ try:
164+ while True:
165+ item = self.queue.get_nowait()
166+ attributes = {"machine": item["machine"], "type": "serial"}
167+ self.log_line(self.sanitise(item["msg"]), attributes)
168+ except queue.Empty:
169+ pass
170+
171+ @contextmanager
172+ def nested(self, message, attributes={}):
173+ eprint(self.maybe_prefix(message, attributes))
174+
175+ self.xml.startElement("nest", attrs={})
176+ self.xml.startElement("head", attributes)
177+ self.xml.characters(message)
178+ self.xml.endElement("head")
179+
180+ tic = time.time()
181+ self.drain_log_queue()
182+ yield
183+ self.drain_log_queue()
184+ toc = time.time()
185+ self.log("({:.2f} seconds)".format(toc - tic))
186+
187+ self.xml.endElement("nest")
188+
189+
190+class Machine:
191+ def __init__(self, args):
192+ if "name" in args:
193+ self.name = args["name"]
194+ else:
195+ self.name = "machine"
196+ try:
197+ cmd = args["startCommand"]
198+ self.name = re.search("run-(.+)-vm$", cmd).group(1)
199+ except KeyError:
200+ pass
201+ except AttributeError:
202+ pass
203+
204+ self.script = args.get("startCommand", self.create_startcommand(args))
205+
206+ tmp_dir = os.environ.get("TMPDIR", tempfile.gettempdir())
207+
208+ def create_dir(name):
209+ path = os.path.join(tmp_dir, name)
210+ os.makedirs(path, mode=0o700, exist_ok=True)
211+ return path
212+
213+ self.state_dir = create_dir("vm-state-{}".format(self.name))
214+ self.shared_dir = create_dir("xchg-shared")
215+
216+ self.booted = False
217+ self.connected = False
218+ self.pid = None
219+ self.socket = None
220+ self.monitor = None
221+ self.logger = args["log"]
222+ self.allow_reboot = args.get("allowReboot", False)
223+
224+ @staticmethod
225+ def create_startcommand(args):
226+ net_backend = "-netdev user,id=net0"
227+ net_frontend = "-device virtio-net-pci,netdev=net0"
228+
229+ if "netBackendArgs" in args:
230+ net_backend += "," + args["netBackendArgs"]
231+
232+ if "netFrontendArgs" in args:
233+ net_frontend += "," + args["netFrontendArgs"]
234+
235+ start_command = (
236+ "qemu-kvm -m 384 " + net_backend + " " + net_frontend + " $QEMU_OPTS "
237+ )
238+
239+ if "hda" in args:
240+ hda_path = os.path.abspath(args["hda"])
241+ if args.get("hdaInterface", "") == "scsi":
242+ start_command += (
243+ "-drive id=hda,file="
244+ + hda_path
245+ + ",werror=report,if=none "
246+ + "-device scsi-hd,drive=hda "
247+ )
248+ else:
249+ start_command += (
250+ "-drive file="
251+ + hda_path
252+ + ",if="
253+ + args["hdaInterface"]
254+ + ",werror=report "
255+ )
256+
257+ if "cdrom" in args:
258+ start_command += "-cdrom " + args["cdrom"] + " "
259+
260+ if "usb" in args:
261+ start_command += (
262+ "-device piix3-usb-uhci -drive "
263+ + "id=usbdisk,file="
264+ + args["usb"]
265+ + ",if=none,readonly "
266+ + "-device usb-storage,drive=usbdisk "
267+ )
268+ if "bios" in args:
269+ start_command += "-bios " + args["bios"] + " "
270+
271+ start_command += args.get("qemuFlags", "")
272+
273+ return start_command
274+
275+ def is_up(self):
276+ return self.booted and self.connected
277+
278+ def log(self, msg):
279+ self.logger.log(msg, {"machine": self.name})
280+
281+ def nested(self, msg, attrs={}):
282+ my_attrs = {"machine": self.name}
283+ my_attrs.update(attrs)
284+ return self.logger.nested(msg, my_attrs)
285+
286+ def wait_for_monitor_prompt(self):
287+ while True:
288+ answer = self.monitor.recv(1024).decode()
289+ if answer.endswith("(qemu) "):
290+ return answer
291+
292+ def send_monitor_command(self, command):
293+ message = ("{}\n".format(command)).encode()
294+ self.log("sending monitor command: {}".format(command))
295+ self.monitor.send(message)
296+ return self.wait_for_monitor_prompt()
297+
298+ def wait_for_unit(self, unit, user=None):
299+ while True:
300+ info = self.get_unit_info(unit, user)
301+ state = info["ActiveState"]
302+ if state == "failed":
303+ raise Exception('unit "{}" reached state "{}"'.format(unit, state))
304+
305+ if state == "inactive":
306+ status, jobs = self.systemctl("list-jobs --full 2>&1", user)
307+ if "No jobs" in jobs:
308+ info = self.get_unit_info(unit)
309+ if info["ActiveState"] == state:
310+ raise Exception(
311+ (
312+ 'unit "{}" is inactive and there ' "are no pending jobs"
313+ ).format(unit)
314+ )
315+ if state == "active":
316+ return True
317+
318+ def get_unit_info(self, unit, user=None):
319+ status, lines = self.systemctl('--no-pager show "{}"'.format(unit), user)
320+ if status != 0:
321+ return None
322+
323+ line_pattern = re.compile(r"^([^=]+)=(.*)$")
324+
325+ def tuple_from_line(line):
326+ match = line_pattern.match(line)
327+ return match[1], match[2]
328+
329+ return dict(
330+ tuple_from_line(line)
331+ for line in lines.split("\n")
332+ if line_pattern.match(line)
333+ )
334+
335+ def systemctl(self, q, user=None):
336+ if user is not None:
337+ q = q.replace("'", "\\'")
338+ return self.execute(
339+ (
340+ "su -l {} -c "
341+ "$'XDG_RUNTIME_DIR=/run/user/`id -u` "
342+ "systemctl --user {}'"
343+ ).format(user, q)
344+ )
345+ return self.execute("systemctl {}".format(q))
346+
347+ def execute(self, command):
348+ self.connect()
349+
350+ out_command = "( {} ); echo '|!EOF' $?\n".format(command)
351+ self.shell.send(out_command.encode())
352+
353+ output = ""
354+ status_code_pattern = re.compile(r"(.*)\|\!EOF\s+(\d+)")
355+
356+ while True:
357+ chunk = self.shell.recv(4096).decode()
358+ match = status_code_pattern.match(chunk)
359+ if match:
360+ output += match[1]
361+ status_code = int(match[2])
362+ return (status_code, output)
363+ output += chunk
364+
365+ def succeed(self, *commands):
366+ """Execute each command and check that it succeeds."""
367+ for command in commands:
368+ with self.nested("must succeed: {}".format(command)):
369+ status, output = self.execute(command)
370+ if status != 0:
371+ self.log("output: {}".format(output))
372+ raise Exception(
373+ "command `{}` failed (exit code {})".format(command, status)
374+ )
375+ return output
376+
377+ def fail(self, *commands):
378+ """Execute each command and check that it fails."""
379+ for command in commands:
380+ with self.nested("must fail: {}".format(command)):
381+ status, output = self.execute(command)
382+ if status == 0:
383+ raise Exception(
384+ "command `{}` unexpectedly succeeded".format(command)
385+ )
386+
387+ def wait_until_succeeds(self, command):
388+ with self.nested("waiting for success: {}".format(command)):
389+ while True:
390+ status, output = self.execute(command)
391+ if status == 0:
392+ return output
393+
394+ def wait_until_fails(self, command):
395+ with self.nested("waiting for failure: {}".format(command)):
396+ while True:
397+ status, output = self.execute(command)
398+ if status != 0:
399+ return output
400+
401+ def wait_for_shutdown(self):
402+ if not self.booted:
403+ return
404+
405+ with self.nested("waiting for the VM to power off"):
406+ sys.stdout.flush()
407+ self.process.wait()
408+
409+ self.pid = None
410+ self.booted = False
411+ self.connected = False
412+
413+ def get_tty_text(self, tty):
414+ status, output = self.execute(
415+ "fold -w$(stty -F /dev/tty{0} size | "
416+ "awk '{{print $2}}') /dev/vcs{0}".format(tty)
417+ )
418+ return output
419+
420+ def wait_until_tty_matches(self, tty, regexp):
421+ matcher = re.compile(regexp)
422+ with self.nested("waiting for {} to appear on tty {}".format(regexp, tty)):
423+ while True:
424+ text = self.get_tty_text(tty)
425+ if len(matcher.findall(text)) > 0:
426+ return True
427+
428+ def send_chars(self, chars):
429+ with self.nested("sending keys ‘{}‘".format(chars)):
430+ for char in chars:
431+ self.send_key(char)
432+
433+ def wait_for_file(self, filename):
434+ with self.nested("waiting for file ‘{}‘".format(filename)):
435+ while True:
436+ status, _ = self.execute("test -e {}".format(filename))
437+ if status == 0:
438+ return True
439+
440+ def wait_for_open_port(self, port):
441+ def port_is_open(_):
442+ status, _ = self.execute("nc -z localhost {}".format(port))
443+ return status == 0
444+
445+ with self.nested("waiting for TCP port {}".format(port)):
446+ retry(port_is_open)
447+
448+ def wait_for_closed_port(self, port):
449+ def port_is_closed(_):
450+ status, _ = self.execute("nc -z localhost {}".format(port))
451+ return status != 0
452+
453+ retry(port_is_closed)
454+
455+ def start_job(self, jobname, user=None):
456+ return self.systemctl("start {}".format(jobname), user)
457+
458+ def stop_job(self, jobname, user=None):
459+ return self.systemctl("stop {}".format(jobname), user)
460+
461+ def wait_for_job(self, jobname):
462+ return self.wait_for_unit(jobname)
463+
464+ def connect(self):
465+ if self.connected:
466+ return
467+
468+ with self.nested("waiting for the VM to finish booting"):
469+ self.start()
470+
471+ tic = time.time()
472+ self.shell.recv(1024)
473+ # TODO: Timeout
474+ toc = time.time()
475+
476+ self.log("connected to guest root shell")
477+ self.log("(connecting took {:.2f} seconds)".format(toc - tic))
478+ self.connected = True
479+
480+ def screenshot(self, filename):
481+ out_dir = os.environ.get("out", os.getcwd())
482+ word_pattern = re.compile(r"^\w+$")
483+ if word_pattern.match(filename):
484+ filename = os.path.join(out_dir, "{}.png".format(filename))
485+ tmp = "{}.ppm".format(filename)
486+
487+ with self.nested(
488+ "making screenshot {}".format(filename),
489+ {"image": os.path.basename(filename)},
490+ ):
491+ self.send_monitor_command("screendump {}".format(tmp))
492+ ret = subprocess.run("pnmtopng {} > {}".format(tmp, filename), shell=True)
493+ os.unlink(tmp)
494+ if ret.returncode != 0:
495+ raise Exception("Cannot convert screenshot")
496+
497+ def get_screen_text(self):
498+ if shutil.which("tesseract") is None:
499+ raise Exception("get_screen_text used but enableOCR is false")
500+
501+ magick_args = (
502+ "-filter Catrom -density 72 -resample 300 "
503+ + "-contrast -normalize -despeckle -type grayscale "
504+ + "-sharpen 1 -posterize 3 -negate -gamma 100 "
505+ + "-blur 1x65535"
506+ )
507+
508+ tess_args = "-c debug_file=/dev/null --psm 11 --oem 2"
509+
510+ with self.nested("performing optical character recognition"):
511+ with tempfile.NamedTemporaryFile() as tmpin:
512+ self.send_monitor_command("screendump {}".format(tmpin.name))
513+
514+ cmd = "convert {} {} tiff:- | tesseract - - {}".format(
515+ magick_args, tmpin.name, tess_args
516+ )
517+ ret = subprocess.run(cmd, shell=True, capture_output=True)
518+ if ret.returncode != 0:
519+ raise Exception(
520+ "OCR failed with exit code {}".format(ret.returncode)
521+ )
522+
523+ return ret.stdout.decode("utf-8")
524+
525+ def wait_for_text(self, regex):
526+ def screen_matches(last):
527+ text = self.get_screen_text()
528+ m = re.search(regex, text)
529+
530+ if last and not m:
531+ self.log("Last OCR attempt failed. Text was: {}".format(text))
532+
533+ return m
534+
535+ with self.nested("waiting for {} to appear on screen".format(regex)):
536+ retry(screen_matches)
537+
538+ def send_key(self, key):
539+ key = CHAR_TO_KEY.get(key, key)
540+ self.send_monitor_command("sendkey {}".format(key))
541+
542+ def start(self):
543+ if self.booted:
544+ return
545+
546+ self.log("starting vm")
547+
548+ def create_socket(path):
549+ if os.path.exists(path):
550+ os.unlink(path)
551+ s = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)
552+ s.bind(path)
553+ s.listen(1)
554+ return s
555+
556+ monitor_path = os.path.join(self.state_dir, "monitor")
557+ self.monitor_socket = create_socket(monitor_path)
558+
559+ shell_path = os.path.join(self.state_dir, "shell")
560+ self.shell_socket = create_socket(shell_path)
561+
562+ qemu_options = (
563+ " ".join(
564+ [
565+ "" if self.allow_reboot else "-no-reboot",
566+ "-monitor unix:{}".format(monitor_path),
567+ "-chardev socket,id=shell,path={}".format(shell_path),
568+ "-device virtio-serial",
569+ "-device virtconsole,chardev=shell",
570+ "-device virtio-rng-pci",
571+ "-serial stdio" if "DISPLAY" in os.environ else "-nographic",
572+ ]
573+ )
574+ + " "
575+ + os.environ.get("QEMU_OPTS", "")
576+ )
577+
578+ environment = {
579+ "QEMU_OPTS": qemu_options,
580+ "SHARED_DIR": self.shared_dir,
581+ "USE_TMPDIR": "1",
582+ }
583+ environment.update(dict(os.environ))
584+
585+ self.process = subprocess.Popen(
586+ self.script,
587+ bufsize=1,
588+ stdin=subprocess.DEVNULL,
589+ stdout=subprocess.PIPE,
590+ stderr=subprocess.STDOUT,
591+ shell=False,
592+ cwd=self.state_dir,
593+ env=environment,
594+ )
595+ self.monitor, _ = self.monitor_socket.accept()
596+ self.shell, _ = self.shell_socket.accept()
597+
598+ def process_serial_output():
599+ for line in self.process.stdout:
600+ line = line.decode().replace("\r", "").rstrip()
601+ eprint("{} # {}".format(self.name, line))
602+ self.logger.enqueue({"msg": line, "machine": self.name})
603+
604+ _thread.start_new_thread(process_serial_output, ())
605+
606+ self.wait_for_monitor_prompt()
607+
608+ self.pid = self.process.pid
609+ self.booted = True
610+
611+ self.log("QEMU running (pid {})".format(self.pid))
612+
613+ def shutdown(self):
614+ if self.booted:
615+ return
616+
617+ self.shell.send("poweroff\n".encode())
618+ self.wait_for_shutdown()
619+
620+ def crash(self):
621+ if self.booted:
622+ return
623+
624+ self.log("forced crash")
625+ self.send_monitor_command("quit")
626+ self.wait_for_shutdown()
627+
628+ def wait_for_x(self):
629+ """Wait until it is possible to connect to the X server. Note that
630+ testing the existence of /tmp/.X11-unix/X0 is insufficient.
631+ """
632+ with self.nested("waiting for the X11 server"):
633+ while True:
634+ cmd = (
635+ "journalctl -b SYSLOG_IDENTIFIER=systemd | "
636+ + 'grep "Reached target Current graphical"'
637+ )
638+ status, _ = self.execute(cmd)
639+ if status != 0:
640+ continue
641+ status, _ = self.execute("[ -e /tmp/.X11-unix/X0 ]")
642+ if status == 0:
643+ return
644+
645+ def sleep(self, secs):
646+ time.sleep(secs)
647+
648+ def block(self):
649+ """Make the machine unreachable by shutting down eth1 (the multicast
650+ interface used to talk to the other VMs). We keep eth0 up so that
651+ the test driver can continue to talk to the machine.
652+ """
653+ self.send_monitor_command("set_link virtio-net-pci.1 off")
654+
655+ def unblock(self):
656+ """Make the machine reachable.
657+ """
658+ self.send_monitor_command("set_link virtio-net-pci.1 on")
659+
660+
661+def create_machine(args):
662+ global log
663+ args["log"] = log
664+ args["redirectSerial"] = os.environ.get("USE_SERIAL", "0") == "1"
665+ return Machine(args)
666+
667+
668+def start_all():
669+ with log.nested("starting all VMs"):
670+ for machine in machines:
671+ machine.start()
672+
673+
674+def join_all():
675+ with log.nested("waiting for all VMs to finish"):
676+ for machine in machines:
677+ machine.wait_for_shutdown()
678+
679+
680+def test_script():
681+ exec(os.environ["testScript"])
682+
683+
684+def run_tests():
685+ tests = os.environ.get("tests", None)
686+ if tests is not None:
687+ with log.nested("running the VM test script"):
688+ try:
689+ exec(tests)
690+ except Exception as e:
691+ eprint("error: {}".format(str(e)))
692+ sys.exit(1)
693+ else:
694+ ptpython.repl.embed(locals(), globals())
695+
696+ # TODO: Collect coverage data
697+
698+ for machine in machines:
699+ if machine.is_up():
700+ machine.execute("sync")
701+
702+ if nr_tests != 0:
703+ log.log("{} out of {} tests succeeded".format(nr_succeeded, nr_tests))
704+
705+
706+@contextmanager
707+def subtest(name):
708+ global nr_tests
709+ global nr_succeeded
710+
711+ with log.nested(name):
712+ nr_tests += 1
713+ try:
714+ yield
715+ nr_succeeded += 1
716+ return True
717+ except Exception as e:
718+ log.log("error: {}".format(str(e)))
719+
720+ return False
721+
722+
723+if __name__ == "__main__":
724+ global log
725+ log = Logger()
726+
727+ vlan_nrs = list(dict.fromkeys(os.environ["VLANS"].split()))
728+ vde_sockets = [create_vlan(v) for v in vlan_nrs]
729+ for nr, vde_socket, _, _ in vde_sockets:
730+ os.environ["QEMU_VDE_SOCKET_{}".format(nr)] = vde_socket
731+
732+ vm_scripts = sys.argv[1:]
733+ machines = [create_machine({"startCommand": s}) for s in vm_scripts]
734+ machine_eval = [
735+ "{0} = machines[{1}]".format(m.name, idx) for idx, m in enumerate(machines)
736+ ]
737+ exec("\n".join(machine_eval))
738+
739+ nr_tests = 0
740+ nr_succeeded = 0
741+
742+ @atexit.register
743+ def clean_up():
744+ with log.nested("cleaning up"):
745+ for machine in machines:
746+ if machine.pid is None:
747+ continue
748+ log.log("killing {} (pid {})".format(machine.name, machine.pid))
749+ machine.process.kill()
750+
751+ for _, _, process, _ in vde_sockets:
752+ process.kill()
753+ log.close()
754+
755+ tic = time.time()
756+ run_tests()
757+ toc = time.time()
758+ print("test script finished in {:.2f}s".format(toc - tic))
nixos/lib/testing-python.nixnew file+279
@@ -0,0 +1,279 @@
1+{ system
2+, pkgs ? import ../.. { inherit system config; }
3+ # Use a minimal kernel?
4+, minimal ? false
5+ # Ignored
6+, config ? {}
7+ # Modules to add to each VM
8+, extraConfigurations ? [] }:
9+
10+with import ./build-vms.nix { inherit system pkgs minimal extraConfigurations; };
11+with pkgs;
12+
13+let
14+ jquery-ui = callPackage ./testing/jquery-ui.nix { };
15+ jquery = callPackage ./testing/jquery.nix { };
16+
17+in rec {
18+
19+ inherit pkgs;
20+
21+
22+ testDriver = let
23+ testDriverScript = ./test-driver/test-driver.py;
24+ in stdenv.mkDerivation {
25+ name = "nixos-test-driver";
26+
27+ nativeBuildInputs = [ makeWrapper ];
28+ buildInputs = [ (python3.withPackages (p: [ p.ptpython ])) ];
29+ checkInputs = with python3Packages; [ pylint black ];
30+
31+ dontUnpack = true;
32+
33+ preferLocalBuild = true;
34+
35+ doCheck = true;
36+ checkPhase = ''
37+ pylint --errors-only ${testDriverScript}
38+ black --check --diff ${testDriverScript}
39+ '';
40+
41+ installPhase =
42+ ''
43+ mkdir -p $out/bin
44+ cp ${testDriverScript} $out/bin/nixos-test-driver
45+ chmod u+x $out/bin/nixos-test-driver
46+ # TODO: copy user script part into this file (append)
47+
48+ wrapProgram $out/bin/nixos-test-driver \
49+ --prefix PATH : "${lib.makeBinPath [ qemu_test vde2 netpbm coreutils ]}" \
50+ '';
51+ };
52+
53+
54+ # Run an automated test suite in the given virtual network.
55+ # `driver' is the script that runs the network.
56+ runTests = driver:
57+ stdenv.mkDerivation {
58+ name = "vm-test-run-${driver.testName}";
59+
60+ requiredSystemFeatures = [ "kvm" "nixos-test" ];
61+
62+ buildInputs = [ libxslt ];
63+
64+ buildCommand =
65+ ''
66+ mkdir -p $out/nix-support
67+
68+ LOGFILE=$out/log.xml tests='exec(os.environ["testScript"])' ${driver}/bin/nixos-test-driver
69+
70+ # Generate a pretty-printed log.
71+ xsltproc --output $out/log.html ${./test-driver/log2html.xsl} $out/log.xml
72+ ln -s ${./test-driver/logfile.css} $out/logfile.css
73+ ln -s ${./test-driver/treebits.js} $out/treebits.js
74+ ln -s ${jquery}/js/jquery.min.js $out/
75+ ln -s ${jquery}/js/jquery.js $out/
76+ ln -s ${jquery-ui}/js/jquery-ui.min.js $out/
77+ ln -s ${jquery-ui}/js/jquery-ui.js $out/
78+
79+ touch $out/nix-support/hydra-build-products
80+ echo "report testlog $out log.html" >> $out/nix-support/hydra-build-products
81+
82+ for i in */xchg/coverage-data; do
83+ mkdir -p $out/coverage-data
84+ mv $i $out/coverage-data/$(dirname $(dirname $i))
85+ done
86+ '';
87+ };
88+
89+
90+ makeTest =
91+ { testScript
92+ , makeCoverageReport ? false
93+ , enableOCR ? false
94+ , name ? "unnamed"
95+ , ...
96+ } @ t:
97+
98+ let
99+ # A standard store path to the vm monitor is built like this:
100+ # /tmp/nix-build-vm-test-run-$name.drv-0/vm-state-machine/monitor
101+ # The max filename length of a unix domain socket is 108 bytes.
102+ # This means $name can at most be 50 bytes long.
103+ maxTestNameLen = 50;
104+ testNameLen = builtins.stringLength name;
105+
106+ testDriverName = with builtins;
107+ if testNameLen > maxTestNameLen then
108+ abort ("The name of the test '${name}' must not be longer than ${toString maxTestNameLen} " +
109+ "it's currently ${toString testNameLen} characters long.")
110+ else
111+ "nixos-test-driver-${name}";
112+
113+ nodes = buildVirtualNetwork (
114+ t.nodes or (if t ? machine then { machine = t.machine; } else { }));
115+
116+ testScript' =
117+ # Call the test script with the computed nodes.
118+ if lib.isFunction testScript
119+ then testScript { inherit nodes; }
120+ else testScript;
121+
122+ vlans = map (m: m.config.virtualisation.vlans) (lib.attrValues nodes);
123+
124+ vms = map (m: m.config.system.build.vm) (lib.attrValues nodes);
125+
126+ ocrProg = tesseract4.override { enableLanguages = [ "eng" ]; };
127+
128+ imagemagick_tiff = imagemagick_light.override { inherit libtiff; };
129+
130+ # Generate onvenience wrappers for running the test driver
131+ # interactively with the specified network, and for starting the
132+ # VMs from the command line.
133+ driver = runCommand testDriverName
134+ { buildInputs = [ makeWrapper];
135+ testScript = testScript';
136+ preferLocalBuild = true;
137+ testName = name;
138+ }
139+ ''
140+ mkdir -p $out/bin
141+
142+ echo -n "$testScript" > $out/test-script
143+ ${python3Packages.black}/bin/black --check --diff $out/test-script
144+
145+ ln -s ${testDriver}/bin/nixos-test-driver $out/bin/
146+ vms=($(for i in ${toString vms}; do echo $i/bin/run-*-vm; done))
147+ wrapProgram $out/bin/nixos-test-driver \
148+ --add-flags "''${vms[*]}" \
149+ ${lib.optionalString enableOCR
150+ "--prefix PATH : '${ocrProg}/bin:${imagemagick_tiff}/bin'"} \
151+ --run "export testScript=\"\$(cat $out/test-script)\"" \
152+ --set VLANS '${toString vlans}'
153+ ln -s ${testDriver}/bin/nixos-test-driver $out/bin/nixos-run-vms
154+ wrapProgram $out/bin/nixos-run-vms \
155+ --add-flags "''${vms[*]}" \
156+ ${lib.optionalString enableOCR "--prefix PATH : '${ocrProg}/bin'"} \
157+ --set tests 'start_all(); join_all();' \
158+ --set VLANS '${toString vlans}' \
159+ ${lib.optionalString (builtins.length vms == 1) "--set USE_SERIAL 1"}
160+ ''; # "
161+
162+ passMeta = drv: drv // lib.optionalAttrs (t ? meta) {
163+ meta = (drv.meta or {}) // t.meta;
164+ };
165+
166+ test = passMeta (runTests driver);
167+ report = passMeta (releaseTools.gcovReport { coverageRuns = [ test ]; });
168+
169+ nodeNames = builtins.attrNames nodes;
170+ invalidNodeNames = lib.filter
171+ (node: builtins.match "^[A-z_][A-z0-9_]+$" node == null) nodeNames;
172+
173+ in
174+ if lib.length invalidNodeNames > 0 then
175+ throw ''
176+ Cannot create machines out of (${lib.concatStringsSep ", " invalidNodeNames})!
177+ All machines are referenced as perl variables in the testing framework which will break the
178+ script when special characters are used.
179+
180+ Please stick to alphanumeric chars and underscores as separation.
181+ ''
182+ else
183+ (if makeCoverageReport then report else test) // {
184+ inherit nodes driver test;
185+ };
186+
187+ runInMachine =
188+ { drv
189+ , machine
190+ , preBuild ? ""
191+ , postBuild ? ""
192+ , ... # ???
193+ }:
194+ let
195+ vm = buildVM { }
196+ [ machine
197+ { key = "run-in-machine";
198+ networking.hostName = "client";
199+ nix.readOnlyStore = false;
200+ virtualisation.writableStore = false;
201+ }
202+ ];
203+
204+ buildrunner = writeText "vm-build" ''
205+ source $1
206+
207+ ${coreutils}/bin/mkdir -p $TMPDIR
208+ cd $TMPDIR
209+
210+ exec $origBuilder $origArgs
211+ '';
212+
213+ testScript = ''
214+ startAll;
215+ $client->waitForUnit("multi-user.target");
216+ ${preBuild}
217+ $client->succeed("env -i ${bash}/bin/bash ${buildrunner} /tmp/xchg/saved-env >&2");
218+ ${postBuild}
219+ $client->succeed("sync"); # flush all data before pulling the plug
220+ '';
221+
222+ vmRunCommand = writeText "vm-run" ''
223+ xchg=vm-state-client/xchg
224+ ${coreutils}/bin/mkdir $out
225+ ${coreutils}/bin/mkdir -p $xchg
226+
227+ for i in $passAsFile; do
228+ i2=''${i}Path
229+ _basename=$(${coreutils}/bin/basename ''${!i2})
230+ ${coreutils}/bin/cp ''${!i2} $xchg/$_basename
231+ eval $i2=/tmp/xchg/$_basename
232+ ${coreutils}/bin/ls -la $xchg
233+ done
234+
235+ unset i i2 _basename
236+ export | ${gnugrep}/bin/grep -v '^xchg=' > $xchg/saved-env
237+ unset xchg
238+
239+ export tests='${testScript}'
240+ ${testDriver}/bin/nixos-test-driver ${vm.config.system.build.vm}/bin/run-*-vm
241+ ''; # */
242+
243+ in
244+ lib.overrideDerivation drv (attrs: {
245+ requiredSystemFeatures = [ "kvm" ];
246+ builder = "${bash}/bin/sh";
247+ args = ["-e" vmRunCommand];
248+ origArgs = attrs.args;
249+ origBuilder = attrs.builder;
250+ });
251+
252+
253+ runInMachineWithX = { require ? [], ... } @ args:
254+ let
255+ client =
256+ { ... }:
257+ {
258+ inherit require;
259+ virtualisation.memorySize = 1024;
260+ services.xserver.enable = true;
261+ services.xserver.displayManager.slim.enable = false;
262+ services.xserver.displayManager.auto.enable = true;
263+ services.xserver.windowManager.default = "icewm";
264+ services.xserver.windowManager.icewm.enable = true;
265+ services.xserver.desktopManager.default = "none";
266+ };
267+ in
268+ runInMachine ({
269+ machine = client;
270+ preBuild =
271+ ''
272+ $client->waitForX;
273+ '';
274+ } // args);
275+
276+
277+ simpleTest = as: (makeTest as).test;
278+
279+}
nixos/tests/acme.nix+35−30
@@ -1,6 +1,6 @@
11let
22 commonConfig = ./common/letsencrypt/common.nix;
3−in import ./make-test.nix {
3+in import ./make-test-python.nix {
44 name = "acme";
55
66 nodes = rec {
@@ -90,39 +90,44 @@ in import ./make-test.nix {
9090 newServerSystem = nodes.webserver2.config.system.build.toplevel;
9191 switchToNewServer = "${newServerSystem}/bin/switch-to-configuration test";
9292 in
93− # Note, waitForUnit does not work for oneshot services that do not have RemainAfterExit=true,
93+ # Note, wait_for_unit does not work for oneshot services that do not have RemainAfterExit=true,
9494 # this is because a oneshot goes from inactive => activating => inactive, and never
9595 # reaches the active state. To work around this, we create some mock target units which
9696 # get pulled in by the oneshot units. The target units linger after activation, and hence we
9797 # can use them to probe that a oneshot fired. It is a bit ugly, but it is the best we can do
9898 ''
99− $client->start;
100− $letsencrypt->start;
101− $acmeStandalone->start;
102−
103− $letsencrypt->waitForUnit("default.target");
104− $letsencrypt->waitForUnit("pebble.service");
105−
106− subtest "can request certificate with HTTPS-01 challenge", sub {
107− $acmeStandalone->waitForUnit("default.target");
108− $acmeStandalone->succeed("systemctl start acme-standalone.com.service");
109− $acmeStandalone->waitForUnit("acme-finished-standalone.com.target");
110− };
111−
112− $client->waitForUnit("default.target");
113−
114− $client->succeed('curl https://acme-v02.api.letsencrypt.org:15000/roots/0 > /tmp/ca.crt');
115− $client->succeed('curl https://acme-v02.api.letsencrypt.org:15000/intermediate-keys/0 >> /tmp/ca.crt');
116−
117− subtest "Can request certificate for nginx service", sub {
118− $webserver->waitForUnit("acme-finished-a.example.com.target");
119− $client->succeed('curl --cacert /tmp/ca.crt https://a.example.com/ | grep -qF "hello world"');
120− };
121−
122− subtest "Can add another certificate for nginx service", sub {
123− $webserver->succeed("/run/current-system/fine-tune/child-1/bin/switch-to-configuration test");
124− $webserver->waitForUnit("acme-finished-b.example.com.target");
125− $client->succeed('curl --cacert /tmp/ca.crt https://b.example.com/ | grep -qF "hello world"');
126− };
99+ client.start()
100+ letsencrypt.start()
101+ acmeStandalone.start()
102+
103+ letsencrypt.wait_for_unit("default.target")
104+ letsencrypt.wait_for_unit("pebble.service")
105+
106+ with subtest("can request certificate with HTTPS-01 challenge"):
107+ acmeStandalone.wait_for_unit("default.target")
108+ acmeStandalone.succeed("systemctl start acme-standalone.com.service")
109+ acmeStandalone.wait_for_unit("acme-finished-standalone.com.target")
110+
111+ client.wait_for_unit("default.target")
112+
113+ client.succeed("curl https://acme-v02.api.letsencrypt.org:15000/roots/0 > /tmp/ca.crt")
114+ client.succeed(
115+ "curl https://acme-v02.api.letsencrypt.org:15000/intermediate-keys/0 >> /tmp/ca.crt"
116+ )
117+
118+ with subtest("Can request certificate for nginx service"):
119+ webserver.wait_for_unit("acme-finished-a.example.com.target")
120+ client.succeed(
121+ "curl --cacert /tmp/ca.crt https://a.example.com/ | grep -qF 'hello world'"
122+ )
123+
124+ with subtest("Can add another certificate for nginx service"):
125+ webserver.succeed(
126+ "/run/current-system/fine-tune/child-1/bin/switch-to-configuration test"
127+ )
128+ webserver.wait_for_unit("acme-finished-b.example.com.target")
129+ client.succeed(
130+ "curl --cacert /tmp/ca.crt https://b.example.com/ | grep -qF 'hello world'"
131+ )
127132 '';
128133}
nixos/tests/ammonite.nix+3−3
@@ -1,4 +1,4 @@
1−import ./make-test.nix ({ pkgs, ...} : {
1+import ./make-test-python.nix ({ pkgs, ...} : {
22 name = "ammonite";
33 meta = with pkgs.stdenv.lib.maintainers; {
44 maintainers = [ nequissimus ];
@@ -13,8 +13,8 @@ import ./make-test.nix ({ pkgs, ...} : {
1313 };
1414
1515 testScript = ''
16− startAll;
16+ start_all()
1717
18− $amm->succeed("amm -c 'val foo = 21; println(foo * 2)' | grep 42")
18+ amm.succeed("amm -c 'val foo = 21; println(foo * 2)' | grep 42")
1919 '';
2020})
nixos/tests/automysqlbackup.nix+18−14
@@ -1,4 +1,4 @@
1−import ./make-test.nix ({ pkgs, lib, ... }:
1+import ./make-test-python.nix ({ pkgs, lib, ... }:
22
33{
44 name = "automysqlbackup";
@@ -15,20 +15,24 @@ import ./make-test.nix ({ pkgs, lib, ... }:
1515 };
1616
1717 testScript = ''
18− startAll;
18+ start_all()
1919
2020 # Need to have mysql started so that it can be populated with data.
21− $machine->waitForUnit("mysql.service");
22−
23− # Wait for testdb to be fully populated (5 rows).
24− $machine->waitUntilSucceeds("mysql -u root -D testdb -N -B -e 'select count(id) from tests' | grep -q 5");
25−
26− # Do a backup and wait for it to start
27− $machine->startJob("automysqlbackup.service");
28− $machine->waitForJob("automysqlbackup.service");
29−
30− # wait for backup file and check that data appears in backup
31− $machine->waitForFile("/var/backup/mysql/daily/testdb");
32− $machine->succeed("${pkgs.gzip}/bin/zcat /var/backup/mysql/daily/testdb/daily_testdb_*.sql.gz | grep hello");
21+ machine.wait_for_unit("mysql.service")
22+
23+ with subtest("Wait for testdb to be fully populated (5 rows)."):
24+ machine.wait_until_succeeds(
25+ "mysql -u root -D testdb -N -B -e 'select count(id) from tests' | grep -q 5"
26+ )
27+
28+ with subtest("Do a backup and wait for it to start"):
29+ machine.start_job("automysqlbackup.service")
30+ machine.wait_for_job("automysqlbackup.service")
31+
32+ with subtest("wait for backup file and check that data appears in backup"):
33+ machine.wait_for_file("/var/backup/mysql/daily/testdb")
34+ machine.succeed(
35+ "${pkgs.gzip}/bin/zcat /var/backup/mysql/daily/testdb/daily_testdb_*.sql.gz | grep hello"
36+ )
3337 '';
3438})
nixos/tests/bittorrent.nix+36−22
@@ -6,7 +6,7 @@
66# which only works if the first client successfully uses the UPnP-IGD
77# protocol to poke a hole in the NAT.
88
9−import ./make-test.nix ({ pkgs, ... }:
9+import ./make-test-python.nix ({ pkgs, ... }:
1010
1111let
1212
@@ -108,42 +108,56 @@ in
108108 testScript =
109109 { nodes, ... }:
110110 ''
111− startAll;
111+ start_all()
112112
113113 # Wait for network and miniupnpd.
114− $router->waitForUnit("network-online.target");
115− $router->waitForUnit("miniupnpd");
114+ router.wait_for_unit("network-online.target")
115+ router.wait_for_unit("miniupnpd")
116116
117117 # Create the torrent.
118− $tracker->succeed("mkdir /tmp/data");
119− $tracker->succeed("cp ${file} /tmp/data/test.tar.bz2");
120− $tracker->succeed("transmission-create /tmp/data/test.tar.bz2 --private --tracker http://${externalTrackerAddress}:6969/announce --outfile /tmp/test.torrent");
121− $tracker->succeed("chmod 644 /tmp/test.torrent");
118+ tracker.succeed("mkdir /tmp/data")
119+ tracker.succeed(
120+ "cp ${file} /tmp/data/test.tar.bz2"
121+ )
122+ tracker.succeed(
123+ "transmission-create /tmp/data/test.tar.bz2 --private --tracker http://${externalTrackerAddress}:6969/announce --outfile /tmp/test.torrent"
124+ )
125+ tracker.succeed("chmod 644 /tmp/test.torrent")
122126
123127 # Start the tracker. !!! use a less crappy tracker
124− $tracker->waitForUnit("network-online.target");
125− $tracker->waitForUnit("opentracker.service");
126− $tracker->waitForOpenPort(6969);
128+ tracker.wait_for_unit("network-online.target")
129+ tracker.wait_for_unit("opentracker.service")
130+ tracker.wait_for_open_port(6969)
127131
128132 # Start the initial seeder.
129− $tracker->succeed("transmission-remote --add /tmp/test.torrent --no-portmap --no-dht --download-dir /tmp/data");
133+ tracker.succeed(
134+ "transmission-remote --add /tmp/test.torrent --no-portmap --no-dht --download-dir /tmp/data"
135+ )
130136
131137 # Now we should be able to download from the client behind the NAT.
132− $tracker->waitForUnit("httpd");
133− $client1->waitForUnit("network-online.target");
134− $client1->succeed("transmission-remote --add http://${externalTrackerAddress}/test.torrent --download-dir /tmp >&2 &");
135− $client1->waitForFile("/tmp/test.tar.bz2");
136− $client1->succeed("cmp /tmp/test.tar.bz2 ${file}");
138+ tracker.wait_for_unit("httpd")
139+ client1.wait_for_unit("network-online.target")
140+ client1.succeed(
141+ "transmission-remote --add http://${externalTrackerAddress}/test.torrent --download-dir /tmp >&2 &"
142+ )
143+ client1.wait_for_file("/tmp/test.tar.bz2")
144+ client1.succeed(
145+ "cmp /tmp/test.tar.bz2 ${file}"
146+ )
137147
138148 # Bring down the initial seeder.
139− # $tracker->stopJob("transmission");
149+ # tracker.stop_job("transmission")
140150
141151 # Now download from the second client. This can only succeed if
142152 # the first client created a NAT hole in the router.
143− $client2->waitForUnit("network-online.target");
144− $client2->succeed("transmission-remote --add http://${externalTrackerAddress}/test.torrent --no-portmap --no-dht --download-dir /tmp >&2 &");
145− $client2->waitForFile("/tmp/test.tar.bz2");
146− $client2->succeed("cmp /tmp/test.tar.bz2 ${file}");
153+ client2.wait_for_unit("network-online.target")
154+ client2.succeed(
155+ "transmission-remote --add http://${externalTrackerAddress}/test.torrent --no-portmap --no-dht --download-dir /tmp >&2 &"
156+ )
157+ client2.wait_for_file("/tmp/test.tar.bz2")
158+ client2.succeed(
159+ "cmp /tmp/test.tar.bz2 ${file}"
160+ )
147161 '';
148162
149163})
nixos/tests/boot.nix+17−18
@@ -3,7 +3,7 @@
33 pkgs ? import ../.. { inherit system config; }
44}:
55
6−with import ../lib/testing.nix { inherit system pkgs; };
6+with import ../lib/testing-python.nix { inherit system pkgs; };
77with pkgs.lib;
88
99let
@@ -17,11 +17,11 @@ let
1717 ];
1818 }).config.system.build.isoImage;
1919
20− perlAttrs = params: "{ ${concatStringsSep ", " (mapAttrsToList (name: param: "${name} => ${builtins.toJSON param}") params)} }";
20+ pythonDict = params: "\n {\n ${concatStringsSep ",\n " (mapAttrsToList (name: param: "\"${name}\": \"${param}\"") params)},\n }\n";
2121
2222 makeBootTest = name: extraConfig:
2323 let
24− machineConfig = perlAttrs ({ qemuFlags = "-m 768"; } // extraConfig);
24+ machineConfig = pythonDict ({ qemuFlags = "-m 768"; } // extraConfig);
2525 in
2626 makeTest {
2727 inherit iso;
@@ -29,16 +29,16 @@ let
2929 nodes = { };
3030 testScript =
3131 ''
32− my $machine = createMachine(${machineConfig});
33− $machine->start;
34− $machine->waitForUnit("multi-user.target");
35− $machine->succeed("nix verify -r --no-trust /run/current-system");
32+ machine = create_machine(${machineConfig})
33+ machine.start()
34+ machine.wait_for_unit("multi-user.target")
35+ machine.succeed("nix verify -r --no-trust /run/current-system")
3636
37− # Test whether the channel got installed correctly.
38− $machine->succeed("nix-instantiate --dry-run '<nixpkgs>' -A hello");
39− $machine->succeed("nix-env --dry-run -iA nixos.procps");
37+ with subtest("Check whether the channel got installed correctly"):
38+ machine.succeed("nix-instantiate --dry-run '<nixpkgs>' -A hello")
39+ machine.succeed("nix-env --dry-run -iA nixos.procps")
4040
41− $machine->shutdown;
41+ machine.shutdown()
4242 '';
4343 };
4444
@@ -60,7 +60,7 @@ let
6060 config.system.build.netbootIpxeScript
6161 ];
6262 };
63− machineConfig = perlAttrs ({
63+ machineConfig = pythonDict ({
6464 qemuFlags = "-boot order=n -m 2000";
6565 netBackendArgs = "tftp=${ipxeBootDir},bootfile=netboot.ipxe";
6666 } // extraConfig);
@@ -68,12 +68,11 @@ let
6868 makeTest {
6969 name = "boot-netboot-" + name;
7070 nodes = { };
71− testScript =
72− ''
73− my $machine = createMachine(${machineConfig});
74− $machine->start;
75− $machine->waitForUnit("multi-user.target");
76− $machine->shutdown;
71+ testScript = ''
72+ machine = create_machine(${machineConfig})
73+ machine.start()
74+ machine.wait_for_unit("multi-user.target")
75+ machine.shutdown()
7776 '';
7877 };
7978in {
nixos/tests/emacs-daemon.nix+13−10
@@ -1,4 +1,4 @@
1−import ./make-test.nix ({ pkgs, ...} : {
1+import ./make-test-python.nix ({ pkgs, ...} : {
22 name = "emacs-daemon";
33 meta = with pkgs.stdenv.lib.maintainers; {
44 maintainers = [ ];
@@ -21,25 +21,28 @@ import ./make-test.nix ({ pkgs, ...} : {
2121 environment.variables.TEST_SYSTEM_VARIABLE = "system variable";
2222 };
2323
24− testScript =
25− ''
26− $machine->waitForUnit("multi-user.target");
24+ testScript = ''
25+ machine.wait_for_unit("multi-user.target")
2726
2827 # checks that the EDITOR environment variable is set
29− $machine->succeed("test \$(basename \"\$EDITOR\") = emacseditor");
28+ machine.succeed('test $(basename "$EDITOR") = emacseditor')
3029
3130 # waits for the emacs service to be ready
32− $machine->waitUntilSucceeds("systemctl --user status emacs.service | grep 'Active: active'");
31+ machine.wait_until_succeeds(
32+ "systemctl --user status emacs.service | grep 'Active: active'"
33+ )
3334
3435 # connects to the daemon
35− $machine->succeed("emacsclient --create-frame \$EDITOR &");
36+ machine.succeed("emacsclient --create-frame $EDITOR &")
3637
3738 # checks that Emacs shows the edited filename
38− $machine->waitForText("emacseditor");
39+ machine.wait_for_text("emacseditor")
3940
4041 # makes sure environment variables are accessible from Emacs
41− $machine->succeed("emacsclient --eval '(getenv \"TEST_SYSTEM_VARIABLE\")'") =~ /system variable/ or die;
42+ machine.succeed(
43+ "emacsclient --eval '(getenv \"TEST_SYSTEM_VARIABLE\")' | grep -q 'system variable'"
44+ )
4245
43− $machine->screenshot("emacsclient");
46+ machine.screenshot("emacsclient")
4447 '';
4548})
nixos/tests/gitea.nix+16−14
@@ -3,7 +3,7 @@
33 pkgs ? import ../.. { inherit system config; }
44}:
55
6−with import ../lib/testing.nix { inherit system pkgs; };
6+with import ../lib/testing-python.nix { inherit system pkgs; };
77with pkgs.lib;
88
99{
@@ -18,11 +18,11 @@ with pkgs.lib;
1818 };
1919
2020 testScript = ''
21− startAll;
21+ start_all()
2222
23− $machine->waitForUnit('gitea.service');
24− $machine->waitForOpenPort('3000');
25− $machine->succeed("curl --fail http://localhost:3000/");
23+ machine.wait_for_unit("gitea.service")
24+ machine.wait_for_open_port(3000)
25+ machine.succeed("curl --fail http://localhost:3000/")
2626 '';
2727 };
2828
@@ -37,11 +37,11 @@ with pkgs.lib;
3737 };
3838
3939 testScript = ''
40− startAll;
40+ start_all()
4141
42− $machine->waitForUnit('gitea.service');
43− $machine->waitForOpenPort('3000');
44− $machine->succeed("curl --fail http://localhost:3000/");
42+ machine.wait_for_unit("gitea.service")
43+ machine.wait_for_open_port(3000)
44+ machine.succeed("curl --fail http://localhost:3000/")
4545 '';
4646 };
4747
@@ -56,12 +56,14 @@ with pkgs.lib;
5656 };
5757
5858 testScript = ''
59− startAll;
59+ start_all()
6060
61− $machine->waitForUnit('gitea.service');
62− $machine->waitForOpenPort('3000');
63− $machine->succeed("curl --fail http://localhost:3000/");
64− $machine->succeed("curl --fail http://localhost:3000/user/sign_up | grep 'Registration is disabled. Please contact your site administrator.'");
61+ machine.wait_for_unit("gitea.service")
62+ machine.wait_for_open_port(3000)
63+ machine.succeed("curl --fail http://localhost:3000/")
64+ machine.succeed(
65+ "curl --fail http://localhost:3000/user/sign_up | grep 'Registration is disabled. Please contact your site administrator.'"
66+ )
6567 '';
6668 };
6769}
nixos/tests/login.nix+45−59
@@ -1,4 +1,4 @@
1−import ./make-test.nix ({ pkgs, latestKernel ? false, ... }:
1+import ./make-test-python.nix ({ pkgs, latestKernel ? false, ... }:
22
33{
44 name = "login";
@@ -12,62 +12,48 @@ import ./make-test.nix ({ pkgs, latestKernel ? false, ... }:
1212 sound.enable = true; # needed for the factl test, /dev/snd/* exists without them but udev doesn't care then
1313 };
1414
15− testScript =
16− ''
17− $machine->waitForUnit('multi-user.target');
18− $machine->waitUntilSucceeds("pgrep -f 'agetty.*tty1'");
19− $machine->screenshot("postboot");
20−
21− subtest "create user", sub {
22− $machine->succeed("useradd -m alice");
23− $machine->succeed("(echo foobar; echo foobar) | passwd alice");
24− };
25−
26− # Check whether switching VTs works.
27− subtest "virtual console switching", sub {
28− $machine->fail("pgrep -f 'agetty.*tty2'");
29− $machine->sendKeys("alt-f2");
30− $machine->waitUntilSucceeds("[ \$(fgconsole) = 2 ]");
31− $machine->waitForUnit('getty@tty2.service');
32− $machine->waitUntilSucceeds("pgrep -f 'agetty.*tty2'");
33− };
34−
35− # Log in as alice on a virtual console.
36− subtest "virtual console login", sub {
37− $machine->waitUntilTTYMatches(2, "login: ");
38− $machine->sendChars("alice\n");
39− $machine->waitUntilTTYMatches(2, "login: alice");
40− $machine->waitUntilSucceeds("pgrep login");
41− $machine->waitUntilTTYMatches(2, "Password: ");
42− $machine->sendChars("foobar\n");
43− $machine->waitUntilSucceeds("pgrep -u alice bash");
44− $machine->sendChars("touch done\n");
45− $machine->waitForFile("/home/alice/done");
46− };
47−
48− # Check whether systemd gives and removes device ownership as
49− # needed.
50− subtest "device permissions", sub {
51− $machine->succeed("getfacl -p /dev/snd/timer | grep -q alice");
52− $machine->sendKeys("alt-f1");
53− $machine->waitUntilSucceeds("[ \$(fgconsole) = 1 ]");
54− $machine->fail("getfacl -p /dev/snd/timer | grep -q alice");
55− $machine->succeed("chvt 2");
56− $machine->waitUntilSucceeds("getfacl -p /dev/snd/timer | grep -q alice");
57− };
58−
59− # Log out.
60− subtest "virtual console logout", sub {
61− $machine->sendChars("exit\n");
62− $machine->waitUntilFails("pgrep -u alice bash");
63− $machine->screenshot("mingetty");
64− };
65−
66− # Check whether ctrl-alt-delete works.
67− subtest "ctrl-alt-delete", sub {
68− $machine->sendKeys("ctrl-alt-delete");
69− $machine->waitForShutdown;
70− };
71− '';
72−
15+ testScript = ''
16+ machine.wait_for_unit("multi-user.target")
17+ machine.wait_until_succeeds("pgrep -f 'agetty.*tty1'")
18+ machine.screenshot("postboot")
19+
20+ with subtest("create user"):
21+ machine.succeed("useradd -m alice")
22+ machine.succeed("(echo foobar; echo foobar) | passwd alice")
23+
24+ with subtest("Check whether switching VTs works"):
25+ machine.fail("pgrep -f 'agetty.*tty2'")
26+ machine.send_key("alt-f2")
27+ machine.wait_until_succeeds("[ $(fgconsole) = 2 ]")
28+ machine.wait_for_unit("getty@tty2.service")
29+ machine.wait_until_succeeds("pgrep -f 'agetty.*tty2'")
30+
31+ with subtest("Log in as alice on a virtual console"):
32+ machine.wait_until_tty_matches(2, "login: ")
33+ machine.send_chars("alice\n")
34+ machine.wait_until_tty_matches(2, "login: alice")
35+ machine.wait_until_succeeds("pgrep login")
36+ machine.wait_until_tty_matches(2, "Password: ")
37+ machine.send_chars("foobar\n")
38+ machine.wait_until_succeeds("pgrep -u alice bash")
39+ machine.send_chars("touch done\n")
40+ machine.wait_for_file("/home/alice/done")
41+
42+ with subtest("Systemd gives and removes device ownership as needed"):
43+ machine.succeed("getfacl /dev/snd/timer | grep -q alice")
44+ machine.send_key("alt-f1")
45+ machine.wait_until_succeeds("[ $(fgconsole) = 1 ]")
46+ machine.fail("getfacl /dev/snd/timer | grep -q alice")
47+ machine.succeed("chvt 2")
48+ machine.wait_until_succeeds("getfacl /dev/snd/timer | grep -q alice")
49+
50+ with subtest("Virtual console logout"):
51+ machine.send_chars("exit\n")
52+ machine.wait_until_fails("pgrep -u alice bash")
53+ machine.screenshot("mingetty")
54+
55+ with subtest("Check whether ctrl-alt-delete works"):
56+ machine.send_key("ctrl-alt-delete")
57+ machine.wait_for_shutdown()
58+ '';
7359})
nixos/tests/make-test-python.nixnew file+9
@@ -0,0 +1,9 @@
1+f: {
2+ system ? builtins.currentSystem,
3+ pkgs ? import ../.. { inherit system; config = {}; },
4+ ...
5+} @ args:
6+
7+with import ../lib/testing-python.nix { inherit system pkgs; };
8+
9+makeTest (if pkgs.lib.isFunction f then f (args // { inherit pkgs; inherit (pkgs) lib; }) else f)
nixos/tests/postgresql.nix+24−20
@@ -3,7 +3,7 @@
33 pkgs ? import ../.. { inherit system config; }
44}:
55
6−with import ../lib/testing.nix { inherit system pkgs; };
6+with import ../lib/testing-python.nix { inherit system pkgs; };
77with pkgs.lib;
88
99let
@@ -40,29 +40,33 @@ let
4040 backupName = if backup-all then "all" else "postgres";
4141 backupService = if backup-all then "postgresqlBackup" else "postgresqlBackup-postgres";
4242 in ''
43− sub check_count {
44− my ($select, $nlines) = @_;
45− return 'test $(sudo -u postgres psql postgres -tAc "' . $select . '"|wc -l) -eq ' . $nlines;
46− }
43+ def check_count(statement, lines):
44+ return 'test $(sudo -u postgres psql postgres -tAc "{}"|wc -l) -eq {}'.format(
45+ statement, lines
46+ )
47+
48+
49+ machine.start()
50+ machine.wait_for_unit("postgresql")
4751
48− $machine->start;
49− $machine->waitForUnit("postgresql");
5052 # postgresql should be available just after unit start
51− $machine->succeed("cat ${test-sql} | sudo -u postgres psql");
52− $machine->shutdown; # make sure that postgresql survive restart (bug #1735)
53− sleep(2);
54− $machine->start;
55− $machine->waitForUnit("postgresql");
56− $machine->fail(check_count("SELECT * FROM sth;", 3));
57− $machine->succeed(check_count("SELECT * FROM sth;", 5));
58− $machine->fail(check_count("SELECT * FROM sth;", 4));
59− $machine->succeed(check_count("SELECT xpath(\'/test/text()\', doc) FROM xmltest;", 1));
53+ machine.succeed(
54+ "cat ${test-sql} | sudo -u postgres psql"
55+ )
56+ machine.shutdown() # make sure that postgresql survive restart (bug #1735)
57+ time.sleep(2)
58+ machine.start()
59+ machine.wait_for_unit("postgresql")
60+ machine.fail(check_count("SELECT * FROM sth;", 3))
61+ machine.succeed(check_count("SELECT * FROM sth;", 5))
62+ machine.fail(check_count("SELECT * FROM sth;", 4))
63+ machine.succeed(check_count("SELECT xpath('/test/text()', doc) FROM xmltest;", 1))
6064
6165 # Check backup service
62− $machine->succeed("systemctl start ${backupService}.service");
63− $machine->succeed("zcat /var/backup/postgresql/${backupName}.sql.gz | grep '<test>ok</test>'");
64− $machine->succeed("stat -c '%a' /var/backup/postgresql/${backupName}.sql.gz | grep 600");
65− $machine->shutdown;
66+ machine.succeed("systemctl start ${backupService}.service")
67+ machine.succeed("zcat /var/backup/postgresql/${backupName}.sql.gz | grep '<test>ok</test>'")
68+ machine.succeed("stat -c '%a' /var/backup/postgresql/${backupName}.sql.gz | grep 600")
69+ machine.shutdown()
6670 '';
6771
6872 };
nixos/tests/quake3.nix+21−21
@@ -1,4 +1,4 @@
1−import ./make-test.nix ({ pkgs, ...} :
1+import ./make-test-python.nix ({ pkgs, ...} :
22
33let
44
@@ -59,37 +59,37 @@ rec {
5959
6060 testScript =
6161 ''
62− startAll;
62+ start_all()
6363
64− $server->waitForUnit("quake3-server");
65− $client1->waitForX;
66− $client2->waitForX;
64+ server.wait_for_unit("quake3-server")
65+ client1.wait_for_x()
66+ client2.wait_for_x()
6767
68− $client1->execute("quake3 +set r_fullscreen 0 +set name Foo +connect server &");
69− $client2->execute("quake3 +set r_fullscreen 0 +set name Bar +connect server &");
68+ client1.execute("quake3 +set r_fullscreen 0 +set name Foo +connect server &")
69+ client2.execute("quake3 +set r_fullscreen 0 +set name Bar +connect server &")
7070
71− $server->waitUntilSucceeds("grep -q 'Foo.*entered the game' /tmp/log");
72− $server->waitUntilSucceeds("grep -q 'Bar.*entered the game' /tmp/log");
71+ server.wait_until_succeeds("grep -q 'Foo.*entered the game' /tmp/log")
72+ server.wait_until_succeeds("grep -q 'Bar.*entered the game' /tmp/log")
7373
74− $server->sleep(10); # wait for a while to get a nice screenshot
74+ server.sleep(10) # wait for a while to get a nice screenshot
7575
76− $client1->block();
76+ client1.block()
7777
78− $server->sleep(20);
78+ server.sleep(20)
7979
80− $client1->screenshot("screen1");
81− $client2->screenshot("screen2");
80+ client1.screenshot("screen1")
81+ client2.screenshot("screen2")
8282
83− $client1->unblock();
83+ client1.unblock()
8484
85− $server->sleep(10);
85+ server.sleep(10)
8686
87− $client1->screenshot("screen3");
88− $client2->screenshot("screen4");
87+ client1.screenshot("screen3")
88+ client2.screenshot("screen4")
8989
90− $client1->shutdown();
91− $client2->shutdown();
92− $server->stopJob("quake3-server");
90+ client1.shutdown()
91+ client2.shutdown()
92+ server.stop_job("quake3-server")
9393 '';
9494
9595})
nixos/tests/wireguard/default.nix+6−6
@@ -2,7 +2,7 @@ let
22 wg-snakeoil-keys = import ./snakeoil-keys.nix;
33in
44
5−import ../make-test.nix ({ pkgs, ...} : {
5+import ../make-test-python.nix ({ pkgs, ...} : {
66 name = "wireguard";
77 meta = with pkgs.stdenv.lib.maintainers; {
88 maintainers = [ ma27 ];
@@ -86,12 +86,12 @@ import ../make-test.nix ({ pkgs, ...} : {
8686 };
8787
8888 testScript = ''
89− startAll;
89+ start_all()
9090
91− $peer0->waitForUnit("wireguard-wg0.service");
92− $peer1->waitForUnit("wireguard-wg0.service");
91+ peer0.wait_for_unit("wireguard-wg0.service")
92+ peer1.wait_for_unit("wireguard-wg0.service")
9393
94− $peer1->succeed("ping -c5 fc00::1");
95− $peer1->succeed("ping -c5 10.23.42.1")
94+ peer1.succeed("ping -c5 fc00::1")
95+ peer1.succeed("ping -c5 10.23.42.1")
9696 '';
9797})
nixos/tests/wireguard/generated.nix+30−26
@@ -1,4 +1,4 @@
1−import ../make-test.nix ({ pkgs, ...} : {
1+import ../make-test-python.nix ({ pkgs, ...} : {
22 name = "wireguard-generated";
33 meta = with pkgs.stdenv.lib.maintainers; {
44 maintainers = [ ma27 grahamc ];
@@ -28,30 +28,34 @@ import ../make-test.nix ({ pkgs, ...} : {
2828 };
2929
3030 testScript = ''
31− startAll;
32−
33− $peer1->waitForUnit("wireguard-wg0.service");
34− $peer2->waitForUnit("wireguard-wg0.service");
35−
36− my ($retcode, $peer1pubkey) = $peer1->execute("wg pubkey < /etc/wireguard/private");
37− $peer1pubkey =~ s/\s+$//;
38− if ($retcode != 0) {
39− die "Could not read public key from peer1";
40− }
41−
42− my ($retcode, $peer2pubkey) = $peer2->execute("wg pubkey < /etc/wireguard/private");
43− $peer2pubkey =~ s/\s+$//;
44− if ($retcode != 0) {
45− die "Could not read public key from peer2";
46− }
47−
48− $peer1->succeed("wg set wg0 peer $peer2pubkey allowed-ips 10.10.10.2/32 endpoint 192.168.1.2:12345 persistent-keepalive 1");
49− $peer1->succeed("ip route replace 10.10.10.2/32 dev wg0 table main");
50−
51− $peer2->succeed("wg set wg0 peer $peer1pubkey allowed-ips 10.10.10.1/32 endpoint 192.168.1.1:12345 persistent-keepalive 1");
52− $peer2->succeed("ip route replace 10.10.10.1/32 dev wg0 table main");
53−
54− $peer1->succeed("ping -c1 10.10.10.2");
55− $peer2->succeed("ping -c1 10.10.10.1");
31+ start_all()
32+
33+ peer1.wait_for_unit("wireguard-wg0.service")
34+ peer2.wait_for_unit("wireguard-wg0.service")
35+
36+ retcode, peer1pubkey = peer1.execute("wg pubkey < /etc/wireguard/private")
37+ if retcode != 0:
38+ raise Exception("Could not read public key from peer1")
39+
40+ retcode, peer2pubkey = peer2.execute("wg pubkey < /etc/wireguard/private")
41+ if retcode != 0:
42+ raise Exception("Could not read public key from peer2")
43+
44+ peer1.succeed(
45+ "wg set wg0 peer {} allowed-ips 10.10.10.2/32 endpoint 192.168.1.2:12345 persistent-keepalive 1".format(
46+ peer2pubkey.strip()
47+ )
48+ )
49+ peer1.succeed("ip route replace 10.10.10.2/32 dev wg0 table main")
50+
51+ peer2.succeed(
52+ "wg set wg0 peer {} allowed-ips 10.10.10.1/32 endpoint 192.168.1.1:12345 persistent-keepalive 1".format(
53+ peer1pubkey.strip()
54+ )
55+ )
56+ peer2.succeed("ip route replace 10.10.10.1/32 dev wg0 table main")
57+
58+ peer1.succeed("ping -c1 10.10.10.2")
59+ peer2.succeed("ping -c1 10.10.10.1")
5660 '';
5761})
nixos/tests/zfs.nix+9−11
@@ -7,7 +7,7 @@ with import ../lib/testing.nix { inherit system pkgs; };
77
88let
99
10− makeTest = import ./make-test.nix;
10+ makeTest = import ./make-test-python.nix;
1111
1212 makeZfsTest = name:
1313 { kernelPackage ? pkgs.linuxPackages_latest
@@ -34,12 +34,12 @@ let
3434 };
3535
3636 testScript = ''
37− $machine->succeed("modprobe zfs");
38− $machine->succeed("zpool status");
37+ machine.succeed("modprobe zfs")
38+ machine.succeed("zpool status")
3939
40− $machine->succeed("ls /dev");
40+ machine.succeed("ls /dev")
4141
42− $machine->succeed(
42+ machine.succeed(
4343 "mkdir /tmp/mnt",
4444
4545 "udevadm settle",
@@ -55,9 +55,7 @@ let
5555 "umount /tmp/mnt",
5656 "zpool destroy rpool",
5757 "udevadm settle"
58−
59− );
60−
58+ )
6159 '' + extraTest;
6260
6361 };
@@ -70,8 +68,8 @@ in {
7068 unstable = makeZfsTest "unstable" {
7169 enableUnstable = true;
7270 extraTest = ''
73− $machine->succeed(
74− "echo password | zpool create -o altroot='/tmp/mnt' -O encryption=aes-256-gcm -O keyformat=passphrase rpool /dev/vdb1",
71+ machine.succeed(
72+ "echo password | zpool create -o altroot=\"/tmp/mnt\" -O encryption=aes-256-gcm -O keyformat=passphrase rpool /dev/vdb1",
7573 "zfs create -o mountpoint=legacy rpool/root",
7674 "mount -t zfs rpool/root /tmp/mnt",
7775 "udevadm settle",
@@ -79,7 +77,7 @@ in {
7977 "umount /tmp/mnt",
8078 "zpool destroy rpool",
8179 "udevadm settle"
82− );
80+ )
8381 '';
8482 };
8583