unit.rst 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. .. _unit-tests:
  2. ==================
  3. Writing Unit Tests
  4. ==================
  5. Introduction
  6. ============
  7. Like many software projects, Salt has two broad-based testing approaches --
  8. integration testing and unit testing. While integration testing focuses on the
  9. interaction between components in a sandboxed environment, unit testing focuses
  10. on the singular implementation of individual functions.
  11. Unit tests should be used specifically to test a function's logic. Unit tests
  12. rely on mocking external resources.
  13. While unit tests are good for ensuring consistent results, they are most
  14. useful when they do not require more than a few mocks. Effort should be
  15. made to mock as many external resources as possible. This effort is encouraged,
  16. but not required. Sometimes the isolation provided by completely mocking the
  17. external dependencies is not worth the effort of mocking those dependencies.
  18. In these cases, requiring an external library to be installed on the
  19. system before running the test file is a useful way to strike this balance.
  20. For example, the unit tests for the MySQL execution module require the
  21. presence of the MySQL python bindings on the system running the test file
  22. before proceeding to run the tests.
  23. Overly detailed mocking can also result in decreased test readability and
  24. brittleness as the tests are more likely to fail when the code or its
  25. dependencies legitimately change. In these cases, it is better to add
  26. dependencies to the test runner dependency state.
  27. Preparing to Write a Unit Test
  28. ==============================
  29. This guide assumes that your Salt development environment is already configured
  30. and that you have a basic understanding of contributing to the Salt codebase.
  31. If you're unfamiliar with either of these topics, please refer to the
  32. :ref:`Installing Salt for Development<installing-for-development>` and the
  33. :ref:`Contributing<contributing>` pages, respectively.
  34. This documentation also assumes that you have an understanding of how to
  35. :ref:`run Salt's test suite<running-the-tests>`, including running the
  36. :ref:`unit test subsection<running-test-subsections>`, running the unit tests
  37. :ref:`without testing daemons<running-unit-tests-no-daemons>` to speed up
  38. development wait times, and running a unit test file, class, or individual test.
  39. Best Practices
  40. ==============
  41. Unit tests should be written to the following specifications.
  42. What to Test?
  43. -------------
  44. Since unit testing focuses on the singular implementation of individual functions,
  45. unit tests should be used specifically to test a function's logic. The following
  46. guidelines should be followed when writing unit tests for Salt's test suite:
  47. - Each ``raise`` and ``return`` statement needs to be independently tested.
  48. - Isolate testing functionality. Don't rely on the pass or failure of other,
  49. separate tests.
  50. - Test functions should contain only one assertion, at most, multiple
  51. assertions can be made, but against the same outcome.
  52. - Many Salt execution modules are merely wrappers for distribution-specific
  53. functionality. If there isn't any logic present in a simple execution module,
  54. consider writing an :ref:`integration test<integration-tests>` instead of
  55. heavily mocking a call to an external dependency.
  56. Mocking Test Data
  57. -----------------
  58. A reasonable effort needs to be made to mock external resources used in the
  59. code being tested, such as APIs, function calls, external data either
  60. globally available or passed in through function arguments, file data, etc.
  61. - Test functions should contain only one assertion and all necessary mock code
  62. and data for that assertion.
  63. - External resources should be mocked in order to "block all of the exits". If a
  64. test function fails because something in an external library wasn't mocked
  65. properly (or at all), this test is not addressing all of the "exits" a function
  66. may experience. We want the Salt code and logic to be tested, specifically.
  67. - Consider the fragility and longevity of a test. If the test is so tightly coupled
  68. to the code being tested, this makes a test unnecessarily fragile.
  69. - Make sure you are not mocking the function to be tested so vigorously that the
  70. test return merely tests the mocked output. The test should always be testing
  71. a function's logic.
  72. Mocking Loader Modules
  73. ----------------------
  74. Salt loader modules use a series of globally available dunder variables,
  75. ``__salt__``, ``__opts__``, ``__pillar__``, etc. To facilitate testing these
  76. modules a helper class was created, ``LoaderModuleMock`` which can be found in
  77. ``tests/support/pytest/loader.py``. The reason for the existence of this class
  78. is because historically one would add these dunder variables directly on the
  79. imported module. This, however, introduces unexpected behavior when running the
  80. full test suite since those attributes would not be removed once we were done
  81. testing the module and would therefore leak to other modules being tested with
  82. unpredictable results. This is the kind of work that should be deferred to
  83. mock, and that's exactly what this class provides.
  84. As an example, if one needs to specify some options which should be available
  85. to the module being tested one should do:
  86. .. code-block:: python
  87. import pytest
  88. import salt.modules.somemodule as somemodule
  89. @pytest.fixture(autouse=True)
  90. def setup_loader():
  91. setup_loader_modules = {somemodule: {"__opts__": {"test": True}}}
  92. with pytest.helpers.loader_mock(setup_loader_modules) as loader_mock:
  93. yield loader_mock
  94. Consider this more extensive example from
  95. ``tests/pytests/unit/beacons/test_sensehat.py``:
  96. .. code-block:: python
  97. from __future__ import absolute_import
  98. import pytest
  99. import salt.beacons.sensehat as sensehat
  100. from tests.support.mock import MagicMock
  101. @pytest.fixture(autouse=True)
  102. def setup_loader():
  103. setup_loader_modules = {
  104. sensehat: {
  105. "__salt__": {
  106. "sensehat.get_humidity": MagicMock(return_value=80),
  107. "sensehat.get_temperature": MagicMock(return_value=30),
  108. "sensehat.get_pressure": MagicMock(return_value=1500),
  109. },
  110. }
  111. }
  112. with pytest.helpers.loader_mock(setup_loader_modules) as loader_mock:
  113. yield loader_mock
  114. def test_non_list_config():
  115. config = {}
  116. ret = sensehat.validate(config)
  117. assert ret == (False, "Configuration for sensehat beacon must be a list.")
  118. def test_empty_config():
  119. config = [{}]
  120. ret = sensehat.validate(config)
  121. assert ret == (False, "Configuration for sensehat beacon requires sensors.")
  122. def test_sensehat_humidity_match():
  123. config = [{"sensors": {"humidity": "70%"}}]
  124. ret = sensehat.validate(config)
  125. assert ret == (True, "Valid beacon configuration")
  126. ret = sensehat.beacon(config)
  127. assert ret == [{"tag": "sensehat/humidity", "humidity": 80}]
  128. def test_sensehat_temperature_match():
  129. config = [{"sensors": {"temperature": 20}}]
  130. ret = sensehat.validate(config)
  131. assert ret == (True, "Valid beacon configuration")
  132. ret = sensehat.beacon(config)
  133. assert ret == [{"tag": "sensehat/temperature", "temperature": 30}]
  134. def test_sensehat_temperature_match_range():
  135. config = [{"sensors": {"temperature": [20, 29]}}]
  136. ret = sensehat.validate(config)
  137. assert ret == (True, "Valid beacon configuration")
  138. ret = sensehat.beacon(config)
  139. assert ret == [{"tag": "sensehat/temperature", "temperature": 30}]
  140. def test_sensehat_pressure_match():
  141. config = [{"sensors": {"pressure": "1400"}}]
  142. ret = sensehat.validate(config)
  143. assert ret == (True, "Valid beacon configuration")
  144. ret = sensehat.beacon(config)
  145. assert ret == [{"tag": "sensehat/pressure", "pressure": 1500}]
  146. def test_sensehat_no_match():
  147. config = [{"sensors": {"pressure": "1600"}}]
  148. ret = sensehat.validate(config)
  149. assert ret == (True, "Valid beacon configuration")
  150. ret = sensehat.beacon(config)
  151. assert ret == []
  152. What happens in the above example is we mock several calls of the ``sensehat``
  153. module to return known expected values to assert against.
  154. Mocking Filehandles
  155. -------------------
  156. .. note::
  157. This documentation applies to the 2018.3 release cycle and newer. The
  158. extended functionality for ``mock_open`` described below does not exist in
  159. the 2017.7 and older release branches.
  160. Opening files in Salt is done using ``salt.utils.files.fopen()``. When testing
  161. code that reads from files, the ``mock_open`` helper can be used to mock
  162. filehandles. Note that is not the same ``mock_open`` as
  163. :py:func:`unittest.mock.mock_open` from the Python standard library, but rather
  164. a separate implementation which has additional functionality.
  165. .. code-block:: python
  166. from tests.support.mock import patch, mock_open
  167. import salt.modules.mymod as mymod
  168. def test_something():
  169. fopen_mock = mock_open(read_data="foo\nbar\nbaz\n")
  170. with patch("salt.utils.files.fopen", fopen_mock):
  171. result = mymod.myfunc()
  172. assert result is True
  173. This will force any filehandle opened to mimic a filehandle which, when read,
  174. produces the specified contents.
  175. .. important::
  176. **String Types**
  177. When configuring your read_data, make sure that you are using
  178. bytestrings (e.g. ``b"foo\nbar\nbaz\n"``) when the code you are testing is
  179. opening a file for binary reading, otherwise the tests will fail. The
  180. mocked filehandles produced by ``mock_open`` will raise a
  181. :py:obj:`TypeError` if you attempt to read a bytestring when opening for
  182. non-binary reading, and similarly will not let you read a string when
  183. opening a file for binary reading. They will also not permit bytestrings to
  184. be "written" if the mocked filehandle was opened for non-binary writing,
  185. and vice-versa when opened for non-binary writing. These enhancements force
  186. test writers to write more accurate tests.
  187. More Complex Scenarios
  188. **********************
  189. .. _unit-tests-multiple-file-paths:
  190. Multiple File Paths
  191. +++++++++++++++++++
  192. What happens when the code being tested reads from more than one file? For
  193. those cases, you can pass ``read_data`` as a dictionary:
  194. .. code-block:: python
  195. import textwrap
  196. from tests.support.mock import patch, mock_open
  197. import salt.modules.mymod as mymod
  198. def test_something():
  199. contents = {
  200. "/etc/foo.conf": textwrap.dedent(
  201. """\
  202. foo
  203. bar
  204. baz
  205. """
  206. ),
  207. "/etc/b*.conf": textwrap.dedent(
  208. """\
  209. one
  210. two
  211. three
  212. """
  213. ),
  214. }
  215. fopen_mock = mock_open(read_data=contents)
  216. with patch("salt.utils.files.fopen", fopen_mock):
  217. result = mymod.myfunc()
  218. assert result is True
  219. This would make ``salt.utils.files.fopen()`` produce filehandles with different
  220. contents depending on which file was being opened by the code being tested.
  221. ``/etc/foo.conf`` and any file matching the pattern ``/etc/b*.conf`` would
  222. work, while opening any other path would result in a
  223. :py:obj:`FileNotFoundError` being raised.
  224. Since file patterns are supported, it is possible to use a pattern of ``'*'``
  225. to define a fallback if no other patterns match the filename being opened. The
  226. below two ``mock_open`` calls would produce identical results:
  227. .. code-block:: python
  228. mock_open(read_data="foo\n")
  229. mock_open(read_data={"*": "foo\n"})
  230. .. note::
  231. Take care when specifying the ``read_data`` as a dictionary, in cases where
  232. the patterns overlap (e.g. when both ``/etc/b*.conf`` and ``/etc/bar.conf``
  233. are in the ``read_data``). Dictionary iteration order will determine which
  234. pattern is attempted first, second, etc., with the exception of ``*`` which
  235. is used when no other pattern matches. If your test case calls for
  236. specifying overlapping patterns, and you are not running Python 3.6 or
  237. newer, then an ``OrderedDict`` can be used to ensure matching is handled in
  238. the desired way:
  239. .. code-block:: python
  240. contents = OrderedDict()
  241. contents["/etc/bar.conf"] = "foo\nbar\nbaz\n"
  242. contents["/etc/b*.conf"] = IOError(errno.EACCES, "Permission denied")
  243. contents["*"] = 'This is a fallback for files not beginning with "/etc/b"\n'
  244. fopen_mock = mock_open(read_data=contents)
  245. Raising Exceptions
  246. ++++++++++++++++++
  247. Instead of a string, an exception can also be used as the ``read_data``:
  248. .. code-block:: python
  249. import errno
  250. from tests.support.mock import patch, mock_open
  251. import salt.modules.mymod as mymod
  252. def test_something():
  253. exc = IOError(errno.EACCES, "Permission denied")
  254. fopen_mock = mock_open(read_data=exc)
  255. with patch("salt.utils.files.fopen", fopen_mock):
  256. mymod.myfunc()
  257. The above example would raise the specified exception when any file is opened.
  258. The expectation would be that ``mymod.myfunc()`` would gracefully handle the
  259. IOError, so a failure to do that would result in it being raised and causing
  260. the test to fail.
  261. Multiple File Contents
  262. ++++++++++++++++++++++
  263. For cases in which a file is being read more than once, and it is necessary to
  264. test a function's behavior based on what the file looks like the second (or
  265. third, etc.) time it is read, just specify the contents for that file as a
  266. list. Each time the file is opened, ``mock_open`` will cycle through the list
  267. and produce a mocked filehandle with the specified contents. For example:
  268. .. code-block:: python
  269. import errno
  270. import textwrap
  271. from tests.support.mock import patch, mock_open
  272. import salt.modules.mymod as mymod
  273. def test_something():
  274. contents = {
  275. "/etc/foo.conf": [
  276. textwrap.dedent(
  277. """\
  278. foo
  279. bar
  280. """
  281. ),
  282. textwrap.dedent(
  283. """\
  284. foo
  285. bar
  286. baz
  287. """
  288. ),
  289. ],
  290. "/etc/b*.conf": [
  291. IOError(errno.ENOENT, "No such file or directory"),
  292. textwrap.dedent(
  293. """\
  294. one
  295. two
  296. three
  297. """
  298. ),
  299. ],
  300. }
  301. fopen_mock = mock_open(read_data=contents)
  302. with patch("salt.utils.files.fopen", fopen_mock):
  303. result = mymod.myfunc()
  304. assert result is True
  305. Using this example, the first time ``/etc/foo.conf`` is opened, it will
  306. simulate a file with the first string in the list as its contents, while the
  307. second time it is opened, the simulated file's contents will be the second
  308. string in the list.
  309. If no more items remain in the list, then attempting to open the file will
  310. raise a :py:obj:`RuntimeError`. In the example above, if ``/etc/foo.conf`` were
  311. to be opened a third time, a :py:obj:`RuntimeError` would be raised.
  312. Note that exceptions can also be mixed in with strings when using this
  313. technique. In the above example, if ``/etc/bar.conf`` were to be opened twice,
  314. the first time would simulate the file not existing, while the second time
  315. would simulate a file with string defined in the second element of the list.
  316. .. note::
  317. Notice that the second path in the ``contents`` dictionary above
  318. (``/etc/b*.conf``) contains an asterisk. The items in the list are cycled
  319. through for each match of a given pattern (*not* separately for each
  320. individual file path), so this means that only two files matching that
  321. pattern could be opened before the next one would raise a
  322. :py:obj:`RuntimeError`.
  323. Accessing the Mocked Filehandles in a Test
  324. ******************************************
  325. .. note::
  326. The code for the ``MockOpen``, ``MockCall``, and ``MockFH`` classes
  327. (referenced below) can be found in ``tests/support/mock.py``. There are
  328. extensive unit tests for them located in ``tests/unit/test_mock.py``.
  329. The above examples simply show how to mock ``salt.utils.files.fopen()`` to
  330. simulate files with the contents you desire, but you can also access the mocked
  331. filehandles (and more), and use them to craft assertions in your tests. To do
  332. so, just add an ``as`` clause to the end of the ``patch`` statement:
  333. .. code-block:: python
  334. fopen_mock = mock_open(read_data="foo\nbar\nbaz\n")
  335. with patch("salt.utils.files.fopen", fopen_mock) as m_open:
  336. # do testing here
  337. ...
  338. ...
  339. When doing this, ``m_open`` will be a ``MockOpen`` instance. It will contain
  340. several useful attributes:
  341. - **read_data** - A dictionary containing the ``read_data`` passed when
  342. ``mock_open`` was invoked. In the event that :ref:`multiple file paths
  343. <unit-tests-multiple-file-paths>` are not used, then this will be a
  344. dictionary mapping ``*`` to the ``read_data`` passed to ``mock_open``.
  345. - **call_count** - An integer representing how many times
  346. ``salt.utils.files.fopen()`` was called to open a file.
  347. - **calls** - A list of ``MockCall`` objects. A ``MockCall`` object is a simple
  348. class which stores the arguments passed to it, making the positional
  349. arguments available via its ``args`` attribute, and the keyword arguments
  350. available via its ``kwargs`` attribute.
  351. .. code-block:: python
  352. from tests.support.mock import patch, mock_open, MockCall
  353. import salt.modules.mymod as mymod
  354. def test_something():
  355. with patch("salt.utils.files.fopen", mock_open(read_data=b"foo\n")) as m_open:
  356. mymod.myfunc()
  357. # Assert that only two opens attempted
  358. assert m_open.call_count == 2
  359. # Assert that only /etc/foo.conf was opened
  360. assert all(call.args[0] == "/etc/foo.conf" for call in m_open.calls)
  361. # Asser that the first open was for binary read, and the
  362. # second was for binary write.
  363. assert m_open.calls == [
  364. MockCall("/etc/foo.conf", "rb"),
  365. MockCall("/etc/foo.conf", "wb"),
  366. ]
  367. Note that ``MockCall`` is imported from ``tests.support.mock`` in the above
  368. example. Also, the second assert above is redundant since it is covered in
  369. the final assert, but both are included simply as an example.
  370. - **filehandles** - A dictionary mapping the unique file paths opened, to lists
  371. of ``MockFH`` objects. Each open creates a unique ``MockFH`` object. Each
  372. ``MockFH`` object itself has a number of useful attributes:
  373. - **filename** - The path to the file which was opened using
  374. ``salt.utils.files.fopen()``
  375. - **call** - A ``MockCall`` object representing the arguments passed to
  376. ``salt.utils.files.fopen()``. Note that this ``MockCall`` is also available
  377. in the parent ``MockOpen`` instance's **calls** list.
  378. - The following methods are mocked using :py:class:`unittest.mock.Mock`
  379. objects, and Mock's built-in asserts (as well as the call data) can be used
  380. as you would with any other Mock object:
  381. - **.read()**
  382. - **.readlines()**
  383. - **.readline()**
  384. - **.close()**
  385. - **.write()**
  386. - **.writelines()**
  387. - **.seek()**
  388. - The read functions (**.read()**, **.readlines()**, **.readline()**) all
  389. work as expected, as does iterating through the file line by line (i.e.
  390. ``for line in fh:``).
  391. - The **.tell()** method is also implemented in such a way that it updates
  392. after each time the mocked filehandle is read, and will report the correct
  393. position. The one caveat here is that **.seek()** doesn't actually work
  394. (it's simply mocked), and will not change the position. Additionally,
  395. neither **.write()** or **.writelines()** will modify the mocked
  396. filehandle's contents.
  397. - The attributes **.write_calls** and **.writelines_calls** (no parenthesis)
  398. are available as shorthands and correspond to lists containing the contents
  399. passed for all calls to **.write()** and **.writelines()**, respectively.
  400. Examples
  401. ++++++++
  402. .. code-block:: python
  403. with patch("salt.utils.files.fopen", mock_open(read_data=contents)) as m_open:
  404. # Run the code you are unit testing
  405. mymod.myfunc()
  406. # Check that only the expected file was opened, and that it was opened
  407. # only once.
  408. assert m_open.call_count == 1
  409. assert list(m_open.filehandles) == ["/etc/foo.conf"]
  410. # "opens" will be a list of all the mocked filehandles opened
  411. opens = m_open.filehandles["/etc/foo.conf"]
  412. # Check that we wrote the expected lines ("expected" here is assumed to
  413. # be a list of strings)
  414. assert opens[0].write_calls == expected
  415. .. code-block:: python
  416. with patch("salt.utils.files.fopen", mock_open(read_data=contents)) as m_open:
  417. # Run the code you are unit testing
  418. mymod.myfunc()
  419. # Check that .readlines() was called (remember, it's a Mock)
  420. m_open.filehandles["/etc/foo.conf"][0].readlines.assert_called()
  421. .. code-block:: python
  422. with patch("salt.utils.files.fopen", mock_open(read_data=contents)) as m_open:
  423. # Run the code you are unit testing
  424. mymod.myfunc()
  425. # Check that we read the file and also wrote to it
  426. m_open.filehandles["/etc/foo.conf"][0].read.assert_called_once()
  427. m_open.filehandles["/etc/foo.conf"][1].writelines.assert_called_once()
  428. .. _`Mock()`: https://github.com/testing-cabal/mock
  429. Naming Conventions
  430. ------------------
  431. Test names and docstrings should indicate what functionality is being tested.
  432. Test functions are named ``test_<fcn>_<test-name>`` where ``<fcn>`` is the function
  433. being tested and ``<test-name>`` describes the ``raise`` or ``return`` being tested.
  434. Unit tests for ``salt/.../<module>.py`` are contained in a file called
  435. ``tests/pytests/unit/.../test_<module>.py``, e.g. the tests for
  436. ``salt/modules/alternatives.py``
  437. are in ``tests/pytests/unit/modules/test_alternatives.py``.
  438. In order for unit tests to get picked up during a run of the unit test suite, each
  439. unit test file must be prefixed with ``test_`` and each individual test must
  440. also be
  441. prefixed with the ``test_`` naming syntax, as described above.
  442. If a function does not start with ``test_``, then the function acts as a "normal"
  443. function and is not considered a testing function. It will not be included in the
  444. test run or testing output. The same principle applies to unit test files that
  445. do not have the ``test_*.py`` naming syntax. This test file naming convention
  446. is how the test runner recognizes that a test file contains tests.
  447. Imports
  448. -------
  449. Most commonly, the following imports are necessary to create a unit test:
  450. .. code-block:: python
  451. import pytest
  452. If you need mock support to your tests, please also import:
  453. .. code-block:: python
  454. from tests.support.mock import MagicMock, patch, call
  455. Evaluating Truth
  456. ================
  457. A longer discussion on the types of assertions one can make can be found by
  458. reading `PyTests's documentation on assertions`__.
  459. .. __: https://docs.pytest.org/en/latest/assert.html
  460. Tests Using Mock Objects
  461. ========================
  462. In many cases, the purpose of a Salt module is to interact with some external
  463. system, whether it be to control a database, manipulate files on a filesystem
  464. or something else. In these varied cases, it's necessary to design a unit test
  465. which can test the function whilst replacing functions which might actually
  466. call out to external systems. One might think of this as "blocking the exits"
  467. for code under tests and redirecting the calls to external systems with our own
  468. code which produces known results during the duration of the test.
  469. To achieve this behavior, Salt makes heavy use of the `MagicMock package`__.
  470. To understand how one might integrate Mock into writing a unit test for Salt,
  471. let's imagine a scenario in which we're testing an execution module that's
  472. designed to operate on a database. Furthermore, let's imagine two separate
  473. methods, here presented in pseduo-code in an imaginary execution module called
  474. 'db.py'.
  475. .. code-block:: python
  476. def create_user(username):
  477. qry = "CREATE USER {0}".format(username)
  478. execute_query(qry)
  479. def execute_query(qry):
  480. # Connect to a database and actually do the query...
  481. ...
  482. Here, let's imagine that we want to create a unit test for the `create_user`
  483. function. In doing so, we want to avoid any calls out to an external system and
  484. so while we are running our unit tests, we want to replace the actual
  485. interaction with a database with a function that can capture the parameters
  486. sent to it and return pre-defined values. Therefore, our task is clear -- to
  487. write a unit test which tests the functionality of `create_user` while also
  488. replacing 'execute_query' with a mocked function.
  489. To begin, we set up the skeleton of our test much like we did before, but with
  490. additional imports for MagicMock:
  491. .. code-block:: python
  492. # Import Salt execution module to test
  493. from salt.modules import db
  494. # Import Mock libraries
  495. from tests.support.mock import MagicMock, patch, call
  496. # Create test case
  497. def test_create_user():
  498. # First, we replace 'execute_query' with our own mock function
  499. with patch.object(db, "execute_query", MagicMock()) as db_exq:
  500. # Now that the exits are blocked, we can run the function under test.
  501. db.create_user("testuser")
  502. # We could now query our mock object to see which calls were made
  503. # to it.
  504. ## print db_exq.mock_calls
  505. # Construct a call object that simulates the way we expected
  506. # execute_query to have been called.
  507. expected_call = call("CREATE USER testuser")
  508. # Compare the expected call with the list of actual calls. The
  509. # test will succeed or fail depending on the output of this
  510. # assertion.
  511. db_exq.assert_has_calls(expected_call)
  512. .. __: https://docs.python.org/3/library/unittest.mock.html
  513. Modifying ``__salt__`` In Place
  514. ===============================
  515. At times, it becomes necessary to make modifications to a module's view of
  516. functions in its own ``__salt__`` dictionary. Luckily, this process is quite
  517. easy.
  518. Below is an example that uses MagicMock's ``patch`` functionality to insert a
  519. function into ``__salt__`` that's actually a MagicMock instance.
  520. .. code-block:: python
  521. def show_patch(self):
  522. with patch.dict(my_module.__salt__, {"function.to_replace": MagicMock()}):
  523. # From this scope, carry on with testing, with a modified __salt__!
  524. ...
  525. .. _simple-unit-example:
  526. A Simple Example
  527. ================
  528. Let's assume that we're testing a very basic function in an imaginary Salt
  529. execution module. Given a module called ``fib.py`` that has a function called
  530. ``calculate(num_of_results)``, which given a ``num_of_results``, produces a list of
  531. sequential Fibonacci numbers of that length.
  532. A unit test to test this function might be commonly placed in a file called
  533. ``tests/unit/modules/test_fib.py``. The convention is to place unit tests for
  534. Salt execution modules in ``test/unit/modules/`` and to name the tests module
  535. prefixed with ``test_*.py``.
  536. Tests are grouped around test cases, which are logically grouped sets of tests
  537. against a piece of functionality in the tested software. Test cases are created
  538. as Python classes in the unit test module. To return to our example, here's how
  539. we might write the skeleton for testing ``fib.py``:
  540. .. code-block:: python
  541. # Import Salt Testing libs
  542. from tests.support.unit import TestCase
  543. # Import Salt execution module to test
  544. import salt.modules.fib as fib
  545. # Create test case class and inherit from Salt's customized TestCase
  546. class FibTestCase(TestCase):
  547. """
  548. This class contains a set of functions that test salt.modules.fib.
  549. """
  550. def test_fib(self):
  551. """
  552. To create a unit test, we should prefix the name with `test_' so
  553. that it's recognized by the test runner.
  554. """
  555. fib_five = (0, 1, 1, 2, 3)
  556. self.assertEqual(fib.calculate(5), fib_five)
  557. At this point, the test can now be run, either individually or as a part of a
  558. full run of the test runner. To ease development, a single test can be
  559. executed:
  560. .. code-block:: bash
  561. tests/runtests.py -v -n unit.modules.test_fib
  562. This will report the status of the test: success, failure, or error. The
  563. ``-v`` flag increases output verbosity.
  564. .. code-block:: bash
  565. tests/runtests.py -n unit.modules.test_fib -v
  566. To review the results of a particular run, take a note of the log location
  567. given in the output for each test:
  568. .. code-block:: text
  569. Logging tests on /var/folders/nl/d809xbq577l3qrbj3ymtpbq80000gn/T/salt-runtests.log
  570. .. _complete-unit-example:
  571. A More Complete Example
  572. =======================
  573. Consider the following function from salt/modules/linux_sysctl.py.
  574. .. code-block:: python
  575. def get(name):
  576. """
  577. Return a single sysctl parameter for this minion
  578. CLI Example:
  579. .. code-block:: bash
  580. salt '*' sysctl.get net.ipv4.ip_forward
  581. """
  582. cmd = "sysctl -n {0}".format(name)
  583. out = __salt__["cmd.run"](cmd)
  584. return out
  585. This function is very simple, comprising only four source lines of code and
  586. having only one return statement, so we know only one test is needed. There
  587. are also two inputs to the function, the ``name`` function argument and the call
  588. to ``__salt__['cmd.run']()``, both of which need to be appropriately mocked.
  589. Mocking a function parameter is straightforward, whereas mocking a function
  590. call will require, in this case, the use of MagicMock. For added isolation, we
  591. will also redefine the ``__salt__`` dictionary such that it only contains
  592. ``'cmd.run'``.
  593. .. code-block:: python
  594. # Import Salt Libs
  595. import salt.modules.linux_sysictl as linux_sysctl
  596. # Import Salt Testing Libs
  597. from tests.support.mixins import LoaderModuleMockMixin
  598. from tests.support.unit import TestCase
  599. from tests.support.mock import MagicMock, patch
  600. class LinuxSysctlTestCase(TestCase, LoaderModuleMockMixin):
  601. """
  602. TestCase for salt.modules.linux_sysctl module
  603. """
  604. def test_get(self):
  605. """
  606. Tests the return of get function
  607. """
  608. mock_cmd = MagicMock(return_value=1)
  609. with patch.dict(linux_sysctl.__salt__, {"cmd.run": mock_cmd}):
  610. self.assertEqual(linux_sysctl.get("net.ipv4.ip_forward"), 1)
  611. Since ``get()`` has only one raise or return statement and that statement is a
  612. success condition, the test function is simply named ``test_get()``. As
  613. described, the single function call parameter, ``name`` is mocked with
  614. ``net.ipv4.ip_forward`` and ``__salt__['cmd.run']`` is replaced by a MagicMock
  615. function object. We are only interested in the return value of
  616. ``__salt__['cmd.run']``, which MagicMock allows us by specifying via
  617. ``return_value=1``. Finally, the test itself tests for equality between the
  618. return value of ``get()`` and the expected return of ``1``. This assertion is
  619. expected to succeed because ``get()`` will determine its return value from
  620. ``__salt__['cmd.run']``, which we have mocked to return ``1``.
  621. .. _complex-unit-example:
  622. A Complex Example
  623. =================
  624. Now consider the ``assign()`` function from the same
  625. salt/modules/linux_sysctl.py source file.
  626. .. code-block:: python
  627. def assign(name, value):
  628. """
  629. Assign a single sysctl parameter for this minion
  630. CLI Example:
  631. .. code-block:: bash
  632. salt '*' sysctl.assign net.ipv4.ip_forward 1
  633. """
  634. value = str(value)
  635. sysctl_file = "/proc/sys/{0}".format(name.replace(".", "/"))
  636. if not os.path.exists(sysctl_file):
  637. raise CommandExecutionError("sysctl {0} does not exist".format(name))
  638. ret = {}
  639. cmd = 'sysctl -w {0}="{1}"'.format(name, value)
  640. data = __salt__["cmd.run_all"](cmd)
  641. out = data["stdout"]
  642. err = data["stderr"]
  643. # Example:
  644. # # sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
  645. # net.ipv4.tcp_rmem = 4096 87380 16777216
  646. regex = re.compile(r"^{0}\s+=\s+{1}$".format(re.escape(name), re.escape(value)))
  647. if not regex.match(out) or "Invalid argument" in str(err):
  648. if data["retcode"] != 0 and err:
  649. error = err
  650. else:
  651. error = out
  652. raise CommandExecutionError("sysctl -w failed: {0}".format(error))
  653. new_name, new_value = out.split(" = ", 1)
  654. ret[new_name] = new_value
  655. return ret
  656. This function contains two raise statements and one return statement, so we
  657. know that we will need (at least) three tests. It has two function arguments
  658. and many references to non-builtin functions. In the tests below you will see
  659. that MagicMock's ``patch()`` method may be used as a context manager or as a
  660. decorator. When patching the salt dunders however, please use the context
  661. manager approach.
  662. There are three test functions, one for each raise and return statement in the
  663. source function. Each function is self-contained and contains all and only the
  664. mocks and data needed to test the raise or return statement it is concerned
  665. with.
  666. .. code-block:: python
  667. # Import Salt Libs
  668. import salt.modules.linux_sysctl as linux_sysctl
  669. from salt.exceptions import CommandExecutionError
  670. # Import Salt Testing Libs
  671. from tests.support.mixins import LoaderModuleMockMixin
  672. from tests.support.unit import TestCase
  673. from tests.support.mock import MagicMock, patch
  674. class LinuxSysctlTestCase(TestCase, LoaderModuleMockMixin):
  675. """
  676. TestCase for salt.modules.linux_sysctl module
  677. """
  678. @patch("os.path.exists", MagicMock(return_value=False))
  679. def test_assign_proc_sys_failed(self):
  680. """
  681. Tests if /proc/sys/<kernel-subsystem> exists or not
  682. """
  683. cmd = {
  684. "pid": 1337,
  685. "retcode": 0,
  686. "stderr": "",
  687. "stdout": "net.ipv4.ip_forward = 1",
  688. }
  689. mock_cmd = MagicMock(return_value=cmd)
  690. with patch.dict(linux_sysctl.__salt__, {"cmd.run_all": mock_cmd}):
  691. self.assertRaises(
  692. CommandExecutionError, linux_sysctl.assign, "net.ipv4.ip_forward", 1
  693. )
  694. @patch("os.path.exists", MagicMock(return_value=True))
  695. def test_assign_cmd_failed(self):
  696. """
  697. Tests if the assignment was successful or not
  698. """
  699. cmd = {
  700. "pid": 1337,
  701. "retcode": 0,
  702. "stderr": 'sysctl: setting key "net.ipv4.ip_forward": Invalid argument',
  703. "stdout": "net.ipv4.ip_forward = backward",
  704. }
  705. mock_cmd = MagicMock(return_value=cmd)
  706. with patch.dict(linux_sysctl.__salt__, {"cmd.run_all": mock_cmd}):
  707. self.assertRaises(
  708. CommandExecutionError,
  709. linux_sysctl.assign,
  710. "net.ipv4.ip_forward",
  711. "backward",
  712. )
  713. @patch("os.path.exists", MagicMock(return_value=True))
  714. def test_assign_success(self):
  715. """
  716. Tests the return of successful assign function
  717. """
  718. cmd = {
  719. "pid": 1337,
  720. "retcode": 0,
  721. "stderr": "",
  722. "stdout": "net.ipv4.ip_forward = 1",
  723. }
  724. ret = {"net.ipv4.ip_forward": "1"}
  725. mock_cmd = MagicMock(return_value=cmd)
  726. with patch.dict(linux_sysctl.__salt__, {"cmd.run_all": mock_cmd}):
  727. self.assertEqual(linux_sysctl.assign("net.ipv4.ip_forward", 1), ret)