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