OILS / data_lang / pretty_test.py View on Github | oilshell.org

115 lines, 87 significant
1#!/usr/bin/env python2
2# coding=utf8
3
4import os
5import unittest
6
7from _devbuild.gen.value_asdl import value, value_t
8from core import ansi
9from data_lang import j8
10from data_lang import pretty # module under test
11from mycpp import mylib, mops
12from typing import Optional
13
14import libc
15
16TEST_DATA_FILENAME = os.path.join(os.path.dirname(__file__), "pretty_test.txt")
17
18
19def IntValue(i):
20 # type: (int) -> value_t
21 return value.Int(mops.IntWiden(i))
22
23
24class PrettyTest(unittest.TestCase):
25
26 @classmethod
27 def setUpClass(cls):
28 # Use settings that make testing easier.
29 cls.printer = pretty.PrettyPrinter()
30 cls.printer.SetUseStyles(False)
31 cls.printer.SetShowTypePrefix(False)
32 # NOTE: We don't SetYshStyle() here ... we changed the format after
33 # writing these tests
34
35 def assertPretty(self, width, value_str, expected, lineno=None):
36 # type: (int, str, str, Optional[int]) -> None
37 parser = j8.Parser(value_str, True)
38 val = parser.ParseValue()
39
40 buf = mylib.BufWriter()
41 self.printer.SetMaxWidth(width)
42 self.printer.PrintValue(val, buf)
43 actual = buf.getvalue()
44
45 if actual != expected:
46 # Print the different with real newlines, for easier reading.
47 print("ACTUAL:")
48 print(actual)
49 print("EXPECTED:")
50 print(expected)
51 print("END")
52 if lineno is not None:
53 print("ON LINE " + str(lineno + 1))
54 self.assertEqual(buf.getvalue(), expected)
55
56 def testsFromFile(self):
57 chunks = [(None, -1, [])]
58 for lineno, line in enumerate(
59 open(TEST_DATA_FILENAME).read().splitlines()):
60 if line.startswith("> "):
61 chunks[-1][2].append(line[2:])
62 elif line.startswith("#"):
63 pass
64 elif line.strip() == "":
65 pass
66 else:
67 for keyword in ["Width", "Input", "Expect"]:
68 if line.startswith(keyword):
69 if chunks[-1][0] != keyword:
70 chunks.append((keyword, lineno, []))
71 parts = line.split(" > ", 1)
72 if len(parts) == 2:
73 chunks[-1][2].append(parts[1])
74 break
75 else:
76 raise Exception(
77 "Invalid pretty printing test case line. Lines must start with one of: Width, Input, Expect, >, #",
78 line)
79
80 test_cases = []
81 width = 80
82 value = ""
83 for (keyword, lineno, lines) in chunks:
84 block = "\n".join(lines)
85 if keyword == "Width":
86 width = int(block)
87 elif keyword == "Input":
88 value = block
89 elif keyword == "Expect":
90 test_cases.append((width, value, block, lineno))
91 else:
92 pass
93
94 for (width, value, expected, lineno) in test_cases:
95 self.assertPretty(width, value, expected, lineno)
96
97 def testStyles(self):
98 self.printer.SetUseStyles(True)
99 self.assertPretty(
100 20, '[null, "ok", 15]', '[' + ansi.BOLD + ansi.RED + 'null' +
101 ansi.RESET + ", " + ansi.GREEN + '"ok"' + ansi.RESET + ", " +
102 ansi.YELLOW + '15' + ansi.RESET + ']')
103 self.printer.SetUseStyles(False)
104
105 def testTypePrefix(self):
106 self.printer.SetShowTypePrefix(True)
107 self.assertPretty(25, '[null, "ok", 15]', '(List) [null, "ok", 15]')
108 self.assertPretty(24, '[null, "ok", 15]', '(List)\n[null, "ok", 15]')
109 self.printer.SetShowTypePrefix(False)
110
111
112if __name__ == '__main__':
113 # To simulate the OVM_MAIN patch in pythonrun.c
114 libc.cpython_reset_locale()
115 unittest.main()