test_custom_matchers.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  2. # not use this file except in compliance with the License. You may obtain
  3. # a copy of the License at
  4. #
  5. # https://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  9. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  10. # License for the specific language governing permissions and limitations
  11. # under the License.
  12. import requests
  13. import six
  14. import requests_mock
  15. from . import base
  16. class FailMatcher(object):
  17. def __init___(self):
  18. self.called = False
  19. def __call__(self, request):
  20. self.called = True
  21. return None
  22. def match_all(request):
  23. return requests_mock.create_response(request, content=six.b('data'))
  24. class CustomMatchersTests(base.TestCase):
  25. def assertMatchAll(self, resp):
  26. self.assertEqual(200, resp.status_code)
  27. self.assertEqual(resp.text, six.u('data'))
  28. @requests_mock.Mocker()
  29. def test_custom_matcher(self, mocker):
  30. mocker.add_matcher(match_all)
  31. resp = requests.get('http://any/thing')
  32. self.assertMatchAll(resp)
  33. @requests_mock.Mocker()
  34. def test_failing_matcher(self, mocker):
  35. failer = FailMatcher()
  36. mocker.add_matcher(match_all)
  37. mocker.add_matcher(failer)
  38. resp = requests.get('http://any/thing')
  39. self.assertMatchAll(resp)
  40. self.assertTrue(failer.called)
  41. @requests_mock.Mocker()
  42. def test_some_pass(self, mocker):
  43. def matcher_a(request):
  44. if 'a' in request.url:
  45. return match_all(request)
  46. return None
  47. mocker.add_matcher(matcher_a)
  48. resp = requests.get('http://any/thing')
  49. self.assertMatchAll(resp)
  50. self.assertRaises(requests_mock.NoMockAddress,
  51. requests.get,
  52. 'http://other/thing')