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