1
0

unit.py 16 KB

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