__init__.py 53 KB

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