helpers.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :copyright: Copyright 2013-2017 by the SaltStack Team, see AUTHORS for more details.
  4. :license: Apache 2.0, see LICENSE for more details.
  5. tests.support.helpers
  6. ~~~~~~~~~~~~~~~~~~~~~
  7. Test support helpers
  8. '''
  9. # pylint: disable=repr-flag-used-in-string,wrong-import-order
  10. # Import Python libs
  11. from __future__ import absolute_import, print_function, unicode_literals
  12. import base64
  13. import errno
  14. import fnmatch
  15. import functools
  16. import inspect
  17. import logging
  18. import os
  19. import random
  20. import shutil
  21. import signal
  22. import socket
  23. import string
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import textwrap
  28. import threading
  29. import time
  30. import tornado.ioloop
  31. import tornado.web
  32. import types
  33. # Import 3rd-party libs
  34. import psutil # pylint: disable=3rd-party-module-not-gated
  35. from salt.ext import six
  36. from salt.ext.six.moves import range, builtins # pylint: disable=import-error,redefined-builtin
  37. try:
  38. from pytestsalt.utils import get_unused_localhost_port # pylint: disable=unused-import
  39. except ImportError:
  40. from tests.integration import get_unused_localhost_port
  41. # Import Salt Tests Support libs
  42. from tests.support.unit import skip, _id, SkipTest
  43. from tests.support.mock import patch
  44. from tests.support.paths import FILES, TMP
  45. # Import Salt libs
  46. import salt.utils.files
  47. import salt.utils.platform
  48. import salt.utils.stringutils
  49. if salt.utils.platform.is_windows():
  50. import salt.utils.win_functions
  51. else:
  52. import pwd
  53. log = logging.getLogger(__name__)
  54. HAS_SYMLINKS = None
  55. def no_symlinks():
  56. '''
  57. Check if git is installed and has symlinks enabled in the configuration.
  58. '''
  59. global HAS_SYMLINKS
  60. if HAS_SYMLINKS is not None:
  61. return not HAS_SYMLINKS
  62. output = ''
  63. try:
  64. output = subprocess.Popen(
  65. ['git', 'config', '--get', 'core.symlinks'],
  66. cwd=TMP,
  67. stdout=subprocess.PIPE).communicate()[0]
  68. except OSError as exc:
  69. if exc.errno != errno.ENOENT:
  70. raise
  71. except subprocess.CalledProcessError:
  72. # git returned non-zero status
  73. pass
  74. HAS_SYMLINKS = False
  75. if output.strip() == 'true':
  76. HAS_SYMLINKS = True
  77. return not HAS_SYMLINKS
  78. def destructiveTest(caller):
  79. '''
  80. Mark a test case as a destructive test for example adding or removing users
  81. from your system.
  82. .. code-block:: python
  83. class MyTestCase(TestCase):
  84. @destructiveTest
  85. def test_create_user(self):
  86. pass
  87. '''
  88. if inspect.isclass(caller):
  89. # We're decorating a class
  90. old_setup = getattr(caller, 'setUp', None)
  91. def setUp(self, *args, **kwargs):
  92. if os.environ.get('DESTRUCTIVE_TESTS', 'False').lower() == 'false':
  93. self.skipTest('Destructive tests are disabled')
  94. if old_setup is not None:
  95. old_setup(self, *args, **kwargs)
  96. caller.setUp = setUp
  97. return caller
  98. # We're simply decorating functions
  99. @functools.wraps(caller)
  100. def wrap(cls):
  101. if os.environ.get('DESTRUCTIVE_TESTS', 'False').lower() == 'false':
  102. cls.skipTest('Destructive tests are disabled')
  103. return caller(cls)
  104. return wrap
  105. def expensiveTest(caller):
  106. '''
  107. Mark a test case as an expensive test, for example, a test which can cost
  108. money(Salt's cloud provider tests).
  109. .. code-block:: python
  110. class MyTestCase(TestCase):
  111. @expensiveTest
  112. def test_create_user(self):
  113. pass
  114. '''
  115. if inspect.isclass(caller):
  116. # We're decorating a class
  117. old_setup = getattr(caller, 'setUp', None)
  118. def setUp(self, *args, **kwargs):
  119. if os.environ.get('EXPENSIVE_TESTS', 'False').lower() == 'false':
  120. self.skipTest('Expensive tests are disabled')
  121. if old_setup is not None:
  122. old_setup(self, *args, **kwargs)
  123. caller.setUp = setUp
  124. return caller
  125. # We're simply decorating functions
  126. @functools.wraps(caller)
  127. def wrap(cls):
  128. if os.environ.get('EXPENSIVE_TESTS', 'False').lower() == 'false':
  129. cls.skipTest('Expensive tests are disabled')
  130. return caller(cls)
  131. return wrap
  132. def flaky(caller=None, condition=True, attempts=4):
  133. '''
  134. Mark a test as flaky. The test will attempt to run five times,
  135. looking for a successful run. After an immediate second try,
  136. it will use an exponential backoff starting with one second.
  137. .. code-block:: python
  138. class MyTestCase(TestCase):
  139. @flaky
  140. def test_sometimes_works(self):
  141. pass
  142. '''
  143. if caller is None:
  144. return functools.partial(flaky, condition=condition, attempts=attempts)
  145. if isinstance(condition, bool) and condition is False:
  146. # Don't even decorate
  147. return caller
  148. elif callable(condition):
  149. if condition() is False:
  150. # Don't even decorate
  151. return caller
  152. if inspect.isclass(caller):
  153. attrs = [n for n in dir(caller) if n.startswith('test_')]
  154. for attrname in attrs:
  155. try:
  156. function = getattr(caller, attrname)
  157. if not inspect.isfunction(function) and not inspect.ismethod(function):
  158. continue
  159. setattr(caller, attrname, flaky(caller=function, condition=condition, attempts=attempts))
  160. except Exception as exc:
  161. log.exception(exc)
  162. continue
  163. return caller
  164. @functools.wraps(caller)
  165. def wrap(cls):
  166. for attempt in range(0, attempts):
  167. try:
  168. if attempt > 0:
  169. # Run through setUp again
  170. # We only run it after the first iteration(>0) because the regular
  171. # test runner will have already ran setUp the first time
  172. setup = getattr(cls, 'setUp', None)
  173. if callable(setup):
  174. setup()
  175. return caller(cls)
  176. except Exception as exc:
  177. exc_info = sys.exc_info()
  178. if isinstance(exc, SkipTest):
  179. six.reraise(*exc_info)
  180. if not isinstance(exc, AssertionError) and log.isEnabledFor(logging.DEBUG):
  181. log.exception(exc, exc_info=exc_info)
  182. if attempt >= attempts -1:
  183. # We won't try to run tearDown once the attempts are exhausted
  184. # because the regular test runner will do that for us
  185. six.reraise(*exc_info)
  186. # Run through tearDown again
  187. teardown = getattr(cls, 'tearDown', None)
  188. if callable(teardown):
  189. teardown()
  190. backoff_time = attempt ** 2
  191. log.info(
  192. 'Found Exception. Waiting %s seconds to retry.',
  193. backoff_time
  194. )
  195. time.sleep(backoff_time)
  196. return cls
  197. return wrap
  198. def requires_sshd_server(caller):
  199. '''
  200. Mark a test as requiring the tests SSH daemon running.
  201. .. code-block:: python
  202. class MyTestCase(TestCase):
  203. @requiresSshdServer
  204. def test_create_user(self):
  205. pass
  206. '''
  207. if inspect.isclass(caller):
  208. # We're decorating a class
  209. old_setup = getattr(caller, 'setUp', None)
  210. def setUp(self, *args, **kwargs):
  211. if os.environ.get('SSH_DAEMON_RUNNING', 'False').lower() == 'false':
  212. self.skipTest('SSH tests are disabled')
  213. if old_setup is not None:
  214. old_setup(self, *args, **kwargs)
  215. caller.setUp = setUp
  216. return caller
  217. # We're simply decorating functions
  218. @functools.wraps(caller)
  219. def wrap(cls):
  220. if os.environ.get('SSH_DAEMON_RUNNING', 'False').lower() == 'false':
  221. cls.skipTest('SSH tests are disabled')
  222. return caller(cls)
  223. return wrap
  224. class RedirectStdStreams(object):
  225. '''
  226. Temporarily redirect system output to file like objects.
  227. Default is to redirect to `os.devnull`, which just mutes output, `stdout`
  228. and `stderr`.
  229. '''
  230. def __init__(self, stdout=None, stderr=None):
  231. # Late import
  232. import salt.utils.files
  233. if stdout is None:
  234. stdout = salt.utils.files.fopen(os.devnull, 'w') # pylint: disable=resource-leakage
  235. if stderr is None:
  236. stderr = salt.utils.files.fopen(os.devnull, 'w') # pylint: disable=resource-leakage
  237. self.__stdout = stdout
  238. self.__stderr = stderr
  239. self.__redirected = False
  240. self.patcher = patch.multiple(sys, stderr=self.__stderr, stdout=self.__stdout)
  241. def __enter__(self):
  242. self.redirect()
  243. return self
  244. def __exit__(self, exc_type, exc_value, traceback):
  245. self.unredirect()
  246. def redirect(self):
  247. self.old_stdout = sys.stdout
  248. self.old_stdout.flush()
  249. self.old_stderr = sys.stderr
  250. self.old_stderr.flush()
  251. self.patcher.start()
  252. self.__redirected = True
  253. def unredirect(self):
  254. if not self.__redirected:
  255. return
  256. try:
  257. self.__stdout.flush()
  258. self.__stdout.close()
  259. except ValueError:
  260. # already closed?
  261. pass
  262. try:
  263. self.__stderr.flush()
  264. self.__stderr.close()
  265. except ValueError:
  266. # already closed?
  267. pass
  268. self.patcher.stop()
  269. def flush(self):
  270. if self.__redirected:
  271. try:
  272. self.__stdout.flush()
  273. except Exception:
  274. pass
  275. try:
  276. self.__stderr.flush()
  277. except Exception:
  278. pass
  279. class TestsLoggingHandler(object):
  280. '''
  281. Simple logging handler which can be used to test if certain logging
  282. messages get emitted or not:
  283. .. code-block:: python
  284. with TestsLoggingHandler() as handler:
  285. # (...) Do what ever you wish here
  286. handler.messages # here are the emitted log messages
  287. '''
  288. def __init__(self, level=0, format='%(levelname)s:%(message)s'):
  289. self.level = level
  290. self.format = format
  291. self.activated = False
  292. self.prev_logging_level = None
  293. def activate(self):
  294. class Handler(logging.Handler):
  295. def __init__(self, level):
  296. logging.Handler.__init__(self, level)
  297. self.messages = []
  298. def emit(self, record):
  299. self.messages.append(self.format(record))
  300. self.handler = Handler(self.level)
  301. formatter = logging.Formatter(self.format)
  302. self.handler.setFormatter(formatter)
  303. logging.root.addHandler(self.handler)
  304. self.activated = True
  305. # Make sure we're running with the lowest logging level with our
  306. # tests logging handler
  307. current_logging_level = logging.root.getEffectiveLevel()
  308. if current_logging_level > logging.DEBUG:
  309. self.prev_logging_level = current_logging_level
  310. logging.root.setLevel(0)
  311. def deactivate(self):
  312. if not self.activated:
  313. return
  314. logging.root.removeHandler(self.handler)
  315. # Restore previous logging level if changed
  316. if self.prev_logging_level is not None:
  317. logging.root.setLevel(self.prev_logging_level)
  318. @property
  319. def messages(self):
  320. if not self.activated:
  321. return []
  322. return self.handler.messages
  323. def clear(self):
  324. self.handler.messages = []
  325. def __enter__(self):
  326. self.activate()
  327. return self
  328. def __exit__(self, type, value, traceback):
  329. self.deactivate()
  330. self.activated = False
  331. # Mimic some handler attributes and methods
  332. @property
  333. def lock(self):
  334. if self.activated:
  335. return self.handler.lock
  336. def createLock(self):
  337. if self.activated:
  338. return self.handler.createLock()
  339. def acquire(self):
  340. if self.activated:
  341. return self.handler.acquire()
  342. def release(self):
  343. if self.activated:
  344. return self.handler.release()
  345. def relative_import(import_name, relative_from='../'):
  346. '''
  347. Update sys.path to include `relative_from` before importing `import_name`
  348. '''
  349. try:
  350. return __import__(import_name)
  351. except ImportError:
  352. previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
  353. sys.path.insert(
  354. 0, os.path.realpath(
  355. os.path.join(
  356. os.path.abspath(
  357. os.path.dirname(previous_frame.filename)
  358. ),
  359. relative_from
  360. )
  361. )
  362. )
  363. return __import__(import_name)
  364. class ForceImportErrorOn(object):
  365. '''
  366. This class is meant to be used in mock'ed test cases which require an
  367. ``ImportError`` to be raised.
  368. >>> import os.path
  369. >>> with ForceImportErrorOn('os.path'):
  370. ... import os.path
  371. ...
  372. Traceback (most recent call last):
  373. File "<stdin>", line 2, in <module>
  374. File "salttesting/helpers.py", line 263, in __import__
  375. 'Forced ImportError raised for {0!r}'.format(name)
  376. ImportError: Forced ImportError raised for 'os.path'
  377. >>>
  378. >>> with ForceImportErrorOn(('os', 'path')):
  379. ... import os.path
  380. ... sys.modules.pop('os', None)
  381. ... from os import path
  382. ...
  383. <module 'os' from '/usr/lib/python2.7/os.pyc'>
  384. Traceback (most recent call last):
  385. File "<stdin>", line 4, in <module>
  386. File "salttesting/helpers.py", line 288, in __fake_import__
  387. name, ', '.join(fromlist)
  388. ImportError: Forced ImportError raised for 'from os import path'
  389. >>>
  390. >>> with ForceImportErrorOn(('os', 'path'), 'os.path'):
  391. ... import os.path
  392. ... sys.modules.pop('os', None)
  393. ... from os import path
  394. ...
  395. Traceback (most recent call last):
  396. File "<stdin>", line 2, in <module>
  397. File "salttesting/helpers.py", line 281, in __fake_import__
  398. 'Forced ImportError raised for {0!r}'.format(name)
  399. ImportError: Forced ImportError raised for 'os.path'
  400. >>>
  401. '''
  402. def __init__(self, *module_names):
  403. self.__module_names = {}
  404. for entry in module_names:
  405. if isinstance(entry, (list, tuple)):
  406. modname = entry[0]
  407. self.__module_names[modname] = set(entry[1:])
  408. else:
  409. self.__module_names[entry] = None
  410. self.__original_import = builtins.__import__
  411. self.patcher = patch.object(builtins, '__import__', self.__fake_import__)
  412. def patch_import_function(self):
  413. self.patcher.start()
  414. def restore_import_funtion(self):
  415. self.patcher.stop()
  416. def __fake_import__(self,
  417. name,
  418. globals_={} if six.PY2 else None,
  419. locals_={} if six.PY2 else None,
  420. fromlist=[] if six.PY2 else (),
  421. level=-1 if six.PY2 else 0):
  422. if name in self.__module_names:
  423. importerror_fromlist = self.__module_names.get(name)
  424. if importerror_fromlist is None:
  425. raise ImportError(
  426. 'Forced ImportError raised for {0!r}'.format(name)
  427. )
  428. if importerror_fromlist.intersection(set(fromlist)):
  429. raise ImportError(
  430. 'Forced ImportError raised for {0!r}'.format(
  431. 'from {0} import {1}'.format(
  432. name, ', '.join(fromlist)
  433. )
  434. )
  435. )
  436. return self.__original_import(name, globals_, locals_, fromlist, level)
  437. def __enter__(self):
  438. self.patch_import_function()
  439. return self
  440. def __exit__(self, exc_type, exc_value, traceback):
  441. self.restore_import_funtion()
  442. class MockWraps(object):
  443. '''
  444. Helper class to be used with the mock library.
  445. To be used in the ``wraps`` keyword of ``Mock`` or ``MagicMock`` where you
  446. want to trigger a side effect for X times, and afterwards, call the
  447. original and un-mocked method.
  448. As an example:
  449. >>> def original():
  450. ... print 'original'
  451. ...
  452. >>> def side_effect():
  453. ... print 'side effect'
  454. ...
  455. >>> mw = MockWraps(original, 2, side_effect)
  456. >>> mw()
  457. side effect
  458. >>> mw()
  459. side effect
  460. >>> mw()
  461. original
  462. >>>
  463. '''
  464. def __init__(self, original, expected_failures, side_effect):
  465. self.__original = original
  466. self.__expected_failures = expected_failures
  467. self.__side_effect = side_effect
  468. self.__call_counter = 0
  469. def __call__(self, *args, **kwargs):
  470. try:
  471. if self.__call_counter < self.__expected_failures:
  472. if isinstance(self.__side_effect, types.FunctionType):
  473. return self.__side_effect()
  474. raise self.__side_effect
  475. return self.__original(*args, **kwargs)
  476. finally:
  477. self.__call_counter += 1
  478. def requires_network(only_local_network=False):
  479. '''
  480. Simple decorator which is supposed to skip a test case in case there's no
  481. network connection to the internet.
  482. '''
  483. def decorator(func):
  484. @functools.wraps(func)
  485. def wrapper(cls):
  486. has_local_network = False
  487. # First lets try if we have a local network. Inspired in
  488. # verify_socket
  489. try:
  490. pubsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  491. retsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  492. pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  493. pubsock.bind(('', 18000))
  494. pubsock.close()
  495. retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  496. retsock.bind(('', 18001))
  497. retsock.close()
  498. has_local_network = True
  499. except socket.error:
  500. # I wonder if we just have IPV6 support?
  501. try:
  502. pubsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  503. retsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  504. pubsock.setsockopt(
  505. socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
  506. )
  507. pubsock.bind(('', 18000))
  508. pubsock.close()
  509. retsock.setsockopt(
  510. socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
  511. )
  512. retsock.bind(('', 18001))
  513. retsock.close()
  514. has_local_network = True
  515. except socket.error:
  516. # Let's continue
  517. pass
  518. if only_local_network is True:
  519. if has_local_network is False:
  520. # Since we're only supposed to check local network, and no
  521. # local network was detected, skip the test
  522. cls.skipTest('No local network was detected')
  523. return func(cls)
  524. # We are using the google.com DNS records as numerical IPs to avoid
  525. # DNS lookups which could greatly slow down this check
  526. for addr in ('173.194.41.198', '173.194.41.199', '173.194.41.200',
  527. '173.194.41.201', '173.194.41.206', '173.194.41.192',
  528. '173.194.41.193', '173.194.41.194', '173.194.41.195',
  529. '173.194.41.196', '173.194.41.197'):
  530. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  531. try:
  532. sock.settimeout(0.25)
  533. sock.connect((addr, 80))
  534. # We connected? Stop the loop
  535. break
  536. except socket.error:
  537. # Let's check the next IP
  538. continue
  539. else:
  540. cls.skipTest('No internet network connection was detected')
  541. finally:
  542. sock.close()
  543. return func(cls)
  544. return wrapper
  545. return decorator
  546. def with_system_user(username, on_existing='delete', delete=True, password=None, groups=None):
  547. '''
  548. Create and optionally destroy a system user to be used within a test
  549. case. The system user is created using the ``user`` salt module.
  550. The decorated testcase function must accept 'username' as an argument.
  551. :param username: The desired username for the system user.
  552. :param on_existing: What to do when the desired username is taken. The
  553. available options are:
  554. * nothing: Do nothing, act as if the user was created.
  555. * delete: delete and re-create the existing user
  556. * skip: skip the test case
  557. '''
  558. if on_existing not in ('nothing', 'delete', 'skip'):
  559. raise RuntimeError(
  560. 'The value of \'on_existing\' can only be one of, '
  561. '\'nothing\', \'delete\' and \'skip\''
  562. )
  563. if not isinstance(delete, bool):
  564. raise RuntimeError(
  565. 'The value of \'delete\' can only be \'True\' or \'False\''
  566. )
  567. def decorator(func):
  568. @functools.wraps(func)
  569. def wrap(cls):
  570. # Let's add the user to the system.
  571. log.debug('Creating system user {0!r}'.format(username))
  572. kwargs = {'timeout': 60, 'groups': groups}
  573. if salt.utils.platform.is_windows():
  574. kwargs.update({'password': password})
  575. create_user = cls.run_function('user.add', [username], **kwargs)
  576. if not create_user:
  577. log.debug('Failed to create system user')
  578. # The user was not created
  579. if on_existing == 'skip':
  580. cls.skipTest(
  581. 'Failed to create system user {0!r}'.format(
  582. username
  583. )
  584. )
  585. if on_existing == 'delete':
  586. log.debug(
  587. 'Deleting the system user {0!r}'.format(
  588. username
  589. )
  590. )
  591. delete_user = cls.run_function(
  592. 'user.delete', [username, True, True]
  593. )
  594. if not delete_user:
  595. cls.skipTest(
  596. 'A user named {0!r} already existed on the '
  597. 'system and re-creating it was not possible'
  598. .format(username)
  599. )
  600. log.debug(
  601. 'Second time creating system user {0!r}'.format(
  602. username
  603. )
  604. )
  605. create_user = cls.run_function('user.add', [username], **kwargs)
  606. if not create_user:
  607. cls.skipTest(
  608. 'A user named {0!r} already existed, was deleted '
  609. 'as requested, but re-creating it was not possible'
  610. .format(username)
  611. )
  612. failure = None
  613. try:
  614. try:
  615. return func(cls, username)
  616. except Exception as exc: # pylint: disable=W0703
  617. log.error(
  618. 'Running {0!r} raised an exception: {1}'.format(
  619. func, exc
  620. ),
  621. exc_info=True
  622. )
  623. # Store the original exception details which will be raised
  624. # a little further down the code
  625. failure = sys.exc_info()
  626. finally:
  627. if delete:
  628. delete_user = cls.run_function(
  629. 'user.delete', [username, True, True], timeout=60
  630. )
  631. if not delete_user:
  632. if failure is None:
  633. log.warning(
  634. 'Although the actual test-case did not fail, '
  635. 'deleting the created system user {0!r} '
  636. 'afterwards did.'.format(username)
  637. )
  638. else:
  639. log.warning(
  640. 'The test-case failed and also did the removal'
  641. ' of the system user {0!r}'.format(username)
  642. )
  643. if failure is not None:
  644. # If an exception was thrown, raise it
  645. six.reraise(failure[0], failure[1], failure[2])
  646. return wrap
  647. return decorator
  648. def with_system_group(group, on_existing='delete', delete=True):
  649. '''
  650. Create and optionally destroy a system group to be used within a test
  651. case. The system user is crated using the ``group`` salt module.
  652. The decorated testcase function must accept 'group' as an argument.
  653. :param group: The desired group name for the system user.
  654. :param on_existing: What to do when the desired username is taken. The
  655. available options are:
  656. * nothing: Do nothing, act as if the group was created
  657. * delete: delete and re-create the existing user
  658. * skip: skip the test case
  659. '''
  660. if on_existing not in ('nothing', 'delete', 'skip'):
  661. raise RuntimeError(
  662. 'The value of \'on_existing\' can only be one of, '
  663. '\'nothing\', \'delete\' and \'skip\''
  664. )
  665. if not isinstance(delete, bool):
  666. raise RuntimeError(
  667. 'The value of \'delete\' can only be \'True\' or \'False\''
  668. )
  669. def decorator(func):
  670. @functools.wraps(func)
  671. def wrap(cls):
  672. # Let's add the user to the system.
  673. log.debug('Creating system group {0!r}'.format(group))
  674. create_group = cls.run_function('group.add', [group])
  675. if not create_group:
  676. log.debug('Failed to create system group')
  677. # The group was not created
  678. if on_existing == 'skip':
  679. cls.skipTest(
  680. 'Failed to create system group {0!r}'.format(group)
  681. )
  682. if on_existing == 'delete':
  683. log.debug(
  684. 'Deleting the system group {0!r}'.format(group)
  685. )
  686. delete_group = cls.run_function('group.delete', [group])
  687. if not delete_group:
  688. cls.skipTest(
  689. 'A group named {0!r} already existed on the '
  690. 'system and re-creating it was not possible'
  691. .format(group)
  692. )
  693. log.debug(
  694. 'Second time creating system group {0!r}'.format(
  695. group
  696. )
  697. )
  698. create_group = cls.run_function('group.add', [group])
  699. if not create_group:
  700. cls.skipTest(
  701. 'A group named {0!r} already existed, was deleted '
  702. 'as requested, but re-creating it was not possible'
  703. .format(group)
  704. )
  705. failure = None
  706. try:
  707. try:
  708. return func(cls, group)
  709. except Exception as exc: # pylint: disable=W0703
  710. log.error(
  711. 'Running {0!r} raised an exception: {1}'.format(
  712. func, exc
  713. ),
  714. exc_info=True
  715. )
  716. # Store the original exception details which will be raised
  717. # a little further down the code
  718. failure = sys.exc_info()
  719. finally:
  720. if delete:
  721. delete_group = cls.run_function('group.delete', [group])
  722. if not delete_group:
  723. if failure is None:
  724. log.warning(
  725. 'Although the actual test-case did not fail, '
  726. 'deleting the created system group {0!r} '
  727. 'afterwards did.'.format(group)
  728. )
  729. else:
  730. log.warning(
  731. 'The test-case failed and also did the removal'
  732. ' of the system group {0!r}'.format(group)
  733. )
  734. if failure is not None:
  735. # If an exception was thrown, raise it
  736. six.reraise(failure[0], failure[1], failure[2])
  737. return wrap
  738. return decorator
  739. def with_system_user_and_group(username, group,
  740. on_existing='delete', delete=True):
  741. '''
  742. Create and optionally destroy a system user and group to be used within a
  743. test case. The system user is crated using the ``user`` salt module, and
  744. the system group is created with the ``group`` salt module.
  745. The decorated testcase function must accept both the 'username' and 'group'
  746. arguments.
  747. :param username: The desired username for the system user.
  748. :param group: The desired name for the system group.
  749. :param on_existing: What to do when the desired username is taken. The
  750. available options are:
  751. * nothing: Do nothing, act as if the user was created.
  752. * delete: delete and re-create the existing user
  753. * skip: skip the test case
  754. '''
  755. if on_existing not in ('nothing', 'delete', 'skip'):
  756. raise RuntimeError(
  757. 'The value of \'on_existing\' can only be one of, '
  758. '\'nothing\', \'delete\' and \'skip\''
  759. )
  760. if not isinstance(delete, bool):
  761. raise RuntimeError(
  762. 'The value of \'delete\' can only be \'True\' or \'False\''
  763. )
  764. def decorator(func):
  765. @functools.wraps(func)
  766. def wrap(cls):
  767. # Let's add the user to the system.
  768. log.debug('Creating system user {0!r}'.format(username))
  769. create_user = cls.run_function('user.add', [username])
  770. log.debug('Creating system group {0!r}'.format(group))
  771. create_group = cls.run_function('group.add', [group])
  772. if not create_user:
  773. log.debug('Failed to create system user')
  774. # The user was not created
  775. if on_existing == 'skip':
  776. cls.skipTest(
  777. 'Failed to create system user {0!r}'.format(
  778. username
  779. )
  780. )
  781. if on_existing == 'delete':
  782. log.debug(
  783. 'Deleting the system user {0!r}'.format(
  784. username
  785. )
  786. )
  787. delete_user = cls.run_function(
  788. 'user.delete', [username, True, True]
  789. )
  790. if not delete_user:
  791. cls.skipTest(
  792. 'A user named {0!r} already existed on the '
  793. 'system and re-creating it was not possible'
  794. .format(username)
  795. )
  796. log.debug(
  797. 'Second time creating system user {0!r}'.format(
  798. username
  799. )
  800. )
  801. create_user = cls.run_function('user.add', [username])
  802. if not create_user:
  803. cls.skipTest(
  804. 'A user named {0!r} already existed, was deleted '
  805. 'as requested, but re-creating it was not possible'
  806. .format(username)
  807. )
  808. if not create_group:
  809. log.debug('Failed to create system group')
  810. # The group was not created
  811. if on_existing == 'skip':
  812. cls.skipTest(
  813. 'Failed to create system group {0!r}'.format(group)
  814. )
  815. if on_existing == 'delete':
  816. log.debug(
  817. 'Deleting the system group {0!r}'.format(group)
  818. )
  819. delete_group = cls.run_function('group.delete', [group])
  820. if not delete_group:
  821. cls.skipTest(
  822. 'A group named {0!r} already existed on the '
  823. 'system and re-creating it was not possible'
  824. .format(group)
  825. )
  826. log.debug(
  827. 'Second time creating system group {0!r}'.format(
  828. group
  829. )
  830. )
  831. create_group = cls.run_function('group.add', [group])
  832. if not create_group:
  833. cls.skipTest(
  834. 'A group named {0!r} already existed, was deleted '
  835. 'as requested, but re-creating it was not possible'
  836. .format(group)
  837. )
  838. failure = None
  839. try:
  840. try:
  841. return func(cls, username, group)
  842. except Exception as exc: # pylint: disable=W0703
  843. log.error(
  844. 'Running {0!r} raised an exception: {1}'.format(
  845. func, exc
  846. ),
  847. exc_info=True
  848. )
  849. # Store the original exception details which will be raised
  850. # a little further down the code
  851. failure = sys.exc_info()
  852. finally:
  853. if delete:
  854. delete_user = cls.run_function(
  855. 'user.delete', [username, True, True]
  856. )
  857. delete_group = cls.run_function('group.delete', [group])
  858. if not delete_user:
  859. if failure is None:
  860. log.warning(
  861. 'Although the actual test-case did not fail, '
  862. 'deleting the created system user {0!r} '
  863. 'afterwards did.'.format(username)
  864. )
  865. else:
  866. log.warning(
  867. 'The test-case failed and also did the removal'
  868. ' of the system user {0!r}'.format(username)
  869. )
  870. if not delete_group:
  871. if failure is None:
  872. log.warning(
  873. 'Although the actual test-case did not fail, '
  874. 'deleting the created system group {0!r} '
  875. 'afterwards did.'.format(group)
  876. )
  877. else:
  878. log.warning(
  879. 'The test-case failed and also did the removal'
  880. ' of the system group {0!r}'.format(group)
  881. )
  882. if failure is not None:
  883. # If an exception was thrown, raise it
  884. six.reraise(failure[0], failure[1], failure[2])
  885. return wrap
  886. return decorator
  887. class WithTempfile(object):
  888. def __init__(self, **kwargs):
  889. self.create = kwargs.pop('create', True)
  890. if 'dir' not in kwargs:
  891. kwargs['dir'] = TMP
  892. if 'prefix' not in kwargs:
  893. kwargs['prefix'] = '__salt.test.'
  894. self.kwargs = kwargs
  895. def __call__(self, func):
  896. self.func = func
  897. return functools.wraps(func)(
  898. lambda testcase, *args, **kwargs: self.wrap(testcase, *args, **kwargs) # pylint: disable=W0108
  899. )
  900. def wrap(self, testcase, *args, **kwargs):
  901. name = salt.utils.files.mkstemp(**self.kwargs)
  902. if not self.create:
  903. os.remove(name)
  904. try:
  905. return self.func(testcase, name, *args, **kwargs)
  906. finally:
  907. try:
  908. os.remove(name)
  909. except OSError:
  910. pass
  911. with_tempfile = WithTempfile
  912. class WithTempdir(object):
  913. def __init__(self, **kwargs):
  914. self.create = kwargs.pop('create', True)
  915. if 'dir' not in kwargs:
  916. kwargs['dir'] = TMP
  917. self.kwargs = kwargs
  918. def __call__(self, func):
  919. self.func = func
  920. return functools.wraps(func)(
  921. lambda testcase, *args, **kwargs: self.wrap(testcase, *args, **kwargs) # pylint: disable=W0108
  922. )
  923. def wrap(self, testcase, *args, **kwargs):
  924. tempdir = tempfile.mkdtemp(**self.kwargs)
  925. if not self.create:
  926. os.rmdir(tempdir)
  927. try:
  928. return self.func(testcase, tempdir, *args, **kwargs)
  929. finally:
  930. shutil.rmtree(tempdir, ignore_errors=True)
  931. with_tempdir = WithTempdir
  932. def requires_system_grains(func):
  933. '''
  934. Function decorator which loads and passes the system's grains to the test
  935. case.
  936. '''
  937. @functools.wraps(func)
  938. def decorator(*args, **kwargs):
  939. if not hasattr(requires_system_grains, '__grains__'):
  940. # Late import
  941. from tests.support.sminion import build_minion_opts
  942. opts = build_minion_opts(minion_id='runtests-internal-sminion')
  943. requires_system_grains.__grains__ = salt.loader.grains(opts)
  944. kwargs['grains'] = requires_system_grains.__grains__
  945. return func(*args, **kwargs)
  946. return decorator
  947. def requires_salt_modules(*names):
  948. '''
  949. Makes sure the passed salt module is available. Skips the test if not
  950. .. versionadded:: 0.5.2
  951. '''
  952. def _check_required_salt_modules(*required_salt_modules):
  953. # Late import
  954. from tests.support.sminion import create_sminion
  955. required_salt_modules = set(required_salt_modules)
  956. sminion = create_sminion(minion_id='runtests-internal-sminion')
  957. available_modules = list(sminion.functions)
  958. not_available_modules = set()
  959. try:
  960. cached_not_available_modules = sminion.__not_availiable_modules__
  961. except AttributeError:
  962. cached_not_available_modules = sminion.__not_availiable_modules__ = set()
  963. if cached_not_available_modules:
  964. for not_available_module in cached_not_available_modules:
  965. if not_available_module in required_salt_modules:
  966. not_available_modules.add(not_available_module)
  967. required_salt_modules.remove(not_available_module)
  968. for required_module_name in required_salt_modules:
  969. search_name = required_module_name
  970. if '.' not in search_name:
  971. search_name += '.*'
  972. if not fnmatch.filter(available_modules, search_name):
  973. not_available_modules.add(required_module_name)
  974. cached_not_available_modules.add(required_module_name)
  975. if not_available_modules:
  976. if len(not_available_modules) == 1:
  977. raise SkipTest('Salt module \'{}\' is not available'.format(*not_available_modules))
  978. raise SkipTest('Salt modules not available: {}'.format(', '.join(not_available_modules)))
  979. def decorator(caller):
  980. if inspect.isclass(caller):
  981. # We're decorating a class
  982. old_setup = getattr(caller, 'setUp', None)
  983. def setUp(self, *args, **kwargs):
  984. _check_required_salt_modules(*names)
  985. if old_setup is not None:
  986. old_setup(self, *args, **kwargs)
  987. caller.setUp = setUp
  988. return caller
  989. # We're simply decorating functions
  990. @functools.wraps(caller)
  991. def wrapper(cls):
  992. _check_required_salt_modules(*names)
  993. return caller(cls)
  994. return wrapper
  995. return decorator
  996. def skip_if_binaries_missing(*binaries, **kwargs):
  997. import salt.utils.path
  998. if len(binaries) == 1:
  999. if isinstance(binaries[0], (list, tuple, set, frozenset)):
  1000. binaries = binaries[0]
  1001. check_all = kwargs.pop('check_all', False)
  1002. message = kwargs.pop('message', None)
  1003. if kwargs:
  1004. raise RuntimeError(
  1005. 'The only supported keyword argument is \'check_all\' and '
  1006. '\'message\'. Invalid keyword arguments: {0}'.format(
  1007. ', '.join(kwargs.keys())
  1008. )
  1009. )
  1010. if check_all:
  1011. for binary in binaries:
  1012. if salt.utils.path.which(binary) is None:
  1013. return skip(
  1014. '{0}The {1!r} binary was not found'.format(
  1015. message and '{0}. '.format(message) or '',
  1016. binary
  1017. )
  1018. )
  1019. elif salt.utils.path.which_bin(binaries) is None:
  1020. return skip(
  1021. '{0}None of the following binaries was found: {1}'.format(
  1022. message and '{0}. '.format(message) or '',
  1023. ', '.join(binaries)
  1024. )
  1025. )
  1026. return _id
  1027. def skip_if_not_root(func):
  1028. if not sys.platform.startswith('win'):
  1029. if os.getuid() != 0:
  1030. func.__unittest_skip__ = True
  1031. func.__unittest_skip_why__ = 'You must be logged in as root to run this test'
  1032. else:
  1033. current_user = salt.utils.win_functions.get_current_user()
  1034. if current_user != 'SYSTEM':
  1035. if not salt.utils.win_functions.is_admin(current_user):
  1036. func.__unittest_skip__ = True
  1037. func.__unittest_skip_why__ = 'You must be logged in as an Administrator to run this test'
  1038. return func
  1039. if sys.platform.startswith('win'):
  1040. SIGTERM = signal.CTRL_BREAK_EVENT # pylint: disable=no-member
  1041. else:
  1042. SIGTERM = signal.SIGTERM
  1043. def collect_child_processes(pid):
  1044. '''
  1045. Try to collect any started child processes of the provided pid
  1046. '''
  1047. # Let's get the child processes of the started subprocess
  1048. try:
  1049. parent = psutil.Process(pid)
  1050. if hasattr(parent, 'children'):
  1051. children = parent.children(recursive=True)
  1052. else:
  1053. children = []
  1054. except psutil.NoSuchProcess:
  1055. children = []
  1056. return children[::-1] # return a reversed list of the children
  1057. def _terminate_process_list(process_list, kill=False, slow_stop=False):
  1058. for process in process_list[:][::-1]: # Iterate over a reversed copy of the list
  1059. if not psutil.pid_exists(process.pid):
  1060. process_list.remove(process)
  1061. continue
  1062. try:
  1063. if not kill and process.status() == psutil.STATUS_ZOMBIE:
  1064. # Zombie processes will exit once child processes also exit
  1065. continue
  1066. try:
  1067. cmdline = process.cmdline()
  1068. except psutil.AccessDenied:
  1069. # OSX is more restrictive about the above information
  1070. cmdline = None
  1071. except OSError:
  1072. cmdline = None
  1073. if not cmdline:
  1074. try:
  1075. cmdline = process.as_dict()
  1076. except Exception:
  1077. cmdline = 'UNKNOWN PROCESS'
  1078. if kill:
  1079. log.info('Killing process(%s): %s', process.pid, cmdline)
  1080. process.kill()
  1081. else:
  1082. log.info('Terminating process(%s): %s', process.pid, cmdline)
  1083. try:
  1084. if slow_stop:
  1085. # Allow coverage data to be written down to disk
  1086. process.send_signal(SIGTERM)
  1087. try:
  1088. process.wait(2)
  1089. except psutil.TimeoutExpired:
  1090. if psutil.pid_exists(process.pid):
  1091. continue
  1092. else:
  1093. process.terminate()
  1094. except OSError as exc:
  1095. if exc.errno not in (errno.ESRCH, errno.EACCES):
  1096. raise
  1097. if not psutil.pid_exists(process.pid):
  1098. process_list.remove(process)
  1099. except psutil.NoSuchProcess:
  1100. process_list.remove(process)
  1101. def terminate_process_list(process_list, kill=False, slow_stop=False):
  1102. def on_process_terminated(proc):
  1103. log.info('Process %s terminated with exit code: %s', getattr(proc, '_cmdline', proc), proc.returncode)
  1104. # Try to terminate processes with the provided kill and slow_stop parameters
  1105. log.info('Terminating process list. 1st step. kill: %s, slow stop: %s', kill, slow_stop)
  1106. # Cache the cmdline since that will be inaccessible once the process is terminated
  1107. for proc in process_list:
  1108. try:
  1109. cmdline = proc.cmdline()
  1110. except (psutil.NoSuchProcess, psutil.AccessDenied):
  1111. # OSX is more restrictive about the above information
  1112. cmdline = None
  1113. if not cmdline:
  1114. try:
  1115. cmdline = proc
  1116. except (psutil.NoSuchProcess, psutil.AccessDenied):
  1117. cmdline = '<could not be retrived; dead process: {0}>'.format(proc)
  1118. proc._cmdline = cmdline
  1119. _terminate_process_list(process_list, kill=kill, slow_stop=slow_stop)
  1120. psutil.wait_procs(process_list, timeout=15, callback=on_process_terminated)
  1121. if process_list:
  1122. # If there's still processes to be terminated, retry and kill them if slow_stop is False
  1123. log.info('Terminating process list. 2nd step. kill: %s, slow stop: %s', slow_stop is False, slow_stop)
  1124. _terminate_process_list(process_list, kill=slow_stop is False, slow_stop=slow_stop)
  1125. psutil.wait_procs(process_list, timeout=10, callback=on_process_terminated)
  1126. if process_list:
  1127. # If there's still processes to be terminated, just kill them, no slow stopping now
  1128. log.info('Terminating process list. 3rd step. kill: True, slow stop: False')
  1129. _terminate_process_list(process_list, kill=True, slow_stop=False)
  1130. psutil.wait_procs(process_list, timeout=5, callback=on_process_terminated)
  1131. if process_list:
  1132. # In there's still processes to be terminated, log a warning about it
  1133. log.warning('Some processes failed to properly terminate: %s', process_list)
  1134. def terminate_process(pid=None, process=None, children=None, kill_children=False, slow_stop=False):
  1135. '''
  1136. Try to terminate/kill the started processe
  1137. '''
  1138. children = children or []
  1139. process_list = []
  1140. def on_process_terminated(proc):
  1141. if proc.returncode:
  1142. log.info('Process %s terminated with exit code: %s', getattr(proc, '_cmdline', proc), proc.returncode)
  1143. else:
  1144. log.info('Process %s terminated', getattr(proc, '_cmdline', proc))
  1145. if pid and not process:
  1146. try:
  1147. process = psutil.Process(pid)
  1148. process_list.append(process)
  1149. except psutil.NoSuchProcess:
  1150. # Process is already gone
  1151. process = None
  1152. if kill_children:
  1153. if process:
  1154. if not children:
  1155. children = collect_child_processes(process.pid)
  1156. else:
  1157. # Let's collect children again since there might be new ones
  1158. children.extend(collect_child_processes(pid))
  1159. if children:
  1160. process_list.extend(children)
  1161. if process_list:
  1162. if process:
  1163. log.info('Stopping process %s and respective children: %s', process, children)
  1164. else:
  1165. log.info('Terminating process list: %s', process_list)
  1166. terminate_process_list(process_list, kill=slow_stop is False, slow_stop=slow_stop)
  1167. if process and psutil.pid_exists(process.pid):
  1168. log.warning('Process left behind which we were unable to kill: %s', process)
  1169. def terminate_process_pid(pid, only_children=False):
  1170. children = []
  1171. process = None
  1172. # Let's begin the shutdown routines
  1173. try:
  1174. process = psutil.Process(pid)
  1175. children = collect_child_processes(pid)
  1176. except psutil.NoSuchProcess:
  1177. log.info('No process with the PID %s was found running', pid)
  1178. if only_children:
  1179. return terminate_process(children=children, kill_children=True, slow_stop=True)
  1180. return terminate_process(pid=pid, process=process, children=children, kill_children=True, slow_stop=True)
  1181. def repeat(caller=None, condition=True, times=5):
  1182. '''
  1183. Repeat a test X amount of times until the first failure.
  1184. .. code-block:: python
  1185. class MyTestCase(TestCase):
  1186. @repeat
  1187. def test_sometimes_works(self):
  1188. pass
  1189. '''
  1190. if caller is None:
  1191. return functools.partial(repeat, condition=condition, times=times)
  1192. if isinstance(condition, bool) and condition is False:
  1193. # Don't even decorate
  1194. return caller
  1195. elif callable(condition):
  1196. if condition() is False:
  1197. # Don't even decorate
  1198. return caller
  1199. if inspect.isclass(caller):
  1200. attrs = [n for n in dir(caller) if n.startswith('test_')]
  1201. for attrname in attrs:
  1202. try:
  1203. function = getattr(caller, attrname)
  1204. if not inspect.isfunction(function) and not inspect.ismethod(function):
  1205. continue
  1206. setattr(caller, attrname, repeat(caller=function, condition=condition, times=times))
  1207. except Exception as exc:
  1208. log.exception(exc)
  1209. continue
  1210. return caller
  1211. @functools.wraps(caller)
  1212. def wrap(cls):
  1213. result = None
  1214. for attempt in range(1, times+1):
  1215. log.info('%s test run %d of %s times', cls, attempt, times)
  1216. caller(cls)
  1217. return cls
  1218. return wrap
  1219. def http_basic_auth(login_cb=lambda username, password: False):
  1220. '''
  1221. A crude decorator to force a handler to request HTTP Basic Authentication
  1222. Example usage:
  1223. .. code-block:: python
  1224. @http_basic_auth(lambda u, p: u == 'foo' and p == 'bar')
  1225. class AuthenticatedHandler(tornado.web.RequestHandler):
  1226. pass
  1227. '''
  1228. def wrapper(handler_class):
  1229. def wrap_execute(handler_execute):
  1230. def check_auth(handler, kwargs):
  1231. auth = handler.request.headers.get('Authorization')
  1232. if auth is None or not auth.startswith('Basic '):
  1233. # No username/password entered yet, we need to return a 401
  1234. # and set the WWW-Authenticate header to request login.
  1235. handler.set_status(401)
  1236. handler.set_header(
  1237. 'WWW-Authenticate', 'Basic realm=Restricted')
  1238. else:
  1239. # Strip the 'Basic ' from the beginning of the auth header
  1240. # leaving the base64-encoded secret
  1241. username, password = \
  1242. base64.b64decode(auth[6:]).split(':', 1)
  1243. if login_cb(username, password):
  1244. # Authentication successful
  1245. return
  1246. else:
  1247. # Authentication failed
  1248. handler.set_status(403)
  1249. handler._transforms = []
  1250. handler.finish()
  1251. def _execute(self, transforms, *args, **kwargs):
  1252. check_auth(self, kwargs)
  1253. return handler_execute(self, transforms, *args, **kwargs)
  1254. return _execute
  1255. handler_class._execute = wrap_execute(handler_class._execute)
  1256. return handler_class
  1257. return wrapper
  1258. def generate_random_name(prefix, size=6):
  1259. '''
  1260. Generates a random name by combining the provided prefix with a randomly generated
  1261. ascii string.
  1262. .. versionadded:: 2018.3.0
  1263. prefix
  1264. The string to prefix onto the randomly generated ascii string.
  1265. size
  1266. The number of characters to generate. Default: 6.
  1267. '''
  1268. return prefix + ''.join(
  1269. random.choice(string.ascii_uppercase + string.digits)
  1270. for x in range(size)
  1271. )
  1272. class Webserver(object):
  1273. '''
  1274. Starts a tornado webserver on 127.0.0.1 on a random available port
  1275. USAGE:
  1276. .. code-block:: python
  1277. from tests.support.helpers import Webserver
  1278. webserver = Webserver('/path/to/web/root')
  1279. webserver.start()
  1280. webserver.stop()
  1281. '''
  1282. def __init__(self,
  1283. root=None,
  1284. port=None,
  1285. wait=5,
  1286. handler=None):
  1287. '''
  1288. root
  1289. Root directory of webserver. If not passed, it will default to the
  1290. location of the base environment of the integration suite's file
  1291. roots (tests/integration/files/file/base/)
  1292. port
  1293. Port on which to listen. If not passed, a random one will be chosen
  1294. at the time the start() function is invoked.
  1295. wait : 5
  1296. Number of seconds to wait for the socket to be open before raising
  1297. an exception
  1298. handler
  1299. Can be used to use a subclass of tornado.web.StaticFileHandler,
  1300. such as when enforcing authentication with the http_basic_auth
  1301. decorator.
  1302. '''
  1303. if port is not None and not isinstance(port, six.integer_types):
  1304. raise ValueError('port must be an integer')
  1305. if root is None:
  1306. root = os.path.join(FILES, 'file', 'base')
  1307. try:
  1308. self.root = os.path.realpath(root)
  1309. except AttributeError:
  1310. raise ValueError('root must be a string')
  1311. self.port = port
  1312. self.wait = wait
  1313. self.handler = handler \
  1314. if handler is not None \
  1315. else tornado.web.StaticFileHandler
  1316. self.web_root = None
  1317. def target(self):
  1318. '''
  1319. Threading target which stands up the tornado application
  1320. '''
  1321. self.ioloop = tornado.ioloop.IOLoop()
  1322. self.ioloop.make_current()
  1323. self.application = tornado.web.Application(
  1324. [(r'/(.*)', self.handler, {'path': self.root})])
  1325. self.application.listen(self.port)
  1326. self.ioloop.start()
  1327. @property
  1328. def listening(self):
  1329. if self.port is None:
  1330. return False
  1331. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1332. return sock.connect_ex(('127.0.0.1', self.port)) == 0
  1333. def url(self, path):
  1334. '''
  1335. Convenience function which, given a file path, will return a URL that
  1336. points to that path. If the path is relative, it will just be appended
  1337. to self.web_root.
  1338. '''
  1339. if self.web_root is None:
  1340. raise RuntimeError('Webserver instance has not been started')
  1341. err_msg = 'invalid path, must be either a relative path or a path ' \
  1342. 'within {0}'.format(self.root)
  1343. try:
  1344. relpath = path \
  1345. if not os.path.isabs(path) \
  1346. else os.path.relpath(path, self.root)
  1347. if relpath.startswith('..' + os.sep):
  1348. raise ValueError(err_msg)
  1349. return '/'.join((self.web_root, relpath))
  1350. except AttributeError:
  1351. raise ValueError(err_msg)
  1352. def start(self):
  1353. '''
  1354. Starts the webserver
  1355. '''
  1356. if self.port is None:
  1357. self.port = get_unused_localhost_port()
  1358. self.web_root = 'http://127.0.0.1:{0}'.format(self.port)
  1359. self.server_thread = threading.Thread(target=self.target)
  1360. self.server_thread.daemon = True
  1361. self.server_thread.start()
  1362. for idx in range(self.wait + 1):
  1363. if self.listening:
  1364. break
  1365. if idx != self.wait:
  1366. time.sleep(1)
  1367. else:
  1368. raise Exception(
  1369. 'Failed to start tornado webserver on 127.0.0.1:{0} within '
  1370. '{1} seconds'.format(self.port, self.wait)
  1371. )
  1372. def stop(self):
  1373. '''
  1374. Stops the webserver
  1375. '''
  1376. self.ioloop.add_callback(self.ioloop.stop)
  1377. self.server_thread.join()
  1378. def win32_kill_process_tree(pid, sig=signal.SIGTERM, include_parent=True,
  1379. timeout=None, on_terminate=None):
  1380. '''
  1381. Kill a process tree (including grandchildren) with signal "sig" and return
  1382. a (gone, still_alive) tuple. "on_terminate", if specified, is a callabck
  1383. function which is called as soon as a child terminates.
  1384. '''
  1385. if pid == os.getpid():
  1386. raise RuntimeError("I refuse to kill myself")
  1387. try:
  1388. parent = psutil.Process(pid)
  1389. except psutil.NoSuchProcess:
  1390. log.debug("PID not found alive: %d", pid)
  1391. return ([], [])
  1392. children = parent.children(recursive=True)
  1393. if include_parent:
  1394. children.append(parent)
  1395. for p in children:
  1396. p.send_signal(sig)
  1397. gone, alive = psutil.wait_procs(children, timeout=timeout,
  1398. callback=on_terminate)
  1399. return (gone, alive)
  1400. def this_user():
  1401. '''
  1402. Get the user associated with the current process.
  1403. '''
  1404. if salt.utils.platform.is_windows():
  1405. return salt.utils.win_functions.get_current_user(with_domain=False)
  1406. return pwd.getpwuid(os.getuid())[0]
  1407. def dedent(text, linesep=os.linesep):
  1408. '''
  1409. A wrapper around textwrap.dedent that also sets line endings.
  1410. '''
  1411. linesep = salt.utils.stringutils.to_unicode(linesep)
  1412. unicode_text = textwrap.dedent(salt.utils.stringutils.to_unicode(text))
  1413. clean_text = linesep.join(unicode_text.splitlines())
  1414. if unicode_text.endswith(u'\n'):
  1415. clean_text += linesep
  1416. if not isinstance(text, six.text_type):
  1417. return salt.utils.stringutils.to_bytes(clean_text)
  1418. return clean_text