test_qube_manager.py 58 KB

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