functional.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. .. _checkfunctional-ref:
  2. Functional testing with Python
  3. ==============================
  4. The ``tests/functional`` directory hosts functional tests written in
  5. Python. They are usually higher level tests, and may interact with
  6. external resources and with various guest operating systems.
  7. The functional tests have initially evolved from the Avocado tests, so there
  8. is a lot of similarity to those tests here (see :ref:`checkavocado-ref` for
  9. details about the Avocado tests).
  10. The tests should be written in the style of the Python `unittest`_ framework,
  11. using stdio for the TAP protocol. The folder ``tests/functional/qemu_test``
  12. provides classes (e.g. the ``QemuBaseTest``, ``QemuUserTest`` and the
  13. ``QemuSystemTest`` classes) and utility functions that help to get your test
  14. into the right shape, e.g. by replacing the 'stdout' python object to redirect
  15. the normal output of your test to stderr instead.
  16. Note that if you don't use one of the QemuBaseTest based classes for your
  17. test, or if you spawn subprocesses from your test, you have to make sure
  18. that there is no TAP-incompatible output written to stdio, e.g. either by
  19. prefixing every line with a "# " to mark the output as a TAP comment, or
  20. e.g. by capturing the stdout output of subprocesses (redirecting it to
  21. stderr is OK).
  22. Tests based on ``qemu_test.QemuSystemTest`` can easily:
  23. * Customize the command line arguments given to the convenience
  24. ``self.vm`` attribute (a QEMUMachine instance)
  25. * Interact with the QEMU monitor, send QMP commands and check
  26. their results
  27. * Interact with the guest OS, using the convenience console device
  28. (which may be useful to assert the effectiveness and correctness of
  29. command line arguments or QMP commands)
  30. * Download (and cache) remote data files, such as firmware and kernel
  31. images
  32. Running tests
  33. -------------
  34. You can run the functional tests simply by executing:
  35. .. code::
  36. make check-functional
  37. It is also possible to run tests for a certain target only, for example
  38. the following line will only run the tests for the x86_64 target:
  39. .. code::
  40. make check-functional-x86_64
  41. To run a single test file without the meson test runner, you can also
  42. execute the file directly by specifying two environment variables first,
  43. the PYTHONPATH that has to include the python folder and the tests/functional
  44. folder of the source tree, and QEMU_TEST_QEMU_BINARY that has to point
  45. to the QEMU binary that should be used for the test. The current working
  46. directory should be your build folder. For example::
  47. $ export PYTHONPATH=../python:../tests/functional
  48. $ export QEMU_TEST_QEMU_BINARY=$PWD/qemu-system-x86_64
  49. $ pyvenv/bin/python3 ../tests/functional/test_file.py
  50. The test framework will automatically purge any scratch files created during
  51. the tests. If needing to debug a failed test, it is possible to keep these
  52. files around on disk by setting ```QEMU_TEST_KEEP_SCRATCH=1``` as an env
  53. variable. Any preserved files will be deleted the next time the test is run
  54. without this variable set.
  55. Overview
  56. --------
  57. The ``tests/functional/qemu_test`` directory provides the ``qemu_test``
  58. Python module, containing the ``qemu_test.QemuSystemTest`` class.
  59. Here is a simple usage example:
  60. .. code::
  61. #!/usr/bin/env python3
  62. from qemu_test import QemuSystemTest
  63. class Version(QemuSystemTest):
  64. def test_qmp_human_info_version(self):
  65. self.vm.launch()
  66. res = self.vm.cmd('human-monitor-command',
  67. command_line='info version')
  68. self.assertRegex(res, r'^(\d+\.\d+\.\d)')
  69. if __name__ == '__main__':
  70. QemuSystemTest.main()
  71. By providing the "hash bang" line at the beginning of the script, marking
  72. the file as executable and by calling into QemuSystemTest.main(), the test
  73. can also be run stand-alone, without a test runner. OTOH when run via a test
  74. runner, the QemuSystemTest.main() function takes care of running the test
  75. functions in the right fassion (e.g. with TAP output that is required by the
  76. meson test runner).
  77. The ``qemu_test.QemuSystemTest`` base test class
  78. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  79. The ``qemu_test.QemuSystemTest`` class has a number of characteristics
  80. that are worth being mentioned.
  81. First of all, it attempts to give each test a ready to use QEMUMachine
  82. instance, available at ``self.vm``. Because many tests will tweak the
  83. QEMU command line, launching the QEMUMachine (by using ``self.vm.launch()``)
  84. is left to the test writer.
  85. The base test class has also support for tests with more than one
  86. QEMUMachine. The way to get machines is through the ``self.get_vm()``
  87. method which will return a QEMUMachine instance. The ``self.get_vm()``
  88. method accepts arguments that will be passed to the QEMUMachine creation
  89. and also an optional ``name`` attribute so you can identify a specific
  90. machine and get it more than once through the tests methods. A simple
  91. and hypothetical example follows:
  92. .. code::
  93. from qemu_test import QemuSystemTest
  94. class MultipleMachines(QemuSystemTest):
  95. def test_multiple_machines(self):
  96. first_machine = self.get_vm()
  97. second_machine = self.get_vm()
  98. self.get_vm(name='third_machine').launch()
  99. first_machine.launch()
  100. second_machine.launch()
  101. first_res = first_machine.cmd(
  102. 'human-monitor-command',
  103. command_line='info version')
  104. second_res = second_machine.cmd(
  105. 'human-monitor-command',
  106. command_line='info version')
  107. third_res = self.get_vm(name='third_machine').cmd(
  108. 'human-monitor-command',
  109. command_line='info version')
  110. self.assertEqual(first_res, second_res, third_res)
  111. At test "tear down", ``qemu_test.QemuSystemTest`` handles all the QEMUMachines
  112. shutdown.
  113. QEMUMachine
  114. -----------
  115. The QEMUMachine API is already widely used in the Python iotests,
  116. device-crash-test and other Python scripts. It's a wrapper around the
  117. execution of a QEMU binary, giving its users:
  118. * the ability to set command line arguments to be given to the QEMU
  119. binary
  120. * a ready to use QMP connection and interface, which can be used to
  121. send commands and inspect its results, as well as asynchronous
  122. events
  123. * convenience methods to set commonly used command line arguments in
  124. a more succinct and intuitive way
  125. QEMU binary selection
  126. ^^^^^^^^^^^^^^^^^^^^^
  127. The QEMU binary used for the ``self.vm`` QEMUMachine instance will
  128. primarily depend on the value of the ``qemu_bin`` class attribute.
  129. If it is not explicitly set by the test code, its default value will
  130. be the result the QEMU_TEST_QEMU_BINARY environment variable.
  131. Debugging hung QEMU
  132. ^^^^^^^^^^^^^^^^^^^
  133. When test cases go wrong it may be helpful to debug a stalled QEMU
  134. process. While the QEMUMachine class owns the primary QMP monitor
  135. socket, it is possible to request a second QMP monitor be created
  136. by setting the ``QEMU_TEST_QMP_BACKDOOR`` env variable to refer
  137. to a UNIX socket name. The ``qmp-shell`` command can then be
  138. attached to the stalled QEMU to examine its live state.
  139. Attribute reference
  140. -------------------
  141. QemuBaseTest
  142. ^^^^^^^^^^^^
  143. The following attributes are available on any ``qemu_test.QemuBaseTest``
  144. instance.
  145. arch
  146. """"
  147. The target architecture of the QEMU binary.
  148. Tests are also free to use this attribute value, for their own needs.
  149. A test may, for instance, use this value when selecting the architecture
  150. of a kernel or disk image to boot a VM with.
  151. qemu_bin
  152. """"""""
  153. The preserved value of the ``QEMU_TEST_QEMU_BINARY`` environment
  154. variable.
  155. QemuUserTest
  156. ^^^^^^^^^^^^
  157. The QemuUserTest class can be used for running an executable via the
  158. usermode emulation binaries.
  159. QemuSystemTest
  160. ^^^^^^^^^^^^^^
  161. The QemuSystemTest class can be used for running tests via one of the
  162. qemu-system-* binaries.
  163. vm
  164. ""
  165. A QEMUMachine instance, initially configured according to the given
  166. ``qemu_bin`` parameter.
  167. cpu
  168. """
  169. The cpu model that will be set to all QEMUMachine instances created
  170. by the test.
  171. machine
  172. """""""
  173. The machine type that will be set to all QEMUMachine instances created
  174. by the test. By using the set_machine() function of the QemuSystemTest
  175. class to set this attribute, you can automatically check whether the
  176. machine is available to skip the test in case it is not built into the
  177. QEMU binary.
  178. Asset handling
  179. --------------
  180. Many functional tests download assets (e.g. Linux kernels, initrds,
  181. firmware images, etc.) from the internet to be able to run tests with
  182. them. This imposes additional challenges to the test framework.
  183. First there is the the problem that some people might not have an
  184. unconstrained internet connection, so such tests should not be run by
  185. default when running ``make check``. To accomplish this situation,
  186. the tests that download files should only be added to the "thorough"
  187. speed mode in the meson.build file, while the "quick" speed mode is
  188. fine for functional tests that can be run without downloading files.
  189. ``make check`` then only runs the quick functional tests along with
  190. the other quick tests from the other test suites. If you choose to
  191. run only run ``make check-functional``, the "thorough" tests will be
  192. executed, too. And to run all functional tests along with the others,
  193. you can use something like::
  194. make -j$(nproc) check SPEED=thorough
  195. The second problem with downloading files from the internet are time
  196. constraints. The time for downloading files should not be taken into
  197. account when the test is running and the timeout of the test is ticking
  198. (since downloading can be very slow, depending on the network bandwidth).
  199. This problem is solved by downloading the assets ahead of time, before
  200. the tests are run. This pre-caching is done with the qemu_test.Asset
  201. class. To use it in your test, declare an asset in your test class with
  202. its URL and SHA256 checksum like this::
  203. ASSET_somename = (
  204. ('https://www.qemu.org/assets/images/qemu_head_200.png'),
  205. '34b74cad46ea28a2966c1d04e102510daf1fd73e6582b6b74523940d5da029dd')
  206. In your test function, you can then get the file name of the cached
  207. asset like this::
  208. def test_function(self):
  209. file_path = self.ASSET_somename.fetch()
  210. The pre-caching will be done automatically when running
  211. ``make check-functional`` (but not when running e.g.
  212. ``make check-functional-<target>``). In case you just want to download
  213. the assets without running the tests, you can do so by running::
  214. make precache-functional
  215. The cache is populated in the ``~/.cache/qemu/download`` directory by
  216. default, but the location can be changed by setting the
  217. ``QEMU_TEST_CACHE_DIR`` environment variable.
  218. Skipping tests
  219. --------------
  220. Since the test framework is based on the common Python unittest framework,
  221. you can use the usual Python decorators which allow for easily skipping
  222. tests running under certain conditions, for example, on the lack of a binary
  223. on the test system or when the running environment is a CI system. For further
  224. information about those decorators, please refer to:
  225. https://docs.python.org/3/library/unittest.html#skipping-tests-and-expected-failures
  226. While the conditions for skipping tests are often specifics of each one, there
  227. are recurring scenarios identified by the QEMU developers and the use of
  228. environment variables became a kind of standard way to enable/disable tests.
  229. Here is a list of the most used variables:
  230. QEMU_TEST_ALLOW_LARGE_STORAGE
  231. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  232. Tests which are going to fetch or produce assets considered *large* are not
  233. going to run unless that ``QEMU_TEST_ALLOW_LARGE_STORAGE=1`` is exported on
  234. the environment.
  235. The definition of *large* is a bit arbitrary here, but it usually means an
  236. asset which occupies at least 1GB of size on disk when uncompressed.
  237. QEMU_TEST_ALLOW_UNTRUSTED_CODE
  238. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  239. There are tests which will boot a kernel image or firmware that can be
  240. considered not safe to run on the developer's workstation, thus they are
  241. skipped by default. The definition of *not safe* is also arbitrary but
  242. usually it means a blob which either its source or build process aren't
  243. public available.
  244. You should export ``QEMU_TEST_ALLOW_UNTRUSTED_CODE=1`` on the environment in
  245. order to allow tests which make use of those kind of assets.
  246. QEMU_TEST_FLAKY_TESTS
  247. ^^^^^^^^^^^^^^^^^^^^^
  248. Some tests are not working reliably and thus are disabled by default.
  249. This includes tests that don't run reliably on GitLab's CI which
  250. usually expose real issues that are rarely seen on developer machines
  251. due to the constraints of the CI environment. If you encounter a
  252. similar situation then raise a bug and then mark the test as shown on
  253. the code snippet below:
  254. .. code::
  255. # See https://gitlab.com/qemu-project/qemu/-/issues/nnnn
  256. @skipUnless(os.getenv('QEMU_TEST_FLAKY_TESTS'), 'Test is unstable on GitLab')
  257. def test(self):
  258. do_something()
  259. Tests should not live in this state forever and should either be fixed
  260. or eventually removed.
  261. QEMU_TEST_ALLOW_SLOW
  262. ^^^^^^^^^^^^^^^^^^^^
  263. Tests that have a very long runtime and might run into timeout issues
  264. e.g. if the QEMU binary has been compiled with debugging options enabled.
  265. To avoid these timeout issues by default and to save some precious CPU
  266. cycles during normal testing, such tests are disabled by default unless
  267. the QEMU_TEST_ALLOW_SLOW environment variable has been set.
  268. .. _unittest: https://docs.python.org/3/library/unittest.html