gtkhelpers.py 14 KB

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