__init__.py 53 KB

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