__init__.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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:
  53. self.stdout = io.BytesIO()
  54. else:
  55. self.stdout = stdout
  56. if stderr == subprocess.PIPE:
  57. self.stderr = io.BytesIO()
  58. else:
  59. self.stderr = stderr
  60. self.returncode = 0
  61. def store_input(self):
  62. value = self.stdin.getvalue()
  63. if (not self.got_any_input or value) and self.input_callback:
  64. self.input_callback(self.stdin.getvalue())
  65. self.got_any_input = True
  66. self.stdin.truncate(0)
  67. def communicate(self, input=None):
  68. if input is not None:
  69. self.stdin.write(input)
  70. self.stdin.close()
  71. self.stdin_close()
  72. return self.stdout, self.stderr
  73. def wait(self):
  74. self.stdin_close()
  75. return 0
  76. def poll(self):
  77. return None
  78. class _AssertNotRaisesContext(object):
  79. """A context manager used to implement TestCase.assertNotRaises methods.
  80. Stolen from unittest and hacked. Regexp support stripped.
  81. """ # pylint: disable=too-few-public-methods
  82. def __init__(self, expected, test_case, expected_regexp=None):
  83. if expected_regexp is not None:
  84. raise NotImplementedError('expected_regexp is unsupported')
  85. self.expected = expected
  86. self.exception = None
  87. self.failureException = test_case.failureException
  88. def __enter__(self):
  89. return self
  90. def __exit__(self, exc_type, exc_value, tb):
  91. if exc_type is None:
  92. return True
  93. if issubclass(exc_type, self.expected):
  94. raise self.failureException(
  95. "{!r} raised, traceback:\n{!s}".format(
  96. exc_value, ''.join(traceback.format_tb(tb))))
  97. else:
  98. # pass through
  99. return False
  100. class QubesTest(qubesadmin.app.QubesBase):
  101. expected_service_calls = None
  102. expected_calls = None
  103. actual_calls = None
  104. service_calls = None
  105. def __init__(self):
  106. super(QubesTest, self).__init__()
  107. #: expected Admin API calls and saved replies for them
  108. self.expected_calls = {}
  109. #: expected qrexec service calls and saved replies for them
  110. self.expected_service_calls = {}
  111. #: actual calls made
  112. self.actual_calls = []
  113. #: rpc service calls
  114. self.service_calls = []
  115. def qubesd_call(self, dest, method, arg=None, payload=None,
  116. payload_stream=None):
  117. if payload_stream:
  118. payload = (payload or b'') + payload_stream.read()
  119. call_key = (dest, method, arg, payload)
  120. self.actual_calls.append(call_key)
  121. if call_key not in self.expected_calls:
  122. raise AssertionError('Unexpected call {!r}'.format(call_key))
  123. return_data = self.expected_calls[call_key]
  124. if isinstance(return_data, list):
  125. try:
  126. return_data = return_data.pop(0)
  127. except IndexError:
  128. raise AssertionError('Extra call {!r}'.format(call_key))
  129. return self._parse_qubesd_response(return_data)
  130. def run_service(self, dest, service, **kwargs):
  131. self.service_calls.append((dest, service, kwargs))
  132. call_key = (dest, service)
  133. # TODO: consider it as a future extension, as a replacement for
  134. # checking app.service_calls later
  135. # if call_key not in self.expected_service_calls:
  136. # raise AssertionError('Unexpected service call {!r}'.format(call_key))
  137. if call_key in self.expected_service_calls:
  138. kwargs = kwargs.copy()
  139. kwargs['stdout'] = io.BytesIO(self.expected_service_calls[call_key])
  140. return TestProcess(lambda input: self.service_calls.append((dest,
  141. service, input)),
  142. stdout=kwargs.get('stdout', None),
  143. stderr=kwargs.get('stderr', None),
  144. )
  145. class QubesTestCase(unittest.TestCase):
  146. def setUp(self):
  147. super(QubesTestCase, self).setUp()
  148. self.app = QubesTest()
  149. def assertAllCalled(self):
  150. self.assertEqual(
  151. set(self.app.expected_calls.keys()),
  152. set(self.app.actual_calls))
  153. # and also check if calls expected multiple times were called
  154. self.assertFalse([(call, ret)
  155. for call, ret in self.app.expected_calls.items() if
  156. isinstance(ret, list) and ret],
  157. 'Some calls not called expected number of times')
  158. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  159. """Fail if an exception of class excClass is raised
  160. by callableObj when invoked with arguments args and keyword
  161. arguments kwargs. If a different type of exception is
  162. raised, it will not be caught, and the test case will be
  163. deemed to have suffered an error, exactly as for an
  164. unexpected exception.
  165. If called with callableObj omitted or None, will return a
  166. context object used like this::
  167. with self.assertRaises(SomeException):
  168. do_something()
  169. The context manager keeps a reference to the exception as
  170. the 'exception' attribute. This allows you to inspect the
  171. exception after the assertion::
  172. with self.assertRaises(SomeException) as cm:
  173. do_something()
  174. the_exception = cm.exception
  175. self.assertEqual(the_exception.error_code, 3)
  176. """
  177. context = _AssertNotRaisesContext(excClass, self)
  178. if callableObj is None:
  179. return context
  180. with context:
  181. callableObj(*args, **kwargs)