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