gtkhelpers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #!/usr/bin/python
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2017 boring-stuff <boring-stuff@users.noreply.github.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. import time
  22. import unittest
  23. from gi.repository import Gtk
  24. from qubespolicy.gtkhelpers import VMListModeler, GtkOneTimerHelper, \
  25. FocusStealingHelper
  26. mock_domains_info = {
  27. 'dom0': {'icon': 'black', 'type': 'AdminVM'},
  28. 'test-red1': {'icon': 'red', 'type': 'AppVM'},
  29. 'test-red2': {'icon': 'red', 'type': 'AppVM'},
  30. 'test-red3': {'icon': 'red', 'type': 'AppVM'},
  31. 'test-source': {'icon': 'green', 'type': 'AppVM'},
  32. 'test-target': {'icon': 'orange', 'type': 'AppVM'},
  33. '$dispvm:test-disp6': {'icon': 'red', 'type': 'DispVM'},
  34. }
  35. mock_whitelist = ["test-red1", "test-red2", "test-red3",
  36. "test-target", "$dispvm:test-disp6"]
  37. class MockComboEntry:
  38. def __init__(self, text):
  39. self._text = text
  40. def get_active_id(self):
  41. return self._text
  42. def get_text(self):
  43. return self._text
  44. class GtkTestCase(unittest.TestCase):
  45. def __init__(self, *args, **kwargs):
  46. unittest.TestCase.__init__(self, *args, **kwargs)
  47. self._smallest_wait = 0.01
  48. def flush_gtk_events(self, wait_seconds=0):
  49. start = time.time()
  50. iterations = 0
  51. remaining_wait = wait_seconds
  52. time_length = 0
  53. if wait_seconds < 0:
  54. raise ValueError("Only non-negative intervals are allowed.")
  55. while remaining_wait >= 0:
  56. while Gtk.events_pending():
  57. Gtk.main_iteration_do(blocking=False)
  58. iterations += 1
  59. time_length = time.time() - start
  60. remaining_wait = wait_seconds - time_length
  61. if remaining_wait > 0:
  62. time.sleep(self._smallest_wait)
  63. return iterations, time_length
  64. class VMListModelerTest(VMListModeler, unittest.TestCase):
  65. def __init__(self, *args, **kwargs):
  66. unittest.TestCase.__init__(self, *args, **kwargs)
  67. VMListModeler.__init__(self, mock_domains_info)
  68. def test_entries_gets_loaded(self):
  69. self.assertIsNotNone(self._entries)
  70. def test_valid_qube_name(self):
  71. self.apply_model(Gtk.ComboBox(), list(mock_domains_info.keys()))
  72. for name in ["test-red1", "test-red2", "test-red3",
  73. "test-target", "Disposable VM (test-disp6)"]:
  74. mock = MockComboEntry(name)
  75. self.assertEquals(name,
  76. self._get_valid_qube_name(mock, mock, mock_whitelist))
  77. self.assertEquals(name,
  78. self._get_valid_qube_name(None, mock, mock_whitelist))
  79. self.assertEquals(name,
  80. self._get_valid_qube_name(mock, None, mock_whitelist))
  81. self.assertIsNone(
  82. self._get_valid_qube_name(None, None, mock_whitelist))
  83. def test_valid_qube_name_whitelist(self):
  84. list_exc = ["$dispvm:test-disp6", "test-red2"]
  85. whitelist = [name for name in mock_whitelist if name not in list_exc]
  86. self.apply_model(Gtk.ComboBox(), whitelist)
  87. for name in list_exc:
  88. mock = MockComboEntry(name)
  89. self.assertIsNone(self._get_valid_qube_name(mock, mock, whitelist))
  90. self.assertIsNone(self._get_valid_qube_name(None, mock, whitelist))
  91. self.assertIsNone(self._get_valid_qube_name(mock, None, whitelist))
  92. def test_invalid_qube_name(self):
  93. self.apply_model(Gtk.ComboBox(), mock_whitelist)
  94. for name in ["test-nonexistant", None, "", 1]:
  95. mock = MockComboEntry(name)
  96. self.assertIsNone(
  97. self._get_valid_qube_name(mock, mock, mock_whitelist))
  98. self.assertIsNone(
  99. self._get_valid_qube_name(None, mock, mock_whitelist))
  100. self.assertIsNone(
  101. self._get_valid_qube_name(mock, None, mock_whitelist))
  102. def test_apply_model(self):
  103. new_object = Gtk.ComboBox()
  104. self.assertIsNone(new_object.get_model())
  105. self.apply_model(new_object, mock_whitelist)
  106. self.assertIsNotNone(new_object.get_model())
  107. def test_apply_model_with_entry(self):
  108. new_object = Gtk.ComboBox.new_with_entry()
  109. self.assertIsNone(new_object.get_model())
  110. self.apply_model(new_object, [])
  111. self.assertIsNotNone(new_object.get_model())
  112. def test_apply_model_only_combobox(self):
  113. invalid_types = [1, "One", u'1', {'1': "one"}, VMListModeler(
  114. mock_domains_info)]
  115. for invalid_type in invalid_types:
  116. with self.assertRaises(TypeError):
  117. self.apply_model(invalid_type, [])
  118. def test_apply_model_whitelist(self):
  119. combo = Gtk.ComboBox()
  120. self.apply_model(combo, list(mock_domains_info.keys()))
  121. self.assertEquals(7, len(combo.get_model()))
  122. names = [entry['api_name'] for entry in self._entries.values()]
  123. self.apply_model(combo, [names[0]])
  124. self.assertEquals(1, len(combo.get_model()))
  125. self.apply_model(combo, [names[0], names[1]])
  126. self.assertEquals(2, len(combo.get_model()))
  127. def test_apply_icon(self):
  128. new_object = Gtk.Entry()
  129. self.assertIsNone(
  130. new_object.get_icon_pixbuf(Gtk.EntryIconPosition.PRIMARY))
  131. self.apply_icon(new_object, "Disposable VM (test-disp6)")
  132. self.assertIsNotNone(
  133. new_object.get_icon_pixbuf(Gtk.EntryIconPosition.PRIMARY))
  134. def test_apply_icon_only_entry(self):
  135. invalid_types = [1, "One", u'1', {'1': "one"}, Gtk.ComboBox()]
  136. for invalid_type in invalid_types:
  137. with self.assertRaises(TypeError):
  138. self.apply_icon(invalid_type, "test-disp6")
  139. def test_apply_icon_only_existing(self):
  140. new_object = Gtk.Entry()
  141. for name in ["test-red1", "test-red2", "test-red3",
  142. "test-target", "Disposable VM (test-disp6)"]:
  143. self.apply_icon(new_object, name)
  144. for name in ["test-nonexistant", None, "", 1]:
  145. with self.assertRaises(ValueError):
  146. self.apply_icon(new_object, name)
  147. class GtkOneTimerHelperTest(GtkOneTimerHelper, GtkTestCase):
  148. def __init__(self, *args, **kwargs):
  149. GtkTestCase.__init__(self, *args, **kwargs)
  150. self._test_time = 0.1
  151. GtkOneTimerHelper.__init__(self, self._test_time)
  152. self._run_timers = []
  153. def _timer_run(self, timer_id):
  154. self._run_timers.append(timer_id)
  155. def test_nothing_runs_automatically(self):
  156. self.flush_gtk_events(self._test_time*2)
  157. self.assertEquals([], self._run_timers)
  158. self.assertEquals(0, self._current_timer_id)
  159. self.assertFalse(self._timer_has_completed())
  160. def test_schedule_one_task(self):
  161. self._timer_schedule()
  162. self.flush_gtk_events(self._test_time*2)
  163. self.assertEquals([1], self._run_timers)
  164. self.assertEquals(1, self._current_timer_id)
  165. self.assertTrue(self._timer_has_completed())
  166. def test_invalidate_completed(self):
  167. self._timer_schedule()
  168. self.flush_gtk_events(self._test_time*2)
  169. self.assertEquals([1], self._run_timers)
  170. self.assertEquals(1, self._current_timer_id)
  171. self.assertTrue(self._timer_has_completed())
  172. self._invalidate_timer_completed()
  173. self.assertFalse(self._timer_has_completed())
  174. def test_schedule_and_cancel_one_task(self):
  175. self._timer_schedule()
  176. self._invalidate_current_timer()
  177. self.flush_gtk_events(self._test_time*2)
  178. self.assertEquals([], self._run_timers)
  179. self.assertEquals(2, self._current_timer_id)
  180. self.assertFalse(self._timer_has_completed())
  181. def test_two_tasks(self):
  182. self._timer_schedule()
  183. self.flush_gtk_events(self._test_time/4)
  184. self._timer_schedule()
  185. self.flush_gtk_events(self._test_time*2)
  186. self.assertEquals([2], self._run_timers)
  187. self.assertEquals(2, self._current_timer_id)
  188. self.assertTrue(self._timer_has_completed())
  189. def test_more_tasks(self):
  190. num = 0
  191. for num in range(1, 10):
  192. self._timer_schedule()
  193. self.flush_gtk_events(self._test_time/4)
  194. self.flush_gtk_events(self._test_time*1.75)
  195. self.assertEquals([num], self._run_timers)
  196. self.assertEquals(num, self._current_timer_id)
  197. self.assertTrue(self._timer_has_completed())
  198. def test_more_tasks_cancel(self):
  199. num = 0
  200. for num in range(1, 10):
  201. self._timer_schedule()
  202. self.flush_gtk_events(self._test_time/4)
  203. self._invalidate_current_timer()
  204. self.flush_gtk_events(int(self._test_time*1.75))
  205. self.assertEquals([], self._run_timers)
  206. self.assertEquals(num+1, self._current_timer_id)
  207. self.assertFalse(self._timer_has_completed())
  208. def test_subsequent_tasks(self):
  209. self._timer_schedule() # 1
  210. self.flush_gtk_events(self._test_time*2)
  211. self.assertEquals([1], self._run_timers)
  212. self.assertEquals(1, self._current_timer_id)
  213. self.assertTrue(self._timer_has_completed())
  214. self._timer_schedule() # 2
  215. self.flush_gtk_events(self._test_time*2)
  216. self.assertEquals([1, 2], self._run_timers)
  217. self.assertEquals(2, self._current_timer_id)
  218. self.assertTrue(self._timer_has_completed())
  219. self._invalidate_timer_completed()
  220. self._timer_schedule() # 3
  221. self._invalidate_current_timer() # 4
  222. self.flush_gtk_events(self._test_time*2)
  223. self.assertEquals([1, 2], self._run_timers)
  224. self.assertEquals(4, self._current_timer_id)
  225. self.assertFalse(self._timer_has_completed())
  226. self._timer_schedule() # 5
  227. self.flush_gtk_events(self._test_time*2)
  228. self.assertEquals([1, 2, 5], self._run_timers)
  229. self.assertEquals(5, self._current_timer_id)
  230. self.assertTrue(self._timer_has_completed())
  231. class FocusStealingHelperMock(FocusStealingHelper):
  232. def simulate_focus(self):
  233. self._window_changed_focus(True)
  234. class FocusStealingHelperTest(FocusStealingHelperMock, GtkTestCase):
  235. def __init__(self, *args, **kwargs):
  236. GtkTestCase.__init__(self, *args, **kwargs)
  237. self._test_time = 0.1
  238. self._test_button = Gtk.Button()
  239. self._test_window = Gtk.Window()
  240. FocusStealingHelperMock.__init__(self, self._test_window,
  241. self._test_button, self._test_time)
  242. def test_nothing_runs_automatically(self):
  243. self.assertFalse(self.can_perform_action())
  244. self.flush_gtk_events(self._test_time*2)
  245. self.assertFalse(self.can_perform_action())
  246. self.assertFalse(self._test_button.get_sensitive())
  247. def test_nothing_runs_automatically_with_request(self):
  248. self.request_sensitivity(True)
  249. self.assertFalse(self.can_perform_action())
  250. self.flush_gtk_events(self._test_time*2)
  251. self.assertFalse(self.can_perform_action())
  252. self.assertFalse(self._test_button.get_sensitive())
  253. def _simulate_focus(self, focused):
  254. self._window_changed_focus(focused)
  255. def test_focus_with_request(self):
  256. self.request_sensitivity(True)
  257. self._simulate_focus(True)
  258. self.flush_gtk_events(self._test_time*2)
  259. self.assertTrue(self.can_perform_action())
  260. self.assertTrue(self._test_button.get_sensitive())
  261. def test_focus_with_late_request(self):
  262. self._simulate_focus(True)
  263. self.flush_gtk_events(self._test_time*2)
  264. self.assertTrue(self.can_perform_action())
  265. self.assertFalse(self._test_button.get_sensitive())
  266. self.request_sensitivity(True)
  267. self.assertTrue(self._test_button.get_sensitive())
  268. def test_immediate_defocus(self):
  269. self.request_sensitivity(True)
  270. self._simulate_focus(True)
  271. self._simulate_focus(False)
  272. self.flush_gtk_events(self._test_time*2)
  273. self.assertFalse(self.can_perform_action())
  274. self.assertFalse(self._test_button.get_sensitive())
  275. def test_focus_then_unfocus(self):
  276. self.request_sensitivity(True)
  277. self._simulate_focus(True)
  278. self.flush_gtk_events(self._test_time*2)
  279. self.assertTrue(self.can_perform_action())
  280. self.assertTrue(self._test_button.get_sensitive())
  281. self._simulate_focus(False)
  282. self.assertFalse(self.can_perform_action())
  283. self.assertFalse(self._test_button.get_sensitive())
  284. def test_focus_cycle(self):
  285. self.request_sensitivity(True)
  286. self._simulate_focus(True)
  287. self.flush_gtk_events(self._test_time*2)
  288. self.assertTrue(self.can_perform_action())
  289. self.assertTrue(self._test_button.get_sensitive())
  290. self._simulate_focus(False)
  291. self.assertFalse(self.can_perform_action())
  292. self.assertFalse(self._test_button.get_sensitive())
  293. self._simulate_focus(True)
  294. self.assertFalse(self.can_perform_action())
  295. self.assertFalse(self._test_button.get_sensitive())
  296. self.flush_gtk_events(self._test_time*2)
  297. self.assertTrue(self.can_perform_action())
  298. self.assertTrue(self._test_button.get_sensitive())
  299. self.request_sensitivity(False)
  300. self.assertTrue(self.can_perform_action())
  301. self.assertFalse(self._test_button.get_sensitive())
  302. self._simulate_focus(False)
  303. self.assertFalse(self.can_perform_action())
  304. self._simulate_focus(True)
  305. self.assertFalse(self.can_perform_action())
  306. self.assertFalse(self._test_button.get_sensitive())
  307. self.flush_gtk_events(self._test_time*2)
  308. self.assertTrue(self.can_perform_action())
  309. self.assertFalse(self._test_button.get_sensitive())
  310. if __name__ == '__main__':
  311. unittest.main()