test_qube_manager.py 59 KB

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