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.StringLikeTest, 11 unittest.TestCase 12 ): 13 14 type2test = UserString 15 16 # Overwrite the three testing methods, because UserString 17 # can't cope with arguments propagated to UserString 18 # (and we don't test with subclasses) 19 def checkequal(self, result, object, methodname, *args, **kwargs): 20 result = self.fixtype(result) 21 object = self.fixtype(object) 22 # we don't fix the arguments, because UserString can't cope with it 23 realresult = getattr(object, methodname)(*args, **kwargs) 24 self.assertEqual( 25 result, 26 realresult 27 ) 28 29 def checkraises(self, exc, obj, methodname, *args, expected_msg=None): 30 obj = self.fixtype(obj) 31 # we don't fix the arguments, because UserString can't cope with it 32 with self.assertRaises(exc) as cm: 33 getattr(obj, methodname)(*args) 34 self.assertNotEqual(str(cm.exception), '') 35 if expected_msg is not None: 36 self.assertEqual(str(cm.exception), expected_msg) 37 38 def checkcall(self, object, methodname, *args): 39 object = self.fixtype(object) 40 # we don't fix the arguments, because UserString can't cope with it 41 getattr(object, methodname)(*args) 42 43 def test_rmod(self): 44 class ustr2(UserString): 45 pass 46 47 class ustr3(ustr2): 48 def __rmod__(self, other): 49 return super().__rmod__(other) 50 51 fmt2 = ustr2('value is %s') 52 str3 = ustr3('TEST') 53 self.assertEqual(fmt2 % str3, 'value is TEST') 54 55 def test_encode_default_args(self): 56 self.checkequal(b'hello', 'hello', 'encode') 57 # Check that encoding defaults to utf-8 58 self.checkequal(b'\xf0\xa3\x91\x96', '\U00023456', 'encode') 59 # Check that errors defaults to 'strict' 60 self.checkraises(UnicodeError, '\ud800', 'encode') 61 62 def test_encode_explicit_none_args(self): 63 self.checkequal(b'hello', 'hello', 'encode', None, None) 64 # Check that encoding defaults to utf-8 65 self.checkequal(b'\xf0\xa3\x91\x96', '\U00023456', 'encode', None, None) 66 # Check that errors defaults to 'strict' 67 self.checkraises(UnicodeError, '\ud800', 'encode', None, None) 68 69 70if __name__ == "__main__": 71 unittest.main() 72