You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compat_tests.py 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. from tempfile import NamedTemporaryFile
  4. from django.utils import six
  5. from django.utils.six.moves import cStringIO
  6. from django.test import TestCase
  7. from oscar.core.compat import UnicodeCSVWriter, existing_user_fields
  8. class unicodeobj(object):
  9. def __init__(self, s):
  10. self.s = s
  11. def __str__(self):
  12. return self.s
  13. def __unicode__(self):
  14. return self.s
  15. class TestExistingUserFields(TestCase):
  16. def test_order(self):
  17. fields = existing_user_fields(['email', 'first_name', 'last_name'])
  18. self.assertEqual(fields, ['email', 'first_name', 'last_name'])
  19. class TestUnicodeCSVWriter(TestCase):
  20. def test_can_write_different_values(self):
  21. writer = UnicodeCSVWriter(open_file=cStringIO())
  22. s = u'ünįcodē'
  23. rows = [[s, unicodeobj(s), 123, datetime.date.today()], ]
  24. writer.writerows(rows)
  25. self.assertRaises(TypeError, writer.writerows, [object()])
  26. def test_context_manager(self):
  27. tmp_file = NamedTemporaryFile()
  28. with UnicodeCSVWriter(filename=tmp_file.name) as writer:
  29. s = u'ünįcodē'
  30. rows = [[s, unicodeobj(s), 123, datetime.date.today()], ]
  31. writer.writerows(rows)
  32. class TestPython3Compatibility(TestCase):
  33. def test_models_define_python_3_compatible_representation(self):
  34. """
  35. In Python 2, models can define __unicode__ to get a text representation,
  36. in Python 3 this is achieved by defining __str__. The
  37. python_2_unicode_compatible decorator helps with that. We must use it
  38. every time we define a text representation; this test checks that it's
  39. used correctly.
  40. """
  41. from django.apps import apps
  42. models = [
  43. model for model in apps.get_models() if 'oscar' in repr(model)]
  44. invalid_models = []
  45. for model in models:
  46. # Use abstract model if it exists
  47. if 'oscar' in repr(model.__base__):
  48. model = model.__base__
  49. dict_ = model.__dict__
  50. if '__str__' in dict_:
  51. if six.PY2:
  52. valid = '__unicode__' in dict_
  53. else:
  54. valid = '__unicode__' not in dict_
  55. else:
  56. valid = '__unicode__' not in dict_
  57. if not valid:
  58. invalid_models.append(model)
  59. if invalid_models:
  60. self.fail(
  61. "Those models don't use the python_2_compatible decorator or define __unicode__: %s" % invalid_models)