test_userstring.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # UserString is a wrapper around the native builtin string type.
  2. # UserString instances should behave similar to builtin string objects.
  3. import unittest
  4. from test import string_tests
  5. from collections import UserString
  6. class UserStringTest(
  7. string_tests.CommonTest,
  8. string_tests.MixinStrUnicodeUserStringTest,
  9. unittest.TestCase
  10. ):
  11. type2test = UserString
  12. # Overwrite the three testing methods, because UserString
  13. # can't cope with arguments propagated to UserString
  14. # (and we don't test with subclasses)
  15. def checkequal(self, result, object, methodname, *args, **kwargs):
  16. result = self.fixtype(result)
  17. object = self.fixtype(object)
  18. # we don't fix the arguments, because UserString can't cope with it
  19. realresult = getattr(object, methodname)(*args, **kwargs)
  20. self.assertEqual(
  21. result,
  22. realresult
  23. )
  24. def checkraises(self, exc, obj, methodname, *args, expected_msg=None):
  25. obj = self.fixtype(obj)
  26. # we don't fix the arguments, because UserString can't cope with it
  27. with self.assertRaises(exc) as cm:
  28. getattr(obj, methodname)(*args)
  29. self.assertNotEqual(str(cm.exception), '')
  30. if expected_msg is not None:
  31. self.assertEqual(str(cm.exception), expected_msg)
  32. def checkcall(self, object, methodname, *args):
  33. object = self.fixtype(object)
  34. # we don't fix the arguments, because UserString can't cope with it
  35. getattr(object, methodname)(*args)
  36. def test_rmod(self):
  37. class ustr2(UserString):
  38. pass
  39. class ustr3(ustr2):
  40. def __rmod__(self, other):
  41. return super().__rmod__(other)
  42. fmt2 = ustr2('value is %s')
  43. str3 = ustr3('TEST')
  44. self.assertEqual(fmt2 % str3, 'value is TEST')
  45. def test_encode_default_args(self):
  46. self.checkequal(b'hello', 'hello', 'encode')
  47. # Check that encoding defaults to utf-8
  48. self.checkequal(b'\xf0\xa3\x91\x96', '\U00023456', 'encode')
  49. # Check that errors defaults to 'strict'
  50. self.checkraises(UnicodeError, '\ud800', 'encode')
  51. def test_encode_explicit_none_args(self):
  52. self.checkequal(b'hello', 'hello', 'encode', None, None)
  53. # Check that encoding defaults to utf-8
  54. self.checkequal(b'\xf0\xa3\x91\x96', '\U00023456', 'encode', None, None)
  55. # Check that errors defaults to 'strict'
  56. self.checkraises(UnicodeError, '\ud800', 'encode', None, None)
  57. if __name__ == "__main__":
  58. unittest.main()