unit.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. ============================
  5. Unittest Compatibility Layer
  6. ============================
  7. Compatibility layer to use :mod:`unittest <python2:unittest>` under Python
  8. 2.7 or `unittest2`_ under Python 2.6 without having to worry about which is
  9. in use.
  10. .. attention::
  11. Please refer to Python's :mod:`unittest <python2:unittest>`
  12. documentation as the ultimate source of information, this is just a
  13. compatibility layer.
  14. .. _`unittest2`: https://pypi.python.org/pypi/unittest2
  15. '''
  16. # pylint: disable=unused-import,blacklisted-module,deprecated-method
  17. # Import python libs
  18. from __future__ import absolute_import, print_function, unicode_literals
  19. import os
  20. import sys
  21. import logging
  22. from unittest import (
  23. TestLoader as _TestLoader,
  24. TextTestRunner as _TextTestRunner,
  25. TestCase as _TestCase,
  26. expectedFailure,
  27. TestSuite as _TestSuite,
  28. skip,
  29. skipIf as _skipIf,
  30. TestResult,
  31. TextTestResult as _TextTestResult
  32. )
  33. from unittest.case import _id, SkipTest
  34. from salt.ext import six
  35. try:
  36. import psutil
  37. HAS_PSUTIL = True
  38. except ImportError:
  39. HAS_PSUTIL = False
  40. log = logging.getLogger(__name__)
  41. # Set SHOW_PROC to True to show
  42. # process details when running in verbose mode
  43. # i.e. [CPU:15.1%|MEM:48.3%|Z:0]
  44. SHOW_PROC = 'NO_SHOW_PROC' not in os.environ
  45. LOREM_IPSUM = '''\
  46. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget urna a arcu lacinia sagittis.
  47. Sed scelerisque, lacus eget malesuada vestibulum, justo diam facilisis tortor, in sodales dolor
  48. nibh eu urna. Aliquam iaculis massa risus, sed elementum risus accumsan id. Suspendisse mattis,
  49. metus sed lacinia dictum, leo orci dapibus sapien, at porttitor sapien nulla ac velit.
  50. Duis ac cursus leo, non varius metus. Sed laoreet felis magna, vel tempor diam malesuada nec.
  51. Quisque cursus odio tortor. In consequat augue nisl, eget lacinia odio vestibulum eget.
  52. Donec venenatis elementum arcu at rhoncus. Nunc pharetra erat in lacinia convallis. Ut condimentum
  53. eu mauris sit amet convallis. Morbi vulputate vel odio non laoreet. Nullam in suscipit tellus.
  54. Sed quis posuere urna.'''
  55. class TestSuite(_TestSuite):
  56. def _handleClassSetUp(self, test, result):
  57. previousClass = getattr(result, '_previousTestClass', None)
  58. currentClass = test.__class__
  59. if currentClass == previousClass or getattr(currentClass, 'setUpClass', None) is None:
  60. return super(TestSuite, self)._handleClassSetUp(test, result)
  61. # Store a reference to all class attributes before running the setUpClass method
  62. initial_class_attributes = dir(test.__class__)
  63. super(TestSuite, self)._handleClassSetUp(test, result)
  64. # Store the difference in in a variable in order to check later if they were deleted
  65. test.__class__._prerun_class_attributes = [
  66. attr for attr in dir(test.__class__) if attr not in initial_class_attributes]
  67. def _tearDownPreviousClass(self, test, result):
  68. # Run any tearDownClass code defined
  69. super(TestSuite, self)._tearDownPreviousClass(test, result)
  70. previousClass = getattr(result, '_previousTestClass', None)
  71. currentClass = test.__class__
  72. if currentClass == previousClass:
  73. return
  74. # See if the previous class attributes have been cleaned
  75. if previousClass and getattr(previousClass, 'tearDownClass', None):
  76. prerun_class_attributes = getattr(previousClass, '_prerun_class_attributes', None)
  77. if prerun_class_attributes is not None:
  78. previousClass._prerun_class_attributes = None
  79. del previousClass._prerun_class_attributes
  80. for attr in prerun_class_attributes:
  81. if hasattr(previousClass, attr):
  82. attr_value = getattr(previousClass, attr, None)
  83. if attr_value is None:
  84. continue
  85. if isinstance(attr_value, (bool,) + six.string_types + six.integer_types):
  86. setattr(previousClass, attr, None)
  87. continue
  88. log.warning('Deleting extra class attribute after test run: %s.%s(%s). '
  89. 'Please consider using \'del self.%s\' on the test class '
  90. '\'tearDownClass()\' method', previousClass.__name__, attr,
  91. str(getattr(previousClass, attr))[:100], attr)
  92. delattr(previousClass, attr)
  93. class TestLoader(_TestLoader):
  94. # We're just subclassing to make sure tha tour TestSuite class is the one used
  95. suiteClass = TestSuite
  96. class TestCase(_TestCase):
  97. # pylint: disable=expected-an-indented-block-comment,too-many-leading-hastag-for-block-comment
  98. ## Commented out because it may be causing tests to hang
  99. ## at the end of the run
  100. #
  101. # _cwd = os.getcwd()
  102. # _chdir_counter = 0
  103. # @classmethod
  104. # def tearDownClass(cls):
  105. # '''
  106. # Overriden method for tearing down all classes in salttesting
  107. #
  108. # This hard-resets the environment between test classes
  109. # '''
  110. # # Compare where we are now compared to where we were when we began this family of tests
  111. # if not cls._cwd == os.getcwd() and cls._chdir_counter > 0:
  112. # os.chdir(cls._cwd)
  113. # print('\nWARNING: A misbehaving test has modified the working directory!\nThe test suite has reset the working directory '
  114. # 'on tearDown() to {0}\n'.format(cls._cwd))
  115. # cls._chdir_counter += 1
  116. # pylint: enable=expected-an-indented-block-comment,too-many-leading-hastag-for-block-comment
  117. def run(self, result=None):
  118. self._prerun_instance_attributes = dir(self)
  119. self.maxDiff = None
  120. outcome = super(TestCase, self).run(result=result)
  121. for attr in dir(self):
  122. if attr == '_prerun_instance_attributes':
  123. continue
  124. if attr in getattr(self.__class__, '_prerun_class_attributes', ()):
  125. continue
  126. if attr not in self._prerun_instance_attributes:
  127. attr_value = getattr(self, attr, None)
  128. if attr_value is None:
  129. continue
  130. if isinstance(attr_value, (bool,) + six.string_types + six.integer_types):
  131. setattr(self, attr, None)
  132. continue
  133. log.warning('Deleting extra class attribute after test run: %s.%s(%s). '
  134. 'Please consider using \'del self.%s\' on the test case '
  135. '\'tearDown()\' method', self.__class__.__name__, attr,
  136. getattr(self, attr), attr)
  137. delattr(self, attr)
  138. self._prerun_instance_attributes = None
  139. del self._prerun_instance_attributes
  140. return outcome
  141. def shortDescription(self):
  142. desc = _TestCase.shortDescription(self)
  143. if HAS_PSUTIL and SHOW_PROC:
  144. show_zombie_processes = 'SHOW_PROC_ZOMBIES' in os.environ
  145. proc_info = '[CPU:{0}%|MEM:{1}%'.format(psutil.cpu_percent(),
  146. psutil.virtual_memory().percent)
  147. if show_zombie_processes:
  148. found_zombies = 0
  149. try:
  150. for proc in psutil.process_iter():
  151. if proc.status == psutil.STATUS_ZOMBIE:
  152. found_zombies += 1
  153. except Exception: # pylint: disable=broad-except
  154. pass
  155. proc_info += '|Z:{0}'.format(found_zombies)
  156. proc_info += '] {short_desc}'.format(short_desc=desc if desc else '')
  157. return proc_info
  158. else:
  159. return _TestCase.shortDescription(self)
  160. def assertEquals(self, *args, **kwargs):
  161. raise DeprecationWarning(
  162. 'The {0}() function is deprecated. Please start using {1}() '
  163. 'instead.'.format('assertEquals', 'assertEqual')
  164. )
  165. # return _TestCase.assertEquals(self, *args, **kwargs)
  166. def assertNotEquals(self, *args, **kwargs):
  167. raise DeprecationWarning(
  168. 'The {0}() function is deprecated. Please start using {1}() '
  169. 'instead.'.format('assertNotEquals', 'assertNotEqual')
  170. )
  171. # return _TestCase.assertNotEquals(self, *args, **kwargs)
  172. def assert_(self, *args, **kwargs):
  173. # The unittest2 library uses this deprecated method, we can't raise
  174. # the exception.
  175. raise DeprecationWarning(
  176. 'The {0}() function is deprecated. Please start using {1}() '
  177. 'instead.'.format('assert_', 'assertTrue')
  178. )
  179. # return _TestCase.assert_(self, *args, **kwargs)
  180. def assertAlmostEquals(self, *args, **kwargs):
  181. raise DeprecationWarning(
  182. 'The {0}() function is deprecated. Please start using {1}() '
  183. 'instead.'.format('assertAlmostEquals', 'assertAlmostEqual')
  184. )
  185. # return _TestCase.assertAlmostEquals(self, *args, **kwargs)
  186. def assertNotAlmostEquals(self, *args, **kwargs):
  187. raise DeprecationWarning(
  188. 'The {0}() function is deprecated. Please start using {1}() '
  189. 'instead.'.format('assertNotAlmostEquals', 'assertNotAlmostEqual')
  190. )
  191. # return _TestCase.assertNotAlmostEquals(self, *args, **kwargs)
  192. def repack_state_returns(self, state_ret):
  193. '''
  194. Accepts a state return dict and returns it back with the top level key
  195. names rewritten such that the ID declaration is the key instead of the
  196. State's unique tag. For example: 'foo' instead of
  197. 'file_|-foo_|-/etc/foo.conf|-managed'
  198. This makes it easier to work with state returns when crafting asserts
  199. after running states.
  200. '''
  201. assert isinstance(state_ret, dict), state_ret
  202. return {x.split('_|-')[1]: y for x, y in six.iteritems(state_ret)}
  203. def failUnlessEqual(self, *args, **kwargs):
  204. raise DeprecationWarning(
  205. 'The {0}() function is deprecated. Please start using {1}() '
  206. 'instead.'.format('failUnlessEqual', 'assertEqual')
  207. )
  208. # return _TestCase.failUnlessEqual(self, *args, **kwargs)
  209. def failIfEqual(self, *args, **kwargs):
  210. raise DeprecationWarning(
  211. 'The {0}() function is deprecated. Please start using {1}() '
  212. 'instead.'.format('failIfEqual', 'assertNotEqual')
  213. )
  214. # return _TestCase.failIfEqual(self, *args, **kwargs)
  215. def failUnless(self, *args, **kwargs):
  216. raise DeprecationWarning(
  217. 'The {0}() function is deprecated. Please start using {1}() '
  218. 'instead.'.format('failUnless', 'assertTrue')
  219. )
  220. # return _TestCase.failUnless(self, *args, **kwargs)
  221. def failIf(self, *args, **kwargs):
  222. raise DeprecationWarning(
  223. 'The {0}() function is deprecated. Please start using {1}() '
  224. 'instead.'.format('failIf', 'assertFalse')
  225. )
  226. # return _TestCase.failIf(self, *args, **kwargs)
  227. def failUnlessRaises(self, *args, **kwargs):
  228. raise DeprecationWarning(
  229. 'The {0}() function is deprecated. Please start using {1}() '
  230. 'instead.'.format('failUnlessRaises', 'assertRaises')
  231. )
  232. # return _TestCase.failUnlessRaises(self, *args, **kwargs)
  233. def failUnlessAlmostEqual(self, *args, **kwargs):
  234. raise DeprecationWarning(
  235. 'The {0}() function is deprecated. Please start using {1}() '
  236. 'instead.'.format('failUnlessAlmostEqual', 'assertAlmostEqual')
  237. )
  238. # return _TestCase.failUnlessAlmostEqual(self, *args, **kwargs)
  239. def failIfAlmostEqual(self, *args, **kwargs):
  240. raise DeprecationWarning(
  241. 'The {0}() function is deprecated. Please start using {1}() '
  242. 'instead.'.format('failIfAlmostEqual', 'assertNotAlmostEqual')
  243. )
  244. # return _TestCase.failIfAlmostEqual(self, *args, **kwargs)
  245. @staticmethod
  246. def assert_called_once(mock):
  247. '''
  248. mock.assert_called_once only exists in PY3 in 3.6 and newer
  249. '''
  250. try:
  251. mock.assert_called_once()
  252. except AttributeError:
  253. log.warning('assert_called_once invoked, but not available')
  254. if six.PY2:
  255. def assertRegexpMatches(self, *args, **kwds):
  256. raise DeprecationWarning(
  257. 'The {0}() function will be deprecated in python 3. Please start '
  258. 'using {1}() instead.'.format(
  259. 'assertRegexpMatches',
  260. 'assertRegex'
  261. )
  262. )
  263. def assertRegex(self, text, regex, msg=None): # pylint: disable=arguments-differ
  264. # In python 2, alias to the future python 3 function
  265. return _TestCase.assertRegexpMatches(self, text, regex, msg=msg)
  266. def assertNotRegexpMatches(self, *args, **kwds):
  267. raise DeprecationWarning(
  268. 'The {0}() function will be deprecated in python 3. Please start '
  269. 'using {1}() instead.'.format(
  270. 'assertNotRegexpMatches',
  271. 'assertNotRegex'
  272. )
  273. )
  274. def assertNotRegex(self, text, regex, msg=None): # pylint: disable=arguments-differ
  275. # In python 2, alias to the future python 3 function
  276. return _TestCase.assertNotRegexpMatches(self, text, regex, msg=msg)
  277. def assertRaisesRegexp(self, *args, **kwds):
  278. raise DeprecationWarning(
  279. 'The {0}() function will be deprecated in python 3. Please start '
  280. 'using {1}() instead.'.format(
  281. 'assertRaisesRegexp',
  282. 'assertRaisesRegex'
  283. )
  284. )
  285. def assertRaisesRegex(self, exception, regexp, *args, **kwds): # pylint: disable=arguments-differ
  286. # In python 2, alias to the future python 3 function
  287. return _TestCase.assertRaisesRegexp(self, exception, regexp, *args, **kwds)
  288. else:
  289. def assertRegexpMatches(self, *args, **kwds):
  290. raise DeprecationWarning(
  291. 'The {0}() function is deprecated. Please start using {1}() '
  292. 'instead.'.format(
  293. 'assertRegexpMatches',
  294. 'assertRegex'
  295. )
  296. )
  297. def assertNotRegexpMatches(self, *args, **kwds):
  298. raise DeprecationWarning(
  299. 'The {0}() function is deprecated. Please start using {1}() '
  300. 'instead.'.format(
  301. 'assertNotRegexpMatches',
  302. 'assertNotRegex'
  303. )
  304. )
  305. def assertRaisesRegexp(self, *args, **kwds):
  306. raise DeprecationWarning(
  307. 'The {0}() function is deprecated. Please start using {1}() '
  308. 'instead.'.format(
  309. 'assertRaisesRegexp',
  310. 'assertRaisesRegex'
  311. )
  312. )
  313. class TextTestResult(_TextTestResult):
  314. '''
  315. Custom TestResult class whith logs the start and the end of a test
  316. '''
  317. def startTest(self, test):
  318. log.debug('>>>>> START >>>>> {0}'.format(test.id()))
  319. return super(TextTestResult, self).startTest(test)
  320. def stopTest(self, test):
  321. log.debug('<<<<< END <<<<<<< {0}'.format(test.id()))
  322. return super(TextTestResult, self).stopTest(test)
  323. class TextTestRunner(_TextTestRunner):
  324. '''
  325. Custom Text tests runner to log the start and the end of a test case
  326. '''
  327. resultclass = TextTestResult
  328. def skipIf(skip, reason):
  329. from tests.support.runtests import RUNTIME_VARS
  330. if RUNTIME_VARS.PYTEST_SESSION:
  331. import pytest
  332. return pytest.mark.skipif(skip, reason=reason)
  333. return _skipIf(skip, reason)
  334. __all__ = [
  335. 'TestLoader',
  336. 'TextTestRunner',
  337. 'TestCase',
  338. 'expectedFailure',
  339. 'TestSuite',
  340. 'skipIf',
  341. 'TestResult'
  342. ]