testing.rst 34 KB

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