__init__.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. import collections
  24. import os
  25. import subprocess
  26. import unittest
  27. import lxml.etree
  28. import qubes.config
  29. import qubes.events
  30. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  31. in_dom0 = False
  32. #: :py:obj:`False` if outside of git repo,
  33. #: path to root of the directory otherwise
  34. in_git = False
  35. try:
  36. import libvirt
  37. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  38. in_dom0 = True
  39. del libvirt
  40. except libvirt.libvirtError:
  41. pass
  42. try:
  43. in_git = subprocess.check_output(
  44. ['git', 'rev-parse', '--show-toplevel']).strip()
  45. qubes.log.LOGPATH = '/tmp'
  46. qubes.log.LOGFILE = '/tmp/qubes.log'
  47. except subprocess.CalledProcessError:
  48. # git returned nonzero, we are outside git repo
  49. pass
  50. except OSError:
  51. # command not found; let's assume we're outside
  52. pass
  53. def skipUnlessDom0(test_item):
  54. '''Decorator that skips test outside dom0.
  55. Some tests (especially integration tests) have to be run in more or less
  56. working dom0. This is checked by connecting to libvirt.
  57. ''' # pylint: disable=invalid-name
  58. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  59. def skipUnlessGit(test_item):
  60. '''Decorator that skips test outside git repo.
  61. There are very few tests that an be run only in git. One example is
  62. correctness of example code that won't get included in RPM.
  63. ''' # pylint: disable=invalid-name
  64. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  65. class TestEmitter(qubes.events.Emitter):
  66. '''Dummy event emitter which records events fired on it.
  67. Events are counted in :py:attr:`fired_events` attribute, which is
  68. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  69. kwargs)`` object is counted. *event* is event name (a string), *args* is
  70. tuple with positional arguments and *kwargs* is sorted tuple of items from
  71. keyword arguments.
  72. >>> emitter = TestEmitter()
  73. >>> emitter.fired_events
  74. Counter()
  75. >>> emitter.fire_event('event', 1, 2, 3, spam='eggs', foo='bar')
  76. >>> emitter.fired_events
  77. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  78. '''
  79. def __init__(self, *args, **kwargs):
  80. super(TestEmitter, self).__init__(*args, **kwargs)
  81. #: :py:class:`collections.Counter` instance
  82. self.fired_events = collections.Counter()
  83. def fire_event(self, event, *args, **kwargs):
  84. super(TestEmitter, self).fire_event(event, *args, **kwargs)
  85. self.fired_events[(event, args, tuple(sorted(kwargs.items())))] += 1
  86. def fire_event_pre(self, event, *args, **kwargs):
  87. super(TestEmitter, self).fire_event_pre(event, *args, **kwargs)
  88. self.fired_events[(event, args, tuple(sorted(kwargs.items())))] += 1
  89. class QubesTestCase(unittest.TestCase):
  90. '''Base class for Qubes unit tests.
  91. '''
  92. def __str__(self):
  93. return '{}/{}/{}'.format(
  94. '.'.join(self.__class__.__module__.split('.')[2:]),
  95. self.__class__.__name__,
  96. self._testMethodName)
  97. def assertXMLEqual(self, xml1, xml2):
  98. '''Check for equality of two XML objects.
  99. :param xml1: first element
  100. :param xml2: second element
  101. :type xml1: :py:class:`lxml.etree._Element`
  102. :type xml2: :py:class:`lxml.etree._Element`
  103. ''' # pylint: disable=invalid-name
  104. self.assertEqual(xml1.tag, xml2.tag)
  105. self.assertEqual(xml1.text, xml2.text)
  106. self.assertItemsEqual(xml1.keys(), xml2.keys())
  107. for key in xml1.keys():
  108. self.assertEqual(xml1.get(key), xml2.get(key))
  109. def assertEventFired(self, emitter, event, args=None, kwargs=None):
  110. '''Check whether event was fired on given emitter and fail if it did
  111. not.
  112. :param emitter: emitter which is being checked
  113. :type emitter: :py:class:`TestEmitter`
  114. :param str event: event identifier
  115. :param list args: when given, all items must appear in args passed to \
  116. an event
  117. :param list kwargs: when given, all items must appear in kwargs passed \
  118. to an event
  119. ''' # pylint: disable=invalid-name
  120. for ev, ev_args, ev_kwargs in emitter.fired_events:
  121. if ev != event:
  122. continue
  123. if args is not None and any(i not in ev_args for i in args):
  124. continue
  125. if kwargs is not None and any(i not in ev_kwargs for i in kwargs):
  126. continue
  127. return
  128. self.fail('event {!r} did not fire on {!r}'.format(event, emitter))
  129. def assertEventNotFired(self, emitter, event, args=None, kwargs=None):
  130. '''Check whether event was fired on given emitter. Fail if it did.
  131. :param emitter: emitter which is being checked
  132. :type emitter: :py:class:`TestEmitter`
  133. :param str event: event identifier
  134. :param list args: when given, all items must appear in args passed to \
  135. an event
  136. :param list kwargs: when given, all items must appear in kwargs passed \
  137. to an event
  138. ''' # pylint: disable=invalid-name
  139. for ev, ev_args, ev_kwargs in emitter.fired_events:
  140. if ev != event:
  141. continue
  142. if args is not None and any(i not in ev_args for i in args):
  143. continue
  144. if kwargs is not None and any(i not in ev_kwargs for i in kwargs):
  145. continue
  146. self.fail('event {!r} did fire on {!r}'.format(event, emitter))
  147. return
  148. def assertXMLIsValid(self, xml, file=None, schema=None):
  149. '''Check whether given XML fulfills Relax NG schema.
  150. Schema can be given in a couple of ways:
  151. - As separate file. This is most common, and also the only way to
  152. handle file inclusion. Call with file name as second argument.
  153. - As string containing actual schema. Put that string in *schema*
  154. keyword argument.
  155. :param lxml.etree._Element xml: XML element instance to check
  156. :param str file: filename of Relax NG schema
  157. :param str schema: optional explicit schema string
  158. ''' # pylint: disable=invalid-name,redefined-builtin
  159. if schema is not None and file is None:
  160. relaxng = schema
  161. if isinstance(relaxng, str):
  162. relaxng = lxml.etree.XML(relaxng)
  163. # pylint: disable=protected-access
  164. if isinstance(relaxng, lxml.etree._Element):
  165. relaxng = lxml.etree.RelaxNG(relaxng)
  166. elif file is not None and schema is None:
  167. if not os.path.isabs(file):
  168. basedirs = ['/usr/share/doc/qubes/relaxng']
  169. if in_git:
  170. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  171. for basedir in basedirs:
  172. abspath = os.path.join(basedir, file)
  173. if os.path.exists(abspath):
  174. file = abspath
  175. break
  176. relaxng = lxml.etree.RelaxNG(file=file)
  177. else:
  178. raise TypeError("There should be excactly one of 'file' and "
  179. "'schema' arguments specified.")
  180. # We have to be extra careful here in case someone messed up with
  181. # self.failureException. It should by default be AssertionError, just
  182. # what is spewed by RelaxNG(), but who knows what might happen.
  183. try:
  184. relaxng.assert_(xml)
  185. except self.failureException:
  186. raise
  187. except AssertionError as e:
  188. self.fail(str(e))