test_qube_manager.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  1. #!/usr/bin/python3
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2016 Marta Marczykowska-Górecka
  6. # <marmarta@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 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 General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. import asyncio
  23. import contextlib
  24. import logging.handlers
  25. import unittest
  26. import unittest.mock
  27. import subprocess
  28. import datetime
  29. import time
  30. from PyQt5 import QtTest, QtCore, QtWidgets
  31. from PyQt5.QtCore import (Qt, QSize)
  32. from PyQt5.QtGui import (QIcon)
  33. from qubesadmin import Qubes, events, exc
  34. import qubesmanager.qube_manager as qube_manager
  35. from qubesmanager.tests import init_qtapp
  36. icon_size = qube_manager.icon_size
  37. class QubeManagerTest(unittest.TestCase):
  38. def setUp(self):
  39. super(QubeManagerTest, self).setUp()
  40. self.qtapp, self.loop = init_qtapp()
  41. self.mock_qprogress = unittest.mock.patch(
  42. 'PyQt5.QtWidgets.QProgressDialog')
  43. self.mock_qprogress.start()
  44. self.addCleanup(self.mock_qprogress.stop)
  45. self.qapp = Qubes()
  46. self.dispatcher = events.EventsDispatcher(self.qapp)
  47. self.dialog = qube_manager.VmManagerWindow(
  48. self.qtapp, self.qapp, self.dispatcher)
  49. def test_000_window_loads(self):
  50. self.assertTrue(self.dialog.table is not None, "Window did not load")
  51. def test_001_correct_vms_listed(self):
  52. vms_in_table = []
  53. for row in range(self.dialog.table.model().rowCount()):
  54. vm = self._get_table_vm(row)
  55. self.assertIsNotNone(vm)
  56. vms_in_table.append(vm.name)
  57. # check that name is listed correctly
  58. name_item = self._get_table_item(row, "Name")
  59. self.assertEqual(name_item, vm.name,
  60. "Incorrect VM name for {}".format(vm.name))
  61. actual_vms = [vm.name for vm in self.qapp.domains]
  62. self.assertEqual(len(vms_in_table), len(actual_vms),
  63. "Incorrect number of VMs loaded")
  64. self.assertListEqual(sorted(vms_in_table), sorted(actual_vms),
  65. "Incorrect VMs loaded")
  66. def test_002_correct_template_listed(self):
  67. for row in range(self.dialog.table.model().rowCount()):
  68. vm = self._get_table_vm(row)
  69. # check that template is listed correctly
  70. template_item = self._get_table_item(row, "Template")
  71. if getattr(vm, "template", None):
  72. self.assertEqual(vm.template,
  73. template_item,
  74. "Incorrect template for {}".format(vm.name))
  75. else:
  76. self.assertEqual(vm.klass, template_item,
  77. "Incorrect class for {}".format(vm.name))
  78. def test_003_correct_netvm_listed(self):
  79. for row in range(self.dialog.table.model().rowCount()):
  80. vm = self._get_table_vm(row)
  81. # check that netvm is listed correctly
  82. netvm_item = self._get_table_item(row, "NetVM")
  83. netvm_value = getattr(vm, "netvm", None)
  84. if not netvm_value:
  85. netvm_value = "n/a"
  86. if netvm_value and hasattr(vm, "netvm") \
  87. and vm.property_is_default("netvm"):
  88. netvm_value = "default ({})".format(netvm_value)
  89. self.assertEqual(netvm_value,
  90. netvm_item,
  91. "Incorrect netvm for {}".format(vm.name))
  92. def test_004_correct_disk_usage_listed(self):
  93. for row in range(self.dialog.table.model().rowCount()):
  94. vm = self._get_table_vm(row)
  95. size_item = self._get_table_item(row, "Disk Usage")
  96. if vm.klass == 'AdminVM':
  97. size_value = "n/a"
  98. else:
  99. size_value = round(vm.get_disk_utilization() / (1024 * 1024), 2)
  100. size_value = str(size_value) + " MiB"
  101. self.assertEqual(size_value,
  102. size_item,
  103. "Incorrect size for {}".format(vm.name))
  104. def test_005_correct_internal_listed(self):
  105. for row in range(self.dialog.table.model().rowCount()):
  106. vm = self._get_table_vm(row)
  107. internal_item = self._get_table_item(row, "Internal")
  108. internal_value = "Yes" if vm.features.get('internal', False) else ""
  109. self.assertEqual(internal_item, internal_value,
  110. "Incorrect internal value for {}".format(vm.name))
  111. def test_006_correct_ip_listed(self):
  112. for row in range(self.dialog.table.model().rowCount()):
  113. vm = self._get_table_vm(row)
  114. ip_item = self._get_table_item(row, "IP")
  115. if hasattr(vm, 'ip'):
  116. ip_value = getattr(vm, 'ip')
  117. ip_value = "" if ip_value is None else ip_value
  118. else:
  119. ip_value = "n/a"
  120. self.assertEqual(ip_value, ip_item,
  121. "Incorrect ip value for {}".format(vm.name))
  122. def test_007_incl_in_backups_listed(self):
  123. for row in range(self.dialog.table.model().rowCount()):
  124. vm = self._get_table_vm(row)
  125. incl_backups_item = self._get_table_item(row, "Include in backups")
  126. incl_backups_value = getattr(vm, 'include_in_backups', False)
  127. incl_backups_value = "Yes" if incl_backups_value else ""
  128. self.assertEqual(
  129. incl_backups_value, incl_backups_item,
  130. "Incorrect include in backups value for {}".format(vm.name))
  131. def test_008_last_backup_listed(self):
  132. for row in range(self.dialog.table.model().rowCount()):
  133. vm = self._get_table_vm(row)
  134. last_backup_item = self._get_table_item(row, "Last backup")
  135. last_backup_value = getattr(vm, 'backup_timestamp', None)
  136. if last_backup_value:
  137. last_backup_value = str(
  138. datetime.datetime.fromtimestamp(last_backup_value))
  139. self.assertEqual(
  140. last_backup_value, last_backup_item,
  141. "Incorrect last backup value for {}".format(vm.name))
  142. def test_009_def_dispvm_listed(self):
  143. for row in range(self.dialog.table.model().rowCount()):
  144. vm = self._get_table_vm(row)
  145. def_dispvm_item = self._get_table_item(row, "Default DispVM")
  146. if vm.property_is_default("default_dispvm"):
  147. def_dispvm_value = "default ({})".format(
  148. self.qapp.default_dispvm)
  149. else:
  150. def_dispvm_value = getattr(vm, "default_dispvm", None)
  151. self.assertEqual(
  152. def_dispvm_value, def_dispvm_item,
  153. "Incorrect default dispvm value for {}".format(vm.name))
  154. def test_010_is_dvm_template_listed(self):
  155. for row in range(self.dialog.table.model().rowCount()):
  156. vm = self._get_table_vm(row)
  157. is_dvm_template_item = self._get_table_item(row, "Is DVM Template")
  158. is_dvm_template_value = "Yes" if \
  159. getattr(vm, "template_for_dispvms", False) else ""
  160. self.assertEqual(
  161. is_dvm_template_value, is_dvm_template_item,
  162. "Incorrect is DVM template value for {}".format(vm.name))
  163. def test_011_is_label_correct(self):
  164. for row in range(self.dialog.table.model().rowCount()):
  165. vm = self._get_table_vm(row)
  166. icon = QIcon.fromTheme(getattr(vm, 'icon', 'appvm-black'))
  167. icon = icon.pixmap(icon_size)
  168. label_pixmap = self._get_table_item(row, "Label", Qt.DecorationRole)
  169. self.assertEqual(label_pixmap.toImage(), icon.toImage())
  170. def test_012_is_state_correct(self):
  171. for row in range(self.dialog.table.model().rowCount()):
  172. vm = self._get_table_vm(row)
  173. displayed_power_state = self._get_table_item(row, "State")['power']
  174. self.assertEqual(
  175. displayed_power_state, vm.get_power_state(),
  176. "Wrong power state displayed for {}".format(vm.name))
  177. def test_013_incorrect_settings_file(self):
  178. mock_settings = unittest.mock.MagicMock(spec=QtCore.QSettings)
  179. settings_result_dict = {"view/sort_column": "Cthulhu",
  180. "view/sort_order": "Fhtagn",
  181. "view/menubar_visible": "R'lyeh"
  182. }
  183. mock_settings.side_effect = (
  184. lambda x, *args, **kwargs: settings_result_dict.get(x))
  185. with unittest.mock.patch('PyQt5.QtCore.QSettings.value',
  186. mock_settings),\
  187. unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.warning')\
  188. as mock_warning:
  189. self.dialog = qube_manager.VmManagerWindow(
  190. self.qtapp, self.qapp, self.dispatcher)
  191. self.assertEqual(mock_warning.call_count, 1)
  192. def test_100_sorting(self):
  193. col = self.dialog.qubes_model.columns_indices.index("Template")
  194. self.dialog.table.sortByColumn(col, QtCore.Qt.AscendingOrder)
  195. self.__check_sorting("Template")
  196. col = self.dialog.qubes_model.columns_indices.index("Name")
  197. self.dialog.table.sortByColumn(col, QtCore.Qt.AscendingOrder)
  198. self.__check_sorting("Name")
  199. @unittest.mock.patch('qubesmanager.qube_manager.QSettings.setValue')
  200. def test_101_hide_column(self, mock_settings):
  201. model = self.dialog.qubes_model
  202. action_no = model.columns_indices.index('Is DVM Template')
  203. self.dialog.menu_view.actions()[action_no].trigger()
  204. mock_settings.assert_called_with('columns/Is DVM Template', True)
  205. self.dialog.menu_view.actions()[action_no].trigger()
  206. mock_settings.assert_called_with('columns/Is DVM Template', False)
  207. @unittest.mock.patch('qubesmanager.settings.VMSettingsWindow')
  208. def test_200_vm_open_settings(self, mock_window):
  209. selected_vm = self._select_non_admin_vm()
  210. self.assertIsNotNone(selected_vm, "No valid non-admin VM found")
  211. widget = self.dialog.toolbar.widgetForAction(
  212. self.dialog.action_settings)
  213. QtTest.QTest.mouseClick(widget,
  214. QtCore.Qt.LeftButton)
  215. mock_window.assert_called_once_with(
  216. selected_vm, qapp=self.qtapp, init_page="basic", qubesapp=self.qapp)
  217. def test_201_vm_open_settings_admin(self):
  218. self._select_admin_vm()
  219. self.assertFalse(self.dialog.action_settings.isEnabled(),
  220. "Settings not disabled for admin VM")
  221. self.assertFalse(self.dialog.action_editfwrules.isEnabled(),
  222. "Editfw not disabled for admin VM")
  223. self.assertFalse(self.dialog.action_appmenus.isEnabled(),
  224. "Appmenus not disabled for admin VM")
  225. @unittest.mock.patch('qubesmanager.settings.VMSettingsWindow')
  226. def test_202_vm_open_firewall(self, mock_window):
  227. selected_vm = self._select_non_admin_vm()
  228. self.assertIsNotNone(selected_vm, "No valid non-admin VM found")
  229. widget = self.dialog.toolbar.widgetForAction(
  230. self.dialog.action_editfwrules)
  231. QtTest.QTest.mouseClick(widget,
  232. QtCore.Qt.LeftButton)
  233. mock_window.assert_called_once_with(
  234. selected_vm, qapp=self.qtapp, init_page="firewall",
  235. qubesapp=self.qapp)
  236. @unittest.mock.patch('qubesmanager.settings.VMSettingsWindow')
  237. def test_203_vm_open_apps(self, mock_window):
  238. selected_vm = self._select_non_admin_vm()
  239. self.assertIsNotNone(selected_vm, "No valid non-admin VM found")
  240. widget = self.dialog.toolbar.widgetForAction(
  241. self.dialog.action_appmenus)
  242. QtTest.QTest.mouseClick(widget,
  243. QtCore.Qt.LeftButton)
  244. mock_window.assert_called_once_with(
  245. selected_vm, qapp=self.qtapp, init_page="applications",
  246. qubesapp=self.qapp)
  247. @unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.warning')
  248. def test_204_vm_keyboard(self, mock_message):
  249. selected_vm = self._select_non_admin_vm(running=True)
  250. self.assertIsNotNone(selected_vm, "No valid non-admin VM found")
  251. widget = self.dialog.toolbar.widgetForAction(
  252. self.dialog.action_set_keyboard_layout)
  253. with unittest.mock.patch.object(selected_vm, 'run') as mock_run:
  254. QtTest.QTest.mouseClick(widget,
  255. QtCore.Qt.LeftButton)
  256. mock_run.assert_called_once_with("qubes-change-keyboard-layout")
  257. self.assertEqual(mock_message.call_count, 0,
  258. "VM does not support new layout change")
  259. @unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.warning')
  260. def test_205_vm_keyboard_not_running(self, mock_message):
  261. selected_vm = self._select_non_admin_vm(running=False)
  262. self.assertIsNotNone(selected_vm, "No valid non-admin VM found")
  263. widget = self.dialog.toolbar.widgetForAction(
  264. self.dialog.action_set_keyboard_layout)
  265. with unittest.mock.patch.object(selected_vm, 'run') as mock_run:
  266. QtTest.QTest.mouseClick(widget,
  267. QtCore.Qt.LeftButton)
  268. self.assertEqual(mock_run.call_count, 0,
  269. "Keyboard change called on a halted VM")
  270. self.assertEqual(mock_message.call_count, 0,
  271. "Keyboard change called on a halted VM with"
  272. " obsolete keyboard-layout handling")
  273. def test_206_dom0_keyboard(self):
  274. self._select_admin_vm()
  275. self.assertFalse(self.dialog.action_set_keyboard_layout.isEnabled())
  276. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  277. return_value=QtWidgets.QMessageBox.Yes)
  278. def test_207_update_vm_not_running(self, _):
  279. selected_vm = self._select_templatevm(running=False)
  280. self.assertIsNotNone(selected_vm, "No valid template VM found")
  281. widget = self.dialog.toolbar.widgetForAction(
  282. self.dialog.action_updatevm)
  283. with unittest.mock.patch('qubesmanager.qube_manager.UpdateVMThread') \
  284. as mock_update:
  285. QtTest.QTest.mouseClick(widget,
  286. QtCore.Qt.LeftButton)
  287. mock_update.assert_called_once_with(selected_vm)
  288. mock_update().start.assert_called_once_with()
  289. def test_208_update_vm_admin(self):
  290. selected_vm = self._select_admin_vm()
  291. self.assertIsNotNone(selected_vm, "No valid admin VM found")
  292. widget = self.dialog.toolbar.widgetForAction(
  293. self.dialog.action_updatevm)
  294. with unittest.mock.patch('qubesmanager.qube_manager.UpdateVMThread') \
  295. as mock_update:
  296. QtTest.QTest.mouseClick(widget,
  297. QtCore.Qt.LeftButton)
  298. mock_update.assert_called_once_with(selected_vm)
  299. mock_update().start.assert_called_once_with()
  300. @unittest.mock.patch("PyQt5.QtWidgets.QInputDialog.getText",
  301. return_value=("command to run", True))
  302. def test_209_run_command_in_vm(self, _):
  303. selected_vm = self._select_non_admin_vm()
  304. self.assertIsNotNone(selected_vm, "No valid non-admin VM found")
  305. with unittest.mock.patch('qubesmanager.qube_manager.RunCommandThread') \
  306. as mock_thread:
  307. self.dialog.action_run_command_in_vm.trigger()
  308. mock_thread.assert_called_once_with(selected_vm, "command to run")
  309. mock_thread().finished.connect.assert_called_once_with(
  310. self.dialog.clear_threads)
  311. mock_thread().start.assert_called_once_with()
  312. def test_210_run_command_in_adminvm(self):
  313. self._select_admin_vm()
  314. self.assertFalse(self.dialog.action_run_command_in_vm.isEnabled(),
  315. "Should not be able to run commands for dom0")
  316. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.warning")
  317. def test_211_pausevm(self, mock_warn):
  318. selected_vm = self._select_non_admin_vm(running=True)
  319. self.assertTrue(self.dialog.action_pausevm.isEnabled(),
  320. "Pause not enabled for a running VM")
  321. with unittest.mock.patch.object(selected_vm, 'pause') as mock_pause:
  322. self.dialog.action_pausevm.trigger()
  323. mock_pause.assert_called_once_with()
  324. mock_pause.side_effect = exc.QubesException('Error')
  325. self.dialog.action_pausevm.trigger()
  326. self.assertEqual(mock_warn.call_count, 1)
  327. def test_212_resumevm(self):
  328. selected_vm = self._select_non_admin_vm(running=False)
  329. with unittest.mock.patch.object(selected_vm, 'get_power_state')\
  330. as mock_state, \
  331. unittest.mock.patch.object(selected_vm, 'unpause')\
  332. as mock_unpause:
  333. mock_state.return_value = 'Paused'
  334. self.dialog.action_resumevm.trigger()
  335. mock_unpause.assert_called_once_with()
  336. with unittest.mock.patch('qubesmanager.qube_manager.StartVMThread') \
  337. as mock_thread:
  338. self.dialog.action_resumevm.trigger()
  339. mock_thread.assert_called_once_with(selected_vm)
  340. mock_thread().finished.connect.assert_called_once_with(
  341. self.dialog.clear_threads)
  342. mock_thread().start.assert_called_once_with()
  343. def test_213_resume_running_vm(self):
  344. self._select_non_admin_vm(running=True)
  345. self.assertFalse(self.dialog.action_resumevm.isEnabled())
  346. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  347. return_value=QtWidgets.QMessageBox.Yes)
  348. @unittest.mock.patch('PyQt5.QtCore.QTimer.singleShot')
  349. @unittest.mock.patch('qubesmanager.qube_manager.VmShutdownMonitor')
  350. def test_214_shutdownvm(self, mock_monitor, mock_timer, _):
  351. selected_vm = self._select_non_admin_vm(running=True)
  352. with unittest.mock.patch.object(selected_vm, 'shutdown')\
  353. as mock_shutdown:
  354. self.dialog.action_shutdownvm.trigger()
  355. mock_shutdown.assert_called_once_with()
  356. mock_monitor.assert_called_once_with(
  357. selected_vm,
  358. unittest.mock.ANY, unittest.mock.ANY,
  359. unittest.mock.ANY, unittest.mock.ANY)
  360. mock_timer.assert_called_once_with(unittest.mock.ANY,
  361. unittest.mock.ANY)
  362. def test_215_shutdown_halted_vm(self):
  363. self._select_non_admin_vm(running=False)
  364. self.assertFalse(self.dialog.action_shutdownvm.isEnabled())
  365. @unittest.mock.patch('qubesmanager.create_new_vm.NewVmDlg')
  366. def test_216_create_vm(self, mock_new_vm):
  367. action = self.dialog.action_createvm
  368. self.assertTrue(action.isEnabled())
  369. action.trigger()
  370. self.assertEqual(mock_new_vm.call_count, 1,
  371. "Create New VM window did not appear")
  372. def test_217_remove_admin_vm(self):
  373. self._select_admin_vm()
  374. self.assertFalse(self.dialog.action_removevm.isEnabled())
  375. @unittest.mock.patch("qubesmanager.qube_manager.QMessageBox")
  376. @unittest.mock.patch('qubesadmin.utils.vm_dependencies')
  377. def test_218_remove_vm_dependencies(self, mock_dependencies, mock_msgbox):
  378. mock_vm = unittest.mock.Mock(spec=['name'],
  379. **{'name.return_value': 'test-vm'})
  380. mock_dependencies.return_value = [(mock_vm, "test_prop")]
  381. action = self.dialog.action_removevm
  382. self._select_non_admin_vm()
  383. action.trigger()
  384. mock_msgbox().show.assert_called_with()
  385. @unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.warning')
  386. @unittest.mock.patch("PyQt5.QtWidgets.QInputDialog.getText")
  387. @unittest.mock.patch('qubesadmin.utils.vm_dependencies')
  388. def test_219_remove_vm_no_depencies(
  389. self, mock_dependencies, mock_input, mock_warning):
  390. action = self.dialog.action_removevm
  391. selected_vm = self._select_non_admin_vm(running=False)
  392. # test with no dependencies
  393. mock_dependencies.return_value = None
  394. with unittest.mock.patch('qubesmanager.common_threads.RemoveVMThread')\
  395. as mock_thread:
  396. mock_input.return_value = (selected_vm, False)
  397. action.trigger()
  398. self.assertEqual(mock_thread.call_count, 0,
  399. "VM removed despite user clicking 'cancel")
  400. mock_input.return_value = ("wrong_name", True)
  401. action.trigger()
  402. self.assertEqual(mock_warning.call_count, 1)
  403. self.assertEqual(mock_thread.call_count, 0,
  404. "VM removed despite user not confirming the name")
  405. mock_input.return_value = (selected_vm.name, True)
  406. action.trigger()
  407. mock_thread.assert_called_once_with(selected_vm)
  408. mock_thread().finished.connect.assert_called_once_with(
  409. self.dialog.clear_threads)
  410. mock_thread().start.assert_called_once_with()
  411. def test_220_restartvm_halted_vm(self):
  412. self._select_non_admin_vm(running=False)
  413. self.assertFalse(self.dialog.action_restartvm.isEnabled())
  414. @unittest.mock.patch('PyQt5.QtCore.QTimer.singleShot')
  415. @unittest.mock.patch('qubesmanager.qube_manager.VmShutdownMonitor')
  416. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  417. return_value=QtWidgets.QMessageBox.Yes)
  418. def test_221_restartvm_running_vm(self, _msgbox, mock_monitor, _qtimer):
  419. selected_vm = self._select_non_admin_vm(running=True)
  420. action = self.dialog.action_restartvm
  421. # currently the VM is running
  422. with unittest.mock.patch.object(selected_vm, 'shutdown')\
  423. as mock_shutdown:
  424. action.trigger()
  425. mock_shutdown.assert_called_once_with()
  426. mock_monitor.assert_called_once_with(
  427. selected_vm, unittest.mock.ANY,
  428. unittest.mock.ANY, True, unittest.mock.ANY)
  429. @unittest.mock.patch('qubesmanager.qube_manager.StartVMThread')
  430. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  431. return_value=QtWidgets.QMessageBox.Yes)
  432. def test_222_restartvm_shutdown_meantime(self, _, mock_thread):
  433. selected_vm = self._select_non_admin_vm(running=True)
  434. action = self.dialog.action_restartvm
  435. # it was shutdown in the meantime
  436. with unittest.mock.patch.object(
  437. selected_vm, 'is_running', **{'return_value': False}):
  438. action.trigger()
  439. mock_thread.assert_called_once_with(selected_vm)
  440. mock_thread().finished.connect.assert_called_once_with(
  441. self.dialog.clear_threads)
  442. mock_thread().start.assert_called_once_with()
  443. @unittest.mock.patch('qubesmanager.qube_manager.UpdateVMThread')
  444. def test_223_updatevm_running(self, mock_thread):
  445. selected_vm = self._select_non_admin_vm(running=True)
  446. self.dialog.action_updatevm.trigger()
  447. mock_thread.assert_called_once_with(selected_vm)
  448. mock_thread().finished.connect.assert_called_once_with(
  449. self.dialog.clear_threads)
  450. mock_thread().start.assert_called_once_with()
  451. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  452. return_value=QtWidgets.QMessageBox.Yes)
  453. @unittest.mock.patch('qubesmanager.qube_manager.UpdateVMThread')
  454. def test_224_updatevm_halted(self, mock_thread, _):
  455. selected_vm = self._select_non_admin_vm(running=False)
  456. self.dialog.action_updatevm.trigger()
  457. mock_thread.assert_called_once_with(selected_vm)
  458. mock_thread().finished.connect.assert_called_once_with(
  459. self.dialog.clear_threads)
  460. mock_thread().start.assert_called_once_with()
  461. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  462. return_value=QtWidgets.QMessageBox.Yes)
  463. def test_224_killvm(self, _):
  464. selected_vm = self._select_non_admin_vm(running=True)
  465. action = self.dialog.action_killvm
  466. with unittest.mock.patch.object(selected_vm, 'kill') as mock_kill:
  467. action.trigger()
  468. mock_kill.assert_called_once_with()
  469. @unittest.mock.patch("PyQt5.QtWidgets.QMessageBox.question",
  470. return_value=QtWidgets.QMessageBox.Cancel)
  471. def test_225_killvm_cancel(self, _):
  472. selected_vm = self._select_non_admin_vm(running=True)
  473. action = self.dialog.action_killvm
  474. with unittest.mock.patch.object(selected_vm, 'kill') as mock_kill:
  475. action.trigger()
  476. self.assertEqual(mock_kill.call_count, 0,
  477. "Ignored Cancel on kill VM")
  478. @unittest.mock.patch('qubesmanager.global_settings.GlobalSettingsWindow')
  479. def test_226_global_settings(self, mock_settings):
  480. self._select_non_admin_vm()
  481. self.dialog.action_global_settings.trigger()
  482. self.assertEqual(mock_settings.call_count, 1,
  483. "Global Settings not opened")
  484. self._select_admin_vm()
  485. self.dialog.action_global_settings.trigger()
  486. self.assertEqual(mock_settings.call_count, 2,
  487. "Global Settings not opened for the second time")
  488. @unittest.mock.patch('qubesmanager.backup.BackupVMsWindow')
  489. def test_227_backup(self, mock_backup):
  490. self.dialog.action_backup.trigger()
  491. self.assertTrue(self.dialog.action_backup.isEnabled())
  492. self.assertEqual(mock_backup.call_count, 1,
  493. "Backup window does not appear")
  494. @unittest.mock.patch('qubesmanager.restore.RestoreVMsWindow')
  495. def test_228_restore(self, mock_restore):
  496. self.dialog.action_restore.trigger()
  497. self.assertTrue(self.dialog.action_restore.isEnabled())
  498. self.assertEqual(mock_restore.call_count, 1,
  499. "Backup window does not appear")
  500. @unittest.mock.patch('qubesmanager.qube_manager.AboutDialog')
  501. def test_229_about_qubes(self, mock_about):
  502. self.assertTrue(self.dialog.action_about_qubes.isEnabled())
  503. self.dialog.action_about_qubes.trigger()
  504. self.assertEqual(
  505. mock_about.call_count, 1, "About window does not appear")
  506. def test_230_exit_action(self):
  507. self.assertTrue(self.dialog.action_exit.isEnabled())
  508. with unittest.mock.patch.object(self.dialog, 'close') as mock_close:
  509. self.dialog.action_exit.trigger()
  510. mock_close.assert_called_once_with()
  511. @unittest.mock.patch('subprocess.check_call')
  512. def test_231_template_manager(self, mock_subprocess):
  513. self.assertTrue(self.dialog.action_manage_templates.isEnabled())
  514. self.dialog.action_manage_templates.trigger()
  515. mock_subprocess.assert_called_once_with('qubes-template-manager')
  516. @unittest.mock.patch('qubesmanager.clone_vm.CloneVMDlg')
  517. def test_232_clonevm(self, mock_clone):
  518. action = self.dialog.action_clonevm
  519. self._select_admin_vm()
  520. self.assertFalse(action.isEnabled())
  521. selected_vm = self._select_non_admin_vm()
  522. self.assertTrue(action.isEnabled())
  523. action.trigger()
  524. mock_clone.assert_called_once_with(self.qtapp, self.qapp,
  525. src_vm=selected_vm)
  526. def test_233_search_action(self):
  527. self.qtapp.setActiveWindow(self.dialog.searchbox)
  528. self.dialog.action_search.trigger()
  529. self.assertTrue(self.dialog.searchbox.hasFocus())
  530. # input text
  531. self.dialog.searchbox.setText("sys")
  532. # click outside the widget
  533. QtTest.QTest.mouseClick(self.dialog.table, QtCore.Qt.LeftButton)
  534. # click the widget, check if it is correctly activated and the whole
  535. # text was selected
  536. QtTest.QTest.mouseClick(self.dialog.searchbox, QtCore.Qt.LeftButton)
  537. self.assertTrue(self.dialog.searchbox.hasFocus())
  538. self.assertEqual(self.dialog.searchbox.selectedText(), "sys")
  539. def test_234_searchbox(self):
  540. # look for sys
  541. self.dialog.searchbox.setText("sys")
  542. expected_number = \
  543. len([vm for vm in self.qapp.domains if "sys" in vm.name])
  544. actual_number = self._count_visible_table_rows()
  545. self.assertEqual(expected_number, actual_number,
  546. "Incorrect number of vms shown for 'sys'")
  547. # clear search
  548. self.dialog.searchbox.setText("")
  549. expected_number = len([vm for vm in self.qapp.domains])
  550. actual_number = self._count_visible_table_rows()
  551. self.assertEqual(expected_number, actual_number,
  552. "Incorrect number of vms shown for cleared search box")
  553. def test_235_hide_show_toolbars(self):
  554. with unittest.mock.patch('PyQt5.QtCore.QSettings.setValue')\
  555. as mock_setvalue:
  556. self.dialog.action_menubar.trigger()
  557. mock_setvalue.assert_called_with('view/menubar_visible', False)
  558. self.dialog.action_toolbar.trigger()
  559. mock_setvalue.assert_called_with('view/toolbar_visible', False)
  560. self.assertFalse(self.dialog.menubar.isVisible(),
  561. "Menubar not hidden correctly")
  562. self.assertFalse(self.dialog.toolbar.isVisible(),
  563. "Toolbar not hidden correctly")
  564. def test_236_clear_searchbox(self):
  565. self.dialog.searchbox.setText("text")
  566. self.assertEqual(self.dialog.searchbox.text(), "text")
  567. QtTest.QTest.keyPress(self.dialog, QtCore.Qt.Key_Escape)
  568. self.assertEqual(self.dialog.searchbox.text(), "",
  569. "Escape failed to clear searchbox")
  570. expected_number = len([vm for vm in self.qapp.domains])
  571. actual_number = self._count_visible_table_rows()
  572. self.assertEqual(expected_number, actual_number,
  573. "Incorrect number of vms shown for cleared search box")
  574. @unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.information')
  575. @unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.warning')
  576. def test_300_clear_threads(self, mock_warning, mock_info):
  577. mock_thread_finished_ok = unittest.mock.Mock(
  578. spec=['isFinished', 'msg', 'msg_is_success'],
  579. msg=None, msg_is_success=False,
  580. **{'isFinished.return_value': True})
  581. mock_thread_not_finished = unittest.mock.Mock(
  582. spec=['isFinished', 'msg', 'msg_is_success'],
  583. msg=None, msg_is_success=False,
  584. **{'isFinished.return_value': False})
  585. mock_thread_finished_error = unittest.mock.Mock(
  586. spec=['isFinished', 'msg', 'msg_is_success'],
  587. msg=("Error", "Error"), msg_is_success=False,
  588. **{'isFinished.return_value': True})
  589. mock_thread_fin_error_success = unittest.mock.Mock(
  590. spec=['isFinished', 'msg', 'msg_is_success'],
  591. msg=("Done", "Done"), msg_is_success=True,
  592. **{'isFinished.return_value': True})
  593. # single finished thread
  594. self.dialog.threads_list = [mock_thread_not_finished,
  595. mock_thread_finished_ok]
  596. self.dialog.clear_threads()
  597. self.assertEqual(mock_warning.call_count, 0)
  598. self.assertEqual(mock_info.call_count, 0)
  599. self.assertEqual(len(self.dialog.threads_list), 1)
  600. # an error thread and some in-progress ones
  601. self.dialog.threads_list = [mock_thread_not_finished,
  602. mock_thread_not_finished,
  603. mock_thread_finished_error]
  604. self.dialog.clear_threads()
  605. self.assertEqual(mock_warning.call_count, 1)
  606. self.assertEqual(mock_info.call_count, 0)
  607. self.assertEqual(len(self.dialog.threads_list), 2)
  608. # an error-success thread and some in-progress ones
  609. self.dialog.threads_list = [mock_thread_not_finished,
  610. mock_thread_not_finished,
  611. mock_thread_fin_error_success,
  612. mock_thread_finished_error]
  613. self.dialog.clear_threads()
  614. self.assertEqual(mock_warning.call_count, 1)
  615. self.assertEqual(mock_info.call_count, 1)
  616. self.assertEqual(len(self.dialog.threads_list), 3)
  617. def test_400_event_domain_added(self):
  618. number_of_vms = self.dialog.table.model().rowCount()
  619. self.addCleanup(subprocess.call, ["qvm-remove", "-f", "test-vm"])
  620. self._run_command_and_process_events(
  621. ["qvm-create", "--label", "red", "test-vm"])
  622. # a single row was added to the table
  623. self.assertEqual(self.dialog.table.model().rowCount(), number_of_vms+1)
  624. # table contains the correct vms
  625. vms_in_table = self._create_set_of_current_vms()
  626. vms_in_system = set([vm.name for vm in self.qapp.domains])
  627. self.assertEqual(vms_in_table, vms_in_system, "Table not updated "
  628. "correctly after add")
  629. # check if sorting works
  630. self.__check_sorting("Name")
  631. # try opening settings for the added vm
  632. for row in range(self.dialog.table.model().rowCount()):
  633. name = self._get_table_item(row, "Name")
  634. if name == "test-vm":
  635. index = self.dialog.table.model().index(row, 0)
  636. self.dialog.table.setCurrentIndex(index)
  637. break
  638. with unittest.mock.patch('qubesmanager.settings.VMSettingsWindow')\
  639. as mock_settings:
  640. self.dialog.action_settings.trigger()
  641. mock_settings.assert_called_once_with(
  642. self.qapp.domains["test-vm"], qapp = self.qtapp,
  643. init_page = "basic", qubesapp = self.qapp)
  644. def test_401_event_domain_removed(self):
  645. initial_vms = self._create_set_of_current_vms()
  646. self._run_command_and_process_events(
  647. ["qvm-create", "--label", "red", "test-vm"])
  648. current_vms = self._create_set_of_current_vms()
  649. self.assertEqual(len(initial_vms) + 1, len(current_vms))
  650. self._run_command_and_process_events(
  651. ["qvm-remove", "--force", "test-vm"])
  652. current_vms = self._create_set_of_current_vms()
  653. self.assertEqual(initial_vms, current_vms)
  654. # check if sorting works
  655. self.__check_sorting("Name")
  656. def test_403_event_dispvm_added(self):
  657. initial_vms = self._create_set_of_current_vms()
  658. dispvm_template = None
  659. for vm in self.qapp.domains:
  660. if getattr(vm, "template_for_dispvms", False):
  661. dispvm_template = vm.name
  662. break
  663. self.assertIsNotNone(dispvm_template,
  664. "Cannot find a template for dispVMs")
  665. # this requires very long timeout, because it takes time for the
  666. # dispvm to vanish
  667. self._run_command_and_process_events(
  668. ["qvm-run", "--dispvm", dispvm_template, "true"], timeout=60,
  669. additional_timeout=60)
  670. final_vms = self._create_set_of_current_vms()
  671. self.assertEqual(initial_vms, final_vms,
  672. "Failed handling of a created-and-removed dispvm")
  673. def test_404_crashing_dispvm(self):
  674. initial_vms = self._create_set_of_current_vms()
  675. dispvm_template = None
  676. for vm in self.qapp.domains:
  677. if getattr(vm, "template_for_dispvms", False):
  678. dispvm_template = vm.name
  679. break
  680. self.assertIsNotNone(dispvm_template,
  681. "Cannot find a template for dispVMs")
  682. current_memory = getattr(self.qapp.domains[dispvm_template], "memory")
  683. self.addCleanup(
  684. subprocess.call,
  685. ["qvm-prefs", dispvm_template, "memory", str(current_memory)])
  686. subprocess.check_call(
  687. ["qvm-prefs", dispvm_template, "memory", "600000"])
  688. self._run_command_and_process_events(
  689. ["qvm-run", "--dispvm", dispvm_template, "true"], timeout=30,
  690. additional_timeout=15)
  691. final_vms = self._create_set_of_current_vms()
  692. self.assertEqual(initial_vms, final_vms,
  693. "Failed handling of dispvm that crashed on start")
  694. def test_405_prop_change_label(self):
  695. target_vm_name = "work"
  696. vm_row = self._find_vm_row(target_vm_name)
  697. current_label = self._get_table_item(vm_row, "Label", Qt.DecorationRole)
  698. self.addCleanup(
  699. subprocess.call, ["qvm-prefs", target_vm_name, "label", "blue"])
  700. self._run_command_and_process_events(
  701. ["qvm-prefs", target_vm_name, "label", "red"], timeout=20)
  702. new_label = self._get_table_item(vm_row, "Label", Qt.DecorationRole)
  703. self.assertNotEqual(current_label.toImage(), new_label.toImage(),
  704. "Label icon did not change")
  705. icon = QIcon.fromTheme(self.qapp.domains[target_vm_name].label.icon)
  706. icon = icon.pixmap(icon_size)
  707. self.assertEqual(new_label.toImage(), icon.toImage(), "Incorrect label")
  708. def test_406_prop_change_template(self):
  709. target_vm_name = "work"
  710. vm_row = self._find_vm_row(target_vm_name)
  711. old_template = self._get_table_item(vm_row, "Template")
  712. new_template = None
  713. for vm in self.qapp.domains:
  714. if vm.klass == 'TemplateVM' and vm.name != old_template:
  715. new_template = vm.name
  716. break
  717. self.addCleanup(
  718. subprocess.call,
  719. ["qvm-prefs", target_vm_name, "template", old_template])
  720. self._run_command_and_process_events(
  721. ["qvm-prefs", target_vm_name, "template", new_template])
  722. self.assertNotEqual(old_template,
  723. self._get_table_item(vm_row, "Template"),
  724. "Template did not change")
  725. self.assertEqual(
  726. self._get_table_item(vm_row, "Template"),
  727. self.qapp.domains[target_vm_name].template.name,
  728. "Incorrect template")
  729. def test_407_prop_change_netvm(self):
  730. target_vm_name = "work"
  731. vm_row = self._find_vm_row(target_vm_name)
  732. old_netvm = self._get_table_item(vm_row, "NetVM")
  733. new_netvm = None
  734. for vm in self.qapp.domains:
  735. if getattr(vm, "provides_network", False) and vm.name != old_netvm:
  736. new_netvm = vm.name
  737. break
  738. self.addCleanup(
  739. subprocess.call, ["qvm-prefs", target_vm_name, "netvm", old_netvm])
  740. self._run_command_and_process_events(
  741. ["qvm-prefs", target_vm_name, "netvm", new_netvm])
  742. self.assertNotEqual(old_netvm,
  743. self._get_table_item(vm_row, "NetVM"),
  744. "NetVM did not change")
  745. self.assertEqual(
  746. self._get_table_item(vm_row, "NetVM"),
  747. self.qapp.domains[target_vm_name].netvm.name,
  748. "Incorrect NetVM")
  749. @unittest.expectedFailure
  750. def test_408_prop_change_internal(self):
  751. target_vm_name = "work"
  752. vm_row = self._find_vm_row(target_vm_name)
  753. self.addCleanup(subprocess.call,
  754. ["qvm-features", "--unset", "work", "interal"])
  755. self._run_command_and_process_events(
  756. ["qvm-features", "work", "interal", "1"])
  757. self.assertEqual(
  758. self._get_table_item(vm_row, "Internal"),
  759. "Yes",
  760. "Incorrect value for internal VM")
  761. self._run_command_and_process_events(
  762. ["qvm-features", "--unset", "work", "interal"])
  763. self.assertEqual(
  764. self._get_table_item(vm_row, "Internal"),
  765. "",
  766. "Incorrect value for non-internal VM")
  767. def test_409_prop_change_ip(self):
  768. target_vm_name = "work"
  769. vm_row = self._find_vm_row(target_vm_name)
  770. old_ip = self._get_table_item(vm_row, "IP")
  771. new_ip = old_ip.replace(".0.", ".5.")
  772. self.addCleanup(
  773. subprocess.call, ["qvm-prefs", target_vm_name, "ip", old_ip])
  774. self._run_command_and_process_events(
  775. ["qvm-prefs", target_vm_name, "ip", new_ip])
  776. self.assertNotEqual(old_ip,
  777. self._get_table_item(vm_row, "IP"),
  778. "IP did not change")
  779. self.assertEqual(
  780. self._get_table_item(vm_row, "IP"),
  781. self.qapp.domains[target_vm_name].ip,
  782. "Incorrect IP")
  783. def test_410_prop_change_in_backups(self):
  784. target_vm_name = "work"
  785. vm_row = self._find_vm_row(target_vm_name)
  786. old_value = self.qapp.domains[target_vm_name].include_in_backups
  787. new_value = not old_value
  788. self.addCleanup(
  789. subprocess.call,
  790. ["qvm-prefs", target_vm_name, "include_in_backups", str(old_value)])
  791. self._run_command_and_process_events(
  792. ["qvm-prefs", target_vm_name, "include_in_backups", str(new_value)])
  793. self.assertEqual(
  794. self._get_table_item(vm_row, "Internal"),
  795. "Yes" if new_value else "",
  796. "Incorrect value for include_in_backups")
  797. def test_411_prop_change_last_backup(self):
  798. target_vm_name = "work"
  799. target_timestamp = "2015-01-01 17:00:00"
  800. vm_row = self._find_vm_row(target_vm_name)
  801. old_value = self._get_table_item(vm_row, "Last backup")
  802. new_value = datetime.datetime.strptime(
  803. target_timestamp, "%Y-%m-%d %H:%M:%S")
  804. self.addCleanup(
  805. subprocess.call,
  806. ["qvm-prefs", '-D', target_vm_name, "backup_timestamp"])
  807. self._run_command_and_process_events(
  808. ["qvm-prefs", target_vm_name, "backup_timestamp",
  809. str(int(new_value.timestamp()))])
  810. self.assertNotEqual(old_value,
  811. self._get_table_item(vm_row, "Last backup"),
  812. "Last backup date did not change")
  813. self.assertEqual(
  814. self._get_table_item(vm_row, "Last backup"),
  815. target_timestamp,
  816. "Incorrect Last backup date")
  817. def test_412_prop_change_defdispvm(self):
  818. target_vm_name = "work"
  819. vm_row = self._find_vm_row(target_vm_name)
  820. old_default_dispvm =\
  821. self._get_table_item(vm_row, "Default DispVM")
  822. new_default_dispvm = None
  823. for vm in self.qapp.domains:
  824. if getattr(vm, "template_for_dispvms", False) and vm.name !=\
  825. old_default_dispvm:
  826. new_default_dispvm = vm.name
  827. break
  828. self.addCleanup(
  829. subprocess.call,
  830. ["qvm-prefs", target_vm_name, "default_dispvm", old_default_dispvm])
  831. self._run_command_and_process_events(
  832. ["qvm-prefs", target_vm_name, "default_dispvm", new_default_dispvm])
  833. self.assertNotEqual(
  834. old_default_dispvm,
  835. self._get_table_item(vm_row, "Default DispVM"),
  836. "Default DispVM did not change")
  837. self.assertEqual(
  838. self._get_table_item(vm_row, "Default DispVM"),
  839. self.qapp.domains[target_vm_name].default_dispvm.name,
  840. "Incorrect Default DispVM")
  841. def test_413_prop_change_templ_disp(self):
  842. target_vm_name = "work"
  843. vm_row = self._find_vm_row(target_vm_name)
  844. self.addCleanup(
  845. subprocess.call,
  846. ["qvm-prefs", "--default", target_vm_name, "template_for_dispvms"])
  847. self._run_command_and_process_events(
  848. ["qvm-prefs", target_vm_name, "template_for_dispvms", "True"])
  849. self.assertEqual(
  850. self._get_table_item(vm_row, "Is DVM Template"),
  851. "Yes",
  852. "Incorrect value for DVM Template")
  853. self._run_command_and_process_events(
  854. ["qvm-prefs", "--default", target_vm_name, "template_for_dispvms"])
  855. self.assertEqual(
  856. self._get_table_item(vm_row, "Is DVM Template"),
  857. "",
  858. "Incorrect value for not DVM Template")
  859. def test_414_vm_state_change(self):
  860. target_vm_name = "work"
  861. vm_row = self._find_vm_row(target_vm_name)
  862. self.assertFalse(self.qapp.domains[target_vm_name].is_running())
  863. self.addCleanup(
  864. subprocess.call,
  865. ["qvm-shutdown", "--wait", target_vm_name])
  866. self._run_command_and_process_events(
  867. ["qvm-start", target_vm_name], timeout=60)
  868. displayed_state = self._get_table_item(vm_row, "State")
  869. self.assertEqual(displayed_state['power'], 'Running',
  870. "Power state failed to update on start")
  871. self._run_command_and_process_events(
  872. ["qvm-shutdown", "--wait", target_vm_name], timeout=30)
  873. displayed_state = self._get_table_item(vm_row, "State")
  874. self.assertEqual(displayed_state['power'], 'Halted',
  875. "Power state failed to update on shutdown")
  876. def test_415_template_vm_started(self):
  877. # check whether changing state of a template_vm causes all other
  878. # vms depending on it to check theirs
  879. target_vm_name = None
  880. for vm in self.qapp.domains:
  881. if vm.klass == 'TemplateVM':
  882. for vm2 in self.qapp.domains:
  883. if getattr(vm2, 'template', None) == vm.name:
  884. target_vm_name = vm.name
  885. break
  886. if target_vm_name:
  887. break
  888. for i in range(self.dialog.table.model().rowCount()):
  889. self._get_table_vminfo(i).update = unittest.mock.Mock()
  890. self.addCleanup(
  891. subprocess.call,
  892. ["qvm-shutdown", "--wait", target_vm_name])
  893. self._run_command_and_process_events(
  894. ["qvm-start", target_vm_name], timeout=60)
  895. for i in range(self.dialog.table.model().rowCount()):
  896. call_count = self._get_table_vminfo(
  897. i).update.call_count
  898. if self._get_table_item(i, "Template") == target_vm_name:
  899. self.assertGreater(call_count, 0)
  900. elif self._get_table_item(i, "Name") == target_vm_name:
  901. self.assertGreater(call_count, 0)
  902. else:
  903. self.assertEqual(call_count, 0)
  904. def test_500_logs(self):
  905. self._select_admin_vm()
  906. self.assertTrue(self.dialog.logs_menu.isEnabled())
  907. dom0_logs = set()
  908. for c in self.dialog.logs_menu.actions():
  909. dom0_logs.add(c.text())
  910. self.assertIsNotNone(
  911. c.data(), "Empty log file found: {}".format(c.text()))
  912. self.assertIn("hypervisor", c.text(),
  913. "Log for dom0 does not contain 'hypervisor'")
  914. selected_vm = self._select_non_admin_vm(running=True).name
  915. self.assertTrue(self.dialog.logs_menu.isEnabled())
  916. vm_logs = set()
  917. for c in self.dialog.logs_menu.actions():
  918. vm_logs.add(c.text())
  919. self.assertIsNotNone(
  920. c.data(),
  921. "Empty log file found: {}".format(c.text()))
  922. self.assertIn(
  923. selected_vm,
  924. c.text(),
  925. "Log for {} does not contain its name".format(selected_vm))
  926. self.assertNotEqual(dom0_logs, vm_logs,
  927. "Same logs found for dom0 and non-adminVM")
  928. def _find_vm_row(self, vm_name):
  929. for row in range(self.dialog.table.model().rowCount()):
  930. name = self._get_table_item(row, "Name")
  931. if name == vm_name:
  932. return row
  933. return None
  934. def _count_visible_table_rows(self):
  935. result = 0
  936. for i in range(self.dialog.table.model().rowCount()):
  937. if not self.dialog.table.isRowHidden(i):
  938. result += 1
  939. return result
  940. def _run_command_and_process_events(self, command, timeout=5,
  941. additional_timeout=None):
  942. """
  943. helper function to run a given command and process eventsDispatcher
  944. events
  945. :param command: list of strings, containing the command and all its
  946. parameters
  947. :param timeout: default 5 seconds
  948. :param additional_timeout: default none
  949. :return:
  950. """
  951. asyncio.set_event_loop(self.loop)
  952. future1 = asyncio.ensure_future(self.dispatcher.listen_for_events())
  953. self.loop.run_until_complete(asyncio.sleep(0))
  954. future2 = asyncio.create_subprocess_exec(*command,
  955. stdout=subprocess.DEVNULL,
  956. stderr=subprocess.DEVNULL)
  957. future2 = self.loop.run_until_complete(future2).wait()
  958. if additional_timeout:
  959. (done, pending) = self.loop.run_until_complete(
  960. asyncio.wait({future1, future2}, timeout=timeout,
  961. return_when=asyncio.FIRST_COMPLETED))
  962. (done, pending) = self.loop.run_until_complete(
  963. asyncio.wait(pending, timeout=additional_timeout))
  964. else:
  965. (done, pending) = self.loop.run_until_complete(
  966. asyncio.wait({future1, future2}, timeout=timeout))
  967. for task in pending:
  968. with contextlib.suppress(asyncio.CancelledError):
  969. task.cancel()
  970. self.loop.call_soon(self.loop.stop)
  971. self.loop.run_forever()
  972. def _create_set_of_current_vms(self):
  973. result = set()
  974. for i in range(self.dialog.table.model().rowCount()):
  975. result.add(self._get_table_item(i, "Name"))
  976. return result
  977. def _select_admin_vm(self):
  978. for row in range(self.dialog.table.model().rowCount()):
  979. template = self._get_table_item(row, "Template")
  980. if template == 'AdminVM':
  981. index = self.dialog.table.model().index(row, 0)
  982. self.dialog.table.setCurrentIndex(index)
  983. return index.data(Qt.UserRole).vm
  984. return None
  985. def _select_non_admin_vm(self, running=None):
  986. for row in range(self.dialog.table.model().rowCount()):
  987. template = self._get_table_item(row, "Template")
  988. vm = self._get_table_vm(row)
  989. if template != 'AdminVM' and \
  990. (running is None
  991. or (running and vm.is_running())
  992. or (not running and not vm.is_running())):
  993. index = self.dialog.table.model().index(row, 0)
  994. self.dialog.table.setCurrentIndex(index)
  995. return vm
  996. return None
  997. def _select_templatevm(self, running=None):
  998. for row in range(self.dialog.table.model().rowCount()):
  999. template = self._get_table_item(row, "Template")
  1000. vm = self._get_table_vm(row)
  1001. if template == 'TemplateVM' and \
  1002. (running is None
  1003. or (running and vm.is_running())
  1004. or (not running and not vm.is_running())):
  1005. index = self.dialog.table.model().index(row, 0)
  1006. self.dialog.table.setCurrentIndex(index)
  1007. return vm
  1008. return None
  1009. def __check_sorting(self, column_name):
  1010. last_text = None
  1011. last_vm = None
  1012. for row in range(self.dialog.table.model().rowCount()):
  1013. vm = self._get_table_item(row, "Name")
  1014. text = self._get_table_item(row, column_name)
  1015. if row == 0:
  1016. self.assertEqual(vm, "dom0", "dom0 is not sorted first")
  1017. elif last_text is None:
  1018. last_text = text
  1019. last_vm = vm
  1020. else:
  1021. if last_text == text:
  1022. self.assertGreater(
  1023. vm.lower(), last_vm.lower(),
  1024. "Incorrect sorting for {}".format(column_name))
  1025. else:
  1026. self.assertGreater(
  1027. text.lower(), last_text.lower(),
  1028. "Incorrect sorting for {}".format(column_name))
  1029. last_text = text
  1030. last_vm = vm
  1031. def _get_table_vminfo(self, row):
  1032. model = self.dialog.table.model()
  1033. return model.index(row, 0).data(Qt.UserRole)
  1034. def _get_table_vm(self, row):
  1035. model = self.dialog.table.model()
  1036. return model.index(row, 0).data(Qt.UserRole).vm
  1037. def _get_table_item(self, row, column_name, role=Qt.DisplayRole):
  1038. model = self.dialog.table.model()
  1039. column = self.dialog.qubes_model.columns_indices.index(column_name)
  1040. return model.index(row, column).data(role)
  1041. class QubeManagerThreadTest(unittest.TestCase):
  1042. def test_01_startvm_thread(self):
  1043. vm = unittest.mock.Mock(spec=['start'])
  1044. thread = qube_manager.StartVMThread(vm)
  1045. thread.run()
  1046. vm.start.assert_called_once_with()
  1047. def test_02_startvm_thread_error(self):
  1048. vm = unittest.mock.Mock(
  1049. spec=['start'],
  1050. **{'start.side_effect': exc.QubesException('Error')})
  1051. thread = qube_manager.StartVMThread(vm)
  1052. thread.run()
  1053. self.assertIsNotNone(thread.msg)
  1054. def test_10_run_command_thread(self):
  1055. vm = unittest.mock.Mock(spec=['run'])
  1056. thread = qube_manager.RunCommandThread(vm, "test_command")
  1057. thread.run()
  1058. vm.run.assert_called_once_with("test_command")
  1059. def test_11_run_command_thread_error(self):
  1060. vm = unittest.mock.Mock(spec=['run'],
  1061. **{'run.side_effect': ChildProcessError})
  1062. thread = qube_manager.RunCommandThread(vm, "test_command")
  1063. thread.run()
  1064. self.assertIsNotNone(thread.msg)
  1065. @unittest.mock.patch('subprocess.check_call')
  1066. def test_20_update_vm_thread_dom0(self, check_call):
  1067. vm = unittest.mock.Mock(spec=['klass'])
  1068. vm.klass = 'AdminVM'
  1069. thread = qube_manager.UpdateVMThread(vm)
  1070. thread.run()
  1071. check_call.assert_called_once_with(
  1072. ["/usr/bin/qubes-dom0-update", "--clean", "--gui"])
  1073. @unittest.mock.patch('builtins.open')
  1074. @unittest.mock.patch('subprocess.call')
  1075. def test_21_update_vm_thread_running(self, mock_call, mock_open):
  1076. vm = unittest.mock.Mock(
  1077. spec=['klass', 'is_running', 'run_service_for_stdio', 'run_service'],
  1078. **{'is_running.return_value': True})
  1079. vm.klass = 'AppVM'
  1080. vm.run_service_for_stdio.return_value = (b'changed=no\n', None)
  1081. thread = qube_manager.UpdateVMThread(vm)
  1082. thread.run()
  1083. mock_open.assert_called_with(
  1084. '/usr/libexec/qubes-manager/dsa-4371-update', 'rb')
  1085. vm.run_service_for_stdio.assert_called_once_with(
  1086. "qubes.VMShell", user='root', input=unittest.mock.ANY)
  1087. vm.run_service.assert_called_once_with(
  1088. "qubes.InstallUpdatesGUI", user="root", wait=False)
  1089. self.assertEqual(mock_call.call_count, 0)
  1090. @unittest.mock.patch('builtins.open')
  1091. @unittest.mock.patch('subprocess.call')
  1092. def test_22_update_vm_thread_not_running(self, mock_call, mock_open):
  1093. vm = unittest.mock.Mock(
  1094. spec=['klass', 'is_running', 'run_service_for_stdio',
  1095. 'run_service', 'start', 'name'],
  1096. **{'is_running.return_value': False})
  1097. vm.klass = 'AppVM'
  1098. vm.run_service_for_stdio.return_value = (b'changed=yes\n', None)
  1099. thread = qube_manager.UpdateVMThread(vm)
  1100. thread.run()
  1101. mock_open.assert_called_with(
  1102. '/usr/libexec/qubes-manager/dsa-4371-update', 'rb')
  1103. vm.start.assert_called_once_with()
  1104. vm.run_service_for_stdio.assert_called_once_with(
  1105. "qubes.VMShell", user='root', input=unittest.mock.ANY)
  1106. vm.run_service.assert_called_once_with(
  1107. "qubes.InstallUpdatesGUI", user="root", wait=False)
  1108. self.assertEqual(mock_call.call_count, 1)
  1109. @unittest.mock.patch('builtins.open')
  1110. @unittest.mock.patch('subprocess.check_call')
  1111. def test_23_update_vm_thread_error(self, *_args):
  1112. vm = unittest.mock.Mock(
  1113. spec=['klass', 'is_running'],
  1114. **{'is_running.side_effect': ChildProcessError})
  1115. vm.klass = 'AppVM'
  1116. thread = qube_manager.UpdateVMThread(vm)
  1117. thread.run()
  1118. self.assertIsNotNone(thread.msg)
  1119. class VMShutdownMonitorTest(unittest.TestCase):
  1120. @unittest.mock.patch('qubesmanager.qube_manager.QMessageBox')
  1121. @unittest.mock.patch('PyQt5.QtCore.QTimer')
  1122. def test_01_vm_shutdown_correct(self, mock_timer, mock_question):
  1123. mock_vm = unittest.mock.Mock()
  1124. mock_vm.is_running.return_value = False
  1125. monitor = qube_manager.VmShutdownMonitor(mock_vm)
  1126. monitor.restart_vm_if_needed = unittest.mock.Mock()
  1127. monitor.check_if_vm_has_shutdown()
  1128. self.assertEqual(mock_question.call_count, 0)
  1129. self.assertEqual(mock_timer.call_count, 0)
  1130. monitor.restart_vm_if_needed.assert_called_once_with()
  1131. @unittest.mock.patch('qubesmanager.qube_manager.QMessageBox')
  1132. @unittest.mock.patch('PyQt5.QtCore.QTimer.singleShot')
  1133. def test_02_vm_not_shutdown_wait(self, mock_timer, mock_question):
  1134. mock_question().clickedButton.return_value = 1
  1135. mock_question().addButton.return_value = 0
  1136. mock_vm = unittest.mock.Mock()
  1137. mock_vm.is_running.return_value = True
  1138. mock_vm.start_time = datetime.datetime.now().timestamp() - 3000
  1139. monitor = qube_manager.VmShutdownMonitor(mock_vm, shutdown_time=1)
  1140. time.sleep(3)
  1141. monitor.check_if_vm_has_shutdown()
  1142. self.assertEqual(mock_timer.call_count, 1)
  1143. @unittest.mock.patch('qubesmanager.qube_manager.QMessageBox')
  1144. @unittest.mock.patch('PyQt5.QtCore.QTimer.singleShot')
  1145. def test_03_vm_kill(self, mock_timer, mock_question):
  1146. mock_question().clickedButton.return_value = 1
  1147. mock_question().addButton.return_value = 1
  1148. mock_vm = unittest.mock.Mock()
  1149. mock_vm.is_running.return_value = True
  1150. mock_vm.start_time = datetime.datetime.now().timestamp() - 3000
  1151. monitor = qube_manager.VmShutdownMonitor(mock_vm, shutdown_time=1)
  1152. time.sleep(3)
  1153. monitor.restart_vm_if_needed = unittest.mock.Mock()
  1154. monitor.check_if_vm_has_shutdown()
  1155. self.assertEqual(mock_timer.call_count, 0)
  1156. mock_vm.kill.assert_called_once_with()
  1157. monitor.restart_vm_if_needed.assert_called_once_with()
  1158. @unittest.mock.patch('qubesmanager.qube_manager.QMessageBox')
  1159. @unittest.mock.patch('PyQt5.QtCore.QTimer.singleShot')
  1160. def test_04_check_later(self, mock_timer, mock_question):
  1161. mock_vm = unittest.mock.Mock()
  1162. mock_vm.is_running.return_value = True
  1163. mock_vm.start_time = datetime.datetime.now().timestamp() - 3000
  1164. monitor = qube_manager.VmShutdownMonitor(mock_vm, shutdown_time=3000)
  1165. time.sleep(1)
  1166. monitor.check_if_vm_has_shutdown()
  1167. self.assertEqual(mock_question.call_count, 0)
  1168. self.assertEqual(mock_timer.call_count, 1)
  1169. if __name__ == "__main__":
  1170. ha_syslog = logging.handlers.SysLogHandler('/dev/log')
  1171. ha_syslog.setFormatter(
  1172. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  1173. logging.root.addHandler(ha_syslog)
  1174. unittest.main()