test_qube_manager.py 58 KB

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