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

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