__init__.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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. ex = exc_info[1]
  321. while ex is not None:
  322. traceback.clear_frames(ex.__traceback__)
  323. ex = ex.__context__
  324. def cleanup_gc(self):
  325. gc.collect()
  326. leaked = [obj for obj in gc.get_objects() + gc.garbage
  327. if isinstance(obj,
  328. (qubes.Qubes, qubes.vm.BaseVM,
  329. libvirt.virConnect, libvirt.virDomain))]
  330. if leaked:
  331. try:
  332. import objgraph
  333. objgraph.show_backrefs(leaked,
  334. max_depth=15, extra_info=extra_info,
  335. filename='/tmp/objgraph-{}.png'.format(self.id()))
  336. except ImportError:
  337. pass
  338. # do not keep leaked object references in locals()
  339. leaked = bool(leaked)
  340. assert not leaked
  341. def cleanup_loop(self):
  342. '''Check if the loop is empty'''
  343. # XXX BEWARE this is touching undocumented, implementation-specific
  344. # attributes of the loop. This is most certainly unsupported and likely
  345. # will break when messing with: Python version, kernel family, loop
  346. # implementation, a combination thereof, or other things.
  347. # KEYWORDS for searching:
  348. # win32, SelectorEventLoop, ProactorEventLoop, uvloop, gevent
  349. global libvirt_event_impl
  350. # really destroy all objects that could have used loop and/or libvirt
  351. gc.collect()
  352. # Check for unfinished libvirt business.
  353. if libvirt_event_impl is not None:
  354. try:
  355. self.loop.run_until_complete(asyncio.wait_for(
  356. libvirt_event_impl.drain(), timeout=4))
  357. except asyncio.TimeoutError:
  358. raise AssertionError('libvirt event impl drain timeout')
  359. # this is stupid, but apparently it requires two passes
  360. # to cleanup SIGCHLD handlers
  361. self.loop.stop()
  362. self.loop.run_forever()
  363. self.loop.stop()
  364. self.loop.run_forever()
  365. # Check there are no Tasks left.
  366. assert not self.loop._ready
  367. assert not self.loop._scheduled
  368. # Check the loop watches no descriptors.
  369. # NOTE the loop has a pipe for self-interrupting, created once per
  370. # lifecycle, and it is unwatched only at loop.close(); so we cannot just
  371. # check selector for non-emptiness
  372. assert len(self.loop._selector.get_map()) \
  373. == int(self.loop._ssock is not None)
  374. del self.loop
  375. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  376. """Fail if an exception of class excClass is raised
  377. by callableObj when invoked with arguments args and keyword
  378. arguments kwargs. If a different type of exception is
  379. raised, it will not be caught, and the test case will be
  380. deemed to have suffered an error, exactly as for an
  381. unexpected exception.
  382. If called with callableObj omitted or None, will return a
  383. context object used like this::
  384. with self.assertRaises(SomeException):
  385. do_something()
  386. The context manager keeps a reference to the exception as
  387. the 'exception' attribute. This allows you to inspect the
  388. exception after the assertion::
  389. with self.assertRaises(SomeException) as cm:
  390. do_something()
  391. the_exception = cm.exception
  392. self.assertEqual(the_exception.error_code, 3)
  393. """
  394. context = _AssertNotRaisesContext(excClass, self)
  395. if callableObj is None:
  396. return context
  397. with context:
  398. callableObj(*args, **kwargs)
  399. def assertXMLEqual(self, xml1, xml2, msg=''):
  400. '''Check for equality of two XML objects.
  401. :param xml1: first element
  402. :param xml2: second element
  403. :type xml1: :py:class:`lxml.etree._Element`
  404. :type xml2: :py:class:`lxml.etree._Element`
  405. '''
  406. self.assertEqual(xml1.tag, xml2.tag)
  407. msg += '/' + str(xml1.tag)
  408. if xml1.text is not None and xml2.text is not None:
  409. self.assertEqual(xml1.text.strip(), xml2.text.strip(), msg)
  410. else:
  411. self.assertEqual(xml1.text, xml2.text, msg)
  412. self.assertCountEqual(xml1.keys(), xml2.keys(), msg)
  413. for key in xml1.keys():
  414. self.assertEqual(xml1.get(key), xml2.get(key), msg)
  415. self.assertEqual(len(xml1), len(xml2), msg + ' children count')
  416. for child1, child2 in zip(xml1, xml2):
  417. self.assertXMLEqual(child1, child2, msg=msg)
  418. def assertDevicesEqual(self, devices1, devices2, msg=None):
  419. self.assertEqual(devices1.keys(), devices2.keys(), msg)
  420. for dev_class in devices1.keys():
  421. self.assertEqual(
  422. [str(dev) for dev in devices1[dev_class]],
  423. [str(dev) for dev in devices2[dev_class]],
  424. "Devices of class {} differs{}".format(
  425. dev_class, (": " + msg) if msg else "")
  426. )
  427. def assertEventFired(self, subject, event, kwargs=None):
  428. '''Check whether event was fired on given emitter and fail if it did
  429. not.
  430. :param subject: emitter which is being checked
  431. :type emitter: :py:class:`TestEmitter`
  432. :param str event: event identifier
  433. :param dict kwargs: when given, all items must appear in kwargs passed \
  434. to an event
  435. '''
  436. will_not_match = object()
  437. for ev, ev_kwargs in subject.fired_events:
  438. if ev != event:
  439. continue
  440. if kwargs is not None:
  441. ev_kwargs = dict(ev_kwargs)
  442. if any(ev_kwargs.get(k, will_not_match) != v
  443. for k, v in kwargs.items()):
  444. continue
  445. return
  446. self.fail('event {!r} {}did not fire on {!r}'.format(
  447. event, ('' if kwargs is None else '{!r} '.format(kwargs)), subject))
  448. def assertEventNotFired(self, subject, event, kwargs=None):
  449. '''Check whether event was fired on given emitter. Fail if it did.
  450. :param subject: emitter which is being checked
  451. :type emitter: :py:class:`TestEmitter`
  452. :param str event: event identifier
  453. :param list kwargs: when given, all items must appear in kwargs passed \
  454. to an event
  455. '''
  456. will_not_match = object()
  457. for ev, ev_kwargs in subject.fired_events:
  458. if ev != event:
  459. continue
  460. if kwargs is not None:
  461. ev_kwargs = dict(ev_kwargs)
  462. if any(ev_kwargs.get(k, will_not_match) != v
  463. for k, v in kwargs.items()):
  464. continue
  465. self.fail('event {!r} {}did fire on {!r}'.format(
  466. event,
  467. ('' if kwargs is None else '{!r} '.format(kwargs)),
  468. subject))
  469. return
  470. def assertXMLIsValid(self, xml, file=None, schema=None):
  471. '''Check whether given XML fulfills Relax NG schema.
  472. Schema can be given in a couple of ways:
  473. - As separate file. This is most common, and also the only way to
  474. handle file inclusion. Call with file name as second argument.
  475. - As string containing actual schema. Put that string in *schema*
  476. keyword argument.
  477. :param lxml.etree._Element xml: XML element instance to check
  478. :param str file: filename of Relax NG schema
  479. :param str schema: optional explicit schema string
  480. ''' # pylint: disable=redefined-builtin
  481. if schema is not None and file is None:
  482. relaxng = schema
  483. if isinstance(relaxng, str):
  484. relaxng = lxml.etree.XML(relaxng)
  485. # pylint: disable=protected-access
  486. if isinstance(relaxng, lxml.etree._Element):
  487. relaxng = lxml.etree.RelaxNG(relaxng)
  488. elif file is not None and schema is None:
  489. if not os.path.isabs(file):
  490. basedirs = ['/usr/share/doc/qubes/relaxng']
  491. if in_git:
  492. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  493. for basedir in basedirs:
  494. abspath = os.path.join(basedir, file)
  495. if os.path.exists(abspath):
  496. file = abspath
  497. break
  498. relaxng = lxml.etree.RelaxNG(file=file)
  499. else:
  500. raise TypeError("There should be excactly one of 'file' and "
  501. "'schema' arguments specified.")
  502. # We have to be extra careful here in case someone messed up with
  503. # self.failureException. It should by default be AssertionError, just
  504. # what is spewed by RelaxNG(), but who knows what might happen.
  505. try:
  506. relaxng.assert_(xml)
  507. except self.failureException:
  508. raise
  509. except AssertionError as e:
  510. self.fail(str(e))
  511. @staticmethod
  512. def make_vm_name(name, class_teardown=False):
  513. if class_teardown:
  514. return CLSVMPREFIX + name
  515. else:
  516. return VMPREFIX + name
  517. class SystemTestCase(QubesTestCase):
  518. """
  519. Mixin for integration tests. All the tests here should use self.app
  520. object and when need qubes.xml path - should use :py:data:`XMLPATH`
  521. defined in this file.
  522. Every VM created by test, must use :py:meth:`SystemTestCase.make_vm_name`
  523. for VM name.
  524. By default self.app represents empty collection, if anything is needed
  525. there from the real collection it can be imported from self.host_app in
  526. :py:meth:`SystemTestCase.setUp`. But *can not be modified* in any way -
  527. this include both changing attributes in
  528. :py:attr:`SystemTestCase.host_app` and modifying files of such imported
  529. VM. If test need to make some modification, it must clone the VM first.
  530. If some group of tests needs class-wide initialization, first of all the
  531. author should consider if it is really needed. But if so, setUpClass can
  532. be used to create Qubes(CLASS_XMLPATH) object and create/import required
  533. stuff there. VMs created in :py:meth:`TestCase.setUpClass` should
  534. use self.make_vm_name('...', class_teardown=True) for name creation.
  535. Such (group of) test need to take care about
  536. :py:meth:`TestCase.tearDownClass` implementation itself.
  537. """
  538. # noinspection PyAttributeOutsideInit
  539. def setUp(self):
  540. if not in_dom0:
  541. self.skipTest('outside dom0')
  542. super(SystemTestCase, self).setUp()
  543. self.remove_test_vms()
  544. # need some information from the real qubes.xml - at least installed
  545. # templates; should not be used for testing, only to initialize self.app
  546. self.host_app = qubes.Qubes(os.path.join(
  547. qubes.config.qubes_base_dir,
  548. qubes.config.system_path['qubes_store_filename']))
  549. if os.path.exists(CLASS_XMLPATH):
  550. shutil.copy(CLASS_XMLPATH, XMLPATH)
  551. else:
  552. shutil.copy(self.host_app.store, XMLPATH)
  553. self.app = qubes.Qubes(XMLPATH)
  554. os.environ['QUBES_XML_PATH'] = XMLPATH
  555. self.app.register_event_handlers()
  556. self.qubesd = self.loop.run_until_complete(
  557. qubes.api.create_servers(
  558. qubes.api.admin.QubesAdminAPI,
  559. qubes.api.internal.QubesInternalAPI,
  560. app=self.app, debug=True))
  561. self.addCleanup(self.cleanup_app)
  562. self.app.add_handler('domain-delete', self.close_qdb_on_remove)
  563. def close_qdb_on_remove(self, app, event, vm, **kwargs):
  564. # only close QubesDB connection, do not perform other (destructive)
  565. # actions of vm.close()
  566. if vm._qdb_connection_watch is not None:
  567. asyncio.get_event_loop().remove_reader(
  568. vm._qdb_connection_watch.watch_fd())
  569. vm._qdb_connection_watch.close()
  570. vm._qdb_connection_watch = None
  571. def cleanup_app(self):
  572. self.remove_test_vms()
  573. server = None
  574. for server in self.qubesd:
  575. for sock in server.sockets:
  576. os.unlink(sock.getsockname())
  577. server.close()
  578. del server
  579. # close all existing connections, especially this will interrupt
  580. # running admin.Events calls, which do keep reference to Qubes() and
  581. # libvirt connection
  582. conn = None
  583. for conn in qubes.api.QubesDaemonProtocol.connections:
  584. if conn.transport:
  585. conn.transport.abort()
  586. del conn
  587. self.loop.run_until_complete(asyncio.wait([
  588. server.wait_closed() for server in self.qubesd]))
  589. del self.qubesd
  590. # remove all references to any complex qubes objects, to release
  591. # resources - most importantly file descriptors; this object will live
  592. # during the whole test run, but all the file descriptors would be
  593. # depleted earlier
  594. self.app.close()
  595. self.host_app.close()
  596. del self.app
  597. del self.host_app
  598. for attr in dir(self):
  599. obj_type = type(getattr(self, attr))
  600. if obj_type.__module__.startswith('qubes'):
  601. delattr(self, attr)
  602. # then trigger garbage collector to really destroy those objects
  603. gc.collect()
  604. def init_default_template(self, template=None):
  605. if template is None:
  606. template = self.host_app.default_template
  607. elif isinstance(template, str):
  608. template = self.host_app.domains[template]
  609. self.app.default_template = str(template)
  610. def init_networking(self):
  611. if not self.app.default_template:
  612. self.skipTest('Default template required for testing networking')
  613. default_netvm = self.host_app.default_netvm
  614. # if testing Whonix Workstation based VMs, try to use sys-whonix instead
  615. if self.app.default_template.name.startswith('whonix-ws'):
  616. if 'sys-whonix' in self.host_app.domains:
  617. default_netvm = self.host_app.domains['sys-whonix']
  618. if default_netvm is None:
  619. self.skipTest('Default netvm required')
  620. if not default_netvm.is_running():
  621. self.skipTest('VM {} required to be running'.format(
  622. default_netvm.name))
  623. self.app.default_netvm = str(default_netvm)
  624. def _find_pool(self, volume_group, thin_pool):
  625. ''' Returns the pool matching the specified ``volume_group`` &
  626. ``thin_pool``, or None.
  627. '''
  628. pools = [p for p in self.app.pools
  629. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  630. for pool in pools:
  631. if pool.volume_group == volume_group \
  632. and pool.thin_pool == thin_pool:
  633. return pool
  634. return None
  635. def init_lvm_pool(self):
  636. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  637. path = "/dev/mapper/{!s}-{!s}".format(volume_group, thin_pool)
  638. if not os.path.exists(path):
  639. self.skipTest('LVM thin pool {!r} does not exist'.
  640. format(DEFAULT_LVM_POOL))
  641. self.pool = self._find_pool(volume_group, thin_pool)
  642. if not self.pool:
  643. self.pool = self.app.add_pool(**POOL_CONF)
  644. self.created_pool = True
  645. def _remove_vm_qubes(self, vm):
  646. vmname = vm.name
  647. app = vm.app
  648. # avoid race with DispVM.auto_cleanup=True
  649. try:
  650. self.loop.run_until_complete(
  651. asyncio.wait_for(vm.startup_lock.acquire(), 10))
  652. except asyncio.TimeoutError:
  653. pass
  654. try:
  655. # XXX .is_running() may throw libvirtError if undefined
  656. if vm.is_running():
  657. self.loop.run_until_complete(vm.kill())
  658. except: # pylint: disable=bare-except
  659. pass
  660. try:
  661. self.loop.run_until_complete(vm.remove_from_disk())
  662. except: # pylint: disable=bare-except
  663. pass
  664. try:
  665. del app.domains[vm.qid]
  666. except KeyError:
  667. pass
  668. vm.close()
  669. del vm
  670. app.save()
  671. del app
  672. # Now ensure it really went away. This may not have happened,
  673. # for example if vm.libvirt_domain malfunctioned.
  674. try:
  675. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  676. except: # pylint: disable=bare-except
  677. pass
  678. else:
  679. try:
  680. dom = conn.lookupByName(vmname)
  681. except: # pylint: disable=bare-except
  682. pass
  683. else:
  684. self._remove_vm_libvirt(dom)
  685. conn.close()
  686. self._remove_vm_disk(vmname)
  687. @staticmethod
  688. def _remove_vm_libvirt(dom):
  689. try:
  690. dom.destroy()
  691. except libvirt.libvirtError: # not running
  692. pass
  693. dom.undefine()
  694. @staticmethod
  695. def _remove_vm_disk(vmname):
  696. for dirspec in (
  697. 'qubes_appvms_dir',
  698. 'qubes_servicevms_dir',
  699. 'qubes_templates_dir'):
  700. dirpath = os.path.join(qubes.config.qubes_base_dir,
  701. qubes.config.system_path[dirspec], vmname)
  702. if os.path.exists(dirpath):
  703. if os.path.isdir(dirpath):
  704. shutil.rmtree(dirpath)
  705. else:
  706. os.unlink(dirpath)
  707. @staticmethod
  708. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  709. ''' Remove LVM volumes with given prefix
  710. This is "a bit" drastic, as it removes volumes regardless of volume
  711. group, thin pool etc. But we assume no important data on test system.
  712. '''
  713. try:
  714. volumes = subprocess.check_output(
  715. ['lvs', '--noheadings', '-o', 'vg_name,name',
  716. '--separator', '/']).decode()
  717. if ('/vm-' + prefix) not in volumes:
  718. return
  719. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  720. [vol.strip() for vol in volumes.splitlines()
  721. if ('/vm-' + prefix) in vol],
  722. stdout=subprocess.DEVNULL)
  723. except subprocess.CalledProcessError:
  724. pass
  725. def remove_vms(self, vms):
  726. vms = list(vms)
  727. if not vms:
  728. return
  729. # break dependencies
  730. for vm in vms:
  731. vm.default_dispvm = None
  732. # then remove in reverse topological order (wrt netvm), using naive
  733. # algorithm
  734. # this heavily depends on lack of netvm loops
  735. while vms:
  736. vm = vms.pop(0)
  737. # make sure that all connected VMs are going to be removed,
  738. # otherwise this will loop forever
  739. assert all(x in vms for x in vm.connected_vms)
  740. if list(vm.connected_vms):
  741. # if still something use this VM, put it at the end of queue
  742. # and try next one
  743. vms.append(vm)
  744. continue
  745. self._remove_vm_qubes(vm)
  746. def remove_test_vms(self, xmlpath=XMLPATH, prefix=VMPREFIX):
  747. '''Aggresively remove any domain that has name in testing namespace.
  748. '''
  749. # first, remove them Qubes-way
  750. if os.path.exists(xmlpath):
  751. try:
  752. try:
  753. app = self.app
  754. except AttributeError:
  755. app = qubes.Qubes(xmlpath)
  756. try:
  757. host_app = self.host_app
  758. except AttributeError:
  759. host_app = qubes.Qubes()
  760. self.remove_vms([vm for vm in app.domains
  761. if vm.name.startswith(prefix) or
  762. (isinstance(vm, qubes.vm.dispvm.DispVM) and vm.name
  763. not in host_app.domains)])
  764. if not hasattr(self, 'host_app'):
  765. host_app.close()
  766. del host_app
  767. if not hasattr(self, 'app'):
  768. app.close()
  769. del app
  770. except qubes.exc.QubesException:
  771. pass
  772. os.unlink(xmlpath)
  773. # now remove what was only in libvirt
  774. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  775. for dom in conn.listAllDomains():
  776. if dom.name().startswith(prefix):
  777. self._remove_vm_libvirt(dom)
  778. conn.close()
  779. # finally remove anything that is left on disk
  780. vmnames = set()
  781. for dirspec in (
  782. 'qubes_appvms_dir',
  783. 'qubes_servicevms_dir',
  784. 'qubes_templates_dir'):
  785. dirpath = os.path.join(qubes.config.qubes_base_dir,
  786. qubes.config.system_path[dirspec])
  787. if not os.path.exists(dirpath):
  788. continue
  789. for name in os.listdir(dirpath):
  790. if name.startswith(prefix):
  791. vmnames.add(name)
  792. for vmname in vmnames:
  793. self._remove_vm_disk(vmname)
  794. self._remove_vm_disk_lvm(prefix)
  795. def qrexec_policy(self, service, source, destination, allow=True,
  796. action=None):
  797. """
  798. Allow qrexec calls for duration of the test
  799. :param service: service name
  800. :param source: source VM name
  801. :param destination: destination VM name
  802. :param allow: add rule with 'allow' action, otherwise 'deny'
  803. :param action: custom action, if specified *allow* argument is ignored
  804. :return:
  805. """
  806. return _QrexecPolicyContext(service, source, destination,
  807. allow=allow, action=action)
  808. def wait_for_window(self, title, timeout=30, show=True):
  809. """
  810. Wait for a window with a given title. Depending on show parameter,
  811. it will wait for either window to show or to disappear.
  812. :param title: title of the window to wait for
  813. :param timeout: timeout of the operation, in seconds
  814. :param show: if True - wait for the window to be visible,
  815. otherwise - to not be visible
  816. :return: None
  817. """
  818. wait_count = 0
  819. while subprocess.call(['xdotool', 'search', '--name', title],
  820. stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) \
  821. != int(not show):
  822. wait_count += 1
  823. if wait_count > timeout*10:
  824. self.fail("Timeout while waiting for {} window to {}".format(
  825. title, "show" if show else "hide")
  826. )
  827. self.loop.run_until_complete(asyncio.sleep(0.1))
  828. def enter_keys_in_window(self, title, keys):
  829. """
  830. Search for window with given title, then enter listed keys there.
  831. The function will wait for said window to appear.
  832. :param title: title of window
  833. :param keys: list of keys to enter, as for `xdotool key`
  834. :return: None
  835. """
  836. # 'xdotool search --sync' sometimes crashes on some race when
  837. # accessing window properties
  838. self.wait_for_window(title)
  839. command = ['xdotool', 'search', '--name', title,
  840. 'windowactivate', '--sync',
  841. 'key'] + keys
  842. subprocess.check_call(command)
  843. def shutdown_and_wait(self, vm, timeout=60):
  844. self.loop.run_until_complete(vm.shutdown())
  845. while timeout > 0:
  846. if not vm.is_running():
  847. return
  848. self.loop.run_until_complete(asyncio.sleep(1))
  849. timeout -= 1
  850. name = vm.name
  851. del vm
  852. self.fail("Timeout while waiting for VM {} shutdown".format(name))
  853. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  854. if not os.path.exists('/usr/lib/grub/i386-pc'):
  855. self.skipTest('grub2 not installed')
  856. if not spawn.find_executable('grub2-install'):
  857. self.skipTest('grub2-tools not installed')
  858. if not spawn.find_executable('dracut'):
  859. self.skipTest('dracut not installed')
  860. # create a single partition
  861. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  862. stdin=subprocess.PIPE,
  863. stdout=subprocess.DEVNULL,
  864. stderr=subprocess.STDOUT)
  865. p.communicate('2048,\n')
  866. assert p.returncode == 0, 'sfdisk failed'
  867. # TODO: check if root_img is really file, not already block device
  868. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  869. vm.storage.root_img], stdout=subprocess.PIPE)
  870. (loopdev, _) = p.communicate()
  871. loopdev = loopdev.strip()
  872. looppart = loopdev + 'p1'
  873. assert p.returncode == 0, 'losetup failed'
  874. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  875. mountpoint = tempfile.mkdtemp()
  876. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  877. try:
  878. subprocess.check_call(['sudo', 'grub2-install',
  879. '--target', 'i386-pc',
  880. '--modules', 'part_msdos ext2',
  881. '--boot-directory', mountpoint, loopdev],
  882. stderr=subprocess.DEVNULL
  883. )
  884. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  885. subprocess.check_call(
  886. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  887. with open(grub_cfg, 'w') as f:
  888. f.write(
  889. "set timeout=1\n"
  890. "menuentry 'Default' {\n"
  891. " linux /vmlinuz root=/dev/xvda1 "
  892. "rd.driver.blacklist=bochs_drm "
  893. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  894. " initrd /initrd\n"
  895. "}"
  896. )
  897. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  898. (kernel_version, _) = p.communicate()
  899. kernel_version = kernel_version.strip()
  900. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  901. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  902. init_path = os.path.join(mountpoint, 'init')
  903. with open(init_path, 'w') as f:
  904. f.write(init_script)
  905. os.chmod(init_path, 0o755)
  906. dracut_args = [
  907. '--kver', kernel_version,
  908. '--include', init_path,
  909. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  910. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  911. ]
  912. if extra_files:
  913. dracut_args += ['--install', ' '.join(extra_files)]
  914. subprocess.check_call(
  915. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  916. 'initrd')],
  917. stderr=subprocess.DEVNULL
  918. )
  919. finally:
  920. subprocess.check_call(['sudo', 'umount', mountpoint])
  921. shutil.rmtree(mountpoint)
  922. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  923. def create_bootable_iso(self):
  924. '''Create simple bootable ISO image.
  925. Type 'poweroff' to it to terminate that VM.
  926. '''
  927. isolinux_cfg = (
  928. 'prompt 1\n'
  929. 'label poweroff\n'
  930. ' kernel poweroff.c32\n'
  931. )
  932. output_fd, output_path = tempfile.mkstemp('.iso')
  933. with tempfile.TemporaryDirectory() as tmp_dir:
  934. try:
  935. shutil.copy('/usr/share/syslinux/isolinux.bin', tmp_dir)
  936. shutil.copy('/usr/share/syslinux/ldlinux.c32', tmp_dir)
  937. shutil.copy('/usr/share/syslinux/poweroff.c32', tmp_dir)
  938. with open(os.path.join(tmp_dir, 'isolinux.cfg'), 'w') as cfg:
  939. cfg.write(isolinux_cfg)
  940. subprocess.check_call(['genisoimage', '-o', output_path,
  941. '-c', 'boot.cat',
  942. '-b', 'isolinux.bin',
  943. '-no-emul-boot',
  944. '-boot-load-size', '4',
  945. '-boot-info-table',
  946. '-q',
  947. tmp_dir])
  948. except FileNotFoundError:
  949. self.skipTest('syslinux or genisoimage not installed')
  950. os.close(output_fd)
  951. self.addCleanup(os.unlink, output_path)
  952. return output_path
  953. def create_local_file(self, filename, content, mode='w'):
  954. with open(filename, mode) as file:
  955. file.write(content)
  956. self.addCleanup(os.unlink, filename)
  957. def create_remote_file(self, vm, filename, content):
  958. self.loop.run_until_complete(vm.run_for_stdio(
  959. 'cat > {}'.format(shlex.quote(filename)),
  960. user='root', input=content.encode('utf-8')))
  961. @asyncio.coroutine
  962. def wait_for_session(self, vm):
  963. yield from asyncio.wait_for(
  964. vm.run_service_for_stdio(
  965. 'qubes.WaitForSession', input=vm.default_user.encode()),
  966. timeout=30)
  967. _templates = None
  968. def list_templates():
  969. '''Returns tuple of template names available in the system.'''
  970. global _templates
  971. if _templates is None:
  972. if 'QUBES_TEST_TEMPLATES' in os.environ:
  973. _templates = os.environ['QUBES_TEST_TEMPLATES'].split()
  974. if _templates is None:
  975. try:
  976. app = qubes.Qubes()
  977. _templates = tuple(vm.name for vm in app.domains
  978. if isinstance(vm, qubes.vm.templatevm.TemplateVM) and
  979. vm.features.get('os', None) != 'Windows')
  980. app.close()
  981. del app
  982. except OSError:
  983. _templates = ()
  984. return _templates
  985. def create_testcases_for_templates(name, *bases, module, **kwds):
  986. '''Do-it-all helper for generating per-template tests via load_tests proto
  987. This does several things:
  988. - creates per-template classes
  989. - adds them to module's :py:func:`globals`
  990. - returns an iterable suitable for passing to loader.loadTestsFromNames
  991. TestCase classes created by this function have implicit `.template`
  992. attribute, which contains name of the respective template. They are also
  993. named with given prefix, underscore and template name. If template name
  994. contains characters not valid as part of Python identifier, they are
  995. impossible to get via standard ``.`` operator, though :py:func:`getattr` is
  996. still usable.
  997. >>> class MyTestsMixIn:
  998. ... def test_000_my_test(self):
  999. ... assert self.template.startswith('debian')
  1000. >>> def load_tests(loader, tests, pattern):
  1001. ... tests.addTests(loader.loadTestsFromNames(
  1002. ... qubes.tests.create_testcases_for_templates(
  1003. ... 'TC_00_MyTests', MyTestsMixIn, qubes.tests.SystemTestCase,
  1004. ... module=sys.modules[__name__])))
  1005. *NOTE* adding ``module=sys.modules[__name__]`` is *mandatory*, and to allow
  1006. enforcing this, it uses keyword-only argument syntax, which is only in
  1007. Python 3.
  1008. '''
  1009. # Do not attempt to grab the module from traceback, since we are actually
  1010. # a generator and loadTestsFromNames may also be a generator, so it's not
  1011. # possible to correctly guess frame from stack. Explicit is better than
  1012. # implicit!
  1013. for template in list_templates():
  1014. clsname = name + '_' + template
  1015. if hasattr(module, clsname):
  1016. continue
  1017. cls = type(clsname, bases, {'template': template, **kwds})
  1018. cls.__module__ = module.__name__
  1019. # XXX I wonder what other __dunder__ attrs did I miss
  1020. setattr(module, clsname, cls)
  1021. yield '.'.join((module.__name__, clsname))
  1022. def maybe_create_testcases_on_import(create_testcases_gen):
  1023. '''If certain conditions are met, call *create_testcases_gen* to create
  1024. testcases for templates tests. The purpose is to use it on integration
  1025. tests module(s) import, so the test runner could discover tests without
  1026. using load tests protocol.
  1027. The conditions - any of:
  1028. - QUBES_TEST_TEMPLATES present in the environment (it's possible to
  1029. create test cases without opening qubes.xml)
  1030. - QUBES_TEST_LOAD_ALL present in the environment
  1031. '''
  1032. if 'QUBES_TEST_TEMPLATES' in os.environ or \
  1033. 'QUBES_TEST_LOAD_ALL' in os.environ:
  1034. list(create_testcases_gen())
  1035. def extra_info(obj):
  1036. '''Return short info identifying object.
  1037. For example, if obj is a qube, return its name. This is for use with
  1038. :py:mod:`objgraph` package.
  1039. '''
  1040. # Feel free to extend to other cases.
  1041. if isinstance(obj, qubes.vm.qubesvm.QubesVM):
  1042. try:
  1043. return obj.name
  1044. except AttributeError:
  1045. pass
  1046. if isinstance(obj, unittest.TestCase):
  1047. return obj.id()
  1048. return ''
  1049. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  1050. # discard any tests from this module, because it hosts base classes
  1051. tests = unittest.TestSuite()
  1052. for modname in (
  1053. # unit tests
  1054. 'qubes.tests.events',
  1055. 'qubes.tests.devices',
  1056. 'qubes.tests.devices_block',
  1057. 'qubes.tests.firewall',
  1058. 'qubes.tests.init',
  1059. 'qubes.tests.vm.init',
  1060. 'qubes.tests.storage',
  1061. 'qubes.tests.storage_file',
  1062. 'qubes.tests.storage_reflink',
  1063. 'qubes.tests.storage_lvm',
  1064. 'qubes.tests.storage_kernels',
  1065. 'qubes.tests.ext',
  1066. 'qubes.tests.vm.qubesvm',
  1067. 'qubes.tests.vm.mix.net',
  1068. 'qubes.tests.vm.adminvm',
  1069. 'qubes.tests.vm.appvm',
  1070. 'qubes.tests.vm.dispvm',
  1071. 'qubes.tests.app',
  1072. 'qubes.tests.tarwriter',
  1073. 'qubes.tests.api',
  1074. 'qubes.tests.api_admin',
  1075. 'qubes.tests.api_misc',
  1076. 'qubespolicy.tests',
  1077. 'qubespolicy.tests.cli',
  1078. ):
  1079. tests.addTests(loader.loadTestsFromName(modname))
  1080. # GTK/Glib is way too old there
  1081. if 'TRAVIS' not in os.environ:
  1082. for modname in (
  1083. 'qubespolicy.tests.gtkhelpers',
  1084. 'qubespolicy.tests.rpcconfirmation',
  1085. ):
  1086. tests.addTests(loader.loadTestsFromName(modname))
  1087. tests.addTests(loader.discover(
  1088. os.path.join(os.path.dirname(__file__), 'tools')))
  1089. if not in_dom0:
  1090. return tests
  1091. for modname in (
  1092. # integration tests
  1093. 'qubes.tests.integ.basic',
  1094. 'qubes.tests.integ.storage',
  1095. 'qubes.tests.integ.pvgrub',
  1096. 'qubes.tests.integ.devices_block',
  1097. 'qubes.tests.integ.devices_pci',
  1098. 'qubes.tests.integ.dom0_update',
  1099. 'qubes.tests.integ.network',
  1100. 'qubes.tests.integ.dispvm',
  1101. 'qubes.tests.integ.vm_qrexec_gui',
  1102. 'qubes.tests.integ.mime',
  1103. 'qubes.tests.integ.salt',
  1104. 'qubes.tests.integ.backup',
  1105. 'qubes.tests.integ.backupcompatibility',
  1106. # 'qubes.tests.regressions',
  1107. # external modules
  1108. 'qubes.tests.extra',
  1109. ):
  1110. tests.addTests(loader.loadTestsFromName(modname))
  1111. return tests