__init__.py 5.9 KB

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