1
0

unit.rst 35 KB

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