-
Notifications
You must be signed in to change notification settings - Fork 21
/
test.py
173 lines (140 loc) · 4.84 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from __future__ import print_function
import sys
import ctypes
import textwrap
from nose.tools import assert_equal
from parameterized import parameterized, param
sys.path.append("pp/")
import pp
import pprintpp as p
from pprintpp import Counter, defaultdict, OrderedDict
class PPrintppTestBase(object):
def assertStdout(self, expected, trim=True):
if trim:
expected = textwrap.dedent(expected.rstrip().lstrip("\n"))
# Assumes that nose's capture plugin is active
assert_equal(sys.stdout.getvalue().rstrip(), expected)
class TestPP(PPrintppTestBase):
def test_pp(self):
pp(["hello", "world"])
self.assertStdout("['hello', 'world']")
def test_pp_pprint(self):
pp.pprint("stuff")
self.assertStdout("'stuff'")
def test_fmt(self):
print(pp.pformat("asdf"))
print(pp.fmt("stuff"))
self.assertStdout("""
'asdf'
'stuff'
""")
def test_module_like(self):
print(dir(pp))
print(repr(pp))
class MyDict(dict):
pass
class MyList(list):
pass
class MyTuple(tuple):
pass
class MySet(set):
pass
class MyFrozenSet(frozenset):
pass
class MyOrderedDict(p.OrderedDict):
pass
class MyDefaultDict(p.defaultdict):
pass
class MyCounter(p.Counter):
pass
class MyCounterWithRepr(p.Counter):
def __repr__(self):
return "MyCounterWithRepr('dummy')"
class TestPPrint(PPrintppTestBase):
uni_safe = u"\xe9 \u6f02 \u0e4f \u2661"
uni_unsafe = u"\u200a \u0302 \n"
slashed = lambda s: u"%s'%s'" %(
p.u_prefix,
s.encode("ascii", "backslashreplace").decode("ascii").replace("\n", "\\n")
)
@parameterized([
param("safe", uni_safe, "%s'%s'" %(p.u_prefix, uni_safe)),
param("unsafe", uni_unsafe, slashed(uni_unsafe)),
param("encoding-aware", uni_safe, slashed(uni_safe), encoding="ascii"),
param("high-end-chars", u"\U0002F9B2", slashed(u"\U0002F9B2"), encoding="ascii"),
])
def test_unicode(self, name, input, expected, encoding="utf-8"):
stream = p.TextIO(encoding=encoding)
p.pprint(input, stream=stream)
assert_equal(stream.getvalue().rstrip("\n"), expected)
@parameterized([
param(u"'\\'\"'"),
param(u'"\'"'),
param(u"'\"'"),
param("frozenset(['a', 'b', 'c'])"),
param("set([None, 1, 'a'])"),
param("[]"),
param("[1]"),
param("{}"),
param("{1: 1}"),
param("set()"),
param("set([1])"),
param("frozenset()"),
param("frozenset([1])"),
param("()"),
param("(1, )"),
param("MyDict({})"),
param("MyDict({1: 1})"),
param("MyList([])"),
param("MyList([1])"),
param("MyTuple(())"),
param("MyTuple((1, ))"),
param("MySet()"),
param("MySet([1])"),
param("MyFrozenSet()"),
param("MyFrozenSet([1])"),
] + ([] if not p._test_has_collections else [
param("Counter()"),
param("Counter({1: 1})"),
param("OrderedDict()"),
param("OrderedDict([(1, 1), (5, 5), (2, 2)])"),
param("MyOrderedDict()"),
param("MyOrderedDict([(1, 1)])"),
param("MyCounter()"),
param("MyCounter({1: 1})"),
param("MyCounterWithRepr('dummy')"),
]))
def test_back_and_forth(self, expected):
input = eval(expected)
stream = p.TextIO()
p.pprint(input, stream=stream)
assert_equal(stream.getvalue().rstrip("\n"), expected)
if p._test_has_collections:
@parameterized([
param("defaultdict(%r, {})" %(int, ), defaultdict(int)),
param("defaultdict(%r, {1: 1})" %(int, ), defaultdict(int, [(1, 1)])),
param("MyDefaultDict(%r, {})" %(int, ), MyDefaultDict(int)),
param("MyDefaultDict(%r, {1: 1})" %(int, ), MyDefaultDict(int, [(1, 1)])),
])
def test_expected_input(self, expected, input):
stream = p.TextIO()
p.pprint(input, stream=stream)
assert_equal(stream.getvalue().rstrip("\n"), expected)
def test_unhashable_repr(self):
# In Python 3, C extensions can define a __repr__ method which is an
# instance of `instancemethod`, which is unhashable. It turns out to be
# spectacularly difficult to create an `instancemethod` and attach it to
# a type without using C... so we'll simulate it using a more explicitly
# unhashable type.
# See also: http://stackoverflow.com/q/40876368/71522
class UnhashableCallable(object):
__hash__ = None
def __call__(self):
return "some-repr"
class MyCls(object):
__repr__ = UnhashableCallable()
obj = MyCls()
assert_equal(p.pformat(obj), "some-repr")
if __name__ == "__main__":
import nose
nose.main()