__init__.py 6.3 KB

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