__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/python -O
  2. import collections
  3. import os
  4. import subprocess
  5. import unittest
  6. import lxml.etree
  7. import qubes.config
  8. import qubes.events
  9. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  10. in_dom0 = False
  11. #: :py:obj:`False` if outside of git repo,
  12. #: path to root of the directory otherwise
  13. in_git = False
  14. try:
  15. import libvirt
  16. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  17. in_dom0 = True
  18. del libvirt
  19. except libvirt.libvirtError:
  20. pass
  21. try:
  22. in_git = subprocess.check_output(
  23. ['git', 'rev-parse', '--show-toplevel']).strip()
  24. except subprocess.CalledProcessError:
  25. # git returned nonzero, we are outside git repo
  26. pass
  27. except OSError:
  28. # command not found; let's assume we're outside
  29. pass
  30. def skipUnlessDom0(test_item):
  31. '''Decorator that skips test outside dom0.
  32. Some tests (especially integration tests) have to be run in more or less
  33. working dom0. This is checked by connecting to libvirt.
  34. '''
  35. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  36. def skipUnlessGit(test_item):
  37. '''Decorator that skips test outside git repo.
  38. There are very few tests that an be run only in git. One example is
  39. correctness of example code that won't get included in RPM.
  40. '''
  41. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  42. class TestEmitter(qubes.events.Emitter):
  43. '''Dummy event emitter which records events fired on it.
  44. Events are counted in :py:attr:`fired_events` attribute, which is
  45. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  46. kwargs)`` object is counted. *event* is event name (a string), *args* is
  47. tuple with positional arguments and *kwargs* is sorted tuple of items from
  48. keyword arguments.
  49. >>> emitter = TestEmitter()
  50. >>> emitter.fired_events
  51. Counter()
  52. >>> emitter.fire_event('event', 1, 2, 3, spam='eggs', foo='bar')
  53. >>> emitter.fired_events
  54. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  55. '''
  56. def __init__(self, *args, **kwargs):
  57. super(TestEmitter, self).__init__(*args, **kwargs)
  58. #: :py:class:`collections.Counter` instance
  59. self.fired_events = collections.Counter()
  60. def fire_event(self, event, *args, **kwargs):
  61. super(TestEmitter, self).fire_event(event, *args, **kwargs)
  62. self.fired_events[(event, args, tuple(sorted(kwargs.items())))] += 1
  63. def fire_event_pre(self, event, *args, **kwargs):
  64. super(TestEmitter, self).fire_event_pre(event, *args, **kwargs)
  65. self.fired_events[(event, args, tuple(sorted(kwargs.items())))] += 1
  66. class QubesTestCase(unittest.TestCase):
  67. '''Base class for Qubes unit tests.
  68. '''
  69. def __str__(self):
  70. return '{}/{}/{}'.format(
  71. '.'.join(self.__class__.__module__.split('.')[2:]),
  72. self.__class__.__name__,
  73. self._testMethodName)
  74. def assertXMLEqual(self, xml1, xml2):
  75. '''Check for equality of two XML objects.
  76. :param xml1: first element
  77. :param xml2: second element
  78. :type xml1: :py:class:`lxml.etree._Element`
  79. :type xml2: :py:class:`lxml.etree._Element`
  80. '''
  81. self.assertEqual(xml1.tag, xml2.tag)
  82. self.assertEqual(xml1.text, xml2.text)
  83. self.assertItemsEqual(xml1.keys(), xml2.keys())
  84. for key in xml1.keys():
  85. self.assertEqual(xml1.get(key), xml2.get(key))
  86. def assertEventFired(self, emitter, event, args=[], kwargs=[]):
  87. '''Check whether event was fired on given emitter and fail if it did
  88. not.
  89. :param emitter: emitter which is being checked
  90. :type emitter: :py:class:`TestEmitter`
  91. :param str event: event identifier
  92. :param list args: when given, all items must appear in args passed to \
  93. an event
  94. :param list kwargs: when given, all items must appear in kwargs passed \
  95. to an event
  96. '''
  97. for ev, ev_args, ev_kwargs in emitter.fired_events:
  98. if ev != event:
  99. continue
  100. if any(i not in ev_args for i in args):
  101. continue
  102. if any(i not in ev_kwargs for i in kwargs):
  103. continue
  104. return
  105. self.fail('event {!r} did not fire on {!r}'.format(event, emitter))
  106. def assertEventNotFired(self, emitter, event, args=[], kwargs=[]):
  107. '''Check whether event was fired on given emitter. Fail if it did.
  108. :param emitter: emitter which is being checked
  109. :type emitter: :py:class:`TestEmitter`
  110. :param str event: event identifier
  111. :param list args: when given, all items must appear in args passed to \
  112. an event
  113. :param list kwargs: when given, all items must appear in kwargs passed \
  114. to an event
  115. '''
  116. for ev, ev_args, ev_kwargs in emitter.fired_events:
  117. if ev != event:
  118. continue
  119. if any(i not in ev_args for i in args):
  120. continue
  121. if any(i not in ev_kwargs for i in kwargs):
  122. continue
  123. self.fail('event {!r} did fire on {!r}'.format(event, emitter))
  124. return
  125. def assertXMLIsValid(self, xml, file=None, schema=None):
  126. '''Check whether given XML fulfills Relax NG schema.
  127. Schema can be given in a couple of ways:
  128. - As separate file. This is most common, and also the only way to
  129. handle file inclusion. Call with file name as second argument.
  130. - As string containing actual schema. Put that string in *schema*
  131. keyword argument.
  132. :param lxml.etree._Element xml: XML element instance to check
  133. :param str file: filename of Relax NG schema
  134. :param str schema: optional explicit schema string
  135. '''
  136. if schema is not None and file is None:
  137. relaxng = schema
  138. if isinstance(relaxng, str):
  139. relaxng = lxml.etree.XML(relaxng)
  140. if isinstance(relaxng, lxml.etree._Element):
  141. relaxng = lxml.etree.RelaxNG(relaxng)
  142. elif file is not None and schema is None:
  143. if not os.path.isabs(file):
  144. basedirs = ['/usr/share/doc/qubes/relaxng']
  145. if in_git:
  146. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  147. for basedir in basedirs:
  148. abspath = os.path.join(basedir, file)
  149. if os.path.exists(abspath):
  150. file = abspath
  151. break
  152. relaxng = lxml.etree.RelaxNG(file=file)
  153. else:
  154. raise TypeError("There should be excactly one of 'file' and "
  155. "'schema' arguments specified.")
  156. # We have to be extra careful here in case someone messed up with
  157. # self.failureException. It should by default be AssertionError, just
  158. # what is spewed by RelaxNG(), but who knows what might happen.
  159. try:
  160. relaxng.assert_(xml)
  161. except self.failureException:
  162. raise
  163. except AssertionError as e:
  164. self.fail(str(e))