__init__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 traceback
  21. import unittest
  22. import io
  23. import qubesadmin
  24. import qubesadmin.app
  25. class TestVM(object):
  26. def __init__(self, name, **kwargs):
  27. self.name = name
  28. for key, value in kwargs.items():
  29. setattr(self, key, value)
  30. def get_power_state(self):
  31. return getattr(self, 'power_state', 'Running')
  32. def __str__(self):
  33. return self.name
  34. def __lt__(self, other):
  35. if isinstance(other, TestVM):
  36. return self.name < other.name
  37. return NotImplemented
  38. class TestVMCollection(dict):
  39. def __iter__(self):
  40. return iter(self.values())
  41. class TestProcess(object):
  42. def __init__(self, input_callback=None, stdout=None, stderr=None):
  43. self.input_callback = input_callback
  44. self.stdin = io.BytesIO()
  45. # don't let anyone close it, before we get the value
  46. self.stdin_close = self.stdin.close
  47. if self.input_callback:
  48. self.stdin.close = (
  49. lambda: self.input_callback(self.stdin.getvalue()))
  50. else:
  51. self.stdin.close = lambda: None
  52. self.stdout = stdout
  53. self.stderr = stderr
  54. self.returncode = 0
  55. def communicate(self, input=None):
  56. if input is not None:
  57. self.stdin.write(input)
  58. self.stdin.close()
  59. self.stdin_close()
  60. return self.stdout, self.stderr
  61. def wait(self):
  62. self.stdin_close()
  63. return 0
  64. def poll(self):
  65. return None
  66. class _AssertNotRaisesContext(object):
  67. """A context manager used to implement TestCase.assertNotRaises methods.
  68. Stolen from unittest and hacked. Regexp support stripped.
  69. """ # pylint: disable=too-few-public-methods
  70. def __init__(self, expected, test_case, expected_regexp=None):
  71. if expected_regexp is not None:
  72. raise NotImplementedError('expected_regexp is unsupported')
  73. self.expected = expected
  74. self.exception = None
  75. self.failureException = test_case.failureException
  76. def __enter__(self):
  77. return self
  78. def __exit__(self, exc_type, exc_value, tb):
  79. if exc_type is None:
  80. return True
  81. if issubclass(exc_type, self.expected):
  82. raise self.failureException(
  83. "{!r} raised, traceback:\n{!s}".format(
  84. exc_value, ''.join(traceback.format_tb(tb))))
  85. else:
  86. # pass through
  87. return False
  88. class QubesTest(qubesadmin.app.QubesBase):
  89. expected_calls = None
  90. actual_calls = None
  91. service_calls = None
  92. def __init__(self):
  93. super(QubesTest, self).__init__()
  94. #: expected calls and saved replies for them
  95. self.expected_calls = {}
  96. #: actual calls made
  97. self.actual_calls = []
  98. #: rpc service calls
  99. self.service_calls = []
  100. def qubesd_call(self, dest, method, arg=None, payload=None,
  101. payload_stream=None):
  102. if payload_stream:
  103. payload = payload_stream.read()
  104. call_key = (dest, method, arg, payload)
  105. self.actual_calls.append(call_key)
  106. if call_key not in self.expected_calls:
  107. raise AssertionError('Unexpected call {!r}'.format(call_key))
  108. return_data = self.expected_calls[call_key]
  109. if isinstance(return_data, list):
  110. try:
  111. return_data = return_data.pop(0)
  112. except IndexError:
  113. raise AssertionError('Extra call {!r}'.format(call_key))
  114. return self._parse_qubesd_response(return_data)
  115. def run_service(self, dest, service, **kwargs):
  116. self.service_calls.append((dest, service, kwargs))
  117. return TestProcess(lambda input: self.service_calls.append((dest,
  118. service, input)))
  119. class QubesTestCase(unittest.TestCase):
  120. def setUp(self):
  121. super(QubesTestCase, self).setUp()
  122. self.app = QubesTest()
  123. def assertAllCalled(self):
  124. self.assertEqual(
  125. set(self.app.expected_calls.keys()),
  126. set(self.app.actual_calls))
  127. # and also check if calls expected multiple times were called
  128. self.assertFalse([(call, ret)
  129. for call, ret in self.app.expected_calls.items() if
  130. isinstance(ret, list) and ret],
  131. 'Some calls not called expected number of times')
  132. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  133. """Fail if an exception of class excClass is raised
  134. by callableObj when invoked with arguments args and keyword
  135. arguments kwargs. If a different type of exception is
  136. raised, it will not be caught, and the test case will be
  137. deemed to have suffered an error, exactly as for an
  138. unexpected exception.
  139. If called with callableObj omitted or None, will return a
  140. context object used like this::
  141. with self.assertRaises(SomeException):
  142. do_something()
  143. The context manager keeps a reference to the exception as
  144. the 'exception' attribute. This allows you to inspect the
  145. exception after the assertion::
  146. with self.assertRaises(SomeException) as cm:
  147. do_something()
  148. the_exception = cm.exception
  149. self.assertEqual(the_exception.error_code, 3)
  150. """
  151. context = _AssertNotRaisesContext(excClass, self)
  152. if callableObj is None:
  153. return context
  154. with context:
  155. callableObj(*args, **kwargs)