writing_tests.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. .. _tutorial-salt-testing:
  2. ==================================
  3. Salt's Test Suite: An Introduction
  4. ==================================
  5. .. note::
  6. This tutorial makes a couple of assumptions. The first assumption is that
  7. you have a basic knowledge of Salt. To get up to speed, check out the
  8. :ref:`Salt Walkthrough <tutorial-salt-walk-through>`.
  9. The second assumption is that your Salt development environment is already
  10. configured and that you have a basic understanding of contributing to the
  11. Salt codebase. If you're unfamiliar with either of these topics, please refer
  12. to the :ref:`Installing Salt for Development<installing-for-development>`
  13. and the :ref:`Contributing<contributing>` pages, respectively.
  14. Salt comes with a powerful integration and unit test suite. The test suite
  15. allows for the fully automated run of integration and/or unit tests from a
  16. single interface.
  17. Salt's test suite is located under the ``tests`` directory in the root of Salt's
  18. code base and is divided into two main types of tests:
  19. :ref:`unit tests and integration tests <integration-vs-unit>`. The ``unit`` and
  20. ``integration`` sub-test-suites are located in the ``tests`` directory, which is
  21. where the majority of Salt's test cases are housed.
  22. .. _getting_set_up_for_tests:
  23. Getting Set Up For Tests
  24. ========================
  25. First of all you will need to ensure you install ``nox``.
  26. .. code-block:: bash
  27. pip install nox
  28. Test Directory Structure
  29. ========================
  30. As noted in the introduction to this tutorial, Salt's test suite is located in the
  31. ``tests`` directory in the root of Salt's code base. From there, the tests are divided
  32. into two groups ``integration`` and ``unit``. Within each of these directories, the
  33. directory structure roughly mirrors the directory structure of Salt's own codebase.
  34. For example, the files inside ``tests/integration/modules`` contains tests for the
  35. files located within ``salt/modules``.
  36. .. note::
  37. ``tests/integration`` and ``tests/unit`` are the only directories discussed in
  38. this tutorial. With the exception of the ``tests/runtests.py`` file, which is
  39. used below in the `Running the Test Suite`_ section, the other directories and
  40. files located in ``tests`` are outside the scope of this tutorial.
  41. .. _integration-vs-unit:
  42. Integration vs. Unit
  43. --------------------
  44. Given that Salt's test suite contains two powerful, though very different, testing
  45. approaches, when should you write integration tests and when should you write unit
  46. tests?
  47. Integration tests use Salt masters, minions, and a syndic to test salt functionality
  48. directly and focus on testing the interaction of these components. Salt's integration
  49. test runner includes functionality to run Salt execution modules, runners, states,
  50. shell commands, salt-ssh commands, salt-api commands, and more. This provides a
  51. tremendous ability to use Salt to test itself and makes writing such tests a breeze.
  52. Integration tests are the preferred method of testing Salt functionality when
  53. possible.
  54. Unit tests do not spin up any Salt daemons, but instead find their value in testing
  55. singular implementations of individual functions. Instead of testing against specific
  56. interactions, unit tests should be used to test a function's logic. Unit tests should
  57. be used to test a function's exit point(s) such as any ``return`` or ``raises``
  58. statements.
  59. Unit tests are also useful in cases where writing an integration test might not be
  60. possible. While the integration test suite is extremely powerful, unfortunately at
  61. this time, it does not cover all functional areas of Salt's ecosystem. For example,
  62. at the time of this writing, there is not a way to write integration tests for Proxy
  63. Minions. Since the test runner will need to be adjusted to account for Proxy Minion
  64. processes, unit tests can still provide some testing support in the interim by
  65. testing the logic contained inside Proxy Minion functions.
  66. Running the Test Suite
  67. ======================
  68. Once all of the :ref:`requirements <getting_set_up_for_tests>` are installed, the
  69. ``nox`` command is used to instantiate Salt's test suite:
  70. .. code-block:: bash
  71. nox -e 'pytest-zeromq-3(coverage=False)'
  72. The command above, if executed without any options, will run the entire suite of
  73. integration and unit tests. Some tests require certain flags to run, such as
  74. destructive tests. If these flags are not included, then the test suite will only
  75. perform the tests that don't require special attention.
  76. At the end of the test run, you will see a summary output of the tests that passed,
  77. failed, or were skipped.
  78. You can pass any pytest options after the nox command like so:
  79. .. code-block:: bash
  80. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/unit/modules/test_ps.py
  81. The above command will run the ``test_ps.py`` test with the zeromq transport, python3,
  82. and pytest. The option after ``--`` can include any pytest options.
  83. Running Integration Tests
  84. -------------------------
  85. Salt's set of integration tests use Salt to test itself. The integration portion
  86. of the test suite includes some built-in Salt daemons that will spin up in preparation
  87. of the test run. This list of Salt daemon processes includes:
  88. * 2 Salt Masters
  89. * 2 Salt Minions
  90. * 1 Salt Syndic
  91. These various daemons are used to execute Salt commands and functionality within
  92. the test suite, allowing you to write tests to assert against expected or
  93. unexpected behaviors.
  94. A simple example of a test utilizing a typical master/minion execution module command
  95. is the test for the ``test_ping`` function in the
  96. ``tests/integration/modules/test_test.py``
  97. file:
  98. .. code-block:: python
  99. def test_ping(self):
  100. """
  101. test.ping
  102. """
  103. self.assertTrue(self.run_function("test.ping"))
  104. The test above is a very simple example where the ``test.ping`` function is
  105. executed by Salt's test suite runner and is asserting that the minion returned
  106. with a ``True`` response.
  107. .. _test-selection-options:
  108. Test Selection Options
  109. ~~~~~~~~~~~~~~~~~~~~~~
  110. If you want to run only a subset of tests, this is easily done with pytest. You only
  111. need to point the test runner to the directory. For example if you want to run all
  112. integration module tests:
  113. .. code-block:: bash
  114. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/integration/modules/
  115. Running Unit Tests
  116. ------------------
  117. If you want to run only the unit tests, you can just pass the unit test directory
  118. as an option to the test runner.
  119. The unit tests do not spin up any Salt testing daemons as the integration tests
  120. do and execute very quickly compared to the integration tests.
  121. .. code-block:: bash
  122. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/unit/
  123. .. _running-specific-tests:
  124. Running Specific Tests
  125. ----------------------
  126. There are times when a specific test file, test class, or even a single,
  127. individual test need to be executed, such as when writing new tests. In these
  128. situations, you should use the `pytest syntax`_ to select the specific tests.
  129. For running a single test file, such as the pillar module test file in the
  130. integration test directory, you must provide the file path.
  131. .. code-block:: bash
  132. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/integration/modules/test_pillar.py
  133. Some test files contain only one test class while other test files contain multiple
  134. test classes. To run a specific test class within the file, append the name of
  135. the test class to the end of the file path:
  136. .. code-block:: bash
  137. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/integration/modules/test_pillar.py::PillarModuleTest
  138. To run a single test within a file, append both the name of the test class the
  139. individual test belongs to, as well as the name of the test itself:
  140. .. code-block:: bash
  141. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/integration/modules/test_pillar.py::PillarModuleTest::test_data
  142. The following command is an example of how to execute a single test found in
  143. the ``tests/unit/modules/test_cp.py`` file:
  144. .. code-block:: bash
  145. nox -e 'pytest-zeromq-3(coverage=False)' -- tests/unit/modules/test_cp.py::CpTestCase::test_get_file_not_found
  146. Writing Tests for Salt
  147. ======================
  148. Once you're comfortable running tests, you can now start writing them! Be sure
  149. to review the `Integration vs. Unit`_ section of this tutorial to determine what
  150. type of test makes the most sense for the code you're testing.
  151. .. note::
  152. There are many decorators, naming conventions, and code specifications
  153. required for Salt test files. We will not be covering all of the these specifics
  154. in this tutorial. Please refer to the testing documentation links listed below
  155. in the `Additional Testing Documentation`_ section to learn more about these
  156. requirements.
  157. In the following sections, the test examples assume the "new" test is added to
  158. a test file that is already present and regularly running in the test suite and
  159. is written with the correct requirements.
  160. Writing Integration Tests
  161. -------------------------
  162. Since integration tests validate against a running environment, as explained in the
  163. `Running Integration Tests`_ section of this tutorial, integration tests are very
  164. easy to write and are generally the preferred method of writing Salt tests.
  165. The following integration test is an example taken from the ``test.py`` file in the
  166. ``tests/integration/modules`` directory. This test uses the ``run_function`` method
  167. to test the functionality of a traditional execution module command.
  168. The ``run_function`` method uses the integration test daemons to execute a
  169. ``module.function`` command as you would with Salt. The minion runs the function and
  170. returns. The test also uses `Python's Assert Functions`_ to test that the
  171. minion's return is expected.
  172. .. code-block:: python
  173. def test_ping(self):
  174. """
  175. test.ping
  176. """
  177. self.assertTrue(self.run_function("test.ping"))
  178. Args can be passed in to the ``run_function`` method as well:
  179. .. code-block:: python
  180. def test_echo(self):
  181. """
  182. test.echo
  183. """
  184. self.assertEqual(self.run_function("test.echo", ["text"]), "text")
  185. The next example is taken from the
  186. ``tests/integration/modules/test_aliases.py`` file and
  187. demonstrates how to pass kwargs to the ``run_function`` call. Also note that this
  188. test uses another salt function to ensure the correct data is present (via the
  189. ``aliases.set_target`` call) before attempting to assert what the ``aliases.get_target``
  190. call should return.
  191. .. code-block:: python
  192. def test_set_target(self):
  193. """
  194. aliases.set_target and aliases.get_target
  195. """
  196. set_ret = self.run_function("aliases.set_target", alias="fred", target="bob")
  197. self.assertTrue(set_ret)
  198. tgt_ret = self.run_function("aliases.get_target", alias="fred")
  199. self.assertEqual(tgt_ret, "bob")
  200. Using multiple Salt commands in this manner provides two useful benefits. The first is
  201. that it provides some additional coverage for the ``aliases.set_target`` function.
  202. The second benefit is the call to ``aliases.get_target`` is not dependent on the
  203. presence of any aliases set outside of this test. Tests should not be dependent on
  204. the previous execution, success, or failure of other tests. They should be isolated
  205. from other tests as much as possible.
  206. While it might be tempting to build out a test file where tests depend on one another
  207. before running, this should be avoided. SaltStack recommends that each test should
  208. test a single functionality and not rely on other tests. Therefore, when possible,
  209. individual tests should also be broken up into singular pieces. These are not
  210. hard-and-fast rules, but serve more as recommendations to keep the test suite simple.
  211. This helps with debugging code and related tests when failures occur and problems
  212. are exposed. There may be instances where large tests use many asserts to set up a
  213. use case that protects against potential regressions.
  214. .. note::
  215. The examples above all use the ``run_function`` option to test execution module
  216. functions in a traditional master/minion environment. To see examples of how to
  217. test other common Salt components such as runners, salt-api, and more, please
  218. refer to the :ref:`Integration Test Class Examples<integration-class-examples>`
  219. documentation.
  220. Destructive vs Non-destructive Tests
  221. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  222. Since Salt is used to change the settings and behavior of systems, often, the
  223. best approach to run tests is to make actual changes to an underlying system.
  224. This is where the concept of destructive integration tests comes into play.
  225. Tests can be written to alter the system they are running on. This capability
  226. is what fills in the gap needed to properly test aspects of system management
  227. like package installation.
  228. To write a destructive test, import and use the ``destructiveTest`` decorator for
  229. the test method:
  230. .. code-block:: python
  231. import integration
  232. from tests.support.helpers import destructiveTest
  233. class PkgTest(integration.ModuleCase):
  234. @destructiveTest
  235. def test_pkg_install(self):
  236. ret = self.run_function("pkg.install", name="finch")
  237. self.assertSaltTrueReturn(ret)
  238. ret = self.run_function("pkg.purge", name="finch")
  239. self.assertSaltTrueReturn(ret)
  240. Writing Unit Tests
  241. ------------------
  242. As explained in the `Integration vs. Unit`_ section above, unit tests should be
  243. written to test the *logic* of a function. This includes focusing on testing
  244. ``return`` and ``raises`` statements. Substantial effort should be made to mock
  245. external resources that are used in the code being tested.
  246. External resources that should be mocked include, but are not limited to, APIs,
  247. function calls, external data either globally available or passed in through
  248. function arguments, file data, etc. This practice helps to isolate unit tests to
  249. test Salt logic. One handy way to think about writing unit tests is to "block
  250. all of the exits". More information about how to properly mock external resources
  251. can be found in Salt's :ref:`Unit Test<unit-tests>` documentation.
  252. Salt's unit tests utilize Python's mock class as well as `MagicMock`_. The
  253. ``@patch`` decorator is also heavily used when "blocking all the exits".
  254. A simple example of a unit test currently in use in Salt is the
  255. ``test_get_file_not_found`` test in the ``tests/unit/modules/test_cp.py`` file.
  256. This test uses the ``@patch`` decorator and ``MagicMock`` to mock the return
  257. of the call to Salt's ``cp.hash_file`` execution module function. This ensures
  258. that we're testing the ``cp.get_file`` function directly, instead of inadvertently
  259. testing the call to ``cp.hash_file``, which is used in ``cp.get_file``.
  260. .. code-block:: python
  261. def test_get_file_not_found(self):
  262. """
  263. Test if get_file can't find the file.
  264. """
  265. with patch("salt.modules.cp.hash_file", MagicMock(return_value=False)):
  266. path = "salt://saltines"
  267. dest = "/srv/salt/cheese"
  268. ret = ""
  269. assert cp.get_file(path, dest) == ret
  270. Note that Salt's ``cp`` module is imported at the top of the file, along with all
  271. of the other necessary testing imports. The ``get_file`` function is then called
  272. directed in the testing function, instead of using the ``run_function`` method as
  273. the integration test examples do above.
  274. The call to ``cp.get_file`` returns an empty string when a ``hash_file`` isn't found.
  275. Therefore, the example above is a good illustration of a unit test "blocking
  276. the exits" via the ``@patch`` decorator, as well as testing logic via asserting
  277. against the ``return`` statement in the ``if`` clause. In this example we used the
  278. python ``assert`` to verify the return from ``cp.get_file``. Pytest allows you to use
  279. these `asserts`_ when writing your tests and, in fact, plain `asserts`_ is the preferred
  280. way to assert anything in your tests. As Salt dives deeper into Pytest, the use of
  281. `unittest.TestClass` will be replaced by plain test functions, or test functions grouped
  282. in a class, which **does not** subclass `unittest.TestClass`, which, of course, doesn't
  283. work with unittest assert functions.
  284. There are more examples of writing unit tests of varying complexities available
  285. in the following docs:
  286. * :ref:`Simple Unit Test Example<simple-unit-example>`
  287. * :ref:`Complete Unit Test Example<complete-unit-example>`
  288. * :ref:`Complex Unit Test Example<complex-unit-example>`
  289. .. note::
  290. Considerable care should be made to ensure that you're testing something
  291. useful in your test functions. It is very easy to fall into a situation
  292. where you have mocked so much of the original function that the test
  293. results in only asserting against the data you have provided. This results
  294. in a poor and fragile unit test.
  295. Add a python module dependency to the test run
  296. ----------------------------------------------
  297. The test dependencies for python modules are managed under the ``requirements/static``
  298. directory. You will need to add your module to the appropriate file under ``requirements/static``.
  299. When ``pre-commit`` is run it will create all of the needed requirement files
  300. under ``requirements/static/py3{5,6,7}``. Nox will then use these files to install
  301. the requirements for the tests.
  302. Add a system dependency to the test run
  303. ---------------------------------------
  304. If you need to add a system dependency for the test run, this will need to be added in
  305. the `salt jenkins`_ repo. This repo uses salt states to install system dependencies.
  306. You need to update the ``state-tree/golden-images-provision.sls`` file with
  307. your dependency to ensure it is installed. Once your PR is merged the core team
  308. will need to promote the new images with your new dependency installed.
  309. Checking for Log Messages
  310. =========================
  311. To test to see if a given log message has been emitted, the following pattern
  312. can be used
  313. .. code-block:: python
  314. # Import logging handler
  315. from tests.support.helpers import TstSuiteLoggingHandler
  316. # .. inside test
  317. with TstSuiteLoggingHandler() as handler:
  318. for message in handler.messages:
  319. if message.startswith("ERROR: This is the error message we seek"):
  320. break
  321. else:
  322. raise AssertionError("Did not find error message")
  323. Automated Test Runs
  324. ===================
  325. SaltStack maintains a Jenkins server which can be viewed at
  326. https://jenkinsci.saltstack.com. The tests executed from this Jenkins server
  327. create fresh virtual machines for each test run, then execute the destructive
  328. tests on the new, clean virtual machine. This allows for the execution of tests
  329. across supported platforms.
  330. Additional Testing Documentation
  331. ================================
  332. In addition to this tutorial, there are some other helpful resources and documentation
  333. that go into more depth on Salt's test runner, writing tests for Salt code, and general
  334. Python testing documentation. Please see the follow references for more information:
  335. * :ref:`Salt's Test Suite Documentation<salt-test-suite>`
  336. * :ref:`Integration Tests<integration-tests>`
  337. * :ref:`Unit Tests<unit-tests>`
  338. * `MagicMock`_
  339. * `Python Unittest`_
  340. * `Python's Assert Functions`_
  341. .. _asserts: https://docs.pytest.org/en/latest/assert.html
  342. .. _pytest syntax: https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests
  343. .. _MagicMock: https://docs.python.org/3/library/unittest.mock.html
  344. .. _Python Unittest: https://docs.python.org/2/library/unittest.html
  345. .. _Python's Assert Functions: https://docs.python.org/2/library/unittest.html#assert-methods
  346. .. _salt jenkins: https://github.com/saltstack/salt-jenkins