test_custom_matchers.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 requests_mock
  14. from . import base
  15. class FailMatcher(object):
  16. def __init___(self):
  17. self.called = False
  18. def __call__(self, request):
  19. self.called = True
  20. return None
  21. def match_all(request):
  22. return requests_mock.create_response(request, content=b'data')
  23. class CustomMatchersTests(base.TestCase):
  24. def assertMatchAll(self, resp):
  25. self.assertEqual(200, resp.status_code)
  26. self.assertEqual(resp.text, u'data')
  27. @requests_mock.Mocker()
  28. def test_custom_matcher(self, mocker):
  29. mocker.add_matcher(match_all)
  30. resp = requests.get('http://any/thing')
  31. self.assertMatchAll(resp)
  32. @requests_mock.Mocker()
  33. def test_failing_matcher(self, mocker):
  34. failer = FailMatcher()
  35. mocker.add_matcher(match_all)
  36. mocker.add_matcher(failer)
  37. resp = requests.get('http://any/thing')
  38. self.assertMatchAll(resp)
  39. self.assertTrue(failer.called)
  40. @requests_mock.Mocker()
  41. def test_some_pass(self, mocker):
  42. def matcher_a(request):
  43. if 'a' in request.url:
  44. return match_all(request)
  45. return None
  46. mocker.add_matcher(matcher_a)
  47. resp = requests.get('http://any/thing')
  48. self.assertMatchAll(resp)
  49. self.assertRaises(requests_mock.NoMockAddress,
  50. requests.get,
  51. 'http://other/thing')