__init__.py 50 KB

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