__init__.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. import subprocess
  21. import traceback
  22. import unittest
  23. import io
  24. import qubesadmin
  25. import qubesadmin.app
  26. class TestVM(object):
  27. def __init__(self, name, **kwargs):
  28. self.name = name
  29. self.klass = 'TestVM'
  30. for key, value in kwargs.items():
  31. setattr(self, key, value)
  32. def get_power_state(self):
  33. return getattr(self, 'power_state', 'Running')
  34. def __str__(self):
  35. return self.name
  36. def __lt__(self, other):
  37. if isinstance(other, TestVM):
  38. return self.name < other.name
  39. return NotImplemented
  40. class TestVMCollection(dict):
  41. def __iter__(self):
  42. return iter(self.values())
  43. class TestProcess(object):
  44. def __init__(self, input_callback=None, stdout=None, stderr=None):
  45. self.input_callback = input_callback
  46. self.got_any_input = False
  47. self.stdin = io.BytesIO()
  48. # don't let anyone close it, before we get the value
  49. self.stdin_close = self.stdin.close
  50. self.stdin.close = self.store_input
  51. self.stdin.flush = self.store_input
  52. if stdout == subprocess.PIPE or stdout == subprocess.DEVNULL \
  53. or stdout is None:
  54. self.stdout = io.BytesIO()
  55. else:
  56. self.stdout = stdout
  57. if stderr == subprocess.PIPE or stderr == subprocess.DEVNULL \
  58. or stderr is None:
  59. self.stderr = io.BytesIO()
  60. else:
  61. self.stderr = stderr
  62. self.returncode = 0
  63. def store_input(self):
  64. value = self.stdin.getvalue()
  65. if (not self.got_any_input or value) and self.input_callback:
  66. self.input_callback(self.stdin.getvalue())
  67. self.got_any_input = True
  68. self.stdin.truncate(0)
  69. def communicate(self, input=None):
  70. if input is not None:
  71. self.stdin.write(input)
  72. self.stdin.close()
  73. self.stdin_close()
  74. return self.stdout.read(), self.stderr.read()
  75. def wait(self):
  76. self.stdin_close()
  77. return 0
  78. def poll(self):
  79. return None
  80. class _AssertNotRaisesContext(object):
  81. """A context manager used to implement TestCase.assertNotRaises methods.
  82. Stolen from unittest and hacked. Regexp support stripped.
  83. """ # pylint: disable=too-few-public-methods
  84. def __init__(self, expected, test_case, expected_regexp=None):
  85. if expected_regexp is not None:
  86. raise NotImplementedError('expected_regexp is unsupported')
  87. self.expected = expected
  88. self.exception = None
  89. self.failureException = test_case.failureException
  90. def __enter__(self):
  91. return self
  92. def __exit__(self, exc_type, exc_value, tb):
  93. if exc_type is None:
  94. return True
  95. if issubclass(exc_type, self.expected):
  96. raise self.failureException(
  97. "{!r} raised, traceback:\n{!s}".format(
  98. exc_value, ''.join(traceback.format_tb(tb))))
  99. else:
  100. # pass through
  101. return False
  102. class QubesTest(qubesadmin.app.QubesBase):
  103. expected_service_calls = None
  104. expected_calls = None
  105. actual_calls = None
  106. service_calls = None
  107. def __init__(self):
  108. super(QubesTest, self).__init__()
  109. #: expected Admin API calls and saved replies for them
  110. self.expected_calls = {}
  111. #: expected qrexec service calls and saved replies for them
  112. self.expected_service_calls = {}
  113. #: actual calls made
  114. self.actual_calls = []
  115. #: rpc service calls
  116. self.service_calls = []
  117. def qubesd_call(self, dest, method, arg=None, payload=None,
  118. payload_stream=None):
  119. if payload_stream:
  120. payload = (payload or b'') + payload_stream.read()
  121. call_key = (dest, method, arg, payload)
  122. self.actual_calls.append(call_key)
  123. if call_key not in self.expected_calls:
  124. raise AssertionError('Unexpected call {!r}'.format(call_key))
  125. return_data = self.expected_calls[call_key]
  126. if isinstance(return_data, list):
  127. try:
  128. return_data = return_data.pop(0)
  129. except IndexError:
  130. raise AssertionError('Extra call {!r}'.format(call_key))
  131. return self._parse_qubesd_response(return_data)
  132. def run_service(self, dest, service, **kwargs):
  133. self.service_calls.append((dest, service, kwargs))
  134. call_key = (dest, service)
  135. # TODO: consider it as a future extension, as a replacement for
  136. # checking app.service_calls later
  137. # if call_key not in self.expected_service_calls:
  138. # raise AssertionError('Unexpected service call {!r}'.format(call_key))
  139. if call_key in self.expected_service_calls:
  140. kwargs = kwargs.copy()
  141. kwargs['stdout'] = io.BytesIO(self.expected_service_calls[call_key])
  142. return TestProcess(lambda input: self.service_calls.append((dest,
  143. service, input)),
  144. stdout=kwargs.get('stdout', None),
  145. stderr=kwargs.get('stderr', None),
  146. )
  147. class QubesTestCase(unittest.TestCase):
  148. def setUp(self):
  149. super(QubesTestCase, self).setUp()
  150. self.app = QubesTest()
  151. def assertAllCalled(self):
  152. self.assertEqual(
  153. set(self.app.expected_calls.keys()),
  154. set(self.app.actual_calls))
  155. # and also check if calls expected multiple times were called
  156. self.assertFalse([(call, ret)
  157. for call, ret in self.app.expected_calls.items() if
  158. isinstance(ret, list) and ret],
  159. 'Some calls not called expected number of times')
  160. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  161. """Fail if an exception of class excClass is raised
  162. by callableObj when invoked with arguments args and keyword
  163. arguments kwargs. If a different type of exception is
  164. raised, it will not be caught, and the test case will be
  165. deemed to have suffered an error, exactly as for an
  166. unexpected exception.
  167. If called with callableObj omitted or None, will return a
  168. context object used like this::
  169. with self.assertRaises(SomeException):
  170. do_something()
  171. The context manager keeps a reference to the exception as
  172. the 'exception' attribute. This allows you to inspect the
  173. exception after the assertion::
  174. with self.assertRaises(SomeException) as cm:
  175. do_something()
  176. the_exception = cm.exception
  177. self.assertEqual(the_exception.error_code, 3)
  178. """
  179. context = _AssertNotRaisesContext(excClass, self)
  180. if callableObj is None:
  181. return context
  182. with context:
  183. callableObj(*args, **kwargs)