__init__.py 51 KB

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