__init__.py 47 KB

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