|
1 | 1 | import unittest |
2 | 2 |
|
| 3 | +_dstring_prefixes = "d db df dt dr drb drf drt".split() |
| 4 | +_dstring_prefixes += [p.upper() for p in _dstring_prefixes] |
3 | 5 |
|
4 | 6 | class DStringTestCase(unittest.TestCase): |
5 | 7 | def assertAllRaise(self, exception_type, regex, error_strings): |
6 | 8 | for str in error_strings: |
7 | 9 | with self.subTest(str=str): |
8 | 10 | with self.assertRaisesRegex(exception_type, regex) as cm: |
9 | 11 | eval(str) |
10 | | - # print("Testing expression:", repr(str)) |
11 | | - # print(repr(cm.exception)) |
12 | | - # print(repr(cm.exception.text)) |
13 | 12 |
|
14 | 13 | def test_single_quote(self): |
15 | 14 | exprs = [ |
16 | | - "d'hello'", |
17 | | - 'D"hello"', |
18 | | - "d'hello\\nworld'", |
| 15 | + f"{p}'hello, world'" for p in _dstring_prefixes |
| 16 | + ] + [ |
| 17 | + f'{p}"hello, world"' for p in _dstring_prefixes |
19 | 18 | ] |
20 | 19 | self.assertAllRaise(SyntaxError, "d-string must be triple-quoted", exprs) |
21 | 20 |
|
22 | 21 | def test_empty_dstring(self): |
23 | 22 | exprs = [ |
24 | | - "d''''''", |
25 | | - 'D""""""', |
| 23 | + f"{p}''''''" for p in _dstring_prefixes |
| 24 | + ] + [ |
| 25 | + f'{p}""""""' for p in _dstring_prefixes |
26 | 26 | ] |
27 | 27 | self.assertAllRaise(SyntaxError, "d-string must start with a newline", exprs) |
28 | 28 |
|
29 | 29 | def test_simple_dstring(self): |
30 | | - self.assertEqual(eval('d"""\n hello world\n """'), "hello world\n") |
31 | | - self.assertEqual(eval('d"""\n hello world\n """'), " hello world\n") |
32 | | - self.assertEqual(eval('d"""\n hello world\n"""'), " hello world\n") |
33 | | - self.assertEqual(eval('d"""\n hello world\\\n """'), " hello world") |
34 | | - self.assertEqual(eval('dr"""\n hello world\\\n """'), " hello world\\\n") |
| 30 | + cases = [ |
| 31 | + ('{prefix}"""\n hello world\n """', "hello world\n"), |
| 32 | + ('{prefix}"""\n hello world\n """', " hello world\n"), |
| 33 | + ('{prefix}"""\n hello world\n"""', " hello world\n"), |
| 34 | + ('{prefix}"""\n hello world\\\n """', " hello world"), |
| 35 | + ('{prefix}"""\n hello world\\\n """', " hello world\\\n"), |
| 36 | + ] |
| 37 | + |
| 38 | + for p in _dstring_prefixes: |
| 39 | + bstring = 'b' in p.lower() |
| 40 | + rstring = 'r' in p.lower() |
| 41 | + for source, expected in cases: |
| 42 | + source = source.format(prefix=p) |
| 43 | + if rstring: |
| 44 | + expected = expected.replace('\\', '\\\\').replace('\n', '\\n') |
| 45 | + if bstring: |
| 46 | + expected = expected.encode() |
| 47 | + self.assertEqual(eval(source), expected) |
35 | 48 |
|
36 | 49 |
|
37 | 50 | if __name__ == '__main__': |
|
0 commit comments