|
1 | 1 | import unittest |
2 | 2 | import sys |
3 | 3 | from io import StringIO |
| 4 | +from pprint import PrettyPrinter |
4 | 5 |
|
5 | 6 | from test import support |
6 | 7 |
|
@@ -200,5 +201,44 @@ def test_string_in_loop_on_same_line(self): |
200 | 201 | str(context.exception)) |
201 | 202 |
|
202 | 203 |
|
| 204 | +class PPrintable: |
| 205 | + def __pprint__(self, context, maxlevels, level): |
| 206 | + return 'I feel pretty' |
| 207 | + |
| 208 | + |
| 209 | +class PrettySmart(PrettyPrinter): |
| 210 | + def pformat(self, obj): |
| 211 | + if isinstance(obj, str): |
| 212 | + return obj |
| 213 | + return super().pformat(obj) |
| 214 | + |
| 215 | + |
| 216 | +class TestPrettyPrinting(unittest.TestCase): |
| 217 | + """Test the optional `pretty` keyword argument.""" |
| 218 | + |
| 219 | + def setUp(self): |
| 220 | + self.file = StringIO() |
| 221 | + |
| 222 | + def test_default_pretty(self): |
| 223 | + print('one', 2, file=self.file, pretty=None) |
| 224 | + self.assertEqual(self.file.getvalue(), 'one 2\n') |
| 225 | + |
| 226 | + def test_default_pretty_printer(self): |
| 227 | + print('one', 2, file=self.file, pretty=True) |
| 228 | + self.assertEqual(self.file.getvalue(), "'one' 2\n") |
| 229 | + |
| 230 | + def test_pprint_magic(self): |
| 231 | + print('one', PPrintable(), 2, file=self.file, pretty=True) |
| 232 | + self.assertEqual(self.file.getvalue(), "'one' I feel pretty 2\n") |
| 233 | + |
| 234 | + def test_custom_pprinter(self): |
| 235 | + print('one', PPrintable(), 2, file=self.file, pretty=PrettySmart()) |
| 236 | + self.assertEqual(self.file.getvalue(), "one I feel pretty 2\n") |
| 237 | + |
| 238 | + def test_bad_pprinter(self): |
| 239 | + with self.assertRaises(AttributeError): |
| 240 | + print('one', PPrintable(), 2, file=self.file, pretty=object()) |
| 241 | + |
| 242 | + |
203 | 243 | if __name__ == "__main__": |
204 | 244 | unittest.main() |
0 commit comments