__init__.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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 library is free software; you can redistribute it and/or
  11. # modify it under the terms of the GNU Lesser General Public
  12. # License as published by the Free Software Foundation; either
  13. # version 2.1 of the License, or (at your option) any later version.
  14. #
  15. # This library 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 GNU
  18. # Lesser General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public
  21. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  22. #
  23. """
  24. .. warning::
  25. The test suite hereby claims any domain whose name starts with
  26. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  27. test executing environment. If you have domains named ``test-*``,
  28. don't run the tests.
  29. """
  30. import asyncio
  31. import collections
  32. import functools
  33. import logging
  34. import os
  35. import pathlib
  36. import shlex
  37. import shutil
  38. import subprocess
  39. import sys
  40. import tempfile
  41. import time
  42. import traceback
  43. import unittest
  44. import warnings
  45. from distutils import spawn
  46. import gc
  47. import lxml.etree
  48. import pkg_resources
  49. import qubes
  50. import qubes.api
  51. import qubes.api.admin
  52. import qubes.api.internal
  53. import qubes.backup
  54. import qubes.config
  55. import qubes.devices
  56. import qubes.events
  57. import qubes.exc
  58. import qubes.ext.pci
  59. import qubes.vm.standalonevm
  60. import qubes.vm.templatevm
  61. XMLPATH = '/var/lib/qubes/qubes-test.xml'
  62. CLASS_XMLPATH = '/var/lib/qubes/qubes-class-test.xml'
  63. TEMPLATE = 'fedora-23'
  64. VMPREFIX = 'test-inst-'
  65. CLSVMPREFIX = 'test-cls-'
  66. if 'DEFAULT_LVM_POOL' in os.environ.keys():
  67. DEFAULT_LVM_POOL = os.environ['DEFAULT_LVM_POOL']
  68. else:
  69. DEFAULT_LVM_POOL = 'qubes_dom0/pool00'
  70. POOL_CONF = {'name': 'test-lvm',
  71. 'driver': 'lvm_thin',
  72. 'volume_group': DEFAULT_LVM_POOL.split('/')[0],
  73. 'thin_pool': DEFAULT_LVM_POOL.split('/')[1]}
  74. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  75. in_dom0 = False
  76. #: :py:obj:`False` if outside of git repo,
  77. #: path to root of the directory otherwise
  78. in_git = False
  79. try:
  80. import libvirt
  81. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  82. in_dom0 = True
  83. except libvirt.libvirtError:
  84. pass
  85. if in_dom0:
  86. import libvirtaio
  87. libvirt_event_impl = libvirtaio.virEventRegisterAsyncIOImpl()
  88. else:
  89. libvirt_event_impl = None
  90. try:
  91. in_git = subprocess.check_output(
  92. ['git', 'rev-parse', '--show-toplevel']).decode().strip()
  93. qubes.log.LOGPATH = '/tmp'
  94. qubes.log.LOGFILE = '/tmp/qubes.log'
  95. except subprocess.CalledProcessError:
  96. # git returned nonzero, we are outside git repo
  97. pass
  98. except OSError:
  99. # command not found; let's assume we're outside
  100. pass
  101. def skipUnlessDom0(test_item):
  102. '''Decorator that skips test outside dom0.
  103. Some tests (especially integration tests) have to be run in more or less
  104. working dom0. This is checked by connecting to libvirt.
  105. '''
  106. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  107. def skipUnlessGit(test_item):
  108. '''Decorator that skips test outside git repo.
  109. There are very few tests that an be run only in git. One example is
  110. correctness of example code that won't get included in RPM.
  111. '''
  112. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  113. def skipUnlessEnv(varname):
  114. '''Decorator generator for skipping tests without environment variable set.
  115. Some tests require working X11 display, like those using GTK library, which
  116. segfaults without connection to X.
  117. Other require their own, custom variables.
  118. '''
  119. return unittest.skipUnless(os.getenv(varname), 'no {} set'.format(varname))
  120. class TestEmitter(qubes.events.Emitter):
  121. '''Dummy event emitter which records events fired on it.
  122. Events are counted in :py:attr:`fired_events` attribute, which is
  123. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  124. kwargs)`` object is counted. *event* is event name (a string), *args* is
  125. tuple with positional arguments and *kwargs* is sorted tuple of items from
  126. keyword arguments.
  127. >>> emitter = TestEmitter()
  128. >>> emitter.fired_events
  129. Counter()
  130. >>> emitter.fire_event('event', spam='eggs', foo='bar')
  131. >>> emitter.fired_events
  132. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  133. '''
  134. def __init__(self, *args, **kwargs):
  135. super(TestEmitter, self).__init__(*args, **kwargs)
  136. #: :py:class:`collections.Counter` instance
  137. self.fired_events = collections.Counter()
  138. def fire_event(self, event, **kwargs):
  139. effects = super(TestEmitter, self).fire_event(event, **kwargs)
  140. ev_kwargs = frozenset(
  141. (key,
  142. frozenset(value.items()) if isinstance(value, dict)
  143. else tuple(value) if isinstance(value, list)
  144. else value)
  145. for key, value in kwargs.items()
  146. )
  147. self.fired_events[(event, ev_kwargs)] += 1
  148. return effects
  149. @asyncio.coroutine
  150. def fire_event_async(self, event, pre_event=False, **kwargs):
  151. effects = yield from super(TestEmitter, self).fire_event_async(
  152. event, pre_event=pre_event, **kwargs)
  153. ev_kwargs = frozenset(
  154. (key,
  155. frozenset(value.items()) if isinstance(value, dict) else value)
  156. for key, value in kwargs.items()
  157. )
  158. self.fired_events[(event, ev_kwargs)] += 1
  159. return effects
  160. def expectedFailureIfTemplate(templates):
  161. """
  162. Decorator for marking specific test as expected to fail only for some
  163. templates. Template name is compared as substring, so 'whonix' will
  164. handle both 'whonix-ws' and 'whonix-gw'.
  165. templates can be either a single string, or an iterable
  166. """
  167. def decorator(func):
  168. @functools.wraps(func)
  169. def wrapper(self, *args, **kwargs):
  170. template = self.template
  171. if isinstance(templates, str):
  172. should_expect_fail = template in templates
  173. else:
  174. should_expect_fail = any([template in x for x in templates])
  175. if should_expect_fail:
  176. try:
  177. func(self, *args, **kwargs)
  178. except Exception:
  179. raise unittest.case._ExpectedFailure(sys.exc_info())
  180. raise unittest.case._UnexpectedSuccess()
  181. else:
  182. # Call directly:
  183. func(self, *args, **kwargs)
  184. return wrapper
  185. return decorator
  186. class _AssertNotRaisesContext(object):
  187. """A context manager used to implement TestCase.assertNotRaises methods.
  188. Stolen from unittest and hacked. Regexp support stripped.
  189. """ # pylint: disable=too-few-public-methods
  190. def __init__(self, expected, test_case, expected_regexp=None):
  191. if expected_regexp is not None:
  192. raise NotImplementedError('expected_regexp is unsupported')
  193. self.expected = expected
  194. self.exception = None
  195. self.failureException = test_case.failureException
  196. def __enter__(self):
  197. return self
  198. def __exit__(self, exc_type, exc_value, tb):
  199. if exc_type is None:
  200. return True
  201. if issubclass(exc_type, self.expected):
  202. raise self.failureException(
  203. "{!r} raised, traceback:\n{!s}".format(
  204. exc_value, ''.join(traceback.format_tb(tb))))
  205. else:
  206. # pass through
  207. return False
  208. self.exception = exc_value # store for later retrieval
  209. class _QrexecPolicyContext(object):
  210. '''Context manager for SystemTestCase.qrexec_policy'''
  211. def __init__(self, service, source, destination, allow=True, action=None):
  212. try:
  213. source = source.name
  214. except AttributeError:
  215. pass
  216. try:
  217. destination = destination.name
  218. except AttributeError:
  219. pass
  220. self._filename = pathlib.Path('/etc/qubes-rpc/policy') / service
  221. if action is None:
  222. action = 'allow' if allow else 'deny'
  223. self._rule = '{} {} {}\n'.format(source, destination, action)
  224. self._did_create = False
  225. self._handle = None
  226. def load(self):
  227. if self._handle is None:
  228. try:
  229. self._handle = self._filename.open('r+')
  230. except FileNotFoundError:
  231. self._handle = self._filename.open('w+')
  232. self._did_create = True
  233. self._handle.seek(0)
  234. return self._handle.readlines()
  235. def save(self, rules):
  236. assert self._handle is not None
  237. self._handle.truncate(0)
  238. self._handle.seek(0)
  239. self._handle.write(''.join(rules))
  240. self._handle.flush()
  241. def close(self):
  242. assert self._handle is not None
  243. self._handle.close()
  244. self._handle = None
  245. def __enter__(self):
  246. rules = self.load()
  247. rules.insert(0, self._rule)
  248. self.save(rules)
  249. return self
  250. def __exit__(self, exc_type, exc_value, tb):
  251. if not self._did_create:
  252. try:
  253. rules = self.load()
  254. rules.remove(self._rule)
  255. self.save(rules)
  256. finally:
  257. self.close()
  258. else:
  259. self.close()
  260. self._filename.unlink()
  261. class substitute_entry_points(object):
  262. '''Monkey-patch pkg_resources to substitute one group in iter_entry_points
  263. This is for testing plugins, like device classes.
  264. :param str group: The group that is to be overloaded.
  265. :param str tempgroup: The substitute group.
  266. Inside this context, if one iterates over entry points in overloaded group,
  267. the iteration actually happens over the other group.
  268. This context manager is stackable. To substitute more than one entry point
  269. group, just nest two contexts.
  270. ''' # pylint: disable=invalid-name
  271. def __init__(self, group, tempgroup):
  272. self.group = group
  273. self.tempgroup = tempgroup
  274. self._orig_iter_entry_points = None
  275. def _iter_entry_points(self, group, *args, **kwargs):
  276. if group == self.group:
  277. group = self.tempgroup
  278. return self._orig_iter_entry_points(group, *args, **kwargs)
  279. def __enter__(self):
  280. self._orig_iter_entry_points = pkg_resources.iter_entry_points
  281. pkg_resources.iter_entry_points = self._iter_entry_points
  282. return self
  283. def __exit__(self, exc_type, exc_value, tb):
  284. pkg_resources.iter_entry_points = self._orig_iter_entry_points
  285. self._orig_iter_entry_points = None
  286. class QubesTestCase(unittest.TestCase):
  287. '''Base class for Qubes unit tests.
  288. '''
  289. def __init__(self, *args, **kwargs):
  290. super(QubesTestCase, self).__init__(*args, **kwargs)
  291. self.longMessage = True
  292. self.log = logging.getLogger('{}.{}.{}'.format(
  293. self.__class__.__module__,
  294. self.__class__.__name__,
  295. self._testMethodName))
  296. self.addTypeEqualityFunc(qubes.devices.DeviceManager,
  297. self.assertDevicesEqual)
  298. self.loop = None
  299. def __str__(self):
  300. return '{}/{}/{}'.format(
  301. self.__class__.__module__,
  302. self.__class__.__name__,
  303. self._testMethodName)
  304. def setUp(self):
  305. super().setUp()
  306. self.addCleanup(self.cleanup_gc)
  307. self.loop = asyncio.get_event_loop()
  308. self.addCleanup(self.cleanup_loop)
  309. self.addCleanup(self.cleanup_traceback)
  310. self.addCleanup(qubes.ext.pci._cache_get.cache_clear)
  311. def cleanup_traceback(self):
  312. '''Remove local variables reference from tracebacks to allow garbage
  313. collector to clean all Qubes*() objects, otherwise file descriptors
  314. held by them will leak'''
  315. for test_case, exc_info in self._outcome.errors:
  316. if test_case is not self:
  317. continue
  318. if exc_info is None:
  319. continue
  320. traceback.clear_frames(exc_info[2])
  321. def cleanup_gc(self):
  322. gc.collect()
  323. leaked = [obj for obj in gc.get_objects() + gc.garbage
  324. if isinstance(obj,
  325. (qubes.Qubes, qubes.vm.BaseVM,
  326. libvirt.virConnect, libvirt.virDomain))]
  327. if leaked:
  328. try:
  329. import objgraph
  330. objgraph.show_backrefs(leaked,
  331. max_depth=15, extra_info=extra_info,
  332. filename='/tmp/objgraph-{}.png'.format(self.id()))
  333. except ImportError:
  334. pass
  335. # do not keep leaked object references in locals()
  336. leaked = bool(leaked)
  337. assert not leaked
  338. def cleanup_loop(self):
  339. '''Check if the loop is empty'''
  340. # XXX BEWARE this is touching undocumented, implementation-specific
  341. # attributes of the loop. This is most certainly unsupported and likely
  342. # will break when messing with: Python version, kernel family, loop
  343. # implementation, a combination thereof, or other things.
  344. # KEYWORDS for searching:
  345. # win32, SelectorEventLoop, ProactorEventLoop, uvloop, gevent
  346. global libvirt_event_impl
  347. # really destroy all objects that could have used loop and/or libvirt
  348. gc.collect()
  349. # Check for unfinished libvirt business.
  350. if libvirt_event_impl is not None:
  351. try:
  352. self.loop.run_until_complete(asyncio.wait_for(
  353. libvirt_event_impl.drain(), timeout=4))
  354. except asyncio.TimeoutError:
  355. raise AssertionError('libvirt event impl drain timeout')
  356. # this is stupid, but apparently it requires two passes
  357. # to cleanup SIGCHLD handlers
  358. self.loop.stop()
  359. self.loop.run_forever()
  360. self.loop.stop()
  361. self.loop.run_forever()
  362. # Check there are no Tasks left.
  363. assert not self.loop._ready
  364. assert not self.loop._scheduled
  365. # Check the loop watches no descriptors.
  366. # NOTE the loop has a pipe for self-interrupting, created once per
  367. # lifecycle, and it is unwatched only at loop.close(); so we cannot just
  368. # check selector for non-emptiness
  369. assert len(self.loop._selector.get_map()) \
  370. == int(self.loop._ssock is not None)
  371. del self.loop
  372. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  373. """Fail if an exception of class excClass is raised
  374. by callableObj when invoked with arguments args and keyword
  375. arguments kwargs. If a different type of exception is
  376. raised, it will not be caught, and the test case will be
  377. deemed to have suffered an error, exactly as for an
  378. unexpected exception.
  379. If called with callableObj omitted or None, will return a
  380. context object used like this::
  381. with self.assertRaises(SomeException):
  382. do_something()
  383. The context manager keeps a reference to the exception as
  384. the 'exception' attribute. This allows you to inspect the
  385. exception after the assertion::
  386. with self.assertRaises(SomeException) as cm:
  387. do_something()
  388. the_exception = cm.exception
  389. self.assertEqual(the_exception.error_code, 3)
  390. """
  391. context = _AssertNotRaisesContext(excClass, self)
  392. if callableObj is None:
  393. return context
  394. with context:
  395. callableObj(*args, **kwargs)
  396. def assertXMLEqual(self, xml1, xml2, msg=''):
  397. '''Check for equality of two XML objects.
  398. :param xml1: first element
  399. :param xml2: second element
  400. :type xml1: :py:class:`lxml.etree._Element`
  401. :type xml2: :py:class:`lxml.etree._Element`
  402. '''
  403. self.assertEqual(xml1.tag, xml2.tag)
  404. msg += '/' + str(xml1.tag)
  405. if xml1.text is not None and xml2.text is not None:
  406. self.assertEqual(xml1.text.strip(), xml2.text.strip(), msg)
  407. else:
  408. self.assertEqual(xml1.text, xml2.text, msg)
  409. self.assertCountEqual(xml1.keys(), xml2.keys(), msg)
  410. for key in xml1.keys():
  411. self.assertEqual(xml1.get(key), xml2.get(key), msg)
  412. self.assertEqual(len(xml1), len(xml2), msg + ' children count')
  413. for child1, child2 in zip(xml1, xml2):
  414. self.assertXMLEqual(child1, child2, msg=msg)
  415. def assertDevicesEqual(self, devices1, devices2, msg=None):
  416. self.assertEqual(devices1.keys(), devices2.keys(), msg)
  417. for dev_class in devices1.keys():
  418. self.assertEqual(
  419. [str(dev) for dev in devices1[dev_class]],
  420. [str(dev) for dev in devices2[dev_class]],
  421. "Devices of class {} differs{}".format(
  422. dev_class, (": " + msg) if msg else "")
  423. )
  424. def assertEventFired(self, subject, event, kwargs=None):
  425. '''Check whether event was fired on given emitter and fail if it did
  426. not.
  427. :param subject: emitter which is being checked
  428. :type emitter: :py:class:`TestEmitter`
  429. :param str event: event identifier
  430. :param dict kwargs: when given, all items must appear in kwargs passed \
  431. to an event
  432. '''
  433. will_not_match = object()
  434. for ev, ev_kwargs in subject.fired_events:
  435. if ev != event:
  436. continue
  437. if kwargs is not None:
  438. ev_kwargs = dict(ev_kwargs)
  439. if any(ev_kwargs.get(k, will_not_match) != v
  440. for k, v in kwargs.items()):
  441. continue
  442. return
  443. self.fail('event {!r} {}did not fire on {!r}'.format(
  444. event, ('' if kwargs is None else '{!r} '.format(kwargs)), subject))
  445. def assertEventNotFired(self, subject, event, kwargs=None):
  446. '''Check whether event was fired on given emitter. Fail if it did.
  447. :param subject: emitter which is being checked
  448. :type emitter: :py:class:`TestEmitter`
  449. :param str event: event identifier
  450. :param list kwargs: when given, all items must appear in kwargs passed \
  451. to an event
  452. '''
  453. will_not_match = object()
  454. for ev, ev_kwargs in subject.fired_events:
  455. if ev != event:
  456. continue
  457. if kwargs is not None:
  458. ev_kwargs = dict(ev_kwargs)
  459. if any(ev_kwargs.get(k, will_not_match) != v
  460. for k, v in kwargs.items()):
  461. continue
  462. self.fail('event {!r} {}did fire on {!r}'.format(
  463. event,
  464. ('' if kwargs is None else '{!r} '.format(kwargs)),
  465. subject))
  466. return
  467. def assertXMLIsValid(self, xml, file=None, schema=None):
  468. '''Check whether given XML fulfills Relax NG schema.
  469. Schema can be given in a couple of ways:
  470. - As separate file. This is most common, and also the only way to
  471. handle file inclusion. Call with file name as second argument.
  472. - As string containing actual schema. Put that string in *schema*
  473. keyword argument.
  474. :param lxml.etree._Element xml: XML element instance to check
  475. :param str file: filename of Relax NG schema
  476. :param str schema: optional explicit schema string
  477. ''' # pylint: disable=redefined-builtin
  478. if schema is not None and file is None:
  479. relaxng = schema
  480. if isinstance(relaxng, str):
  481. relaxng = lxml.etree.XML(relaxng)
  482. # pylint: disable=protected-access
  483. if isinstance(relaxng, lxml.etree._Element):
  484. relaxng = lxml.etree.RelaxNG(relaxng)
  485. elif file is not None and schema is None:
  486. if not os.path.isabs(file):
  487. basedirs = ['/usr/share/doc/qubes/relaxng']
  488. if in_git:
  489. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  490. for basedir in basedirs:
  491. abspath = os.path.join(basedir, file)
  492. if os.path.exists(abspath):
  493. file = abspath
  494. break
  495. relaxng = lxml.etree.RelaxNG(file=file)
  496. else:
  497. raise TypeError("There should be excactly one of 'file' and "
  498. "'schema' arguments specified.")
  499. # We have to be extra careful here in case someone messed up with
  500. # self.failureException. It should by default be AssertionError, just
  501. # what is spewed by RelaxNG(), but who knows what might happen.
  502. try:
  503. relaxng.assert_(xml)
  504. except self.failureException:
  505. raise
  506. except AssertionError as e:
  507. self.fail(str(e))
  508. @staticmethod
  509. def make_vm_name(name, class_teardown=False):
  510. if class_teardown:
  511. return CLSVMPREFIX + name
  512. else:
  513. return VMPREFIX + name
  514. class SystemTestCase(QubesTestCase):
  515. """
  516. Mixin for integration tests. All the tests here should use self.app
  517. object and when need qubes.xml path - should use :py:data:`XMLPATH`
  518. defined in this file.
  519. Every VM created by test, must use :py:meth:`SystemTestCase.make_vm_name`
  520. for VM name.
  521. By default self.app represents empty collection, if anything is needed
  522. there from the real collection it can be imported from self.host_app in
  523. :py:meth:`SystemTestCase.setUp`. But *can not be modified* in any way -
  524. this include both changing attributes in
  525. :py:attr:`SystemTestCase.host_app` and modifying files of such imported
  526. VM. If test need to make some modification, it must clone the VM first.
  527. If some group of tests needs class-wide initialization, first of all the
  528. author should consider if it is really needed. But if so, setUpClass can
  529. be used to create Qubes(CLASS_XMLPATH) object and create/import required
  530. stuff there. VMs created in :py:meth:`TestCase.setUpClass` should
  531. use self.make_vm_name('...', class_teardown=True) for name creation.
  532. Such (group of) test need to take care about
  533. :py:meth:`TestCase.tearDownClass` implementation itself.
  534. """
  535. # noinspection PyAttributeOutsideInit
  536. def setUp(self):
  537. if not in_dom0:
  538. self.skipTest('outside dom0')
  539. super(SystemTestCase, self).setUp()
  540. self.remove_test_vms()
  541. # need some information from the real qubes.xml - at least installed
  542. # templates; should not be used for testing, only to initialize self.app
  543. self.host_app = qubes.Qubes(os.path.join(
  544. qubes.config.qubes_base_dir,
  545. qubes.config.system_path['qubes_store_filename']))
  546. if os.path.exists(CLASS_XMLPATH):
  547. shutil.copy(CLASS_XMLPATH, XMLPATH)
  548. else:
  549. shutil.copy(self.host_app.store, XMLPATH)
  550. self.app = qubes.Qubes(XMLPATH)
  551. os.environ['QUBES_XML_PATH'] = XMLPATH
  552. self.app.register_event_handlers()
  553. self.qubesd = self.loop.run_until_complete(
  554. qubes.api.create_servers(
  555. qubes.api.admin.QubesAdminAPI,
  556. qubes.api.internal.QubesInternalAPI,
  557. app=self.app, debug=True))
  558. self.addCleanup(self.cleanup_app)
  559. self.app.add_handler('domain-delete', self.close_qdb_on_remove)
  560. def close_qdb_on_remove(self, app, event, vm, **kwargs):
  561. # only close QubesDB connection, do not perform other (destructive)
  562. # actions of vm.close()
  563. if vm._qdb_connection_watch is not None:
  564. asyncio.get_event_loop().remove_reader(
  565. vm._qdb_connection_watch.watch_fd())
  566. vm._qdb_connection_watch.close()
  567. vm._qdb_connection_watch = None
  568. def cleanup_app(self):
  569. self.remove_test_vms()
  570. server = None
  571. for server in self.qubesd:
  572. for sock in server.sockets:
  573. os.unlink(sock.getsockname())
  574. server.close()
  575. del server
  576. # close all existing connections, especially this will interrupt
  577. # running admin.Events calls, which do keep reference to Qubes() and
  578. # libvirt connection
  579. conn = None
  580. for conn in qubes.api.QubesDaemonProtocol.connections:
  581. if conn.transport:
  582. conn.transport.abort()
  583. del conn
  584. self.loop.run_until_complete(asyncio.wait([
  585. server.wait_closed() for server in self.qubesd]))
  586. del self.qubesd
  587. # remove all references to any complex qubes objects, to release
  588. # resources - most importantly file descriptors; this object will live
  589. # during the whole test run, but all the file descriptors would be
  590. # depleted earlier
  591. self.app.close()
  592. self.host_app.close()
  593. del self.app
  594. del self.host_app
  595. for attr in dir(self):
  596. obj_type = type(getattr(self, attr))
  597. if obj_type.__module__.startswith('qubes'):
  598. delattr(self, attr)
  599. # then trigger garbage collector to really destroy those objects
  600. gc.collect()
  601. def init_default_template(self, template=None):
  602. if template is None:
  603. template = self.host_app.default_template
  604. elif isinstance(template, str):
  605. template = self.host_app.domains[template]
  606. self.app.default_template = str(template)
  607. def init_networking(self):
  608. if not self.app.default_template:
  609. self.skipTest('Default template required for testing networking')
  610. default_netvm = self.host_app.default_netvm
  611. # if testing Whonix Workstation based VMs, try to use sys-whonix instead
  612. if self.app.default_template.name.startswith('whonix-ws'):
  613. if 'sys-whonix' in self.host_app.domains:
  614. default_netvm = self.host_app.domains['sys-whonix']
  615. if default_netvm is None:
  616. self.skipTest('Default netvm required')
  617. if not default_netvm.is_running():
  618. self.skipTest('VM {} required to be running'.format(
  619. default_netvm.name))
  620. self.app.default_netvm = str(default_netvm)
  621. def _find_pool(self, volume_group, thin_pool):
  622. ''' Returns the pool matching the specified ``volume_group`` &
  623. ``thin_pool``, or None.
  624. '''
  625. pools = [p for p in self.app.pools
  626. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  627. for pool in pools:
  628. if pool.volume_group == volume_group \
  629. and pool.thin_pool == thin_pool:
  630. return pool
  631. return None
  632. def init_lvm_pool(self):
  633. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  634. path = "/dev/mapper/{!s}-{!s}".format(volume_group, thin_pool)
  635. if not os.path.exists(path):
  636. self.skipTest('LVM thin pool {!r} does not exist'.
  637. format(DEFAULT_LVM_POOL))
  638. self.pool = self._find_pool(volume_group, thin_pool)
  639. if not self.pool:
  640. self.pool = self.app.add_pool(**POOL_CONF)
  641. self.created_pool = True
  642. def _remove_vm_qubes(self, vm):
  643. vmname = vm.name
  644. app = vm.app
  645. # avoid race with DispVM.auto_cleanup=True
  646. try:
  647. self.loop.run_until_complete(
  648. asyncio.wait_for(vm.startup_lock.acquire(), 10))
  649. except asyncio.TimeoutError:
  650. pass
  651. try:
  652. # XXX .is_running() may throw libvirtError if undefined
  653. if vm.is_running():
  654. self.loop.run_until_complete(vm.kill())
  655. except: # pylint: disable=bare-except
  656. pass
  657. try:
  658. self.loop.run_until_complete(vm.remove_from_disk())
  659. except: # pylint: disable=bare-except
  660. pass
  661. try:
  662. del app.domains[vm.qid]
  663. except KeyError:
  664. pass
  665. vm.close()
  666. del vm
  667. app.save()
  668. del app
  669. # Now ensure it really went away. This may not have happened,
  670. # for example if vm.libvirt_domain malfunctioned.
  671. try:
  672. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  673. except: # pylint: disable=bare-except
  674. pass
  675. else:
  676. try:
  677. dom = conn.lookupByName(vmname)
  678. except: # pylint: disable=bare-except
  679. pass
  680. else:
  681. self._remove_vm_libvirt(dom)
  682. conn.close()
  683. self._remove_vm_disk(vmname)
  684. @staticmethod
  685. def _remove_vm_libvirt(dom):
  686. try:
  687. dom.destroy()
  688. except libvirt.libvirtError: # not running
  689. pass
  690. dom.undefine()
  691. @staticmethod
  692. def _remove_vm_disk(vmname):
  693. for dirspec in (
  694. 'qubes_appvms_dir',
  695. 'qubes_servicevms_dir',
  696. 'qubes_templates_dir'):
  697. dirpath = os.path.join(qubes.config.qubes_base_dir,
  698. qubes.config.system_path[dirspec], vmname)
  699. if os.path.exists(dirpath):
  700. if os.path.isdir(dirpath):
  701. shutil.rmtree(dirpath)
  702. else:
  703. os.unlink(dirpath)
  704. @staticmethod
  705. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  706. ''' Remove LVM volumes with given prefix
  707. This is "a bit" drastic, as it removes volumes regardless of volume
  708. group, thin pool etc. But we assume no important data on test system.
  709. '''
  710. try:
  711. volumes = subprocess.check_output(
  712. ['lvs', '--noheadings', '-o', 'vg_name,name',
  713. '--separator', '/']).decode()
  714. if ('/vm-' + prefix) not in volumes:
  715. return
  716. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  717. [vol.strip() for vol in volumes.splitlines()
  718. if ('/vm-' + prefix) in vol],
  719. stdout=subprocess.DEVNULL)
  720. except subprocess.CalledProcessError:
  721. pass
  722. def remove_vms(self, vms):
  723. vms = list(vms)
  724. if not vms:
  725. return
  726. # break dependencies
  727. for vm in vms:
  728. vm.default_dispvm = None
  729. # then remove in reverse topological order (wrt netvm), using naive
  730. # algorithm
  731. # this heavily depends on lack of netvm loops
  732. while vms:
  733. vm = vms.pop(0)
  734. # make sure that all connected VMs are going to be removed,
  735. # otherwise this will loop forever
  736. assert all(x in vms for x in vm.connected_vms)
  737. if list(vm.connected_vms):
  738. # if still something use this VM, put it at the end of queue
  739. # and try next one
  740. vms.append(vm)
  741. continue
  742. self._remove_vm_qubes(vm)
  743. def remove_test_vms(self, xmlpath=XMLPATH, prefix=VMPREFIX):
  744. '''Aggresively remove any domain that has name in testing namespace.
  745. '''
  746. # first, remove them Qubes-way
  747. if os.path.exists(xmlpath):
  748. try:
  749. try:
  750. app = self.app
  751. except AttributeError:
  752. app = qubes.Qubes(xmlpath)
  753. try:
  754. host_app = self.host_app
  755. except AttributeError:
  756. host_app = qubes.Qubes()
  757. self.remove_vms([vm for vm in app.domains
  758. if vm.name.startswith(prefix) or
  759. (isinstance(vm, qubes.vm.dispvm.DispVM) and vm.name
  760. not in host_app.domains)])
  761. if not hasattr(self, 'host_app'):
  762. host_app.close()
  763. del host_app
  764. if not hasattr(self, 'app'):
  765. app.close()
  766. del app
  767. except qubes.exc.QubesException:
  768. pass
  769. os.unlink(xmlpath)
  770. # now remove what was only in libvirt
  771. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  772. for dom in conn.listAllDomains():
  773. if dom.name().startswith(prefix):
  774. self._remove_vm_libvirt(dom)
  775. conn.close()
  776. # finally remove anything that is left on disk
  777. vmnames = set()
  778. for dirspec in (
  779. 'qubes_appvms_dir',
  780. 'qubes_servicevms_dir',
  781. 'qubes_templates_dir'):
  782. dirpath = os.path.join(qubes.config.qubes_base_dir,
  783. qubes.config.system_path[dirspec])
  784. if not os.path.exists(dirpath):
  785. continue
  786. for name in os.listdir(dirpath):
  787. if name.startswith(prefix):
  788. vmnames.add(name)
  789. for vmname in vmnames:
  790. self._remove_vm_disk(vmname)
  791. self._remove_vm_disk_lvm(prefix)
  792. def qrexec_policy(self, service, source, destination, allow=True,
  793. action=None):
  794. """
  795. Allow qrexec calls for duration of the test
  796. :param service: service name
  797. :param source: source VM name
  798. :param destination: destination VM name
  799. :param allow: add rule with 'allow' action, otherwise 'deny'
  800. :param action: custom action, if specified *allow* argument is ignored
  801. :return:
  802. """
  803. return _QrexecPolicyContext(service, source, destination,
  804. allow=allow, action=action)
  805. def wait_for_window(self, title, timeout=30, show=True):
  806. """
  807. Wait for a window with a given title. Depending on show parameter,
  808. it will wait for either window to show or to disappear.
  809. :param title: title of the window to wait for
  810. :param timeout: timeout of the operation, in seconds
  811. :param show: if True - wait for the window to be visible,
  812. otherwise - to not be visible
  813. :return: None
  814. """
  815. wait_count = 0
  816. while subprocess.call(['xdotool', 'search', '--name', title],
  817. stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) \
  818. != int(not show):
  819. wait_count += 1
  820. if wait_count > timeout*10:
  821. self.fail("Timeout while waiting for {} window to {}".format(
  822. title, "show" if show else "hide")
  823. )
  824. self.loop.run_until_complete(asyncio.sleep(0.1))
  825. def enter_keys_in_window(self, title, keys):
  826. """
  827. Search for window with given title, then enter listed keys there.
  828. The function will wait for said window to appear.
  829. :param title: title of window
  830. :param keys: list of keys to enter, as for `xdotool key`
  831. :return: None
  832. """
  833. # 'xdotool search --sync' sometimes crashes on some race when
  834. # accessing window properties
  835. self.wait_for_window(title)
  836. command = ['xdotool', 'search', '--name', title,
  837. 'windowactivate', '--sync',
  838. 'key'] + keys
  839. subprocess.check_call(command)
  840. def shutdown_and_wait(self, vm, timeout=60):
  841. self.loop.run_until_complete(vm.shutdown())
  842. while timeout > 0:
  843. if not vm.is_running():
  844. return
  845. self.loop.run_until_complete(asyncio.sleep(1))
  846. timeout -= 1
  847. name = vm.name
  848. del vm
  849. self.fail("Timeout while waiting for VM {} shutdown".format(name))
  850. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  851. if not os.path.exists('/usr/lib/grub/i386-pc'):
  852. self.skipTest('grub2 not installed')
  853. if not spawn.find_executable('grub2-install'):
  854. self.skipTest('grub2-tools not installed')
  855. if not spawn.find_executable('dracut'):
  856. self.skipTest('dracut not installed')
  857. # create a single partition
  858. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  859. stdin=subprocess.PIPE,
  860. stdout=subprocess.DEVNULL,
  861. stderr=subprocess.STDOUT)
  862. p.communicate('2048,\n')
  863. assert p.returncode == 0, 'sfdisk failed'
  864. # TODO: check if root_img is really file, not already block device
  865. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  866. vm.storage.root_img], stdout=subprocess.PIPE)
  867. (loopdev, _) = p.communicate()
  868. loopdev = loopdev.strip()
  869. looppart = loopdev + 'p1'
  870. assert p.returncode == 0, 'losetup failed'
  871. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  872. mountpoint = tempfile.mkdtemp()
  873. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  874. try:
  875. subprocess.check_call(['sudo', 'grub2-install',
  876. '--target', 'i386-pc',
  877. '--modules', 'part_msdos ext2',
  878. '--boot-directory', mountpoint, loopdev],
  879. stderr=subprocess.DEVNULL
  880. )
  881. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  882. subprocess.check_call(
  883. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  884. with open(grub_cfg, 'w') as f:
  885. f.write(
  886. "set timeout=1\n"
  887. "menuentry 'Default' {\n"
  888. " linux /vmlinuz root=/dev/xvda1 "
  889. "rd.driver.blacklist=bochs_drm "
  890. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  891. " initrd /initrd\n"
  892. "}"
  893. )
  894. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  895. (kernel_version, _) = p.communicate()
  896. kernel_version = kernel_version.strip()
  897. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  898. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  899. init_path = os.path.join(mountpoint, 'init')
  900. with open(init_path, 'w') as f:
  901. f.write(init_script)
  902. os.chmod(init_path, 0o755)
  903. dracut_args = [
  904. '--kver', kernel_version,
  905. '--include', init_path,
  906. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  907. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  908. ]
  909. if extra_files:
  910. dracut_args += ['--install', ' '.join(extra_files)]
  911. subprocess.check_call(
  912. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  913. 'initrd')],
  914. stderr=subprocess.DEVNULL
  915. )
  916. finally:
  917. subprocess.check_call(['sudo', 'umount', mountpoint])
  918. shutil.rmtree(mountpoint)
  919. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  920. def create_bootable_iso(self):
  921. '''Create simple bootable ISO image.
  922. Type 'poweroff' to it to terminate that VM.
  923. '''
  924. isolinux_cfg = (
  925. 'prompt 1\n'
  926. 'label poweroff\n'
  927. ' kernel poweroff.c32\n'
  928. )
  929. output_fd, output_path = tempfile.mkstemp('.iso')
  930. with tempfile.TemporaryDirectory() as tmp_dir:
  931. try:
  932. shutil.copy('/usr/share/syslinux/isolinux.bin', tmp_dir)
  933. shutil.copy('/usr/share/syslinux/ldlinux.c32', tmp_dir)
  934. shutil.copy('/usr/share/syslinux/poweroff.c32', tmp_dir)
  935. with open(os.path.join(tmp_dir, 'isolinux.cfg'), 'w') as cfg:
  936. cfg.write(isolinux_cfg)
  937. subprocess.check_call(['genisoimage', '-o', output_path,
  938. '-c', 'boot.cat',
  939. '-b', 'isolinux.bin',
  940. '-no-emul-boot',
  941. '-boot-load-size', '4',
  942. '-boot-info-table',
  943. '-q',
  944. tmp_dir])
  945. except FileNotFoundError:
  946. self.skipTest('syslinux or genisoimage not installed')
  947. os.close(output_fd)
  948. self.addCleanup(os.unlink, output_path)
  949. return output_path
  950. def create_local_file(self, filename, content, mode='w'):
  951. with open(filename, mode) as file:
  952. file.write(content)
  953. self.addCleanup(os.unlink, filename)
  954. def create_remote_file(self, vm, filename, content):
  955. self.loop.run_until_complete(vm.run_for_stdio(
  956. 'cat > {}'.format(shlex.quote(filename)),
  957. user='root', input=content.encode('utf-8')))
  958. @asyncio.coroutine
  959. def wait_for_session(self, vm):
  960. yield from asyncio.wait_for(
  961. vm.run_service_for_stdio(
  962. 'qubes.WaitForSession', input=vm.default_user.encode()),
  963. timeout=30)
  964. _templates = None
  965. def list_templates():
  966. '''Returns tuple of template names available in the system.'''
  967. global _templates
  968. if _templates is None:
  969. try:
  970. app = qubes.Qubes()
  971. _templates = tuple(vm.name for vm in app.domains
  972. if isinstance(vm, qubes.vm.templatevm.TemplateVM) and
  973. vm.features.get('os', None) != 'Windows')
  974. app.close()
  975. del app
  976. except OSError:
  977. _templates = ()
  978. return _templates
  979. def create_testcases_for_templates(name, *bases, module, **kwds):
  980. '''Do-it-all helper for generating per-template tests via load_tests proto
  981. This does several things:
  982. - creates per-template classes
  983. - adds them to module's :py:func:`globals`
  984. - returns an iterable suitable for passing to loader.loadTestsFromNames
  985. TestCase classes created by this function have implicit `.template`
  986. attribute, which contains name of the respective template. They are also
  987. named with given prefix, underscore and template name. If template name
  988. contains characters not valid as part of Python identifier, they are
  989. impossible to get via standard ``.`` operator, though :py:func:`getattr` is
  990. still usable.
  991. >>> class MyTestsMixIn:
  992. ... def test_000_my_test(self):
  993. ... assert self.template.startswith('debian')
  994. >>> def load_tests(loader, tests, pattern):
  995. ... tests.addTests(loader.loadTestsFromNames(
  996. ... qubes.tests.create_testcases_for_templates(
  997. ... 'TC_00_MyTests', MyTestsMixIn, qubes.tests.SystemTestCase,
  998. ... module=sys.modules[__name__])))
  999. *NOTE* adding ``module=sys.modules[__name__]`` is *mandatory*, and to allow
  1000. enforcing this, it uses keyword-only argument syntax, which is only in
  1001. Python 3.
  1002. '''
  1003. # Do not attempt to grab the module from traceback, since we are actually
  1004. # a generator and loadTestsFromNames may also be a generator, so it's not
  1005. # possible to correctly guess frame from stack. Explicit is better than
  1006. # implicit!
  1007. for template in list_templates():
  1008. clsname = name + '_' + template
  1009. cls = type(clsname, bases, {'template': template, **kwds})
  1010. cls.__module__ = module.__name__
  1011. # XXX I wonder what other __dunder__ attrs did I miss
  1012. setattr(module, clsname, cls)
  1013. yield '.'.join((module.__name__, clsname))
  1014. def extra_info(obj):
  1015. '''Return short info identifying object.
  1016. For example, if obj is a qube, return its name. This is for use with
  1017. :py:mod:`objgraph` package.
  1018. '''
  1019. # Feel free to extend to other cases.
  1020. if isinstance(obj, qubes.vm.qubesvm.QubesVM):
  1021. try:
  1022. return obj.name
  1023. except AttributeError:
  1024. pass
  1025. if isinstance(obj, unittest.TestCase):
  1026. return obj.id()
  1027. return ''
  1028. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  1029. # discard any tests from this module, because it hosts base classes
  1030. tests = unittest.TestSuite()
  1031. for modname in (
  1032. # unit tests
  1033. 'qubes.tests.events',
  1034. 'qubes.tests.devices',
  1035. 'qubes.tests.devices_block',
  1036. 'qubes.tests.firewall',
  1037. 'qubes.tests.init',
  1038. 'qubes.tests.vm.init',
  1039. 'qubes.tests.storage',
  1040. 'qubes.tests.storage_file',
  1041. 'qubes.tests.storage_reflink',
  1042. 'qubes.tests.storage_lvm',
  1043. 'qubes.tests.storage_kernels',
  1044. 'qubes.tests.ext',
  1045. 'qubes.tests.vm.qubesvm',
  1046. 'qubes.tests.vm.mix.net',
  1047. 'qubes.tests.vm.adminvm',
  1048. 'qubes.tests.vm.appvm',
  1049. 'qubes.tests.vm.dispvm',
  1050. 'qubes.tests.app',
  1051. 'qubes.tests.tarwriter',
  1052. 'qubes.tests.api',
  1053. 'qubes.tests.api_admin',
  1054. 'qubes.tests.api_misc',
  1055. 'qubespolicy.tests',
  1056. 'qubespolicy.tests.cli',
  1057. ):
  1058. tests.addTests(loader.loadTestsFromName(modname))
  1059. # GTK/Glib is way too old there
  1060. if 'TRAVIS' not in os.environ:
  1061. for modname in (
  1062. 'qubespolicy.tests.gtkhelpers',
  1063. 'qubespolicy.tests.rpcconfirmation',
  1064. ):
  1065. tests.addTests(loader.loadTestsFromName(modname))
  1066. tests.addTests(loader.discover(
  1067. os.path.join(os.path.dirname(__file__), 'tools')))
  1068. if not in_dom0:
  1069. return tests
  1070. for modname in (
  1071. # integration tests
  1072. 'qubes.tests.integ.basic',
  1073. 'qubes.tests.integ.storage',
  1074. 'qubes.tests.integ.pvgrub',
  1075. 'qubes.tests.integ.devices_pci',
  1076. 'qubes.tests.integ.dom0_update',
  1077. 'qubes.tests.integ.network',
  1078. 'qubes.tests.integ.dispvm',
  1079. 'qubes.tests.integ.vm_qrexec_gui',
  1080. 'qubes.tests.integ.mime',
  1081. 'qubes.tests.integ.salt',
  1082. 'qubes.tests.integ.backup',
  1083. 'qubes.tests.integ.backupcompatibility',
  1084. # 'qubes.tests.regressions',
  1085. # external modules
  1086. 'qubes.tests.extra',
  1087. ):
  1088. tests.addTests(loader.loadTestsFromName(modname))
  1089. return tests