xmlunit.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. :copyright: Copyright 2014 by the SaltStack Team, see AUTHORS for more details.
  5. :license: Apache 2.0, see LICENSE for more details.
  6. tests.support.xmlunit
  7. ~~~~~~~~~~~~~~~~~~~
  8. XML Unit Tests
  9. '''
  10. # pylint: disable=wrong-import-order,wrong-import-position
  11. # Import python libs
  12. from __future__ import absolute_import
  13. import io
  14. import sys
  15. import logging
  16. # Import 3rd-party libs
  17. from salt.ext import six
  18. log = logging.getLogger(__name__)
  19. try:
  20. import xmlrunner.runner
  21. import xmlrunner.result
  22. HAS_XMLRUNNER = True
  23. class _DelegateIO(object):
  24. '''
  25. This class defines an object that captures whatever is written to
  26. a stream or file.
  27. '''
  28. def __init__(self, delegate):
  29. self._captured = six.StringIO()
  30. self.delegate = delegate
  31. def write(self, text):
  32. if six.PY2 and isinstance(text, six.text_type):
  33. text = text.encode(__salt_system_encoding__)
  34. self._captured.write(text)
  35. self.delegate.write(text)
  36. def fileno(self):
  37. return self.delegate.fileno()
  38. def __getattr__(self, attr):
  39. try:
  40. return getattr(self._captured, attr)
  41. except (AttributeError, io.UnsupportedOperation):
  42. return getattr(self.delegate, attr)
  43. class _XMLTestResult(xmlrunner.result._XMLTestResult):
  44. def startTest(self, test):
  45. log.debug('>>>>> START >>>>> {0}'.format(test.id()))
  46. # xmlrunner classes are NOT new-style classes
  47. xmlrunner.result._XMLTestResult.startTest(self, test)
  48. if self.buffer:
  49. # Let's override the values of self._stdXXX_buffer
  50. # We want a similar sys.stdXXX file like behaviour
  51. self._stderr_buffer = _DelegateIO(sys.__stderr__)
  52. self._stdout_buffer = _DelegateIO(sys.__stdout__)
  53. sys.stderr = self._stderr_buffer
  54. sys.stdout = self._stdout_buffer
  55. def stopTest(self, test):
  56. log.debug('<<<<< END <<<<<<< {0}'.format(test.id()))
  57. # xmlrunner classes are NOT new-style classes
  58. return xmlrunner.result._XMLTestResult.stopTest(self, test)
  59. class XMLTestRunner(xmlrunner.runner.XMLTestRunner):
  60. def _make_result(self):
  61. return _XMLTestResult(
  62. self.stream,
  63. self.descriptions,
  64. self.verbosity,
  65. self.elapsed_times
  66. )
  67. def run(self, test):
  68. result = xmlrunner.runner.XMLTestRunner.run(self, test)
  69. self.stream.writeln('Finished generating XML reports')
  70. return result
  71. except ImportError:
  72. HAS_XMLRUNNER = False
  73. class XMLTestRunner(object):
  74. '''
  75. This is a dumb class just so we don't break projects at import time
  76. '''