def test_mixed_unicode_str(self): # from Python 2.7 test suite def test(expected, fmt, *args, **kwargs): self.assertEqual(f(fmt).format(*args, **kwargs), expected) # test mixing unicode and str self.assertEqual(_strformat(u'abc', 's'), u'abc') self.assertEqual(_strformat(u'abc', '->10s'), u'-------abc') # test combining string and unicode test(u'foobar', u"foo{0}", 'bar') # This will try to convert the argument from unicode to str, which # will succeed test('foobar', "foo{0}", u'bar') # This will try to convert the argument from unicode to str, which # will fail self.assertRaises(UnicodeEncodeError, f("foo{0}").format, u'\u1000bar')
def _format_field(value, parts, conv, spec, want_bytes=False): for k, part, _ in parts: if k: if part.isdigit(): value = value[int(part)] else: value = value[part] else: value = getattr(value, part) if conv: value = ((conv == 'r') and '%r' or '%s') % (value,) format_value = getattr(value, '__format__', None) if format_value and (hasattr(value, 'strftime') or not isinstance(format_value, builtin_function_or_method)): value = format_value(spec) else: # Skip the __format__ method for builtin types value = _strformat(value, spec) if want_bytes and isinstance(value, unicode): return str(value) return value
def _check_strformat(self, expected, fmt, value): value, expected = self._prepare(value, expected) # test both with and without the trailing 's' self.assertEqual(_strformat(value, fmt), expected) self.assertEqual(_strformat(value, fmt + 's'), expected)