1
0

unit.py 17 KB

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