]> git.proxmox.com Git - mirror_qemu.git/blob - docs/devel/testing.rst
Merge remote-tracking branch 'remotes/vivier/tags/m68k-for-6.0-pull-request' into...
[mirror_qemu.git] / docs / devel / testing.rst
1 ===============
2 Testing in QEMU
3 ===============
4
5 This document describes the testing infrastructure in QEMU.
6
7 Testing with "make check"
8 =========================
9
10 The "make check" testing family includes most of the C based tests in QEMU. For
11 a quick help, run ``make check-help`` from the source tree.
12
13 The usual way to run these tests is:
14
15 .. code::
16
17 make check
18
19 which includes QAPI schema tests, unit tests, QTests and some iotests.
20 Different sub-types of "make check" tests will be explained below.
21
22 Before running tests, it is best to build QEMU programs first. Some tests
23 expect the executables to exist and will fail with obscure messages if they
24 cannot find them.
25
26 Unit tests
27 ----------
28
29 Unit tests, which can be invoked with ``make check-unit``, are simple C tests
30 that typically link to individual QEMU object files and exercise them by
31 calling exported functions.
32
33 If you are writing new code in QEMU, consider adding a unit test, especially
34 for utility modules that are relatively stateless or have few dependencies. To
35 add a new unit test:
36
37 1. Create a new source file. For example, ``tests/foo-test.c``.
38
39 2. Write the test. Normally you would include the header file which exports
40 the module API, then verify the interface behaves as expected from your
41 test. The test code should be organized with the glib testing framework.
42 Copying and modifying an existing test is usually a good idea.
43
44 3. Add the test to ``tests/meson.build``. The unit tests are listed in a
45 dictionary called ``tests``. The values are any additional sources and
46 dependencies to be linked with the test. For a simple test whose source
47 is in ``tests/foo-test.c``, it is enough to add an entry like::
48
49 {
50 ...
51 'foo-test': [],
52 ...
53 }
54
55 Since unit tests don't require environment variables, the simplest way to debug
56 a unit test failure is often directly invoking it or even running it under
57 ``gdb``. However there can still be differences in behavior between ``make``
58 invocations and your manual run, due to ``$MALLOC_PERTURB_`` environment
59 variable (which affects memory reclamation and catches invalid pointers better)
60 and gtester options. If necessary, you can run
61
62 .. code::
63
64 make check-unit V=1
65
66 and copy the actual command line which executes the unit test, then run
67 it from the command line.
68
69 QTest
70 -----
71
72 QTest is a device emulation testing framework. It can be very useful to test
73 device models; it could also control certain aspects of QEMU (such as virtual
74 clock stepping), with a special purpose "qtest" protocol. Refer to
75 :doc:`qtest` for more details.
76
77 QTest cases can be executed with
78
79 .. code::
80
81 make check-qtest
82
83 QAPI schema tests
84 -----------------
85
86 The QAPI schema tests validate the QAPI parser used by QMP, by feeding
87 predefined input to the parser and comparing the result with the reference
88 output.
89
90 The input/output data is managed under the ``tests/qapi-schema`` directory.
91 Each test case includes four files that have a common base name:
92
93 * ``${casename}.json`` - the file contains the JSON input for feeding the
94 parser
95 * ``${casename}.out`` - the file contains the expected stdout from the parser
96 * ``${casename}.err`` - the file contains the expected stderr from the parser
97 * ``${casename}.exit`` - the expected error code
98
99 Consider adding a new QAPI schema test when you are making a change on the QAPI
100 parser (either fixing a bug or extending/modifying the syntax). To do this:
101
102 1. Add four files for the new case as explained above. For example:
103
104 ``$EDITOR tests/qapi-schema/foo.{json,out,err,exit}``.
105
106 2. Add the new test in ``tests/Makefile.include``. For example:
107
108 ``qapi-schema += foo.json``
109
110 check-block
111 -----------
112
113 ``make check-block`` runs a subset of the block layer iotests (the tests that
114 are in the "auto" group).
115 See the "QEMU iotests" section below for more information.
116
117 GCC gcov support
118 ----------------
119
120 ``gcov`` is a GCC tool to analyze the testing coverage by
121 instrumenting the tested code. To use it, configure QEMU with
122 ``--enable-gcov`` option and build. Then run ``make check`` as usual.
123
124 If you want to gather coverage information on a single test the ``make
125 clean-gcda`` target can be used to delete any existing coverage
126 information before running a single test.
127
128 You can generate a HTML coverage report by executing ``make
129 coverage-html`` which will create
130 ``meson-logs/coveragereport/index.html``.
131
132 Further analysis can be conducted by running the ``gcov`` command
133 directly on the various .gcda output files. Please read the ``gcov``
134 documentation for more information.
135
136 QEMU iotests
137 ============
138
139 QEMU iotests, under the directory ``tests/qemu-iotests``, is the testing
140 framework widely used to test block layer related features. It is higher level
141 than "make check" tests and 99% of the code is written in bash or Python
142 scripts. The testing success criteria is golden output comparison, and the
143 test files are named with numbers.
144
145 To run iotests, make sure QEMU is built successfully, then switch to the
146 ``tests/qemu-iotests`` directory under the build directory, and run ``./check``
147 with desired arguments from there.
148
149 By default, "raw" format and "file" protocol is used; all tests will be
150 executed, except the unsupported ones. You can override the format and protocol
151 with arguments:
152
153 .. code::
154
155 # test with qcow2 format
156 ./check -qcow2
157 # or test a different protocol
158 ./check -nbd
159
160 It's also possible to list test numbers explicitly:
161
162 .. code::
163
164 # run selected cases with qcow2 format
165 ./check -qcow2 001 030 153
166
167 Cache mode can be selected with the "-c" option, which may help reveal bugs
168 that are specific to certain cache mode.
169
170 More options are supported by the ``./check`` script, run ``./check -h`` for
171 help.
172
173 Writing a new test case
174 -----------------------
175
176 Consider writing a tests case when you are making any changes to the block
177 layer. An iotest case is usually the choice for that. There are already many
178 test cases, so it is possible that extending one of them may achieve the goal
179 and save the boilerplate to create one. (Unfortunately, there isn't a 100%
180 reliable way to find a related one out of hundreds of tests. One approach is
181 using ``git grep``.)
182
183 Usually an iotest case consists of two files. One is an executable that
184 produces output to stdout and stderr, the other is the expected reference
185 output. They are given the same number in file names. E.g. Test script ``055``
186 and reference output ``055.out``.
187
188 In rare cases, when outputs differ between cache mode ``none`` and others, a
189 ``.out.nocache`` file is added. In other cases, when outputs differ between
190 image formats, more than one ``.out`` files are created ending with the
191 respective format names, e.g. ``178.out.qcow2`` and ``178.out.raw``.
192
193 There isn't a hard rule about how to write a test script, but a new test is
194 usually a (copy and) modification of an existing case. There are a few
195 commonly used ways to create a test:
196
197 * A Bash script. It will make use of several environmental variables related
198 to the testing procedure, and could source a group of ``common.*`` libraries
199 for some common helper routines.
200
201 * A Python unittest script. Import ``iotests`` and create a subclass of
202 ``iotests.QMPTestCase``, then call ``iotests.main`` method. The downside of
203 this approach is that the output is too scarce, and the script is considered
204 harder to debug.
205
206 * A simple Python script without using unittest module. This could also import
207 ``iotests`` for launching QEMU and utilities etc, but it doesn't inherit
208 from ``iotests.QMPTestCase`` therefore doesn't use the Python unittest
209 execution. This is a combination of 1 and 2.
210
211 Pick the language per your preference since both Bash and Python have
212 comparable library support for invoking and interacting with QEMU programs. If
213 you opt for Python, it is strongly recommended to write Python 3 compatible
214 code.
215
216 Both Python and Bash frameworks in iotests provide helpers to manage test
217 images. They can be used to create and clean up images under the test
218 directory. If no I/O or any protocol specific feature is needed, it is often
219 more convenient to use the pseudo block driver, ``null-co://``, as the test
220 image, which doesn't require image creation or cleaning up. Avoid system-wide
221 devices or files whenever possible, such as ``/dev/null`` or ``/dev/zero``.
222 Otherwise, image locking implications have to be considered. For example,
223 another application on the host may have locked the file, possibly leading to a
224 test failure. If using such devices are explicitly desired, consider adding
225 ``locking=off`` option to disable image locking.
226
227 Test case groups
228 ----------------
229
230 "Tests may belong to one or more test groups, which are defined in the form
231 of a comment in the test source file. By convention, test groups are listed
232 in the second line of the test file, after the "#!/..." line, like this:
233
234 .. code::
235
236 #!/usr/bin/env python3
237 # group: auto quick
238 #
239 ...
240
241 Another way of defining groups is creating the tests/qemu-iotests/group.local
242 file. This should be used only for downstream (this file should never appear
243 in upstream). This file may be used for defining some downstream test groups
244 or for temporarily disabling tests, like this:
245
246 .. code::
247
248 # groups for some company downstream process
249 #
250 # ci - tests to run on build
251 # down - our downstream tests, not for upstream
252 #
253 # Format of each line is:
254 # TEST_NAME TEST_GROUP [TEST_GROUP ]...
255
256 013 ci
257 210 disabled
258 215 disabled
259 our-ugly-workaround-test down ci
260
261 Note that the following group names have a special meaning:
262
263 - quick: Tests in this group should finish within a few seconds.
264
265 - auto: Tests in this group are used during "make check" and should be
266 runnable in any case. That means they should run with every QEMU binary
267 (also non-x86), with every QEMU configuration (i.e. must not fail if
268 an optional feature is not compiled in - but reporting a "skip" is ok),
269 work at least with the qcow2 file format, work with all kind of host
270 filesystems and users (e.g. "nobody" or "root") and must not take too
271 much memory and disk space (since CI pipelines tend to fail otherwise).
272
273 - disabled: Tests in this group are disabled and ignored by check.
274
275 .. _docker-ref:
276
277 Docker based tests
278 ==================
279
280 Introduction
281 ------------
282
283 The Docker testing framework in QEMU utilizes public Docker images to build and
284 test QEMU in predefined and widely accessible Linux environments. This makes
285 it possible to expand the test coverage across distros, toolchain flavors and
286 library versions.
287
288 Prerequisites
289 -------------
290
291 Install "docker" with the system package manager and start the Docker service
292 on your development machine, then make sure you have the privilege to run
293 Docker commands. Typically it means setting up passwordless ``sudo docker``
294 command or login as root. For example:
295
296 .. code::
297
298 $ sudo yum install docker
299 $ # or `apt-get install docker` for Ubuntu, etc.
300 $ sudo systemctl start docker
301 $ sudo docker ps
302
303 The last command should print an empty table, to verify the system is ready.
304
305 An alternative method to set up permissions is by adding the current user to
306 "docker" group and making the docker daemon socket file (by default
307 ``/var/run/docker.sock``) accessible to the group:
308
309 .. code::
310
311 $ sudo groupadd docker
312 $ sudo usermod $USER -a -G docker
313 $ sudo chown :docker /var/run/docker.sock
314
315 Note that any one of above configurations makes it possible for the user to
316 exploit the whole host with Docker bind mounting or other privileged
317 operations. So only do it on development machines.
318
319 Quickstart
320 ----------
321
322 From source tree, type ``make docker`` to see the help. Testing can be started
323 without configuring or building QEMU (``configure`` and ``make`` are done in
324 the container, with parameters defined by the make target):
325
326 .. code::
327
328 make docker-test-build@min-glib
329
330 This will create a container instance using the ``min-glib`` image (the image
331 is downloaded and initialized automatically), in which the ``test-build`` job
332 is executed.
333
334 Images
335 ------
336
337 Along with many other images, the ``min-glib`` image is defined in a Dockerfile
338 in ``tests/docker/dockerfiles/``, called ``min-glib.docker``. ``make docker``
339 command will list all the available images.
340
341 To add a new image, simply create a new ``.docker`` file under the
342 ``tests/docker/dockerfiles/`` directory.
343
344 A ``.pre`` script can be added beside the ``.docker`` file, which will be
345 executed before building the image under the build context directory. This is
346 mainly used to do necessary host side setup. One such setup is ``binfmt_misc``,
347 for example, to make qemu-user powered cross build containers work.
348
349 Tests
350 -----
351
352 Different tests are added to cover various configurations to build and test
353 QEMU. Docker tests are the executables under ``tests/docker`` named
354 ``test-*``. They are typically shell scripts and are built on top of a shell
355 library, ``tests/docker/common.rc``, which provides helpers to find the QEMU
356 source and build it.
357
358 The full list of tests is printed in the ``make docker`` help.
359
360 Tools
361 -----
362
363 There are executables that are created to run in a specific Docker environment.
364 This makes it easy to write scripts that have heavy or special dependencies,
365 but are still very easy to use.
366
367 Currently the only tool is ``travis``, which mimics the Travis-CI tests in a
368 container. It runs in the ``travis`` image:
369
370 .. code::
371
372 make docker-travis@travis
373
374 Debugging a Docker test failure
375 -------------------------------
376
377 When CI tasks, maintainers or yourself report a Docker test failure, follow the
378 below steps to debug it:
379
380 1. Locally reproduce the failure with the reported command line. E.g. run
381 ``make docker-test-mingw@fedora J=8``.
382 2. Add "V=1" to the command line, try again, to see the verbose output.
383 3. Further add "DEBUG=1" to the command line. This will pause in a shell prompt
384 in the container right before testing starts. You could either manually
385 build QEMU and run tests from there, or press Ctrl-D to let the Docker
386 testing continue.
387 4. If you press Ctrl-D, the same building and testing procedure will begin, and
388 will hopefully run into the error again. After that, you will be dropped to
389 the prompt for debug.
390
391 Options
392 -------
393
394 Various options can be used to affect how Docker tests are done. The full
395 list is in the ``make docker`` help text. The frequently used ones are:
396
397 * ``V=1``: the same as in top level ``make``. It will be propagated to the
398 container and enable verbose output.
399 * ``J=$N``: the number of parallel tasks in make commands in the container,
400 similar to the ``-j $N`` option in top level ``make``. (The ``-j`` option in
401 top level ``make`` will not be propagated into the container.)
402 * ``DEBUG=1``: enables debug. See the previous "Debugging a Docker test
403 failure" section.
404
405 Thread Sanitizer
406 ================
407
408 Thread Sanitizer (TSan) is a tool which can detect data races. QEMU supports
409 building and testing with this tool.
410
411 For more information on TSan:
412
413 https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual
414
415 Thread Sanitizer in Docker
416 ---------------------------
417 TSan is currently supported in the ubuntu2004 docker.
418
419 The test-tsan test will build using TSan and then run make check.
420
421 .. code::
422
423 make docker-test-tsan@ubuntu2004
424
425 TSan warnings under docker are placed in files located at build/tsan/.
426
427 We recommend using DEBUG=1 to allow launching the test from inside the docker,
428 and to allow review of the warnings generated by TSan.
429
430 Building and Testing with TSan
431 ------------------------------
432
433 It is possible to build and test with TSan, with a few additional steps.
434 These steps are normally done automatically in the docker.
435
436 There is a one time patch needed in clang-9 or clang-10 at this time:
437
438 .. code::
439
440 sed -i 's/^const/static const/g' \
441 /usr/lib/llvm-10/lib/clang/10.0.0/include/sanitizer/tsan_interface.h
442
443 To configure the build for TSan:
444
445 .. code::
446
447 ../configure --enable-tsan --cc=clang-10 --cxx=clang++-10 \
448 --disable-werror --extra-cflags="-O0"
449
450 The runtime behavior of TSAN is controlled by the TSAN_OPTIONS environment
451 variable.
452
453 More information on the TSAN_OPTIONS can be found here:
454
455 https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags
456
457 For example:
458
459 .. code::
460
461 export TSAN_OPTIONS=suppressions=<path to qemu>/tests/tsan/suppressions.tsan \
462 detect_deadlocks=false history_size=7 exitcode=0 \
463 log_path=<build path>/tsan/tsan_warning
464
465 The above exitcode=0 has TSan continue without error if any warnings are found.
466 This allows for running the test and then checking the warnings afterwards.
467 If you want TSan to stop and exit with error on warnings, use exitcode=66.
468
469 TSan Suppressions
470 -----------------
471 Keep in mind that for any data race warning, although there might be a data race
472 detected by TSan, there might be no actual bug here. TSan provides several
473 different mechanisms for suppressing warnings. In general it is recommended
474 to fix the code if possible to eliminate the data race rather than suppress
475 the warning.
476
477 A few important files for suppressing warnings are:
478
479 tests/tsan/suppressions.tsan - Has TSan warnings we wish to suppress at runtime.
480 The comment on each suppression will typically indicate why we are
481 suppressing it. More information on the file format can be found here:
482
483 https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions
484
485 tests/tsan/blacklist.tsan - Has TSan warnings we wish to disable
486 at compile time for test or debug.
487 Add flags to configure to enable:
488
489 "--extra-cflags=-fsanitize-blacklist=<src path>/tests/tsan/blacklist.tsan"
490
491 More information on the file format can be found here under "Blacklist Format":
492
493 https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags
494
495 TSan Annotations
496 ----------------
497 include/qemu/tsan.h defines annotations. See this file for more descriptions
498 of the annotations themselves. Annotations can be used to suppress
499 TSan warnings or give TSan more information so that it can detect proper
500 relationships between accesses of data.
501
502 Annotation examples can be found here:
503
504 https://github.com/llvm/llvm-project/tree/master/compiler-rt/test/tsan/
505
506 Good files to start with are: annotate_happens_before.cpp and ignore_race.cpp
507
508 The full set of annotations can be found here:
509
510 https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/tsan/rtl/tsan_interface_ann.cpp
511
512 VM testing
513 ==========
514
515 This test suite contains scripts that bootstrap various guest images that have
516 necessary packages to build QEMU. The basic usage is documented in ``Makefile``
517 help which is displayed with ``make vm-help``.
518
519 Quickstart
520 ----------
521
522 Run ``make vm-help`` to list available make targets. Invoke a specific make
523 command to run build test in an image. For example, ``make vm-build-freebsd``
524 will build the source tree in the FreeBSD image. The command can be executed
525 from either the source tree or the build dir; if the former, ``./configure`` is
526 not needed. The command will then generate the test image in ``./tests/vm/``
527 under the working directory.
528
529 Note: images created by the scripts accept a well-known RSA key pair for SSH
530 access, so they SHOULD NOT be exposed to external interfaces if you are
531 concerned about attackers taking control of the guest and potentially
532 exploiting a QEMU security bug to compromise the host.
533
534 QEMU binaries
535 -------------
536
537 By default, qemu-system-x86_64 is searched in $PATH to run the guest. If there
538 isn't one, or if it is older than 2.10, the test won't work. In this case,
539 provide the QEMU binary in env var: ``QEMU=/path/to/qemu-2.10+``.
540
541 Likewise the path to qemu-img can be set in QEMU_IMG environment variable.
542
543 Make jobs
544 ---------
545
546 The ``-j$X`` option in the make command line is not propagated into the VM,
547 specify ``J=$X`` to control the make jobs in the guest.
548
549 Debugging
550 ---------
551
552 Add ``DEBUG=1`` and/or ``V=1`` to the make command to allow interactive
553 debugging and verbose output. If this is not enough, see the next section.
554 ``V=1`` will be propagated down into the make jobs in the guest.
555
556 Manual invocation
557 -----------------
558
559 Each guest script is an executable script with the same command line options.
560 For example to work with the netbsd guest, use ``$QEMU_SRC/tests/vm/netbsd``:
561
562 .. code::
563
564 $ cd $QEMU_SRC/tests/vm
565
566 # To bootstrap the image
567 $ ./netbsd --build-image --image /var/tmp/netbsd.img
568 <...>
569
570 # To run an arbitrary command in guest (the output will not be echoed unless
571 # --debug is added)
572 $ ./netbsd --debug --image /var/tmp/netbsd.img uname -a
573
574 # To build QEMU in guest
575 $ ./netbsd --debug --image /var/tmp/netbsd.img --build-qemu $QEMU_SRC
576
577 # To get to an interactive shell
578 $ ./netbsd --interactive --image /var/tmp/netbsd.img sh
579
580 Adding new guests
581 -----------------
582
583 Please look at existing guest scripts for how to add new guests.
584
585 Most importantly, create a subclass of BaseVM and implement ``build_image()``
586 method and define ``BUILD_SCRIPT``, then finally call ``basevm.main()`` from
587 the script's ``main()``.
588
589 * Usually in ``build_image()``, a template image is downloaded from a
590 predefined URL. ``BaseVM._download_with_cache()`` takes care of the cache and
591 the checksum, so consider using it.
592
593 * Once the image is downloaded, users, SSH server and QEMU build deps should
594 be set up:
595
596 - Root password set to ``BaseVM.ROOT_PASS``
597 - User ``BaseVM.GUEST_USER`` is created, and password set to
598 ``BaseVM.GUEST_PASS``
599 - SSH service is enabled and started on boot,
600 ``$QEMU_SRC/tests/keys/id_rsa.pub`` is added to ssh's ``authorized_keys``
601 file of both root and the normal user
602 - DHCP client service is enabled and started on boot, so that it can
603 automatically configure the virtio-net-pci NIC and communicate with QEMU
604 user net (10.0.2.2)
605 - Necessary packages are installed to untar the source tarball and build
606 QEMU
607
608 * Write a proper ``BUILD_SCRIPT`` template, which should be a shell script that
609 untars a raw virtio-blk block device, which is the tarball data blob of the
610 QEMU source tree, then configure/build it. Running "make check" is also
611 recommended.
612
613 Image fuzzer testing
614 ====================
615
616 An image fuzzer was added to exercise format drivers. Currently only qcow2 is
617 supported. To start the fuzzer, run
618
619 .. code::
620
621 tests/image-fuzzer/runner.py -c '[["qemu-img", "info", "$test_img"]]' /tmp/test qcow2
622
623 Alternatively, some command different from "qemu-img info" can be tested, by
624 changing the ``-c`` option.
625
626 Acceptance tests using the Avocado Framework
627 ============================================
628
629 The ``tests/acceptance`` directory hosts functional tests, also known
630 as acceptance level tests. They're usually higher level tests, and
631 may interact with external resources and with various guest operating
632 systems.
633
634 These tests are written using the Avocado Testing Framework (which must
635 be installed separately) in conjunction with a the ``avocado_qemu.Test``
636 class, implemented at ``tests/acceptance/avocado_qemu``.
637
638 Tests based on ``avocado_qemu.Test`` can easily:
639
640 * Customize the command line arguments given to the convenience
641 ``self.vm`` attribute (a QEMUMachine instance)
642
643 * Interact with the QEMU monitor, send QMP commands and check
644 their results
645
646 * Interact with the guest OS, using the convenience console device
647 (which may be useful to assert the effectiveness and correctness of
648 command line arguments or QMP commands)
649
650 * Interact with external data files that accompany the test itself
651 (see ``self.get_data()``)
652
653 * Download (and cache) remote data files, such as firmware and kernel
654 images
655
656 * Have access to a library of guest OS images (by means of the
657 ``avocado.utils.vmimage`` library)
658
659 * Make use of various other test related utilities available at the
660 test class itself and at the utility library:
661
662 - http://avocado-framework.readthedocs.io/en/latest/api/test/avocado.html#avocado.Test
663 - http://avocado-framework.readthedocs.io/en/latest/api/utils/avocado.utils.html
664
665 Running tests
666 -------------
667
668 You can run the acceptance tests simply by executing:
669
670 .. code::
671
672 make check-acceptance
673
674 This involves the automatic creation of Python virtual environment
675 within the build tree (at ``tests/venv``) which will have all the
676 right dependencies, and will save tests results also within the
677 build tree (at ``tests/results``).
678
679 Note: the build environment must be using a Python 3 stack, and have
680 the ``venv`` and ``pip`` packages installed. If necessary, make sure
681 ``configure`` is called with ``--python=`` and that those modules are
682 available. On Debian and Ubuntu based systems, depending on the
683 specific version, they may be on packages named ``python3-venv`` and
684 ``python3-pip``.
685
686 The scripts installed inside the virtual environment may be used
687 without an "activation". For instance, the Avocado test runner
688 may be invoked by running:
689
690 .. code::
691
692 tests/venv/bin/avocado run $OPTION1 $OPTION2 tests/acceptance/
693
694 Manual Installation
695 -------------------
696
697 To manually install Avocado and its dependencies, run:
698
699 .. code::
700
701 pip install --user avocado-framework
702
703 Alternatively, follow the instructions on this link:
704
705 https://avocado-framework.readthedocs.io/en/latest/guides/user/chapters/installing.html
706
707 Overview
708 --------
709
710 The ``tests/acceptance/avocado_qemu`` directory provides the
711 ``avocado_qemu`` Python module, containing the ``avocado_qemu.Test``
712 class. Here's a simple usage example:
713
714 .. code::
715
716 from avocado_qemu import Test
717
718
719 class Version(Test):
720 """
721 :avocado: tags=quick
722 """
723 def test_qmp_human_info_version(self):
724 self.vm.launch()
725 res = self.vm.command('human-monitor-command',
726 command_line='info version')
727 self.assertRegexpMatches(res, r'^(\d+\.\d+\.\d)')
728
729 To execute your test, run:
730
731 .. code::
732
733 avocado run version.py
734
735 Tests may be classified according to a convention by using docstring
736 directives such as ``:avocado: tags=TAG1,TAG2``. To run all tests
737 in the current directory, tagged as "quick", run:
738
739 .. code::
740
741 avocado run -t quick .
742
743 The ``avocado_qemu.Test`` base test class
744 -----------------------------------------
745
746 The ``avocado_qemu.Test`` class has a number of characteristics that
747 are worth being mentioned right away.
748
749 First of all, it attempts to give each test a ready to use QEMUMachine
750 instance, available at ``self.vm``. Because many tests will tweak the
751 QEMU command line, launching the QEMUMachine (by using ``self.vm.launch()``)
752 is left to the test writer.
753
754 The base test class has also support for tests with more than one
755 QEMUMachine. The way to get machines is through the ``self.get_vm()``
756 method which will return a QEMUMachine instance. The ``self.get_vm()``
757 method accepts arguments that will be passed to the QEMUMachine creation
758 and also an optional `name` attribute so you can identify a specific
759 machine and get it more than once through the tests methods. A simple
760 and hypothetical example follows:
761
762 .. code::
763
764 from avocado_qemu import Test
765
766
767 class MultipleMachines(Test):
768 def test_multiple_machines(self):
769 first_machine = self.get_vm()
770 second_machine = self.get_vm()
771 self.get_vm(name='third_machine').launch()
772
773 first_machine.launch()
774 second_machine.launch()
775
776 first_res = first_machine.command(
777 'human-monitor-command',
778 command_line='info version')
779
780 second_res = second_machine.command(
781 'human-monitor-command',
782 command_line='info version')
783
784 third_res = self.get_vm(name='third_machine').command(
785 'human-monitor-command',
786 command_line='info version')
787
788 self.assertEquals(first_res, second_res, third_res)
789
790 At test "tear down", ``avocado_qemu.Test`` handles all the QEMUMachines
791 shutdown.
792
793 QEMUMachine
794 ~~~~~~~~~~~
795
796 The QEMUMachine API is already widely used in the Python iotests,
797 device-crash-test and other Python scripts. It's a wrapper around the
798 execution of a QEMU binary, giving its users:
799
800 * the ability to set command line arguments to be given to the QEMU
801 binary
802
803 * a ready to use QMP connection and interface, which can be used to
804 send commands and inspect its results, as well as asynchronous
805 events
806
807 * convenience methods to set commonly used command line arguments in
808 a more succinct and intuitive way
809
810 QEMU binary selection
811 ~~~~~~~~~~~~~~~~~~~~~
812
813 The QEMU binary used for the ``self.vm`` QEMUMachine instance will
814 primarily depend on the value of the ``qemu_bin`` parameter. If it's
815 not explicitly set, its default value will be the result of a dynamic
816 probe in the same source tree. A suitable binary will be one that
817 targets the architecture matching host machine.
818
819 Based on this description, test writers will usually rely on one of
820 the following approaches:
821
822 1) Set ``qemu_bin``, and use the given binary
823
824 2) Do not set ``qemu_bin``, and use a QEMU binary named like
825 "qemu-system-${arch}", either in the current
826 working directory, or in the current source tree.
827
828 The resulting ``qemu_bin`` value will be preserved in the
829 ``avocado_qemu.Test`` as an attribute with the same name.
830
831 Attribute reference
832 -------------------
833
834 Besides the attributes and methods that are part of the base
835 ``avocado.Test`` class, the following attributes are available on any
836 ``avocado_qemu.Test`` instance.
837
838 vm
839 ~~
840
841 A QEMUMachine instance, initially configured according to the given
842 ``qemu_bin`` parameter.
843
844 arch
845 ~~~~
846
847 The architecture can be used on different levels of the stack, e.g. by
848 the framework or by the test itself. At the framework level, it will
849 currently influence the selection of a QEMU binary (when one is not
850 explicitly given).
851
852 Tests are also free to use this attribute value, for their own needs.
853 A test may, for instance, use the same value when selecting the
854 architecture of a kernel or disk image to boot a VM with.
855
856 The ``arch`` attribute will be set to the test parameter of the same
857 name. If one is not given explicitly, it will either be set to
858 ``None``, or, if the test is tagged with one (and only one)
859 ``:avocado: tags=arch:VALUE`` tag, it will be set to ``VALUE``.
860
861 machine
862 ~~~~~~~
863
864 The machine type that will be set to all QEMUMachine instances created
865 by the test.
866
867 The ``machine`` attribute will be set to the test parameter of the same
868 name. If one is not given explicitly, it will either be set to
869 ``None``, or, if the test is tagged with one (and only one)
870 ``:avocado: tags=machine:VALUE`` tag, it will be set to ``VALUE``.
871
872 qemu_bin
873 ~~~~~~~~
874
875 The preserved value of the ``qemu_bin`` parameter or the result of the
876 dynamic probe for a QEMU binary in the current working directory or
877 source tree.
878
879 Parameter reference
880 -------------------
881
882 To understand how Avocado parameters are accessed by tests, and how
883 they can be passed to tests, please refer to::
884
885 https://avocado-framework.readthedocs.io/en/latest/guides/writer/chapters/writing.html#accessing-test-parameters
886
887 Parameter values can be easily seen in the log files, and will look
888 like the following:
889
890 .. code::
891
892 PARAMS (key=qemu_bin, path=*, default=./qemu-system-x86_64) => './qemu-system-x86_64
893
894 arch
895 ~~~~
896
897 The architecture that will influence the selection of a QEMU binary
898 (when one is not explicitly given).
899
900 Tests are also free to use this parameter value, for their own needs.
901 A test may, for instance, use the same value when selecting the
902 architecture of a kernel or disk image to boot a VM with.
903
904 This parameter has a direct relation with the ``arch`` attribute. If
905 not given, it will default to None.
906
907 machine
908 ~~~~~~~
909
910 The machine type that will be set to all QEMUMachine instances created
911 by the test.
912
913
914 qemu_bin
915 ~~~~~~~~
916
917 The exact QEMU binary to be used on QEMUMachine.
918
919 Skipping tests
920 --------------
921 The Avocado framework provides Python decorators which allow for easily skip
922 tests running under certain conditions. For example, on the lack of a binary
923 on the test system or when the running environment is a CI system. For further
924 information about those decorators, please refer to::
925
926 https://avocado-framework.readthedocs.io/en/latest/guides/writer/chapters/writing.html#skipping-tests
927
928 While the conditions for skipping tests are often specifics of each one, there
929 are recurring scenarios identified by the QEMU developers and the use of
930 environment variables became a kind of standard way to enable/disable tests.
931
932 Here is a list of the most used variables:
933
934 AVOCADO_ALLOW_LARGE_STORAGE
935 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
936 Tests which are going to fetch or produce assets considered *large* are not
937 going to run unless that `AVOCADO_ALLOW_LARGE_STORAGE=1` is exported on
938 the environment.
939
940 The definition of *large* is a bit arbitrary here, but it usually means an
941 asset which occupies at least 1GB of size on disk when uncompressed.
942
943 AVOCADO_ALLOW_UNTRUSTED_CODE
944 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
945 There are tests which will boot a kernel image or firmware that can be
946 considered not safe to run on the developer's workstation, thus they are
947 skipped by default. The definition of *not safe* is also arbitrary but
948 usually it means a blob which either its source or build process aren't
949 public available.
950
951 You should export `AVOCADO_ALLOW_UNTRUSTED_CODE=1` on the environment in
952 order to allow tests which make use of those kind of assets.
953
954 AVOCADO_TIMEOUT_EXPECTED
955 ~~~~~~~~~~~~~~~~~~~~~~~~
956 The Avocado framework has a timeout mechanism which interrupts tests to avoid the
957 test suite of getting stuck. The timeout value can be set via test parameter or
958 property defined in the test class, for further details::
959
960 https://avocado-framework.readthedocs.io/en/latest/guides/writer/chapters/writing.html#setting-a-test-timeout
961
962 Even though the timeout can be set by the test developer, there are some tests
963 that may not have a well-defined limit of time to finish under certain
964 conditions. For example, tests that take longer to execute when QEMU is
965 compiled with debug flags. Therefore, the `AVOCADO_TIMEOUT_EXPECTED` variable
966 has been used to determine whether those tests should run or not.
967
968 GITLAB_CI
969 ~~~~~~~~~
970 A number of tests are flagged to not run on the GitLab CI. Usually because
971 they proved to the flaky or there are constraints on the CI environment which
972 would make them fail. If you encounter a similar situation then use that
973 variable as shown on the code snippet below to skip the test:
974
975 .. code::
976
977 @skipIf(os.getenv('GITLAB_CI'), 'Running on GitLab')
978 def test(self):
979 do_something()
980
981 Uninstalling Avocado
982 --------------------
983
984 If you've followed the manual installation instructions above, you can
985 easily uninstall Avocado. Start by listing the packages you have
986 installed::
987
988 pip list --user
989
990 And remove any package you want with::
991
992 pip uninstall <package_name>
993
994 If you've used ``make check-acceptance``, the Python virtual environment where
995 Avocado is installed will be cleaned up as part of ``make check-clean``.
996
997 Testing with "make check-tcg"
998 =============================
999
1000 The check-tcg tests are intended for simple smoke tests of both
1001 linux-user and softmmu TCG functionality. However to build test
1002 programs for guest targets you need to have cross compilers available.
1003 If your distribution supports cross compilers you can do something as
1004 simple as::
1005
1006 apt install gcc-aarch64-linux-gnu
1007
1008 The configure script will automatically pick up their presence.
1009 Sometimes compilers have slightly odd names so the availability of
1010 them can be prompted by passing in the appropriate configure option
1011 for the architecture in question, for example::
1012
1013 $(configure) --cross-cc-aarch64=aarch64-cc
1014
1015 There is also a ``--cross-cc-flags-ARCH`` flag in case additional
1016 compiler flags are needed to build for a given target.
1017
1018 If you have the ability to run containers as the user you can also
1019 take advantage of the build systems "Docker" support. It will then use
1020 containers to build any test case for an enabled guest where there is
1021 no system compiler available. See :ref:`docker-ref` for details.
1022
1023 Running subset of tests
1024 -----------------------
1025
1026 You can build the tests for one architecture::
1027
1028 make build-tcg-tests-$TARGET
1029
1030 And run with::
1031
1032 make run-tcg-tests-$TARGET
1033
1034 Adding ``V=1`` to the invocation will show the details of how to
1035 invoke QEMU for the test which is useful for debugging tests.
1036
1037 TCG test dependencies
1038 ---------------------
1039
1040 The TCG tests are deliberately very light on dependencies and are
1041 either totally bare with minimal gcc lib support (for softmmu tests)
1042 or just glibc (for linux-user tests). This is because getting a cross
1043 compiler to work with additional libraries can be challenging.
1044
1045 Other TCG Tests
1046 ---------------
1047
1048 There are a number of out-of-tree test suites that are used for more
1049 extensive testing of processor features.
1050
1051 KVM Unit Tests
1052 ~~~~~~~~~~~~~~
1053
1054 The KVM unit tests are designed to run as a Guest OS under KVM but
1055 there is no reason why they can't exercise the TCG as well. It
1056 provides a minimal OS kernel with hooks for enabling the MMU as well
1057 as reporting test results via a special device::
1058
1059 https://git.kernel.org/pub/scm/virt/kvm/kvm-unit-tests.git
1060
1061 Linux Test Project
1062 ~~~~~~~~~~~~~~~~~~
1063
1064 The LTP is focused on exercising the syscall interface of a Linux
1065 kernel. It checks that syscalls behave as documented and strives to
1066 exercise as many corner cases as possible. It is a useful test suite
1067 to run to exercise QEMU's linux-user code::
1068
1069 https://linux-test-project.github.io/