__init__.py 52 KB

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