__init__.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. # pylint: disable=invalid-name
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2014-2015
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. """
  25. .. warning::
  26. The test suite hereby claims any domain whose name starts with
  27. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  28. test executing environment. If you have domains named ``test-*``,
  29. don't run the tests.
  30. """
  31. import asyncio
  32. import collections
  33. import functools
  34. import logging
  35. import os
  36. import pathlib
  37. import shlex
  38. import shutil
  39. import subprocess
  40. import sys
  41. import tempfile
  42. import time
  43. import traceback
  44. import unittest
  45. import warnings
  46. from distutils import spawn
  47. import lxml.etree
  48. import pkg_resources
  49. import qubes.api
  50. import qubes.api.admin
  51. import qubes.backup
  52. import qubes.config
  53. import qubes.devices
  54. import qubes.events
  55. import qubes.exc
  56. import qubes.vm.standalonevm
  57. XMLPATH = '/var/lib/qubes/qubes-test.xml'
  58. CLASS_XMLPATH = '/var/lib/qubes/qubes-class-test.xml'
  59. TEMPLATE = 'fedora-23'
  60. VMPREFIX = 'test-inst-'
  61. CLSVMPREFIX = 'test-cls-'
  62. if 'DEFAULT_LVM_POOL' in os.environ.keys():
  63. DEFAULT_LVM_POOL = os.environ['DEFAULT_LVM_POOL']
  64. else:
  65. DEFAULT_LVM_POOL = 'qubes_dom0/pool00'
  66. POOL_CONF = {'name': 'test-lvm',
  67. 'driver': 'lvm_thin',
  68. 'volume_group': DEFAULT_LVM_POOL.split('/')[0],
  69. 'thin_pool': DEFAULT_LVM_POOL.split('/')[1]}
  70. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  71. in_dom0 = False
  72. #: :py:obj:`False` if outside of git repo,
  73. #: path to root of the directory otherwise
  74. in_git = False
  75. try:
  76. import libvirt
  77. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  78. in_dom0 = True
  79. except libvirt.libvirtError:
  80. pass
  81. try:
  82. in_git = subprocess.check_output(
  83. ['git', 'rev-parse', '--show-toplevel']).decode().strip()
  84. qubes.log.LOGPATH = '/tmp'
  85. qubes.log.LOGFILE = '/tmp/qubes.log'
  86. except subprocess.CalledProcessError:
  87. # git returned nonzero, we are outside git repo
  88. pass
  89. except OSError:
  90. # command not found; let's assume we're outside
  91. pass
  92. def skipUnlessDom0(test_item):
  93. '''Decorator that skips test outside dom0.
  94. Some tests (especially integration tests) have to be run in more or less
  95. working dom0. This is checked by connecting to libvirt.
  96. '''
  97. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  98. def skipUnlessGit(test_item):
  99. '''Decorator that skips test outside git repo.
  100. There are very few tests that an be run only in git. One example is
  101. correctness of example code that won't get included in RPM.
  102. '''
  103. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  104. class TestEmitter(qubes.events.Emitter):
  105. '''Dummy event emitter which records events fired on it.
  106. Events are counted in :py:attr:`fired_events` attribute, which is
  107. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  108. kwargs)`` object is counted. *event* is event name (a string), *args* is
  109. tuple with positional arguments and *kwargs* is sorted tuple of items from
  110. keyword arguments.
  111. >>> emitter = TestEmitter()
  112. >>> emitter.fired_events
  113. Counter()
  114. >>> emitter.fire_event('event', spam='eggs', foo='bar')
  115. >>> emitter.fired_events
  116. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  117. '''
  118. def __init__(self, *args, **kwargs):
  119. super(TestEmitter, self).__init__(*args, **kwargs)
  120. #: :py:class:`collections.Counter` instance
  121. self.fired_events = collections.Counter()
  122. def fire_event(self, event, **kwargs):
  123. effects = super(TestEmitter, self).fire_event(event, **kwargs)
  124. ev_kwargs = frozenset(
  125. (key,
  126. frozenset(value.items()) if isinstance(value, dict) else value)
  127. for key, value in kwargs.items()
  128. )
  129. self.fired_events[(event, ev_kwargs)] += 1
  130. return effects
  131. def fire_event_pre(self, event, **kwargs):
  132. effects = super(TestEmitter, self).fire_event_pre(event, **kwargs)
  133. ev_kwargs = frozenset(
  134. (key,
  135. frozenset(value.items()) if isinstance(value, dict) else value)
  136. for key, value in kwargs.items()
  137. )
  138. self.fired_events[(event, ev_kwargs)] += 1
  139. return effects
  140. def expectedFailureIfTemplate(templates):
  141. """
  142. Decorator for marking specific test as expected to fail only for some
  143. templates. Template name is compared as substring, so 'whonix' will
  144. handle both 'whonix-ws' and 'whonix-gw'.
  145. templates can be either a single string, or an iterable
  146. """
  147. def decorator(func):
  148. @functools.wraps(func)
  149. def wrapper(self, *args, **kwargs):
  150. template = self.template
  151. if isinstance(templates, str):
  152. should_expect_fail = template in templates
  153. else:
  154. should_expect_fail = any([template in x for x in templates])
  155. if should_expect_fail:
  156. try:
  157. func(self, *args, **kwargs)
  158. except Exception:
  159. raise unittest.case._ExpectedFailure(sys.exc_info())
  160. raise unittest.case._UnexpectedSuccess()
  161. else:
  162. # Call directly:
  163. func(self, *args, **kwargs)
  164. return wrapper
  165. return decorator
  166. class _AssertNotRaisesContext(object):
  167. """A context manager used to implement TestCase.assertNotRaises methods.
  168. Stolen from unittest and hacked. Regexp support stripped.
  169. """ # pylint: disable=too-few-public-methods
  170. def __init__(self, expected, test_case, expected_regexp=None):
  171. if expected_regexp is not None:
  172. raise NotImplementedError('expected_regexp is unsupported')
  173. self.expected = expected
  174. self.exception = None
  175. self.failureException = test_case.failureException
  176. def __enter__(self):
  177. return self
  178. def __exit__(self, exc_type, exc_value, tb):
  179. if exc_type is None:
  180. return True
  181. if issubclass(exc_type, self.expected):
  182. raise self.failureException(
  183. "{!r} raised, traceback:\n{!s}".format(
  184. exc_value, ''.join(traceback.format_tb(tb))))
  185. else:
  186. # pass through
  187. return False
  188. self.exception = exc_value # store for later retrieval
  189. class _QrexecPolicyContext(object):
  190. '''Context manager for SystemTestsMixin.qrexec_policy'''
  191. def __init__(self, service, source, destination, allow=True):
  192. try:
  193. source = source.name
  194. except AttributeError:
  195. pass
  196. try:
  197. destination = destination.name
  198. except AttributeError:
  199. pass
  200. self._filename = pathlib.Path('/etc/qubes-rpc/policy') / service
  201. self._rule = '{} {} {}\n'.format(source, destination,
  202. 'allow' if allow else 'deny')
  203. self._did_create = False
  204. self._handle = None
  205. def load(self):
  206. if self._handle is None:
  207. try:
  208. self._handle = self._filename.open('r+')
  209. except FileNotFoundError:
  210. self._handle = self._filename.open('w+')
  211. self._did_create = True
  212. self._handle.seek(0)
  213. return self._handle.readlines()
  214. def save(self, rules):
  215. assert self._handle is not None
  216. self._handle.truncate(0)
  217. self._handle.seek(0)
  218. self._handle.write(''.join(rules))
  219. self._handle.flush()
  220. def close(self):
  221. assert self._handle is not None
  222. self._handle.close()
  223. self._handle = None
  224. def __enter__(self):
  225. rules = self.load()
  226. rules.insert(0, self._rule)
  227. self.save(self._rule)
  228. return self
  229. def __exit__(self, exc_type, exc_value, tb):
  230. if not self._did_create:
  231. try:
  232. rules = self.load()
  233. rules.remove(self._rule)
  234. self.save(rules)
  235. finally:
  236. self.close()
  237. else:
  238. self.close()
  239. self._filename.unlink()
  240. class substitute_entry_points(object):
  241. '''Monkey-patch pkg_resources to substitute one group in iter_entry_points
  242. This is for testing plugins, like device classes.
  243. :param str group: The group that is to be overloaded.
  244. :param str tempgroup: The substitute group.
  245. Inside this context, if one iterates over entry points in overloaded group,
  246. the iteration actually happens over the other group.
  247. This context manager is stackable. To substitute more than one entry point
  248. group, just nest two contexts.
  249. ''' # pylint: disable=invalid-name
  250. def __init__(self, group, tempgroup):
  251. self.group = group
  252. self.tempgroup = tempgroup
  253. self._orig_iter_entry_points = None
  254. def _iter_entry_points(self, group, *args, **kwargs):
  255. if group == self.group:
  256. group = self.tempgroup
  257. return self._orig_iter_entry_points(group, *args, **kwargs)
  258. def __enter__(self):
  259. self._orig_iter_entry_points = pkg_resources.iter_entry_points
  260. pkg_resources.iter_entry_points = self._iter_entry_points
  261. return self
  262. def __exit__(self, exc_type, exc_value, tb):
  263. pkg_resources.iter_entry_points = self._orig_iter_entry_points
  264. self._orig_iter_entry_points = None
  265. class BeforeCleanExit(BaseException):
  266. '''Raised from :py:meth:`QubesTestCase.tearDown` when
  267. :py:attr:`qubes.tests.run.QubesDNCTestResult.do_not_clean` is set.'''
  268. pass
  269. class QubesTestCase(unittest.TestCase):
  270. '''Base class for Qubes unit tests.
  271. '''
  272. def __init__(self, *args, **kwargs):
  273. super(QubesTestCase, self).__init__(*args, **kwargs)
  274. self.longMessage = True
  275. self.log = logging.getLogger('{}.{}.{}'.format(
  276. self.__class__.__module__,
  277. self.__class__.__name__,
  278. self._testMethodName))
  279. self.addTypeEqualityFunc(qubes.devices.DeviceManager,
  280. self.assertDevicesEqual)
  281. self.loop = None
  282. def __str__(self):
  283. return '{}/{}/{}'.format(
  284. self.__class__.__module__,
  285. self.__class__.__name__,
  286. self._testMethodName)
  287. def setUp(self):
  288. super().setUp()
  289. self.loop = asyncio.new_event_loop()
  290. asyncio.set_event_loop(self.loop)
  291. def tearDown(self):
  292. super(QubesTestCase, self).tearDown()
  293. # The loop, when closing, throws a warning if there is
  294. # some unfinished bussiness. Let's catch that.
  295. with warnings.catch_warnings():
  296. warnings.simplefilter('error')
  297. self.loop.close()
  298. # TODO: find better way in py3
  299. try:
  300. result = self._outcome.result
  301. except:
  302. result = self._resultForDoCleanups
  303. failed_test_cases = result.failures \
  304. + result.errors \
  305. + [(tc, None) for tc in result.unexpectedSuccesses]
  306. if getattr(result, 'do_not_clean', False) \
  307. and any(tc is self for tc, exc in failed_test_cases):
  308. raise BeforeCleanExit()
  309. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  310. """Fail if an exception of class excClass is raised
  311. by callableObj when invoked with arguments args and keyword
  312. arguments kwargs. If a different type of exception is
  313. raised, it will not be caught, and the test case will be
  314. deemed to have suffered an error, exactly as for an
  315. unexpected exception.
  316. If called with callableObj omitted or None, will return a
  317. context object used like this::
  318. with self.assertRaises(SomeException):
  319. do_something()
  320. The context manager keeps a reference to the exception as
  321. the 'exception' attribute. This allows you to inspect the
  322. exception after the assertion::
  323. with self.assertRaises(SomeException) as cm:
  324. do_something()
  325. the_exception = cm.exception
  326. self.assertEqual(the_exception.error_code, 3)
  327. """
  328. context = _AssertNotRaisesContext(excClass, self)
  329. if callableObj is None:
  330. return context
  331. with context:
  332. callableObj(*args, **kwargs)
  333. def assertXMLEqual(self, xml1, xml2):
  334. '''Check for equality of two XML objects.
  335. :param xml1: first element
  336. :param xml2: second element
  337. :type xml1: :py:class:`lxml.etree._Element`
  338. :type xml2: :py:class:`lxml.etree._Element`
  339. ''' # pylint: disable=invalid-name
  340. self.assertEqual(xml1.tag, xml2.tag)
  341. self.assertEqual(xml1.text, xml2.text)
  342. self.assertCountEqual(xml1.keys(), xml2.keys())
  343. for key in xml1.keys():
  344. self.assertEqual(xml1.get(key), xml2.get(key))
  345. def assertDevicesEqual(self, devices1, devices2, msg=None):
  346. self.assertEqual(devices1.keys(), devices2.keys(), msg)
  347. for dev_class in devices1.keys():
  348. self.assertEqual(
  349. [str(dev) for dev in devices1[dev_class]],
  350. [str(dev) for dev in devices2[dev_class]],
  351. "Devices of class {} differs{}".format(
  352. dev_class, (": " + msg) if msg else "")
  353. )
  354. def assertEventFired(self, subject, event, kwargs=None):
  355. '''Check whether event was fired on given emitter and fail if it did
  356. not.
  357. :param subject: emitter which is being checked
  358. :type emitter: :py:class:`TestEmitter`
  359. :param str event: event identifier
  360. :param list kwargs: when given, all items must appear in kwargs passed \
  361. to an event
  362. '''
  363. will_not_match = object()
  364. for ev, ev_kwargs in subject.fired_events:
  365. if ev != event:
  366. continue
  367. if kwargs is not None:
  368. ev_kwargs = dict(ev_kwargs)
  369. if any(ev_kwargs.get(k, will_not_match) != v
  370. for k, v in kwargs.items()):
  371. continue
  372. return
  373. self.fail('event {!r} {}did not fire on {!r}'.format(
  374. event, ('' if kwargs is None else '{!r} '.format(kwargs)), subject))
  375. def assertEventNotFired(self, subject, event, kwargs=None):
  376. '''Check whether event was fired on given emitter. Fail if it did.
  377. :param subject: emitter which is being checked
  378. :type emitter: :py:class:`TestEmitter`
  379. :param str event: event identifier
  380. :param list kwargs: when given, all items must appear in kwargs passed \
  381. to an event
  382. '''
  383. will_not_match = object()
  384. for ev, ev_kwargs in subject.fired_events:
  385. if ev != event:
  386. continue
  387. if kwargs is not None:
  388. ev_kwargs = dict(ev_kwargs)
  389. if any(ev_kwargs.get(k, will_not_match) != v
  390. for k, v in kwargs.items()):
  391. continue
  392. self.fail('event {!r} {}did fire on {!r}'.format(
  393. event,
  394. ('' if kwargs is None else '{!r} '.format(kwargs)),
  395. subject))
  396. return
  397. def assertXMLIsValid(self, xml, file=None, schema=None):
  398. '''Check whether given XML fulfills Relax NG schema.
  399. Schema can be given in a couple of ways:
  400. - As separate file. This is most common, and also the only way to
  401. handle file inclusion. Call with file name as second argument.
  402. - As string containing actual schema. Put that string in *schema*
  403. keyword argument.
  404. :param lxml.etree._Element xml: XML element instance to check
  405. :param str file: filename of Relax NG schema
  406. :param str schema: optional explicit schema string
  407. ''' # pylint: disable=redefined-builtin
  408. if schema is not None and file is None:
  409. relaxng = schema
  410. if isinstance(relaxng, str):
  411. relaxng = lxml.etree.XML(relaxng)
  412. # pylint: disable=protected-access
  413. if isinstance(relaxng, lxml.etree._Element):
  414. relaxng = lxml.etree.RelaxNG(relaxng)
  415. elif file is not None and schema is None:
  416. if not os.path.isabs(file):
  417. basedirs = ['/usr/share/doc/qubes/relaxng']
  418. if in_git:
  419. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  420. for basedir in basedirs:
  421. abspath = os.path.join(basedir, file)
  422. if os.path.exists(abspath):
  423. file = abspath
  424. break
  425. relaxng = lxml.etree.RelaxNG(file=file)
  426. else:
  427. raise TypeError("There should be excactly one of 'file' and "
  428. "'schema' arguments specified.")
  429. # We have to be extra careful here in case someone messed up with
  430. # self.failureException. It should by default be AssertionError, just
  431. # what is spewed by RelaxNG(), but who knows what might happen.
  432. try:
  433. relaxng.assert_(xml)
  434. except self.failureException:
  435. raise
  436. except AssertionError as e:
  437. self.fail(str(e))
  438. @staticmethod
  439. def make_vm_name(name, class_teardown=False):
  440. if class_teardown:
  441. return CLSVMPREFIX + name
  442. else:
  443. return VMPREFIX + name
  444. class SystemTestsMixin(object):
  445. """
  446. Mixin for integration tests. All the tests here should use self.app
  447. object and when need qubes.xml path - should use :py:data:`XMLPATH`
  448. defined in this file.
  449. Every VM created by test, must use :py:meth:`SystemTestsMixin.make_vm_name`
  450. for VM name.
  451. By default self.app represents empty collection, if anything is needed
  452. there from the real collection it can be imported from self.host_app in
  453. :py:meth:`SystemTestsMixin.setUp`. But *can not be modified* in any way -
  454. this include both changing attributes in
  455. :py:attr:`SystemTestsMixin.host_app` and modifying files of such imported
  456. VM. If test need to make some modification, it must clone the VM first.
  457. If some group of tests needs class-wide initialization, first of all the
  458. author should consider if it is really needed. But if so, setUpClass can
  459. be used to create Qubes(CLASS_XMLPATH) object and create/import required
  460. stuff there. VMs created in :py:meth:`TestCase.setUpClass` should
  461. use self.make_vm_name('...', class_teardown=True) for name creation.
  462. """
  463. # noinspection PyAttributeOutsideInit
  464. def setUp(self):
  465. if not in_dom0:
  466. self.skipTest('outside dom0')
  467. super(SystemTestsMixin, self).setUp()
  468. self.remove_test_vms()
  469. # need some information from the real qubes.xml - at least installed
  470. # templates; should not be used for testing, only to initialize self.app
  471. self.host_app = qubes.Qubes(os.path.join(
  472. qubes.config.system_path['qubes_base_dir'],
  473. qubes.config.system_path['qubes_store_filename']))
  474. if os.path.exists(CLASS_XMLPATH):
  475. shutil.copy(CLASS_XMLPATH, XMLPATH)
  476. else:
  477. shutil.copy(self.host_app.store, XMLPATH)
  478. self.app = qubes.Qubes(XMLPATH)
  479. os.environ['QUBES_XML_PATH'] = XMLPATH
  480. self.qubesd = self.loop.run_until_complete(
  481. qubes.api.create_servers(
  482. qubes.api.admin.QubesAdminAPI,
  483. qubes.api.internal.QubesInternalAPI,
  484. app=self.app, debug=True))
  485. def init_default_template(self, template=None):
  486. if template is None:
  487. template = self.host_app.default_template
  488. elif isinstance(template, str):
  489. template = self.host_app.domains[template]
  490. self.app.default_template = str(template)
  491. def init_networking(self):
  492. if not self.app.default_template:
  493. self.skipTest('Default template required for testing networking')
  494. default_netvm = self.host_app.default_netvm
  495. # if testing Whonix Workstation based VMs, try to use sys-whonix instead
  496. if self.app.default_template.name.startswith('whonix-ws'):
  497. if 'sys-whonix' in self.host_app.domains:
  498. default_netvm = self.host_app.domains['sys-whonix']
  499. if default_netvm is None:
  500. self.skipTest('Default netvm required')
  501. if not default_netvm.is_running():
  502. self.skipTest('VM {} required to be running'.format(
  503. default_netvm.name))
  504. self.app.default_netvm = str(default_netvm)
  505. def _find_pool(self, volume_group, thin_pool):
  506. ''' Returns the pool matching the specified ``volume_group`` &
  507. ``thin_pool``, or None.
  508. '''
  509. pools = [p for p in self.app.pools
  510. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  511. for pool in pools:
  512. if pool.volume_group == volume_group \
  513. and pool.thin_pool == thin_pool:
  514. return pool
  515. return None
  516. def init_lvm_pool(self):
  517. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  518. path = "/dev/mapper/{!s}-{!s}".format(volume_group, thin_pool)
  519. if not os.path.exists(path):
  520. self.skipTest('LVM thin pool {!r} does not exist'.
  521. format(DEFAULT_LVM_POOL))
  522. self.pool = self._find_pool(volume_group, thin_pool)
  523. if not self.pool:
  524. self.pool = self.app.add_pool(**POOL_CONF)
  525. self.created_pool = True
  526. def tearDown(self):
  527. self.remove_test_vms()
  528. # close the servers before super(), because that might close the loop
  529. for server in self.qubesd:
  530. for sock in server.sockets:
  531. os.unlink(sock.getsockname())
  532. server.close()
  533. self.loop.run_until_complete(asyncio.wait([
  534. server.wait_closed() for server in self.qubesd]))
  535. super(SystemTestsMixin, self).tearDown()
  536. # remove all references to VM objects, to release resources - most
  537. # importantly file descriptors; this object will live
  538. # during the whole test run, but all the file descriptors would be
  539. # depleted earlier
  540. del self.app
  541. del self.host_app
  542. for attr in dir(self):
  543. if isinstance(getattr(self, attr), qubes.vm.BaseVM):
  544. delattr(self, attr)
  545. @classmethod
  546. def tearDownClass(cls):
  547. super(SystemTestsMixin, cls).tearDownClass()
  548. if not in_dom0:
  549. return
  550. cls.remove_test_vms(xmlpath=CLASS_XMLPATH, prefix=CLSVMPREFIX)
  551. @classmethod
  552. def _remove_vm_qubes(cls, vm):
  553. vmname = vm.name
  554. app = vm.app
  555. try:
  556. # XXX .is_running() may throw libvirtError if undefined
  557. if vm.is_running():
  558. vm.kill()
  559. except: # pylint: disable=bare-except
  560. pass
  561. try:
  562. vm.remove_from_disk()
  563. except: # pylint: disable=bare-except
  564. pass
  565. del app.domains[vm.qid]
  566. del vm
  567. app.save()
  568. del app
  569. # Now ensure it really went away. This may not have happened,
  570. # for example if vm.libvirt_domain malfunctioned.
  571. try:
  572. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  573. dom = conn.lookupByName(vmname)
  574. except: # pylint: disable=bare-except
  575. pass
  576. else:
  577. cls._remove_vm_libvirt(dom)
  578. cls._remove_vm_disk(vmname)
  579. @staticmethod
  580. def _remove_vm_libvirt(dom):
  581. try:
  582. dom.destroy()
  583. except libvirt.libvirtError: # not running
  584. pass
  585. dom.undefine()
  586. @staticmethod
  587. def _remove_vm_disk(vmname):
  588. for dirspec in (
  589. 'qubes_appvms_dir',
  590. 'qubes_servicevms_dir',
  591. 'qubes_templates_dir'):
  592. dirpath = os.path.join(qubes.config.system_path['qubes_base_dir'],
  593. qubes.config.system_path[dirspec], vmname)
  594. if os.path.exists(dirpath):
  595. if os.path.isdir(dirpath):
  596. shutil.rmtree(dirpath)
  597. else:
  598. os.unlink(dirpath)
  599. @staticmethod
  600. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  601. ''' Remove LVM volumes with given prefix
  602. This is "a bit" drastic, as it removes volumes regardless of volume
  603. group, thin pool etc. But we assume no important data on test system.
  604. '''
  605. try:
  606. volumes = subprocess.check_output(
  607. ['sudo', 'lvs', '--noheadings', '-o', 'vg_name,name',
  608. '--separator', '/']).decode()
  609. if ('/' + prefix) not in volumes:
  610. return
  611. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  612. [vol.strip() for vol in volumes.splitlines()
  613. if ('/' + prefix) in vol],
  614. stdout=open(os.devnull, 'w'))
  615. except subprocess.CalledProcessError:
  616. pass
  617. @classmethod
  618. def remove_vms(cls, vms):
  619. for vm in vms:
  620. cls._remove_vm_qubes(vm)
  621. @classmethod
  622. def remove_test_vms(cls, xmlpath=XMLPATH, prefix=VMPREFIX):
  623. '''Aggresively remove any domain that has name in testing namespace.
  624. '''
  625. # first, remove them Qubes-way
  626. if os.path.exists(xmlpath):
  627. try:
  628. cls.remove_vms(vm for vm in qubes.Qubes(xmlpath).domains
  629. if vm.name.startswith(prefix))
  630. except (qubes.exc.QubesException, lxml.etree.XMLSyntaxError):
  631. # If qubes-test.xml is broken that much it doesn't even load,
  632. # simply remove it. VMs will be cleaned up the hard way.
  633. # TODO logging?
  634. pass
  635. os.unlink(xmlpath)
  636. # now remove what was only in libvirt
  637. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  638. for dom in conn.listAllDomains():
  639. if dom.name().startswith(prefix):
  640. cls._remove_vm_libvirt(dom)
  641. conn.close()
  642. # finally remove anything that is left on disk
  643. vmnames = set()
  644. for dirspec in (
  645. 'qubes_appvms_dir',
  646. 'qubes_servicevms_dir',
  647. 'qubes_templates_dir'):
  648. dirpath = os.path.join(qubes.config.system_path['qubes_base_dir'],
  649. qubes.config.system_path[dirspec])
  650. for name in os.listdir(dirpath):
  651. if name.startswith(prefix):
  652. vmnames.add(name)
  653. for vmname in vmnames:
  654. cls._remove_vm_disk(vmname)
  655. cls._remove_vm_disk_lvm(prefix)
  656. def qrexec_policy(self, service, source, destination, allow=True):
  657. """
  658. Allow qrexec calls for duration of the test
  659. :param service: service name
  660. :param source: source VM name
  661. :param destination: destination VM name
  662. :return:
  663. """
  664. return _QrexecPolicyContext(service, source, destination, allow=allow)
  665. def wait_for_window(self, title, timeout=30, show=True):
  666. """
  667. Wait for a window with a given title. Depending on show parameter,
  668. it will wait for either window to show or to disappear.
  669. :param title: title of the window to wait for
  670. :param timeout: timeout of the operation, in seconds
  671. :param show: if True - wait for the window to be visible,
  672. otherwise - to not be visible
  673. :return: None
  674. """
  675. wait_count = 0
  676. while subprocess.call(['xdotool', 'search', '--name', title],
  677. stdout=open(os.path.devnull, 'w'), stderr=subprocess.STDOUT) \
  678. == int(show):
  679. wait_count += 1
  680. if wait_count > timeout*10:
  681. self.fail("Timeout while waiting for {} window to {}".format(
  682. title, "show" if show else "hide")
  683. )
  684. time.sleep(0.1)
  685. def enter_keys_in_window(self, title, keys):
  686. """
  687. Search for window with given title, then enter listed keys there.
  688. The function will wait for said window to appear.
  689. :param title: title of window
  690. :param keys: list of keys to enter, as for `xdotool key`
  691. :return: None
  692. """
  693. # 'xdotool search --sync' sometimes crashes on some race when
  694. # accessing window properties
  695. self.wait_for_window(title)
  696. command = ['xdotool', 'search', '--name', title,
  697. 'windowactivate', '--sync',
  698. 'key'] + keys
  699. subprocess.check_call(command)
  700. def shutdown_and_wait(self, vm, timeout=60):
  701. vm.shutdown()
  702. while timeout > 0:
  703. if not vm.is_running():
  704. return
  705. time.sleep(1)
  706. timeout -= 1
  707. self.fail("Timeout while waiting for VM {} shutdown".format(vm.name))
  708. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  709. if not os.path.exists('/usr/lib/grub/i386-pc'):
  710. self.skipTest('grub2 not installed')
  711. if not spawn.find_executable('grub2-install'):
  712. self.skipTest('grub2-tools not installed')
  713. if not spawn.find_executable('dracut'):
  714. self.skipTest('dracut not installed')
  715. # create a single partition
  716. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  717. stdin=subprocess.PIPE,
  718. stdout=open(os.devnull, 'w'),
  719. stderr=subprocess.STDOUT)
  720. p.communicate('2048,\n')
  721. assert p.returncode == 0, 'sfdisk failed'
  722. # TODO: check if root_img is really file, not already block device
  723. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  724. vm.storage.root_img], stdout=subprocess.PIPE)
  725. (loopdev, _) = p.communicate()
  726. loopdev = loopdev.strip()
  727. looppart = loopdev + 'p1'
  728. assert p.returncode == 0, 'losetup failed'
  729. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  730. mountpoint = tempfile.mkdtemp()
  731. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  732. try:
  733. subprocess.check_call(['sudo', 'grub2-install',
  734. '--target', 'i386-pc',
  735. '--modules', 'part_msdos ext2',
  736. '--boot-directory', mountpoint, loopdev],
  737. stderr=open(os.devnull, 'w')
  738. )
  739. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  740. subprocess.check_call(
  741. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  742. with open(grub_cfg, 'w') as f:
  743. f.write(
  744. "set timeout=1\n"
  745. "menuentry 'Default' {\n"
  746. " linux /vmlinuz root=/dev/xvda1 "
  747. "rd.driver.blacklist=bochs_drm "
  748. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  749. " initrd /initrd\n"
  750. "}"
  751. )
  752. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  753. (kernel_version, _) = p.communicate()
  754. kernel_version = kernel_version.strip()
  755. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  756. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  757. init_path = os.path.join(mountpoint, 'init')
  758. with open(init_path, 'w') as f:
  759. f.write(init_script)
  760. os.chmod(init_path, 0o755)
  761. dracut_args = [
  762. '--kver', kernel_version,
  763. '--include', init_path,
  764. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  765. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  766. ]
  767. if extra_files:
  768. dracut_args += ['--install', ' '.join(extra_files)]
  769. subprocess.check_call(
  770. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  771. 'initrd')],
  772. stderr=open(os.devnull, 'w')
  773. )
  774. finally:
  775. subprocess.check_call(['sudo', 'umount', mountpoint])
  776. shutil.rmtree(mountpoint)
  777. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  778. def create_local_file(self, filename, content, mode='w'):
  779. with open(filename, mode) as file:
  780. file.write(content)
  781. self.addCleanup(os.unlink, filename)
  782. def create_remote_file(self, vm, filename, content):
  783. self.loop.run_until_complete(vm.run_for_stdio(
  784. 'cat > {}'.format(shlex.quote(filename)),
  785. user='root', input=content.encode('utf-8')))
  786. @asyncio.coroutine
  787. def wait_for_session(self, vm):
  788. yield from asyncio.wait_for(
  789. vm.run_service_for_stdio(
  790. 'qubes.WaitForSession', input=vm.default_user.encode()),
  791. timeout=30)
  792. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  793. # discard any tests from this module, because it hosts base classes
  794. tests = unittest.TestSuite()
  795. for modname in (
  796. # unit tests
  797. 'qubes.tests.events',
  798. 'qubes.tests.devices',
  799. 'qubes.tests.devices_block',
  800. 'qubes.tests.firewall',
  801. 'qubes.tests.init',
  802. 'qubes.tests.vm.init',
  803. 'qubes.tests.storage',
  804. 'qubes.tests.storage_file',
  805. 'qubes.tests.storage_lvm',
  806. 'qubes.tests.storage_kernels',
  807. 'qubes.tests.ext',
  808. 'qubes.tests.vm.qubesvm',
  809. 'qubes.tests.vm.mix.net',
  810. 'qubes.tests.vm.adminvm',
  811. 'qubes.tests.vm.appvm',
  812. 'qubes.tests.app',
  813. 'qubes.tests.tarwriter',
  814. 'qubes.tests.api',
  815. 'qubes.tests.api_admin',
  816. 'qubes.tests.api_misc',
  817. 'qubespolicy.tests',
  818. ):
  819. tests.addTests(loader.loadTestsFromName(modname))
  820. # GTK/Glib is way too old there
  821. if 'TRAVIS' not in os.environ:
  822. for modname in (
  823. 'qubespolicy.tests.gtkhelpers',
  824. 'qubespolicy.tests.rpcconfirmation',
  825. ):
  826. tests.addTests(loader.loadTestsFromName(modname))
  827. tests.addTests(loader.discover(
  828. os.path.join(os.path.dirname(__file__), 'tools')))
  829. if not in_dom0:
  830. return tests
  831. for modname in (
  832. # integration tests
  833. 'qubes.tests.integ.basic',
  834. 'qubes.tests.integ.storage',
  835. 'qubes.tests.integ.devices_pci',
  836. 'qubes.tests.integ.dom0_update',
  837. 'qubes.tests.integ.network',
  838. 'qubes.tests.integ.dispvm',
  839. 'qubes.tests.integ.vm_qrexec_gui',
  840. 'qubes.tests.integ.backup',
  841. 'qubes.tests.integ.backupcompatibility',
  842. # 'qubes.tests.regressions',
  843. # external modules
  844. # 'qubes.tests.extra',
  845. ):
  846. tests.addTests(loader.loadTestsFromName(modname))
  847. return tests