def _check_raises(self, expected_exception, fmt, *args, **kwargs): fmt = self._prepare(fmt) try: f(fmt).format(*args, **kwargs) except expected_exception: pass else: raise self.failureException('%s not raised' % expected_exception.__name__)
def test_format_subclass(self): # from Python 2.7 test suite class U(unicode): def __unicode__(self): return u'__unicode__ overridden' u = U(u'xxx') self.assertEqual("%s" % u, u'__unicode__ overridden') self.assertEqual(f("{}").format(u), '__unicode__ overridden')
def test_format_subclass(self): # from Python 2.7 test suite class U(unicode): if python_3: def __str__(self): return '__unicode__ overridden' else: def __unicode__(self): return u('__unicode__ overridden') s = U('xxx') self.assertEqual(f("{}").format(s), '__unicode__ overridden') self.assertEqual("%s" % s, u('__unicode__ overridden'))
def _test_format(string, *args, **kwargs): """Compare with standard implementation. Return a pair (tuple) of results (standard_result, actual_result). """ # Monkey patch the _format_field to skip builtin method __format__ 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 # Monkey patch the _format_field to skip builtin method __format__ import stringformat as mod original_format_field = mod._format_field mod._format_field = _format_field try: s1 = repr(string.format(*args, **kwargs)) except Exception: s1 = repr_exc() try: try: s2 = repr(f(string).format(*args, **kwargs)) except Exception: s2 = repr_exc() finally: mod._format_field = original_format_field return s1, s2
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 test_format(self): # from Python 2.7 test suite test = self._check_format # Safety check self.assertTrue(hasattr(f(''), 'format')) # def test(expected, fmt, *args, **kwargs): # assert f(fmt).format(*args, **kwargs) == expected test('', '') test('a', 'a') test('ab', 'ab') test('a{', 'a{{') test('a}', 'a}}') test('{b', '{{b') test('}b', '}}b') test('a{b', 'a{{b') # examples from the PEP: test("My name is Fred", "My name is {0}", "Fred") test("My name is Fred", "My name is {0[name]}", dict(name="Fred")) test("My name is Fred :-{}", "My name is {0} :-{{}}", "Fred") import datetime d = datetime.date(2007, 8, 18) test("The year is 2007", "The year is {0.year}", d) # classes we'll use for testing class C: def __init__(self, x=100): self._x = x def __format__(self, spec): return spec class D: def __init__(self, x): self.x = x def __format__(self, spec): return str(self.x) # class with __str__, but no __format__ class E: def __init__(self, x): self.x = x def __str__(self): return 'E(' + self.x + ')' # class with __repr__, but no __format__ or __str__ class F: def __init__(self, x): self.x = x def __repr__(self): return 'F(' + self.x + ')' # class with __format__ that forwards to string, for some format_spec's class G: def __init__(self, x): self.x = x def __str__(self): return "string is " + self.x def __format__(self, format_spec): if format_spec == 'd': return 'G(' + self.x + ')' return object.__format__(self, format_spec) # class that returns a bad type from __format__ class H: def __format__(self, format_spec): return 1.0 class I(datetime.date): def __format__(self, format_spec): return self.strftime(str(format_spec)) class J(int): def __format__(self, format_spec): return int.__format__(self * 2, format_spec) test('abc', 'abc') test('abc', '{0}', 'abc') test('abc', '{0:}', 'abc') test('Xabc', 'X{0}', 'abc') test('abcX', '{0}X', 'abc') test('XabcY', 'X{0}Y', 'abc') test('abc', '{1}', 1, 'abc') test('Xabc', 'X{1}', 1, 'abc') test('abcX', '{1}X', 1, 'abc') test('XabcY', 'X{1}Y', 1, 'abc') test('-15', '{0}', -15) test('-15abc', '{0}{1}', -15, 'abc') test('-15Xabc', '{0}X{1}', -15, 'abc') test('{', '{{') test('}', '}}') test('{}', '{{}}') test('{x}', '{{x}}') test('{123}', '{{{0}}}', 123) test('{{0}}', '{{{{0}}}}') test('}{', '}}{{') test('}x{', '}}x{{') # weird field names test('baz', '{0[foo-bar]}', {'foo-bar': 'baz'}) test('baz', '{0[foo bar]}', {'foo bar': 'baz'}) test('3', '{0[ ]}', {' ': 3}) test('20', '{foo._x}', foo=C(20)) test('2010', '{1}{0}', D(10), D(20)) test('abc', '{0._x.x}', C(D('abc'))) test('abc', '{0[0]}', ['abc', 'def']) test('def', '{0[1]}', ['abc', 'def']) test('def', '{0[1][0]}', ['abc', ['def']]) test('def', '{0[1][0].x}', ['abc', [D('def')]]) # strings test('abc', '{0:.3s}', 'abc') test('ab', '{0:.3s}', 'ab') test('abc', '{0:.3s}', 'abcdef') test('', '{0:.0s}', 'abcdef') test('abc', '{0:3.3s}', 'abc') test('abc', '{0:2.3s}', 'abc') test('ab ', '{0:3.2s}', 'abc') test('result', '{0:x<0s}', 'result') test('result', '{0:x<5s}', 'result') test('result', '{0:x<6s}', 'result') test('resultx', '{0:x<7s}', 'result') test('resultxx', '{0:x<8s}', 'result') test('result ', '{0: <7s}', 'result') test('result ', '{0:<7s}', 'result') test(' result', '{0:>7s}', 'result') test(' result', '{0:>8s}', 'result') test(' result ', '{0:^8s}', 'result') test(' result ', '{0:^9s}', 'result') test(' result ', '{0:^10s}', 'result') test('a' + ' ' * 9999, '{0:10000}', 'a') test(' ' * 10000, '{0:10000}', '') test(' ' * 10000000, '{0:10000000}', '') # format specifiers for user defined type test('abc', '{0:abc}', C()) # !r and !s coercions test('Hello', '{0!s}', 'Hello') test('Hello', '{0!s}', 'Hello') test('Hello ', '{0!s:15}', 'Hello') test('Hello ', '{0!s:15s}', 'Hello') test("'Hello'", '{0!r}', 'Hello') test("'Hello'", '{0!r:}', 'Hello') test('F(Hello)', '{0!r}', F('Hello')) # test fallback to object.__format__ test('{}', '{0}', {}) test('[]', '{0}', []) test('[1]', '{0}', [1]) test('E(data)', '{0}', E('data')) # XXX pending deprecation # * object.__format__ with a non-empty format string is deprecated test(' E(data) ', '{0:^10}', E('data')) test(' E(data) ', '{0:^10s}', E('data')) if has_object_format: test(' string is data', '{0:>15s}', G('data')) test('G(data)', '{0:d}', G('data')) test('string is data', '{0!s}', G('data')) test('date: 2007-08-27', '{0:date: %Y-%m-%d}', I(year=2007, month=8, day=27)) if has_object_format: # test deriving from a builtin type and overriding __format__ test('20', '{0}', J(10)) # string format specifiers test('a', '{0:}', 'a') # computed format specifiers test('hello', '{0:.{1}}', 'hello world', 5) test('hello', '{0:.{1}s}', 'hello world', 5) test('hello', '{0:.{precision}s}', 'hello world', precision=5) test('hello ', '{0:{width}.{precision}s}', 'hello world', width=10, precision=5) test('hello ', '{0:{width}.{precision}s}', 'hello world', width='10', precision='5')
def test(expected, fmt, *args, **kwargs): self.assertEqual(f(fmt).format(*args, **kwargs), expected)
def _check_format(self, expected, fmt, *args, **kwargs): fmt, expected = self._prepare(fmt, expected) self.assertEqual(f(fmt).format(*args, **kwargs), expected)
value = _strformat(value, spec) if want_bytes and isinstance(value, unicode): return str(value) return value # Monkey patch the _format_field to skip builtin method __format__ import stringformat as mod original_format_field = mod._format_field mod._format_field = _format_field try: s1 = repr(string.format(*args, **kwargs)) except Exception, exc: s1 = repr(exc) try: try: s2 = repr(f(string).format(*args, **kwargs)) except Exception, exc: s2 = repr(exc) finally: mod._format_field = original_format_field return s1, s2 _BaseFormatterTest25 = BaseFormatterTest class BaseFormatterTest(_BaseFormatterTest25): def _check_strformat(self, expected, fmt, value): check_strformat = super(BaseFormatterTest, self)._check_strformat check_strformat(expected, fmt, value) value, expected = self._prepare(value, expected)