unit.rst 35 KB

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