|
| 1 | +import pickle |
| 2 | +import unittest |
1 | 3 | from string.templatelib import Template, Interpolation |
2 | 4 |
|
3 | | -from test.test_string._support import TStringTestCase, fstring |
| 5 | +from test.test_string._support import TStringBaseCase, fstring |
4 | 6 |
|
5 | 7 |
|
6 | | -class TestTemplate(TStringTestCase): |
| 8 | +class TestTemplate(unittest.TestCase, TStringBaseCase): |
| 9 | + |
| 10 | + def test_common(self): |
| 11 | + self.assertEqual(type(t'').__name__, 'Template') |
| 12 | + self.assertEqual(type(t'').__qualname__, 'Template') |
| 13 | + self.assertEqual(type(t'').__module__, 'string.templatelib') |
| 14 | + |
| 15 | + a = 'a' |
| 16 | + i = t'{a}'.interpolations[0] |
| 17 | + self.assertEqual(type(i).__name__, 'Interpolation') |
| 18 | + self.assertEqual(type(i).__qualname__, 'Interpolation') |
| 19 | + self.assertEqual(type(i).__module__, 'string.templatelib') |
7 | 20 |
|
8 | 21 | def test_basic_creation(self): |
9 | 22 | # Simple t-string creation |
@@ -53,3 +66,44 @@ def test_creation_interleaving(self): |
53 | 66 | t, ('', '', ''), [('Maria', 'name'), ('Python', 'language')] |
54 | 67 | ) |
55 | 68 | self.assertEqual(fstring(t), 'MariaPython') |
| 69 | + |
| 70 | + def test_pickle_template(self): |
| 71 | + user = 'test' |
| 72 | + for template in ( |
| 73 | + t'', |
| 74 | + t"No values", |
| 75 | + t'With inter {user}', |
| 76 | + t'With ! {user!r}', |
| 77 | + t'With format {1 / 0.3:.2f}', |
| 78 | + Template(), |
| 79 | + Template('a'), |
| 80 | + Template(Interpolation('Nikita', 'name', None, '')), |
| 81 | + Template('a', Interpolation('Nikita', 'name', 'r', '')), |
| 82 | + ): |
| 83 | + for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 84 | + with self.subTest(proto=proto, template=template): |
| 85 | + pickled = pickle.dumps(template, protocol=proto) |
| 86 | + unpickled = pickle.loads(pickled) |
| 87 | + |
| 88 | + self.assertEqual(unpickled.values, template.values) |
| 89 | + self.assertEqual(fstring(unpickled), fstring(template)) |
| 90 | + |
| 91 | + def test_pickle_interpolation(self): |
| 92 | + for interpolation in ( |
| 93 | + Interpolation('Nikita', 'name', None, ''), |
| 94 | + Interpolation('Nikita', 'name', 'r', ''), |
| 95 | + Interpolation(1/3, 'x', None, '.2f'), |
| 96 | + ): |
| 97 | + for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 98 | + with self.subTest(proto=proto, interpolation=interpolation): |
| 99 | + pickled = pickle.dumps(interpolation, protocol=proto) |
| 100 | + unpickled = pickle.loads(pickled) |
| 101 | + |
| 102 | + self.assertEqual(unpickled.value, interpolation.value) |
| 103 | + self.assertEqual(unpickled.expression, interpolation.expression) |
| 104 | + self.assertEqual(unpickled.conversion, interpolation.conversion) |
| 105 | + self.assertEqual(unpickled.format_spec, interpolation.format_spec) |
| 106 | + |
| 107 | + |
| 108 | +if __name__ == '__main__': |
| 109 | + unittest.main() |
0 commit comments