__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. # pylint: disable=invalid-name
  4. #
  5. # The Qubes OS Project, https://www.qubes-os.org/
  6. #
  7. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  8. # Copyright (C) 2014-2015
  9. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  10. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  11. #
  12. # This program is free software; you can redistribute it and/or modify
  13. # it under the terms of the GNU General Public License as published by
  14. # the Free Software Foundation; either version 2 of the License, or
  15. # (at your option) any later version.
  16. #
  17. # This program is distributed in the hope that it will be useful,
  18. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. # GNU General Public License for more details.
  21. #
  22. # You should have received a copy of the GNU General Public License along
  23. # with this program; if not, write to the Free Software Foundation, Inc.,
  24. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  25. #
  26. import collections
  27. import multiprocessing
  28. import logging
  29. import os
  30. import shutil
  31. import subprocess
  32. import sys
  33. import traceback
  34. import unittest
  35. import lxml.etree
  36. import time
  37. import qubes.config
  38. import qubes.events
  39. XMLPATH = '/var/lib/qubes/qubes-test.xml'
  40. CLASS_XMLPATH = '/var/lib/qubes/qubes-class-test.xml'
  41. TEMPLATE = 'fedora-23'
  42. VMPREFIX = 'test-inst-'
  43. CLSVMPREFIX = 'test-cls-'
  44. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  45. in_dom0 = False
  46. #: :py:obj:`False` if outside of git repo,
  47. #: path to root of the directory otherwise
  48. in_git = False
  49. try:
  50. import libvirt
  51. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  52. in_dom0 = True
  53. except libvirt.libvirtError:
  54. pass
  55. try:
  56. in_git = subprocess.check_output(
  57. ['git', 'rev-parse', '--show-toplevel']).strip()
  58. qubes.log.LOGPATH = '/tmp'
  59. qubes.log.LOGFILE = '/tmp/qubes.log'
  60. except subprocess.CalledProcessError:
  61. # git returned nonzero, we are outside git repo
  62. pass
  63. except OSError:
  64. # command not found; let's assume we're outside
  65. pass
  66. def skipUnlessDom0(test_item):
  67. '''Decorator that skips test outside dom0.
  68. Some tests (especially integration tests) have to be run in more or less
  69. working dom0. This is checked by connecting to libvirt.
  70. '''
  71. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  72. def skipUnlessGit(test_item):
  73. '''Decorator that skips test outside git repo.
  74. There are very few tests that an be run only in git. One example is
  75. correctness of example code that won't get included in RPM.
  76. '''
  77. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  78. class TestEmitter(qubes.events.Emitter):
  79. '''Dummy event emitter which records events fired on it.
  80. Events are counted in :py:attr:`fired_events` attribute, which is
  81. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  82. kwargs)`` object is counted. *event* is event name (a string), *args* is
  83. tuple with positional arguments and *kwargs* is sorted tuple of items from
  84. keyword arguments.
  85. >>> emitter = TestEmitter()
  86. >>> emitter.fired_events
  87. Counter()
  88. >>> emitter.fire_event('event', 1, 2, 3, spam='eggs', foo='bar')
  89. >>> emitter.fired_events
  90. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  91. '''
  92. def __init__(self, *args, **kwargs):
  93. super(TestEmitter, self).__init__(*args, **kwargs)
  94. #: :py:class:`collections.Counter` instance
  95. self.fired_events = collections.Counter()
  96. def fire_event(self, event, *args, **kwargs):
  97. super(TestEmitter, self).fire_event(event, *args, **kwargs)
  98. self.fired_events[(event, args, tuple(sorted(kwargs.items())))] += 1
  99. def fire_event_pre(self, event, *args, **kwargs):
  100. super(TestEmitter, self).fire_event_pre(event, *args, **kwargs)
  101. self.fired_events[(event, args, tuple(sorted(kwargs.items())))] += 1
  102. class _AssertNotRaisesContext(object):
  103. """A context manager used to implement TestCase.assertNotRaises methods.
  104. Stolen from unittest and hacked. Regexp support stripped.
  105. """ # pylint: disable=too-few-public-methods
  106. def __init__(self, expected, test_case, expected_regexp=None):
  107. if expected_regexp is not None:
  108. raise NotImplementedError('expected_regexp is unsupported')
  109. self.expected = expected
  110. self.exception = None
  111. self.failureException = test_case.failureException
  112. def __enter__(self):
  113. return self
  114. def __exit__(self, exc_type, exc_value, tb):
  115. if exc_type is None:
  116. return True
  117. if issubclass(exc_type, self.expected):
  118. raise self.failureException(
  119. "{!r} raised, traceback:\n{!s}".format(
  120. exc_value, ''.join(traceback.format_tb(tb))))
  121. else:
  122. # pass through
  123. return False
  124. self.exception = exc_value # store for later retrieval
  125. class BeforeCleanExit(BaseException):
  126. '''Raised from :py:meth:`QubesTestCase.tearDown` when
  127. :py:attr:`qubes.tests.run.QubesDNCTestResult.do_not_clean` is set.'''
  128. pass
  129. class QubesTestCase(unittest.TestCase):
  130. '''Base class for Qubes unit tests.
  131. '''
  132. def __init__(self, *args, **kwargs):
  133. super(QubesTestCase, self).__init__(*args, **kwargs)
  134. self.longMessage = True
  135. self.log = logging.getLogger('{}.{}.{}'.format(
  136. self.__class__.__module__,
  137. self.__class__.__name__,
  138. self._testMethodName))
  139. def __str__(self):
  140. return '{}/{}/{}'.format(
  141. '.'.join(self.__class__.__module__.split('.')[2:]),
  142. self.__class__.__name__,
  143. self._testMethodName)
  144. def tearDown(self):
  145. super(QubesTestCase, self).tearDown()
  146. result = self._resultForDoCleanups
  147. failed_test_cases = result.failures \
  148. + result.errors \
  149. + [(tc, None) for tc in result.unexpectedSuccesses]
  150. if getattr(result, 'do_not_clean', False) \
  151. and any(tc is self for tc, exc in failed_test_cases):
  152. raise BeforeCleanExit()
  153. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  154. """Fail if an exception of class excClass is raised
  155. by callableObj when invoked with arguments args and keyword
  156. arguments kwargs. If a different type of exception is
  157. raised, it will not be caught, and the test case will be
  158. deemed to have suffered an error, exactly as for an
  159. unexpected exception.
  160. If called with callableObj omitted or None, will return a
  161. context object used like this::
  162. with self.assertRaises(SomeException):
  163. do_something()
  164. The context manager keeps a reference to the exception as
  165. the 'exception' attribute. This allows you to inspect the
  166. exception after the assertion::
  167. with self.assertRaises(SomeException) as cm:
  168. do_something()
  169. the_exception = cm.exception
  170. self.assertEqual(the_exception.error_code, 3)
  171. """
  172. context = _AssertNotRaisesContext(excClass, self)
  173. if callableObj is None:
  174. return context
  175. with context:
  176. callableObj(*args, **kwargs)
  177. def assertXMLEqual(self, xml1, xml2):
  178. '''Check for equality of two XML objects.
  179. :param xml1: first element
  180. :param xml2: second element
  181. :type xml1: :py:class:`lxml.etree._Element`
  182. :type xml2: :py:class:`lxml.etree._Element`
  183. ''' # pylint: disable=invalid-name
  184. self.assertEqual(xml1.tag, xml2.tag)
  185. self.assertEqual(xml1.text, xml2.text)
  186. self.assertItemsEqual(xml1.keys(), xml2.keys())
  187. for key in xml1.keys():
  188. self.assertEqual(xml1.get(key), xml2.get(key))
  189. def assertEventFired(self, emitter, event, args=None, kwargs=None):
  190. '''Check whether event was fired on given emitter and fail if it did
  191. not.
  192. :param emitter: emitter which is being checked
  193. :type emitter: :py:class:`TestEmitter`
  194. :param str event: event identifier
  195. :param list args: when given, all items must appear in args passed to \
  196. an event
  197. :param list kwargs: when given, all items must appear in kwargs passed \
  198. to an event
  199. '''
  200. for ev, ev_args, ev_kwargs in emitter.fired_events:
  201. if ev != event:
  202. continue
  203. if args is not None and any(i not in ev_args for i in args):
  204. continue
  205. if kwargs is not None and any(i not in ev_kwargs for i in kwargs):
  206. continue
  207. return
  208. self.fail('event {!r} did not fire on {!r}'.format(event, emitter))
  209. def assertEventNotFired(self, emitter, event, args=None, kwargs=None):
  210. '''Check whether event was fired on given emitter. Fail if it did.
  211. :param emitter: emitter which is being checked
  212. :type emitter: :py:class:`TestEmitter`
  213. :param str event: event identifier
  214. :param list args: when given, all items must appear in args passed to \
  215. an event
  216. :param list kwargs: when given, all items must appear in kwargs passed \
  217. to an event
  218. '''
  219. for ev, ev_args, ev_kwargs in emitter.fired_events:
  220. if ev != event:
  221. continue
  222. if args is not None and any(i not in ev_args for i in args):
  223. continue
  224. if kwargs is not None and any(i not in ev_kwargs for i in kwargs):
  225. continue
  226. self.fail('event {!r} did fire on {!r}'.format(event, emitter))
  227. return
  228. def assertXMLIsValid(self, xml, file=None, schema=None):
  229. '''Check whether given XML fulfills Relax NG schema.
  230. Schema can be given in a couple of ways:
  231. - As separate file. This is most common, and also the only way to
  232. handle file inclusion. Call with file name as second argument.
  233. - As string containing actual schema. Put that string in *schema*
  234. keyword argument.
  235. :param lxml.etree._Element xml: XML element instance to check
  236. :param str file: filename of Relax NG schema
  237. :param str schema: optional explicit schema string
  238. ''' # pylint: disable=redefined-builtin
  239. if schema is not None and file is None:
  240. relaxng = schema
  241. if isinstance(relaxng, str):
  242. relaxng = lxml.etree.XML(relaxng)
  243. # pylint: disable=protected-access
  244. if isinstance(relaxng, lxml.etree._Element):
  245. relaxng = lxml.etree.RelaxNG(relaxng)
  246. elif file is not None and schema is None:
  247. if not os.path.isabs(file):
  248. basedirs = ['/usr/share/doc/qubes/relaxng']
  249. if in_git:
  250. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  251. for basedir in basedirs:
  252. abspath = os.path.join(basedir, file)
  253. if os.path.exists(abspath):
  254. file = abspath
  255. break
  256. relaxng = lxml.etree.RelaxNG(file=file)
  257. else:
  258. raise TypeError("There should be excactly one of 'file' and "
  259. "'schema' arguments specified.")
  260. # We have to be extra careful here in case someone messed up with
  261. # self.failureException. It should by default be AssertionError, just
  262. # what is spewed by RelaxNG(), but who knows what might happen.
  263. try:
  264. relaxng.assert_(xml)
  265. except self.failureException:
  266. raise
  267. except AssertionError as e:
  268. self.fail(str(e))
  269. @staticmethod
  270. def make_vm_name(name, class_teardown=False):
  271. if class_teardown:
  272. return CLSVMPREFIX + name
  273. else:
  274. return VMPREFIX + name
  275. class SystemTestsMixin(object):
  276. """
  277. Mixin for integration tests. All the tests here should use self.app
  278. object and when need qubes.xml path - should use :py:data:`XMLPATH`
  279. defined in this file.
  280. Every VM created by test, must use :py:meth:`SystemTestsMixin.make_vm_name`
  281. for VM name.
  282. By default self.app represents empty collection, if anything is needed
  283. there from the real collection it can be imported from self.host_app in
  284. :py:meth:`SystemTestsMixin.setUp`. But *can not be modified* in any way -
  285. this include both changing attributes in
  286. :py:attr:`SystemTestsMixin.host_app` and modifying files of such imported
  287. VM. If test need to make some modification, it must clone the VM first.
  288. If some group of tests needs class-wide initialization, first of all the
  289. author should consider if it is really needed. But if so, setUpClass can
  290. be used to create Qubes(CLASS_XMLPATH) object and create/import required
  291. stuff there. VMs created in :py:meth:`TestCase.setUpClass` should
  292. use self.make_vm_name('...', class_teardown=True) for name creation.
  293. """
  294. # noinspection PyAttributeOutsideInit
  295. def setUp(self):
  296. if not in_dom0:
  297. self.skipTest('outside dom0')
  298. super(SystemTestsMixin, self).setUp()
  299. self.remove_test_vms()
  300. # need some information from the real qubes.xml - at least installed
  301. # templates; should not be used for testing, only to initialize self.app
  302. self.host_app = qubes.Qubes(os.path.join(
  303. qubes.config.system_path['qubes_base_dir'],
  304. qubes.config.system_path['qubes_store_filename']))
  305. if os.path.exists(CLASS_XMLPATH):
  306. shutil.copy(CLASS_XMLPATH, XMLPATH)
  307. self.app = qubes.Qubes(XMLPATH)
  308. else:
  309. self.app = qubes.Qubes.create_empty_store(qubes.tests.XMLPATH,
  310. default_kernel=self.host_app.default_kernel,
  311. clockvm=None,
  312. updatevm=None
  313. )
  314. os.environ['QUBES_XML_PATH'] = XMLPATH
  315. def init_default_template(self, template=None):
  316. if template is None:
  317. template = self.host_app.default_template
  318. elif isinstance(template, basestring):
  319. template = self.host_app.domains[template]
  320. template_vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  321. name=template.name,
  322. uuid=template.uuid,
  323. label='black')
  324. self.app.default_template = template_vm
  325. def reload_db(self):
  326. self.app = qubes.Qubes(qubes.tests.XMLPATH)
  327. def save_and_reload_db(self):
  328. self.app.save()
  329. self.reload_db()
  330. def tearDown(self):
  331. super(SystemTestsMixin, self).tearDown()
  332. self.remove_test_vms()
  333. # remove all references to VM objects, to release resources - most
  334. # importantly file descriptors; this object will live
  335. # during the whole test run, but all the file descriptors would be
  336. # depleted earlier
  337. del self.app
  338. del self.host_app
  339. for attr in dir(self):
  340. if isinstance(getattr(self, attr), qubes.vm.BaseVM):
  341. delattr(self, attr)
  342. @classmethod
  343. def tearDownClass(cls):
  344. super(SystemTestsMixin, cls).tearDownClass()
  345. if not in_dom0:
  346. return
  347. cls.remove_test_vms(xmlpath=CLASS_XMLPATH, prefix=CLSVMPREFIX)
  348. @classmethod
  349. def _remove_vm_qubes(cls, vm):
  350. vmname = vm.name
  351. app = vm.app
  352. try:
  353. # XXX .is_running() may throw libvirtError if undefined
  354. if vm.is_running():
  355. vm.force_shutdown()
  356. except: # pylint: disable=bare-except
  357. pass
  358. try:
  359. vm.remove_from_disk()
  360. except: # pylint: disable=bare-except
  361. pass
  362. try:
  363. vm.libvirt_domain.undefine()
  364. except (AttributeError, libvirt.libvirtError):
  365. pass
  366. del app.domains[vm]
  367. del vm
  368. app.save()
  369. del app
  370. # Now ensure it really went away. This may not have happened,
  371. # for example if vm.libvirt_domain malfunctioned.
  372. try:
  373. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  374. dom = conn.lookupByName(vmname)
  375. except: # pylint: disable=bare-except
  376. pass
  377. else:
  378. cls._remove_vm_libvirt(dom)
  379. cls._remove_vm_disk(vmname)
  380. @staticmethod
  381. def _remove_vm_libvirt(dom):
  382. try:
  383. dom.destroy()
  384. except libvirt.libvirtError: # not running
  385. pass
  386. dom.undefine()
  387. @staticmethod
  388. def _remove_vm_disk(vmname):
  389. for dirspec in (
  390. 'qubes_appvms_dir',
  391. 'qubes_servicevms_dir',
  392. 'qubes_templates_dir'):
  393. dirpath = os.path.join(qubes.config.system_path['qubes_base_dir'],
  394. qubes.config.system_path[dirspec], vmname)
  395. if os.path.exists(dirpath):
  396. if os.path.isdir(dirpath):
  397. shutil.rmtree(dirpath)
  398. else:
  399. os.unlink(dirpath)
  400. @classmethod
  401. def remove_vms(cls, vms):
  402. for vm in vms:
  403. cls._remove_vm_qubes(vm)
  404. @classmethod
  405. def remove_test_vms(cls, xmlpath=XMLPATH, prefix=VMPREFIX):
  406. '''Aggresively remove any domain that has name in testing namespace.
  407. .. warning::
  408. The test suite hereby claims any domain whose name starts with
  409. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  410. test executing environment. If you have domains named ``test-*``,
  411. don't run the tests.
  412. '''
  413. # first, remove them Qubes-way
  414. if os.path.exists(xmlpath):
  415. try:
  416. cls.remove_vms(vm for vm in qubes.Qubes(xmlpath).domains
  417. if vm.name.startswith(prefix))
  418. except qubes.exc.QubesException:
  419. # If qubes-test.xml is broken that much it doesn't even load,
  420. # simply remove it. VMs will be cleaned up the hard way.
  421. # TODO logging?
  422. pass
  423. os.unlink(xmlpath)
  424. # now remove what was only in libvirt
  425. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  426. for dom in conn.listAllDomains():
  427. if dom.name().startswith(prefix):
  428. cls._remove_vm_libvirt(dom)
  429. conn.close()
  430. # finally remove anything that is left on disk
  431. vmnames = set()
  432. for dirspec in (
  433. 'qubes_appvms_dir',
  434. 'qubes_servicevms_dir',
  435. 'qubes_templates_dir'):
  436. dirpath = os.path.join(qubes.config.system_path['qubes_base_dir'],
  437. qubes.config.system_path[dirspec])
  438. for name in os.listdir(dirpath):
  439. if name.startswith(prefix):
  440. vmnames.add(name)
  441. for vmname in vmnames:
  442. cls._remove_vm_disk(vmname)
  443. def wait_for_window(self, title, timeout=30, show=True):
  444. """
  445. Wait for a window with a given title. Depending on show parameter,
  446. it will wait for either window to show or to disappear.
  447. :param title: title of the window to wait for
  448. :param timeout: timeout of the operation, in seconds
  449. :param show: if True - wait for the window to be visible,
  450. otherwise - to not be visible
  451. :return: None
  452. """
  453. wait_count = 0
  454. while subprocess.call(['xdotool', 'search', '--name', title],
  455. stdout=open(os.path.devnull, 'w'),
  456. stderr=subprocess.STDOUT) == int(show):
  457. wait_count += 1
  458. if wait_count > timeout*10:
  459. self.fail("Timeout while waiting for {} window to {}".format(
  460. title, "show" if show else "hide")
  461. )
  462. time.sleep(0.1)
  463. def enter_keys_in_window(self, title, keys):
  464. """
  465. Search for window with given title, then enter listed keys there.
  466. The function will wait for said window to appear.
  467. :param title: title of window
  468. :param keys: list of keys to enter, as for `xdotool key`
  469. :return: None
  470. """
  471. # 'xdotool search --sync' sometimes crashes on some race when
  472. # accessing window properties
  473. self.wait_for_window(title)
  474. command = ['xdotool', 'search', '--name', title,
  475. 'windowactivate',
  476. 'key'] + keys
  477. subprocess.check_call(command)
  478. def shutdown_and_wait(self, vm, timeout=60):
  479. vm.shutdown()
  480. while timeout > 0:
  481. if not vm.is_running():
  482. return
  483. time.sleep(1)
  484. timeout -= 1
  485. self.fail("Timeout while waiting for VM {} shutdown".format(vm.name))
  486. # noinspection PyAttributeOutsideInit
  487. class BackupTestsMixin(SystemTestsMixin):
  488. def setUp(self):
  489. super(BackupTestsMixin, self).setUp()
  490. self.init_default_template()
  491. self.error_detected = multiprocessing.Queue()
  492. self.verbose = False
  493. if self.verbose:
  494. print >>sys.stderr, "-> Creating backupvm"
  495. self.backupdir = os.path.join(os.environ["HOME"], "test-backup")
  496. if os.path.exists(self.backupdir):
  497. shutil.rmtree(self.backupdir)
  498. os.mkdir(self.backupdir)
  499. def tearDown(self):
  500. super(BackupTestsMixin, self).tearDown()
  501. shutil.rmtree(self.backupdir)
  502. def print_progress(self, progress):
  503. if self.verbose:
  504. print >> sys.stderr, "\r-> Backing up files: {0}%...".format(progress)
  505. def error_callback(self, message):
  506. self.error_detected.put(message)
  507. if self.verbose:
  508. print >> sys.stderr, "ERROR: {0}".format(message)
  509. def print_callback(self, msg):
  510. if self.verbose:
  511. print msg
  512. def fill_image(self, path, size=None, sparse=False):
  513. block_size = 4096
  514. if self.verbose:
  515. print >>sys.stderr, "-> Filling %s" % path
  516. f = open(path, 'w+')
  517. if size is None:
  518. f.seek(0, 2)
  519. size = f.tell()
  520. f.seek(0)
  521. for block_num in xrange(size/block_size):
  522. f.write('a' * block_size)
  523. if sparse:
  524. f.seek(block_size, 1)
  525. f.close()
  526. # NOTE: this was create_basic_vms
  527. def create_backup_vms(self):
  528. template = self.app.default_template
  529. vms = []
  530. vmname = self.make_vm_name('test-net')
  531. if self.verbose:
  532. print >>sys.stderr, "-> Creating %s" % vmname
  533. testnet = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  534. name=vmname, template=template, provides_network=True)
  535. testnet.create_on_disk(verbose=self.verbose)
  536. vms.append(testnet)
  537. self.fill_image(testnet.private_img, 20*1024*1024)
  538. vmname = self.make_vm_name('test1')
  539. if self.verbose:
  540. print >>sys.stderr, "-> Creating %s" % vmname
  541. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  542. name=vmname, template=template)
  543. testvm1.uses_default_netvm = False
  544. testvm1.netvm = testnet
  545. testvm1.create_on_disk(verbose=self.verbose)
  546. vms.append(testvm1)
  547. self.fill_image(testvm1.private_img, 100*1024*1024)
  548. vmname = self.make_vm_name('testhvm1')
  549. if self.verbose:
  550. print >>sys.stderr, "-> Creating %s" % vmname
  551. testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  552. hvm=True)
  553. testvm2.create_on_disk(verbose=self.verbose)
  554. self.fill_image(testvm2.root_img, 1024*1024*1024, True)
  555. vms.append(testvm2)
  556. self.app.save()
  557. return vms
  558. def make_backup(self, vms, prepare_kwargs=dict(), do_kwargs=dict(),
  559. target=None, expect_failure=False):
  560. # XXX: bakup_prepare and backup_do don't support host_collection
  561. # self.qc.unlock_db()
  562. if target is None:
  563. target = self.backupdir
  564. try:
  565. files_to_backup = \
  566. qubes.backup.backup_prepare(vms,
  567. print_callback=self.print_callback,
  568. **prepare_kwargs)
  569. except qubes.qubes.QubesException as e:
  570. if not expect_failure:
  571. self.fail("QubesException during backup_prepare: %s" % str(e))
  572. else:
  573. raise
  574. try:
  575. qubes.backup.backup_do(target, files_to_backup, "qubes",
  576. progress_callback=self.print_progress,
  577. **do_kwargs)
  578. except qubes.qubes.QubesException as e:
  579. if not expect_failure:
  580. self.fail("QubesException during backup_do: %s" % str(e))
  581. else:
  582. raise
  583. # FIXME why?
  584. self.reload_db()
  585. def restore_backup(self, source=None, appvm=None, options=None,
  586. expect_errors=None):
  587. if source is None:
  588. backupfile = os.path.join(self.backupdir,
  589. sorted(os.listdir(self.backupdir))[-1])
  590. else:
  591. backupfile = source
  592. with self.assertNotRaises(qubes.qubes.QubesException):
  593. backup_info = qubes.backup.backup_restore_prepare(
  594. backupfile, "qubes",
  595. host_collection=self.app,
  596. print_callback=self.print_callback,
  597. appvm=appvm,
  598. options=options or {})
  599. if self.verbose:
  600. qubes.backup.backup_restore_print_summary(backup_info)
  601. with self.assertNotRaises(qubes.qubes.QubesException):
  602. qubes.backup.backup_restore_do(
  603. backup_info,
  604. host_collection=self.app,
  605. print_callback=self.print_callback if self.verbose else None,
  606. error_callback=self.error_callback)
  607. # maybe someone forgot to call .save()
  608. self.reload_db()
  609. errors = []
  610. if expect_errors is None:
  611. expect_errors = []
  612. while not self.error_detected.empty():
  613. current_error = self.error_detected.get()
  614. if any(map(current_error.startswith, expect_errors)):
  615. continue
  616. errors.append(current_error)
  617. self.assertTrue(len(errors) == 0,
  618. "Error(s) detected during backup_restore_do: %s" %
  619. '\n'.join(errors))
  620. if not appvm and not os.path.isdir(backupfile):
  621. os.unlink(backupfile)
  622. def create_sparse(self, path, size):
  623. f = open(path, "w")
  624. f.truncate(size)
  625. f.close()
  626. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  627. # discard any tests from this module, because it hosts base classes
  628. tests = unittest.TestSuite()
  629. for modname in (
  630. # unit tests
  631. 'qubes.tests.events',
  632. 'qubes.tests.init1',
  633. 'qubes.tests.vm.init',
  634. 'qubes.tests.storage',
  635. 'qubes.tests.storage_xen',
  636. 'qubes.tests.vm.qubesvm',
  637. 'qubes.tests.vm.adminvm',
  638. 'qubes.tests.init2',
  639. ):
  640. tests.addTests(loader.loadTestsFromName(modname))
  641. tests.addTests(loader.discover(
  642. os.path.join(os.path.dirname(__file__), 'tools')))
  643. for modname in (
  644. # integration tests
  645. 'qubes.tests.int.basic',
  646. 'qubes.tests.int.dom0_update',
  647. # 'qubes.tests.network',
  648. # 'qubes.tests.vm_qrexec_gui',
  649. # 'qubes.tests.backup',
  650. # 'qubes.tests.backupcompatibility',
  651. # 'qubes.tests.regressions',
  652. # tool tests
  653. 'qubes.tests.int.tools.qubes_create',
  654. 'qubes.tests.int.tools.qvm_run',
  655. ):
  656. tests.addTests(loader.loadTestsFromName(modname))
  657. return tests