__init__.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. import json
  5. from django.test import TestCase as DjangoTestCase
  6. from django.utils.encoding import smart_text
  7. from django.utils.functional import wraps
  8. from mock import patch
  9. from django_browserid.auth import BrowserIDBackend
  10. from django_browserid.base import MockVerifier
  11. def fake_create_user(email):
  12. pass
  13. class mock_browserid(object):
  14. """
  15. Mock verification in :class:`django_browserid.auth.BrowserIDBackend`.
  16. Can be used as a context manager or as a decorator:
  17. with mock_browserid('a@b.com'):
  18. django_browserid.verify('random-token') # = {'status': 'okay',
  19. # 'email': 'a@b.com',
  20. # ...}
  21. @mock_browserid(None)
  22. def browserid_test():
  23. django_browserid.verify('random-token') # = False
  24. """
  25. def __init__(self, email, **kwargs):
  26. """
  27. :param email:
  28. Email to return in the verification result. If None, the verification will fail.
  29. :param kwargs:
  30. Keyword arguments are passed on to :class:`django_browserid.base.MockVerifier`, which
  31. updates the verification result with them.
  32. """
  33. self.patcher = patch.object(BrowserIDBackend, 'get_verifier')
  34. self.return_value = MockVerifier(email, **kwargs)
  35. def __enter__(self):
  36. mock = self.patcher.start()
  37. mock.return_value = self.return_value
  38. return mock
  39. def __exit__(self, exc_type, exc_value, traceback):
  40. self.patcher.stop()
  41. def __call__(self, func):
  42. @wraps(func)
  43. def inner(*args, **kwargs):
  44. with self:
  45. return func(*args, **kwargs)
  46. return inner
  47. class TestCase(DjangoTestCase):
  48. def assert_json_equals(self, json_str, value):
  49. return self.assertEqual(json.loads(smart_text(json_str)), value)
  50. def shortDescription(self):
  51. # Stop nose using the test docstring and instead the test method
  52. # name.
  53. pass
  54. class JSON_STRING(object):
  55. """
  56. Test object that is considered equal to any string that, when
  57. decoded as JSON, is equal to the value passed in the constructor.
  58. Useful for testing against JSON strings with dicts where the key
  59. ordering doesn't matter.
  60. """
  61. def __init__(self, value):
  62. self.value = value
  63. def __eq__(self, other):
  64. return json.loads(other) == self.value
  65. def __ne__(self, other):
  66. return not self.__eq__(other)
  67. def __repr__(self):
  68. return '<JSON_STRING {0}>'.format(self.value)