_pytest_plugin.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import pytest
  2. # RHEL 7 ships pytest 2.7 which doesn't have the 'bool' type to addini. This
  3. # broke pytest for EPEL: https://bugzilla.redhat.com/show_bug.cgi?id=1605138
  4. # If it's older than 2.9 we handle bool conversion ourselves. Remove this when
  5. # we can rely on a newer pytest.
  6. #
  7. # Version 3 is also where the @yield_fixture decorator was deprecated and you
  8. # can now just use @fixture, so we handle both of those cases as well.
  9. try:
  10. _pytest_version = tuple([
  11. int(x) for x in pytest.__version__.split('.')[:2]
  12. ])
  13. _pytest29 = _pytest_version >= (2, 9)
  14. _pytest30 = _pytest_version >= (3, 0)
  15. except Exception:
  16. _pytest29 = False
  17. _pytest30 = False
  18. if not _pytest29:
  19. _case_type = None
  20. _case_default = 'false'
  21. # Copied from pytest 2.9.0 where bool was introduced. It's what happens
  22. # internally if we specify a bool type argument.
  23. def _strtobool(val):
  24. """Convert a string representation of truth to true (1) or false (0).
  25. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  26. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  27. 'val' is anything else.
  28. .. note:: copied from distutils.util
  29. """
  30. val = val.lower()
  31. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  32. return 1
  33. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  34. return 0
  35. else:
  36. raise ValueError("invalid truth value %r" % (val,))
  37. def _bool_value(value):
  38. return bool(_strtobool(value.strip()))
  39. else:
  40. _case_type = 'bool'
  41. _case_default = False
  42. def _bool_value(value):
  43. return value
  44. if _pytest30:
  45. _fixture_type = pytest.fixture
  46. else:
  47. _fixture_type = pytest.yield_fixture
  48. def pytest_addoption(parser):
  49. parser.addini('requests_mock_case_sensitive',
  50. 'Use case sensitive matching in requests_mock',
  51. type=_case_type,
  52. default=_case_default)
  53. @_fixture_type(scope='function') # executed on every test
  54. def requests_mock(request):
  55. """Mock out the requests component of your code with defined responses.
  56. Mocks out any requests made through the python requests library with useful
  57. responses for unit testing. See:
  58. https://requests-mock.readthedocs.io/en/latest/
  59. """
  60. # pytest plugins get loaded immediately. If we import requests_mock it
  61. # imports requests and then SSL which prevents gevent patching. Late load.
  62. import requests_mock as rm_module
  63. case_sensitive = request.config.getini('requests_mock_case_sensitive')
  64. kw = {'case_sensitive': _bool_value(case_sensitive)}
  65. with rm_module.Mocker(**kw) as m:
  66. yield m