test_util.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import json
  2. from django.core.exceptions import ImproperlyConfigured
  3. from django.test.utils import override_settings
  4. from django.utils import six
  5. from django.utils.functional import lazy
  6. from django_browserid.tests import TestCase
  7. from django_browserid.util import import_from_setting, LazyEncoder, same_origin
  8. def _lazy_string():
  9. return 'blah'
  10. lazy_string = lazy(_lazy_string, six.text_type)()
  11. class TestLazyEncoder(TestCase):
  12. def test_lazy(self):
  13. thing = ['foo', lazy_string]
  14. thing_json = json.dumps(thing, cls=LazyEncoder)
  15. self.assertEqual('["foo", "blah"]', thing_json)
  16. import_value = 1
  17. class ImportFromSettingTests(TestCase):
  18. def test_no_setting(self):
  19. """If the setting doesn't exist, raise ImproperlyConfigured."""
  20. with self.assertRaises(ImproperlyConfigured):
  21. import_from_setting('DOES_NOT_EXIST')
  22. @override_settings(TEST_SETTING={})
  23. def test_invalid_import(self):
  24. """
  25. If the setting isn't a proper string, raise
  26. ImproperlyConfigured.
  27. """
  28. with self.assertRaises(ImproperlyConfigured):
  29. import_from_setting('TEST_SETTING')
  30. @override_settings(TEST_SETTING='does.not.exist')
  31. def test_error_importing(self):
  32. """
  33. If there is an error importing the module, raise
  34. ImproperlyConfigured.
  35. """
  36. with self.assertRaises(ImproperlyConfigured):
  37. import_from_setting('TEST_SETTING')
  38. @override_settings(TEST_SETTING='django_browserid.tests.test_util.missing_value')
  39. def test_missing_attribute(self):
  40. """
  41. If the module is imported, but the function isn't found, raise
  42. ImproperlyConfigured.
  43. """
  44. with self.assertRaises(ImproperlyConfigured):
  45. import_from_setting('TEST_SETTING')
  46. @override_settings(TEST_SETTING='django_browserid.tests.test_util.import_value')
  47. def test_existing_attribute(self):
  48. """
  49. If the module is imported and has the requested function,
  50. return it.
  51. """
  52. self.assertEqual(import_from_setting('TEST_SETTING'), 1)
  53. class SameOriginTests(TestCase):
  54. def test_match(self):
  55. self.assertTrue(same_origin('https://example.com', 'https://example.com'))
  56. self.assertTrue(same_origin('https://example.com:80', 'https://example.com:80'))
  57. self.assertTrue(same_origin('https://example.com:80/different/path?query=4&five=6',
  58. 'https://example.com:80/no/match#path'))
  59. def test_no_match(self):
  60. self.assertFalse(same_origin('http://example.com', 'http://example.org'))
  61. self.assertFalse(same_origin('https://example.com', 'http://example.com'))
  62. self.assertFalse(same_origin('http://example.com:443', 'http://example.com:80'))