gtkhelpers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. import gi # isort:skip
  24. gi.require_version('Gtk', '3.0') # isort:skip
  25. from gi.repository import Gtk # isort:skip pylint:
  26. from qubes.tests import skipUnlessEnv
  27. from qubespolicy.gtkhelpers import VMListModeler, GtkOneTimerHelper, \
  28. FocusStealingHelper
  29. mock_domains_info = {
  30. 'dom0': {'icon': 'black', 'type': 'AdminVM'},
  31. 'test-red1': {'icon': 'red', 'type': 'AppVM'},
  32. 'test-red2': {'icon': 'red', 'type': 'AppVM'},
  33. 'test-red3': {'icon': 'red', 'type': 'AppVM'},
  34. 'test-source': {'icon': 'green', 'type': 'AppVM'},
  35. 'test-target': {'icon': 'orange', 'type': 'AppVM'},
  36. '$dispvm:test-disp6': {'icon': 'red', 'type': 'DispVM'},
  37. }
  38. mock_whitelist = ["test-red1", "test-red2", "test-red3",
  39. "test-target", "$dispvm:test-disp6"]
  40. class MockComboEntry:
  41. def __init__(self, text):
  42. self._text = text
  43. def get_active_id(self):
  44. return self._text
  45. def get_text(self):
  46. return self._text
  47. class GtkTestCase(unittest.TestCase):
  48. def __init__(self, *args, **kwargs):
  49. unittest.TestCase.__init__(self, *args, **kwargs)
  50. self._smallest_wait = 0.01
  51. def flush_gtk_events(self, wait_seconds=0):
  52. start = time.time()
  53. iterations = 0
  54. remaining_wait = wait_seconds
  55. time_length = 0
  56. if wait_seconds < 0:
  57. raise ValueError("Only non-negative intervals are allowed.")
  58. while remaining_wait >= 0:
  59. while Gtk.events_pending():
  60. Gtk.main_iteration_do(blocking=False)
  61. iterations += 1
  62. time_length = time.time() - start
  63. remaining_wait = wait_seconds - time_length
  64. if remaining_wait > 0:
  65. time.sleep(self._smallest_wait)
  66. return iterations, time_length
  67. @skipUnlessEnv('DISPLAY')
  68. class VMListModelerTest(VMListModeler, unittest.TestCase):
  69. def __init__(self, *args, **kwargs):
  70. unittest.TestCase.__init__(self, *args, **kwargs)
  71. VMListModeler.__init__(self, mock_domains_info)
  72. def test_entries_gets_loaded(self):
  73. self.assertIsNotNone(self._entries)
  74. def test_valid_qube_name(self):
  75. self.apply_model(Gtk.ComboBox(), list(mock_domains_info.keys()))
  76. for name in ["test-red1", "test-red2", "test-red3",
  77. "test-target", "Disposable VM (test-disp6)"]:
  78. mock = MockComboEntry(name)
  79. self.assertEquals(name,
  80. self._get_valid_qube_name(mock, mock, mock_whitelist))
  81. self.assertEquals(name,
  82. self._get_valid_qube_name(None, mock, mock_whitelist))
  83. self.assertEquals(name,
  84. self._get_valid_qube_name(mock, None, mock_whitelist))
  85. self.assertIsNone(
  86. self._get_valid_qube_name(None, None, mock_whitelist))
  87. def test_valid_qube_name_whitelist(self):
  88. list_exc = ["$dispvm:test-disp6", "test-red2"]
  89. whitelist = [name for name in mock_whitelist if name not in list_exc]
  90. self.apply_model(Gtk.ComboBox(), whitelist)
  91. for name in list_exc:
  92. mock = MockComboEntry(name)
  93. self.assertIsNone(self._get_valid_qube_name(mock, mock, whitelist))
  94. self.assertIsNone(self._get_valid_qube_name(None, mock, whitelist))
  95. self.assertIsNone(self._get_valid_qube_name(mock, None, whitelist))
  96. def test_invalid_qube_name(self):
  97. self.apply_model(Gtk.ComboBox(), mock_whitelist)
  98. for name in ["test-nonexistant", None, "", 1]:
  99. mock = MockComboEntry(name)
  100. self.assertIsNone(
  101. self._get_valid_qube_name(mock, mock, mock_whitelist))
  102. self.assertIsNone(
  103. self._get_valid_qube_name(None, mock, mock_whitelist))
  104. self.assertIsNone(
  105. self._get_valid_qube_name(mock, None, mock_whitelist))
  106. def test_apply_model(self):
  107. new_object = Gtk.ComboBox()
  108. self.assertIsNone(new_object.get_model())
  109. self.apply_model(new_object, mock_whitelist)
  110. self.assertIsNotNone(new_object.get_model())
  111. def test_apply_model_with_entry(self):
  112. new_object = Gtk.ComboBox.new_with_entry()
  113. self.assertIsNone(new_object.get_model())
  114. self.apply_model(new_object, [])
  115. self.assertIsNotNone(new_object.get_model())
  116. def test_apply_model_only_combobox(self):
  117. invalid_types = [1, "One", u'1', {'1': "one"}, VMListModeler(
  118. mock_domains_info)]
  119. for invalid_type in invalid_types:
  120. with self.assertRaises(TypeError):
  121. self.apply_model(invalid_type, [])
  122. def test_apply_model_whitelist(self):
  123. combo = Gtk.ComboBox()
  124. self.apply_model(combo, list(mock_domains_info.keys()))
  125. self.assertEquals(7, len(combo.get_model()))
  126. names = [entry['api_name'] for entry in self._entries.values()]
  127. self.apply_model(combo, [names[0]])
  128. self.assertEquals(1, len(combo.get_model()))
  129. self.apply_model(combo, [names[0], names[1]])
  130. self.assertEquals(2, len(combo.get_model()))
  131. def test_apply_icon(self):
  132. new_object = Gtk.Entry()
  133. self.assertIsNone(
  134. new_object.get_icon_pixbuf(Gtk.EntryIconPosition.PRIMARY))
  135. self.apply_icon(new_object, "Disposable VM (test-disp6)")
  136. self.assertIsNotNone(
  137. new_object.get_icon_pixbuf(Gtk.EntryIconPosition.PRIMARY))
  138. def test_apply_icon_only_entry(self):
  139. invalid_types = [1, "One", u'1', {'1': "one"}, Gtk.ComboBox()]
  140. for invalid_type in invalid_types:
  141. with self.assertRaises(TypeError):
  142. self.apply_icon(invalid_type, "test-disp6")
  143. def test_apply_icon_only_existing(self):
  144. new_object = Gtk.Entry()
  145. for name in ["test-red1", "test-red2", "test-red3",
  146. "test-target", "Disposable VM (test-disp6)"]:
  147. self.apply_icon(new_object, name)
  148. for name in ["test-nonexistant", None, "", 1]:
  149. with self.assertRaises(ValueError):
  150. self.apply_icon(new_object, name)
  151. class GtkOneTimerHelperTest(GtkOneTimerHelper, GtkTestCase):
  152. def __init__(self, *args, **kwargs):
  153. GtkTestCase.__init__(self, *args, **kwargs)
  154. self._test_time = 0.1
  155. GtkOneTimerHelper.__init__(self, self._test_time)
  156. self._run_timers = []
  157. def _timer_run(self, timer_id):
  158. self._run_timers.append(timer_id)
  159. def test_nothing_runs_automatically(self):
  160. self.flush_gtk_events(self._test_time*2)
  161. self.assertEquals([], self._run_timers)
  162. self.assertEquals(0, self._current_timer_id)
  163. self.assertFalse(self._timer_has_completed())
  164. def test_schedule_one_task(self):
  165. self._timer_schedule()
  166. self.flush_gtk_events(self._test_time*2)
  167. self.assertEquals([1], self._run_timers)
  168. self.assertEquals(1, self._current_timer_id)
  169. self.assertTrue(self._timer_has_completed())
  170. def test_invalidate_completed(self):
  171. self._timer_schedule()
  172. self.flush_gtk_events(self._test_time*2)
  173. self.assertEquals([1], self._run_timers)
  174. self.assertEquals(1, self._current_timer_id)
  175. self.assertTrue(self._timer_has_completed())
  176. self._invalidate_timer_completed()
  177. self.assertFalse(self._timer_has_completed())
  178. def test_schedule_and_cancel_one_task(self):
  179. self._timer_schedule()
  180. self._invalidate_current_timer()
  181. self.flush_gtk_events(self._test_time*2)
  182. self.assertEquals([], self._run_timers)
  183. self.assertEquals(2, self._current_timer_id)
  184. self.assertFalse(self._timer_has_completed())
  185. def test_two_tasks(self):
  186. self._timer_schedule()
  187. self.flush_gtk_events(self._test_time/4)
  188. self._timer_schedule()
  189. self.flush_gtk_events(self._test_time*2)
  190. self.assertEquals([2], self._run_timers)
  191. self.assertEquals(2, self._current_timer_id)
  192. self.assertTrue(self._timer_has_completed())
  193. def test_more_tasks(self):
  194. num = 0
  195. for num in range(1, 10):
  196. self._timer_schedule()
  197. self.flush_gtk_events(self._test_time/4)
  198. self.flush_gtk_events(self._test_time*1.75)
  199. self.assertEquals([num], self._run_timers)
  200. self.assertEquals(num, self._current_timer_id)
  201. self.assertTrue(self._timer_has_completed())
  202. def test_more_tasks_cancel(self):
  203. num = 0
  204. for num in range(1, 10):
  205. self._timer_schedule()
  206. self.flush_gtk_events(self._test_time/4)
  207. self._invalidate_current_timer()
  208. self.flush_gtk_events(int(self._test_time*1.75))
  209. self.assertEquals([], self._run_timers)
  210. self.assertEquals(num+1, self._current_timer_id)
  211. self.assertFalse(self._timer_has_completed())
  212. def test_subsequent_tasks(self):
  213. self._timer_schedule() # 1
  214. self.flush_gtk_events(self._test_time*2)
  215. self.assertEquals([1], self._run_timers)
  216. self.assertEquals(1, self._current_timer_id)
  217. self.assertTrue(self._timer_has_completed())
  218. self._timer_schedule() # 2
  219. self.flush_gtk_events(self._test_time*2)
  220. self.assertEquals([1, 2], self._run_timers)
  221. self.assertEquals(2, self._current_timer_id)
  222. self.assertTrue(self._timer_has_completed())
  223. self._invalidate_timer_completed()
  224. self._timer_schedule() # 3
  225. self._invalidate_current_timer() # 4
  226. self.flush_gtk_events(self._test_time*2)
  227. self.assertEquals([1, 2], self._run_timers)
  228. self.assertEquals(4, self._current_timer_id)
  229. self.assertFalse(self._timer_has_completed())
  230. self._timer_schedule() # 5
  231. self.flush_gtk_events(self._test_time*2)
  232. self.assertEquals([1, 2, 5], self._run_timers)
  233. self.assertEquals(5, self._current_timer_id)
  234. self.assertTrue(self._timer_has_completed())
  235. class FocusStealingHelperMock(FocusStealingHelper):
  236. def simulate_focus(self):
  237. self._window_changed_focus(True)
  238. @skipUnlessEnv('DISPLAY')
  239. class FocusStealingHelperTest(FocusStealingHelperMock, GtkTestCase):
  240. def __init__(self, *args, **kwargs):
  241. GtkTestCase.__init__(self, *args, **kwargs)
  242. self._test_time = 0.1
  243. self._test_button = Gtk.Button()
  244. self._test_window = Gtk.Window()
  245. FocusStealingHelperMock.__init__(self, self._test_window,
  246. self._test_button, self._test_time)
  247. def test_nothing_runs_automatically(self):
  248. self.assertFalse(self.can_perform_action())
  249. self.flush_gtk_events(self._test_time*2)
  250. self.assertFalse(self.can_perform_action())
  251. self.assertFalse(self._test_button.get_sensitive())
  252. def test_nothing_runs_automatically_with_request(self):
  253. self.request_sensitivity(True)
  254. self.assertFalse(self.can_perform_action())
  255. self.flush_gtk_events(self._test_time*2)
  256. self.assertFalse(self.can_perform_action())
  257. self.assertFalse(self._test_button.get_sensitive())
  258. def _simulate_focus(self, focused):
  259. self._window_changed_focus(focused)
  260. def test_focus_with_request(self):
  261. self.request_sensitivity(True)
  262. self._simulate_focus(True)
  263. self.flush_gtk_events(self._test_time*2)
  264. self.assertTrue(self.can_perform_action())
  265. self.assertTrue(self._test_button.get_sensitive())
  266. def test_focus_with_late_request(self):
  267. self._simulate_focus(True)
  268. self.flush_gtk_events(self._test_time*2)
  269. self.assertTrue(self.can_perform_action())
  270. self.assertFalse(self._test_button.get_sensitive())
  271. self.request_sensitivity(True)
  272. self.assertTrue(self._test_button.get_sensitive())
  273. def test_immediate_defocus(self):
  274. self.request_sensitivity(True)
  275. self._simulate_focus(True)
  276. self._simulate_focus(False)
  277. self.flush_gtk_events(self._test_time*2)
  278. self.assertFalse(self.can_perform_action())
  279. self.assertFalse(self._test_button.get_sensitive())
  280. def test_focus_then_unfocus(self):
  281. self.request_sensitivity(True)
  282. self._simulate_focus(True)
  283. self.flush_gtk_events(self._test_time*2)
  284. self.assertTrue(self.can_perform_action())
  285. self.assertTrue(self._test_button.get_sensitive())
  286. self._simulate_focus(False)
  287. self.assertFalse(self.can_perform_action())
  288. self.assertFalse(self._test_button.get_sensitive())
  289. def test_focus_cycle(self):
  290. self.request_sensitivity(True)
  291. self._simulate_focus(True)
  292. self.flush_gtk_events(self._test_time*2)
  293. self.assertTrue(self.can_perform_action())
  294. self.assertTrue(self._test_button.get_sensitive())
  295. self._simulate_focus(False)
  296. self.assertFalse(self.can_perform_action())
  297. self.assertFalse(self._test_button.get_sensitive())
  298. self._simulate_focus(True)
  299. self.assertFalse(self.can_perform_action())
  300. self.assertFalse(self._test_button.get_sensitive())
  301. self.flush_gtk_events(self._test_time*2)
  302. self.assertTrue(self.can_perform_action())
  303. self.assertTrue(self._test_button.get_sensitive())
  304. self.request_sensitivity(False)
  305. self.assertTrue(self.can_perform_action())
  306. self.assertFalse(self._test_button.get_sensitive())
  307. self._simulate_focus(False)
  308. self.assertFalse(self.can_perform_action())
  309. self._simulate_focus(True)
  310. self.assertFalse(self.can_perform_action())
  311. self.assertFalse(self._test_button.get_sensitive())
  312. self.flush_gtk_events(self._test_time*2)
  313. self.assertTrue(self.can_perform_action())
  314. self.assertFalse(self._test_button.get_sensitive())
  315. if __name__ == '__main__':
  316. unittest.main()