]> Git Repo - qemu.git/blob - docs/devel/testing.rst
Merge remote-tracking branch 'remotes/vivier2/tags/linux-user-for-3.0-pull-request...
[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, and QTests. Different sub-types
20 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/Makefile.include``. First, name the unit test
45    program and add it to ``$(check-unit-y)``; then add a rule to build the
46    executable. Optionally, you can add a magical variable to support ``gcov``.
47    For example:
48
49 .. code::
50
51   check-unit-y += tests/foo-test$(EXESUF)
52   tests/foo-test$(EXESUF): tests/foo-test.o $(test-util-obj-y)
53   ...
54   gcov-files-foo-test-y = util/foo.c
55
56 Since unit tests don't require environment variables, the simplest way to debug
57 a unit test failure is often directly invoking it or even running it under
58 ``gdb``. However there can still be differences in behavior between ``make``
59 invocations and your manual run, due to ``$MALLOC_PERTURB_`` environment
60 variable (which affects memory reclamation and catches invalid pointers better)
61 and gtester options. If necessary, you can run
62
63 .. code::
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 the
75 documentation in ``qtest.c`` for more details of the protocol.
76
77 QTest cases can be executed with
78
79 .. code::
80
81    make check-qtest
82
83 The QTest library is implemented by ``tests/libqtest.c`` and the API is defined
84 in ``tests/libqtest.h``.
85
86 Consider adding a new QTest case when you are introducing a new virtual
87 hardware, or extending one if you are adding functionalities to an existing
88 virtual device.
89
90 On top of libqtest, a higher level library, ``libqos``, was created to
91 encapsulate common tasks of device drivers, such as memory management and
92 communicating with system buses or devices. Many virtual device tests use
93 libqos instead of directly calling into libqtest.
94
95 Steps to add a new QTest case are:
96
97 1. Create a new source file for the test. (More than one file can be added as
98    necessary.) For example, ``tests/test-foo-device.c``.
99
100 2. Write the test code with the glib and libqtest/libqos API. See also existing
101    tests and the library headers for reference.
102
103 3. Register the new test in ``tests/Makefile.include``. Add the test executable
104    name to an appropriate ``check-qtest-*-y`` variable. For example:
105
106    ``check-qtest-generic-y = tests/test-foo-device$(EXESUF)``
107
108 4. Add object dependencies of the executable in the Makefile, including the
109    test source file(s) and other interesting objects. For example:
110
111    ``tests/test-foo-device$(EXESUF): tests/test-foo-device.o $(libqos-obj-y)``
112
113 Debugging a QTest failure is slightly harder than the unit test because the
114 tests look up QEMU program names in the environment variables, such as
115 ``QTEST_QEMU_BINARY`` and ``QTEST_QEMU_IMG``, and also because it is not easy
116 to attach gdb to the QEMU process spawned from the test. But manual invoking
117 and using gdb on the test is still simple to do: find out the actual command
118 from the output of
119
120 .. code::
121   make check-qtest V=1
122
123 which you can run manually.
124
125 QAPI schema tests
126 -----------------
127
128 The QAPI schema tests validate the QAPI parser used by QMP, by feeding
129 predefined input to the parser and comparing the result with the reference
130 output.
131
132 The input/output data is managed under the ``tests/qapi-schema`` directory.
133 Each test case includes four files that have a common base name:
134
135   * ``${casename}.json`` - the file contains the JSON input for feeding the
136     parser
137   * ``${casename}.out`` - the file contains the expected stdout from the parser
138   * ``${casename}.err`` - the file contains the expected stderr from the parser
139   * ``${casename}.exit`` - the expected error code
140
141 Consider adding a new QAPI schema test when you are making a change on the QAPI
142 parser (either fixing a bug or extending/modifying the syntax). To do this:
143
144 1. Add four files for the new case as explained above. For example:
145
146   ``$EDITOR tests/qapi-schema/foo.{json,out,err,exit}``.
147
148 2. Add the new test in ``tests/Makefile.include``. For example:
149
150   ``qapi-schema += foo.json``
151
152 check-block
153 -----------
154
155 ``make check-block`` is a legacy command to invoke block layer iotests and is
156 rarely used. See "QEMU iotests" section below for more information.
157
158 GCC gcov support
159 ----------------
160
161 ``gcov`` is a GCC tool to analyze the testing coverage by
162 instrumenting the tested code. To use it, configure QEMU with
163 ``--enable-gcov`` option and build. Then run ``make check`` as usual.
164
165 If you want to gather coverage information on a single test the ``make
166 clean-coverage`` target can be used to delete any existing coverage
167 information before running a single test.
168
169 You can generate a HTML coverage report by executing ``make
170 coverage-report`` which will create
171 ./reports/coverage/coverage-report.html. If you want to create it
172 elsewhere simply execute ``make /foo/bar/baz/coverage-report.html``.
173
174 Further analysis can be conducted by running the ``gcov`` command
175 directly on the various .gcda output files. Please read the ``gcov``
176 documentation for more information.
177
178 QEMU iotests
179 ============
180
181 QEMU iotests, under the directory ``tests/qemu-iotests``, is the testing
182 framework widely used to test block layer related features. It is higher level
183 than "make check" tests and 99% of the code is written in bash or Python
184 scripts.  The testing success criteria is golden output comparison, and the
185 test files are named with numbers.
186
187 To run iotests, make sure QEMU is built successfully, then switch to the
188 ``tests/qemu-iotests`` directory under the build directory, and run ``./check``
189 with desired arguments from there.
190
191 By default, "raw" format and "file" protocol is used; all tests will be
192 executed, except the unsupported ones. You can override the format and protocol
193 with arguments:
194
195 .. code::
196
197   # test with qcow2 format
198   ./check -qcow2
199   # or test a different protocol
200   ./check -nbd
201
202 It's also possible to list test numbers explicitly:
203
204 .. code::
205
206   # run selected cases with qcow2 format
207   ./check -qcow2 001 030 153
208
209 Cache mode can be selected with the "-c" option, which may help reveal bugs
210 that are specific to certain cache mode.
211
212 More options are supported by the ``./check`` script, run ``./check -h`` for
213 help.
214
215 Writing a new test case
216 -----------------------
217
218 Consider writing a tests case when you are making any changes to the block
219 layer. An iotest case is usually the choice for that. There are already many
220 test cases, so it is possible that extending one of them may achieve the goal
221 and save the boilerplate to create one.  (Unfortunately, there isn't a 100%
222 reliable way to find a related one out of hundreds of tests.  One approach is
223 using ``git grep``.)
224
225 Usually an iotest case consists of two files. One is an executable that
226 produces output to stdout and stderr, the other is the expected reference
227 output. They are given the same number in file names. E.g. Test script ``055``
228 and reference output ``055.out``.
229
230 In rare cases, when outputs differ between cache mode ``none`` and others, a
231 ``.out.nocache`` file is added. In other cases, when outputs differ between
232 image formats, more than one ``.out`` files are created ending with the
233 respective format names, e.g. ``178.out.qcow2`` and ``178.out.raw``.
234
235 There isn't a hard rule about how to write a test script, but a new test is
236 usually a (copy and) modification of an existing case.  There are a few
237 commonly used ways to create a test:
238
239 * A Bash script. It will make use of several environmental variables related
240   to the testing procedure, and could source a group of ``common.*`` libraries
241   for some common helper routines.
242
243 * A Python unittest script. Import ``iotests`` and create a subclass of
244   ``iotests.QMPTestCase``, then call ``iotests.main`` method. The downside of
245   this approach is that the output is too scarce, and the script is considered
246   harder to debug.
247
248 * A simple Python script without using unittest module. This could also import
249   ``iotests`` for launching QEMU and utilities etc, but it doesn't inherit
250   from ``iotests.QMPTestCase`` therefore doesn't use the Python unittest
251   execution. This is a combination of 1 and 2.
252
253 Pick the language per your preference since both Bash and Python have
254 comparable library support for invoking and interacting with QEMU programs. If
255 you opt for Python, it is strongly recommended to write Python 3 compatible
256 code.
257
258 Both Python and Bash frameworks in iotests provide helpers to manage test
259 images. They can be used to create and clean up images under the test
260 directory. If no I/O or any protocol specific feature is needed, it is often
261 more convenient to use the pseudo block driver, ``null-co://``, as the test
262 image, which doesn't require image creation or cleaning up. Avoid system-wide
263 devices or files whenever possible, such as ``/dev/null`` or ``/dev/zero``.
264 Otherwise, image locking implications have to be considered.  For example,
265 another application on the host may have locked the file, possibly leading to a
266 test failure.  If using such devices are explicitly desired, consider adding
267 ``locking=off`` option to disable image locking.
268
269 Docker based tests
270 ==================
271
272 Introduction
273 ------------
274
275 The Docker testing framework in QEMU utilizes public Docker images to build and
276 test QEMU in predefined and widely accessible Linux environments.  This makes
277 it possible to expand the test coverage across distros, toolchain flavors and
278 library versions.
279
280 Prerequisites
281 -------------
282
283 Install "docker" with the system package manager and start the Docker service
284 on your development machine, then make sure you have the privilege to run
285 Docker commands. Typically it means setting up passwordless ``sudo docker``
286 command or login as root. For example:
287
288 .. code::
289
290   $ sudo yum install docker
291   $ # or `apt-get install docker` for Ubuntu, etc.
292   $ sudo systemctl start docker
293   $ sudo docker ps
294
295 The last command should print an empty table, to verify the system is ready.
296
297 An alternative method to set up permissions is by adding the current user to
298 "docker" group and making the docker daemon socket file (by default
299 ``/var/run/docker.sock``) accessible to the group:
300
301 .. code::
302
303   $ sudo groupadd docker
304   $ sudo usermod $USER -G docker
305   $ sudo chown :docker /var/run/docker.sock
306
307 Note that any one of above configurations makes it possible for the user to
308 exploit the whole host with Docker bind mounting or other privileged
309 operations.  So only do it on development machines.
310
311 Quickstart
312 ----------
313
314 From source tree, type ``make docker`` to see the help. Testing can be started
315 without configuring or building QEMU (``configure`` and ``make`` are done in
316 the container, with parameters defined by the make target):
317
318 .. code::
319
320   make docker-test-build@min-glib
321
322 This will create a container instance using the ``min-glib`` image (the image
323 is downloaded and initialized automatically), in which the ``test-build`` job
324 is executed.
325
326 Images
327 ------
328
329 Along with many other images, the ``min-glib`` image is defined in a Dockerfile
330 in ``tests/docker/dockefiles/``, called ``min-glib.docker``. ``make docker``
331 command will list all the available images.
332
333 To add a new image, simply create a new ``.docker`` file under the
334 ``tests/docker/dockerfiles/`` directory.
335
336 A ``.pre`` script can be added beside the ``.docker`` file, which will be
337 executed before building the image under the build context directory. This is
338 mainly used to do necessary host side setup. One such setup is ``binfmt_misc``,
339 for example, to make qemu-user powered cross build containers work.
340
341 Tests
342 -----
343
344 Different tests are added to cover various configurations to build and test
345 QEMU.  Docker tests are the executables under ``tests/docker`` named
346 ``test-*``. They are typically shell scripts and are built on top of a shell
347 library, ``tests/docker/common.rc``, which provides helpers to find the QEMU
348 source and build it.
349
350 The full list of tests is printed in the ``make docker`` help.
351
352 Tools
353 -----
354
355 There are executables that are created to run in a specific Docker environment.
356 This makes it easy to write scripts that have heavy or special dependencies,
357 but are still very easy to use.
358
359 Currently the only tool is ``travis``, which mimics the Travis-CI tests in a
360 container. It runs in the ``travis`` image:
361
362 .. code::
363
364   make docker-travis@travis
365
366 Debugging a Docker test failure
367 -------------------------------
368
369 When CI tasks, maintainers or yourself report a Docker test failure, follow the
370 below steps to debug it:
371
372 1. Locally reproduce the failure with the reported command line. E.g. run
373    ``make docker-test-mingw@fedora J=8``.
374 2. Add "V=1" to the command line, try again, to see the verbose output.
375 3. Further add "DEBUG=1" to the command line. This will pause in a shell prompt
376    in the container right before testing starts. You could either manually
377    build QEMU and run tests from there, or press Ctrl-D to let the Docker
378    testing continue.
379 4. If you press Ctrl-D, the same building and testing procedure will begin, and
380    will hopefully run into the error again. After that, you will be dropped to
381    the prompt for debug.
382
383 Options
384 -------
385
386 Various options can be used to affect how Docker tests are done. The full
387 list is in the ``make docker`` help text. The frequently used ones are:
388
389 * ``V=1``: the same as in top level ``make``. It will be propagated to the
390   container and enable verbose output.
391 * ``J=$N``: the number of parallel tasks in make commands in the container,
392   similar to the ``-j $N`` option in top level ``make``. (The ``-j`` option in
393   top level ``make`` will not be propagated into the container.)
394 * ``DEBUG=1``: enables debug. See the previous "Debugging a Docker test
395   failure" section.
396
397 VM testing
398 ==========
399
400 This test suite contains scripts that bootstrap various guest images that have
401 necessary packages to build QEMU. The basic usage is documented in ``Makefile``
402 help which is displayed with ``make vm-test``.
403
404 Quickstart
405 ----------
406
407 Run ``make vm-test`` to list available make targets. Invoke a specific make
408 command to run build test in an image. For example, ``make vm-build-freebsd``
409 will build the source tree in the FreeBSD image. The command can be executed
410 from either the source tree or the build dir; if the former, ``./configure`` is
411 not needed. The command will then generate the test image in ``./tests/vm/``
412 under the working directory.
413
414 Note: images created by the scripts accept a well-known RSA key pair for SSH
415 access, so they SHOULD NOT be exposed to external interfaces if you are
416 concerned about attackers taking control of the guest and potentially
417 exploiting a QEMU security bug to compromise the host.
418
419 QEMU binary
420 -----------
421
422 By default, qemu-system-x86_64 is searched in $PATH to run the guest. If there
423 isn't one, or if it is older than 2.10, the test won't work. In this case,
424 provide the QEMU binary in env var: ``QEMU=/path/to/qemu-2.10+``.
425
426 Make jobs
427 ---------
428
429 The ``-j$X`` option in the make command line is not propagated into the VM,
430 specify ``J=$X`` to control the make jobs in the guest.
431
432 Debugging
433 ---------
434
435 Add ``DEBUG=1`` and/or ``V=1`` to the make command to allow interactive
436 debugging and verbose output. If this is not enough, see the next section.
437
438 Manual invocation
439 -----------------
440
441 Each guest script is an executable script with the same command line options.
442 For example to work with the netbsd guest, use ``$QEMU_SRC/tests/vm/netbsd``:
443
444 .. code::
445
446     $ cd $QEMU_SRC/tests/vm
447
448     # To bootstrap the image
449     $ ./netbsd --build-image --image /var/tmp/netbsd.img
450     <...>
451
452     # To run an arbitrary command in guest (the output will not be echoed unless
453     # --debug is added)
454     $ ./netbsd --debug --image /var/tmp/netbsd.img uname -a
455
456     # To build QEMU in guest
457     $ ./netbsd --debug --image /var/tmp/netbsd.img --build-qemu $QEMU_SRC
458
459     # To get to an interactive shell
460     $ ./netbsd --interactive --image /var/tmp/netbsd.img sh
461
462 Adding new guests
463 -----------------
464
465 Please look at existing guest scripts for how to add new guests.
466
467 Most importantly, create a subclass of BaseVM and implement ``build_image()``
468 method and define ``BUILD_SCRIPT``, then finally call ``basevm.main()`` from
469 the script's ``main()``.
470
471 * Usually in ``build_image()``, a template image is downloaded from a
472   predefined URL. ``BaseVM._download_with_cache()`` takes care of the cache and
473   the checksum, so consider using it.
474
475 * Once the image is downloaded, users, SSH server and QEMU build deps should
476   be set up:
477
478   - Root password set to ``BaseVM.ROOT_PASS``
479   - User ``BaseVM.GUEST_USER`` is created, and password set to
480     ``BaseVM.GUEST_PASS``
481   - SSH service is enabled and started on boot,
482     ``$QEMU_SRC/tests/keys/id_rsa.pub`` is added to ssh's ``authorized_keys``
483     file of both root and the normal user
484   - DHCP client service is enabled and started on boot, so that it can
485     automatically configure the virtio-net-pci NIC and communicate with QEMU
486     user net (10.0.2.2)
487   - Necessary packages are installed to untar the source tarball and build
488     QEMU
489
490 * Write a proper ``BUILD_SCRIPT`` template, which should be a shell script that
491   untars a raw virtio-blk block device, which is the tarball data blob of the
492   QEMU source tree, then configure/build it. Running "make check" is also
493   recommended.
494
495 Image fuzzer testing
496 ====================
497
498 An image fuzzer was added to exercise format drivers. Currently only qcow2 is
499 supported. To start the fuzzer, run
500
501 .. code::
502
503   tests/image-fuzzer/runner.py -c '[["qemu-img", "info", "$test_img"]]' /tmp/test qcow2
504
505 Alternatively, some command different from "qemu-img info" can be tested, by
506 changing the ``-c`` option.
507
508 Acceptance tests using the Avocado Framework
509 ============================================
510
511 The ``tests/acceptance`` directory hosts functional tests, also known
512 as acceptance level tests.  They're usually higher level tests, and
513 may interact with external resources and with various guest operating
514 systems.
515
516 These tests are written using the Avocado Testing Framework (which must
517 be installed separately) in conjunction with a the ``avocado_qemu.Test``
518 class, implemented at ``tests/acceptance/avocado_qemu``.
519
520 Tests based on ``avocado_qemu.Test`` can easily:
521
522  * Customize the command line arguments given to the convenience
523    ``self.vm`` attribute (a QEMUMachine instance)
524
525  * Interact with the QEMU monitor, send QMP commands and check
526    their results
527
528  * Interact with the guest OS, using the convenience console device
529    (which may be useful to assert the effectiveness and correctness of
530    command line arguments or QMP commands)
531
532  * Interact with external data files that accompany the test itself
533    (see ``self.get_data()``)
534
535  * Download (and cache) remote data files, such as firmware and kernel
536    images
537
538  * Have access to a library of guest OS images (by means of the
539    ``avocado.utils.vmimage`` library)
540
541  * Make use of various other test related utilities available at the
542    test class itself and at the utility library:
543
544    - http://avocado-framework.readthedocs.io/en/latest/api/test/avocado.html#avocado.Test
545    - http://avocado-framework.readthedocs.io/en/latest/api/utils/avocado.utils.html
546
547 Installation
548 ------------
549
550 To install Avocado and its dependencies, run:
551
552 .. code::
553
554   pip install --user avocado-framework
555
556 Alternatively, follow the instructions on this link:
557
558   http://avocado-framework.readthedocs.io/en/latest/GetStartedGuide.html#installing-avocado
559
560 Overview
561 --------
562
563 This directory provides the ``avocado_qemu`` Python module, containing
564 the ``avocado_qemu.Test`` class.  Here's a simple usage example:
565
566 .. code::
567
568   from avocado_qemu import Test
569
570
571   class Version(Test):
572       """
573       :avocado: enable
574       :avocado: tags=quick
575       """
576       def test_qmp_human_info_version(self):
577           self.vm.launch()
578           res = self.vm.command('human-monitor-command',
579                                 command_line='info version')
580           self.assertRegexpMatches(res, r'^(\d+\.\d+\.\d)')
581
582 To execute your test, run:
583
584 .. code::
585
586   avocado run version.py
587
588 Tests may be classified according to a convention by using docstring
589 directives such as ``:avocado: tags=TAG1,TAG2``.  To run all tests
590 in the current directory, tagged as "quick", run:
591
592 .. code::
593
594   avocado run -t quick .
595
596 The ``avocado_qemu.Test`` base test class
597 -----------------------------------------
598
599 The ``avocado_qemu.Test`` class has a number of characteristics that
600 are worth being mentioned right away.
601
602 First of all, it attempts to give each test a ready to use QEMUMachine
603 instance, available at ``self.vm``.  Because many tests will tweak the
604 QEMU command line, launching the QEMUMachine (by using ``self.vm.launch()``)
605 is left to the test writer.
606
607 At test "tear down", ``avocado_qemu.Test`` handles the QEMUMachine
608 shutdown.
609
610 QEMUMachine
611 ~~~~~~~~~~~
612
613 The QEMUMachine API is already widely used in the Python iotests,
614 device-crash-test and other Python scripts.  It's a wrapper around the
615 execution of a QEMU binary, giving its users:
616
617  * the ability to set command line arguments to be given to the QEMU
618    binary
619
620  * a ready to use QMP connection and interface, which can be used to
621    send commands and inspect its results, as well as asynchronous
622    events
623
624  * convenience methods to set commonly used command line arguments in
625    a more succinct and intuitive way
626
627 QEMU binary selection
628 ~~~~~~~~~~~~~~~~~~~~~
629
630 The QEMU binary used for the ``self.vm`` QEMUMachine instance will
631 primarily depend on the value of the ``qemu_bin`` parameter.  If it's
632 not explicitly set, its default value will be the result of a dynamic
633 probe in the same source tree.  A suitable binary will be one that
634 targets the architecture matching host machine.
635
636 Based on this description, test writers will usually rely on one of
637 the following approaches:
638
639 1) Set ``qemu_bin``, and use the given binary
640
641 2) Do not set ``qemu_bin``, and use a QEMU binary named like
642    "${arch}-softmmu/qemu-system-${arch}", either in the current
643    working directory, or in the current source tree.
644
645 The resulting ``qemu_bin`` value will be preserved in the
646 ``avocado_qemu.Test`` as an attribute with the same name.
647
648 Attribute reference
649 -------------------
650
651 Besides the attributes and methods that are part of the base
652 ``avocado.Test`` class, the following attributes are available on any
653 ``avocado_qemu.Test`` instance.
654
655 vm
656 ~~
657
658 A QEMUMachine instance, initially configured according to the given
659 ``qemu_bin`` parameter.
660
661 qemu_bin
662 ~~~~~~~~
663
664 The preserved value of the ``qemu_bin`` parameter or the result of the
665 dynamic probe for a QEMU binary in the current working directory or
666 source tree.
667
668 Parameter reference
669 -------------------
670
671 To understand how Avocado parameters are accessed by tests, and how
672 they can be passed to tests, please refer to::
673
674   http://avocado-framework.readthedocs.io/en/latest/WritingTests.html#accessing-test-parameters
675
676 Parameter values can be easily seen in the log files, and will look
677 like the following:
678
679 .. code::
680
681   PARAMS (key=qemu_bin, path=*, default=x86_64-softmmu/qemu-system-x86_64) => 'x86_64-softmmu/qemu-system-x86_64
682
683 qemu_bin
684 ~~~~~~~~
685
686 The exact QEMU binary to be used on QEMUMachine.
687
688 Uninstalling Avocado
689 --------------------
690
691 If you've followed the installation instructions above, you can easily
692 uninstall Avocado.  Start by listing the packages you have installed::
693
694   pip list --user
695
696 And remove any package you want with::
697
698   pip uninstall <package_name>
This page took 0.065658 seconds and 4 git commands to generate.