##// END OF EJS Templates
added path import in test_text
Marin Gilles -
Show More
@@ -1,192 +1,193 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.text"""
2 """Tests for IPython.utils.text"""
3 from __future__ import print_function
3 from __future__ import print_function
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2011 The IPython Development Team
6 # Copyright (C) 2011 The IPython Development Team
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import os
16 import os
17 import math
17 import math
18 import random
18 import random
19 import sys
19 import sys
20
20
21 import nose.tools as nt
21 import nose.tools as nt
22 import path
22
23
23 from IPython.utils import text
24 from IPython.utils import text
24
25
25 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
26 # Globals
27 # Globals
27 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
28
29
29 def test_columnize():
30 def test_columnize():
30 """Basic columnize tests."""
31 """Basic columnize tests."""
31 size = 5
32 size = 5
32 items = [l*size for l in 'abc']
33 items = [l*size for l in 'abc']
33 out = text.columnize(items, displaywidth=80)
34 out = text.columnize(items, displaywidth=80)
34 nt.assert_equal(out, 'aaaaa bbbbb ccccc\n')
35 nt.assert_equal(out, 'aaaaa bbbbb ccccc\n')
35 out = text.columnize(items, displaywidth=12)
36 out = text.columnize(items, displaywidth=12)
36 nt.assert_equal(out, 'aaaaa ccccc\nbbbbb\n')
37 nt.assert_equal(out, 'aaaaa ccccc\nbbbbb\n')
37 out = text.columnize(items, displaywidth=10)
38 out = text.columnize(items, displaywidth=10)
38 nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\n')
39 nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\n')
39
40
40 def test_columnize_random():
41 def test_columnize_random():
41 """Test with random input to hopfully catch edge case """
42 """Test with random input to hopfully catch edge case """
42 for nitems in [random.randint(2,70) for i in range(2,20)]:
43 for nitems in [random.randint(2,70) for i in range(2,20)]:
43 displaywidth = random.randint(20,200)
44 displaywidth = random.randint(20,200)
44 rand_len = [random.randint(2,displaywidth) for i in range(nitems)]
45 rand_len = [random.randint(2,displaywidth) for i in range(nitems)]
45 items = ['x'*l for l in rand_len]
46 items = ['x'*l for l in rand_len]
46 out = text.columnize(items, displaywidth=displaywidth)
47 out = text.columnize(items, displaywidth=displaywidth)
47 longer_line = max([len(x) for x in out.split('\n')])
48 longer_line = max([len(x) for x in out.split('\n')])
48 longer_element = max(rand_len)
49 longer_element = max(rand_len)
49 if longer_line > displaywidth:
50 if longer_line > displaywidth:
50 print("Columnize displayed something lager than displaywidth : %s " % longer_line)
51 print("Columnize displayed something lager than displaywidth : %s " % longer_line)
51 print("longer element : %s " % longer_element)
52 print("longer element : %s " % longer_element)
52 print("displaywidth : %s " % displaywidth)
53 print("displaywidth : %s " % displaywidth)
53 print("number of element : %s " % nitems)
54 print("number of element : %s " % nitems)
54 print("size of each element :\n %s" % rand_len)
55 print("size of each element :\n %s" % rand_len)
55 assert False
56 assert False
56
57
57 def test_columnize_medium():
58 def test_columnize_medium():
58 """Test with inputs than shouldn't be wider tahn 80 """
59 """Test with inputs than shouldn't be wider tahn 80 """
59 size = 40
60 size = 40
60 items = [l*size for l in 'abc']
61 items = [l*size for l in 'abc']
61 out = text.columnize(items, displaywidth=80)
62 out = text.columnize(items, displaywidth=80)
62 nt.assert_equal(out, '\n'.join(items+['']))
63 nt.assert_equal(out, '\n'.join(items+['']))
63
64
64 def test_columnize_long():
65 def test_columnize_long():
65 """Test columnize with inputs longer than the display window"""
66 """Test columnize with inputs longer than the display window"""
66 size = 11
67 size = 11
67 items = [l*size for l in 'abc']
68 items = [l*size for l in 'abc']
68 out = text.columnize(items, displaywidth=size-1)
69 out = text.columnize(items, displaywidth=size-1)
69 nt.assert_equal(out, '\n'.join(items+['']))
70 nt.assert_equal(out, '\n'.join(items+['']))
70
71
71 def eval_formatter_check(f):
72 def eval_formatter_check(f):
72 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"cafΓ©", b="cafΓ©")
73 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"cafΓ©", b="cafΓ©")
73 s = f.format("{n} {n//4} {stuff.split()[0]}", **ns)
74 s = f.format("{n} {n//4} {stuff.split()[0]}", **ns)
74 nt.assert_equal(s, "12 3 hello")
75 nt.assert_equal(s, "12 3 hello")
75 s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns)
76 s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns)
76 nt.assert_equal(s, "12 6 4 3 2 2 1")
77 nt.assert_equal(s, "12 6 4 3 2 2 1")
77 s = f.format('{[n//i for i in range(1,8)]}', **ns)
78 s = f.format('{[n//i for i in range(1,8)]}', **ns)
78 nt.assert_equal(s, "[12, 6, 4, 3, 2, 2, 1]")
79 nt.assert_equal(s, "[12, 6, 4, 3, 2, 2, 1]")
79 s = f.format("{stuff!s}", **ns)
80 s = f.format("{stuff!s}", **ns)
80 nt.assert_equal(s, ns['stuff'])
81 nt.assert_equal(s, ns['stuff'])
81 s = f.format("{stuff!r}", **ns)
82 s = f.format("{stuff!r}", **ns)
82 nt.assert_equal(s, repr(ns['stuff']))
83 nt.assert_equal(s, repr(ns['stuff']))
83
84
84 # Check with unicode:
85 # Check with unicode:
85 s = f.format("{u}", **ns)
86 s = f.format("{u}", **ns)
86 nt.assert_equal(s, ns['u'])
87 nt.assert_equal(s, ns['u'])
87 # This decodes in a platform dependent manner, but it shouldn't error out
88 # This decodes in a platform dependent manner, but it shouldn't error out
88 s = f.format("{b}", **ns)
89 s = f.format("{b}", **ns)
89
90
90 nt.assert_raises(NameError, f.format, '{dne}', **ns)
91 nt.assert_raises(NameError, f.format, '{dne}', **ns)
91
92
92 def eval_formatter_slicing_check(f):
93 def eval_formatter_slicing_check(f):
93 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
94 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
94 s = f.format(" {stuff.split()[:]} ", **ns)
95 s = f.format(" {stuff.split()[:]} ", **ns)
95 nt.assert_equal(s, " ['hello', 'there'] ")
96 nt.assert_equal(s, " ['hello', 'there'] ")
96 s = f.format(" {stuff.split()[::-1]} ", **ns)
97 s = f.format(" {stuff.split()[::-1]} ", **ns)
97 nt.assert_equal(s, " ['there', 'hello'] ")
98 nt.assert_equal(s, " ['there', 'hello'] ")
98 s = f.format("{stuff[::2]}", **ns)
99 s = f.format("{stuff[::2]}", **ns)
99 nt.assert_equal(s, ns['stuff'][::2])
100 nt.assert_equal(s, ns['stuff'][::2])
100
101
101 nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
102 nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
102
103
103 def eval_formatter_no_slicing_check(f):
104 def eval_formatter_no_slicing_check(f):
104 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
105 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
105
106
106 s = f.format('{n:x} {pi**2:+f}', **ns)
107 s = f.format('{n:x} {pi**2:+f}', **ns)
107 nt.assert_equal(s, "c +9.869604")
108 nt.assert_equal(s, "c +9.869604")
108
109
109 s = f.format('{stuff[slice(1,4)]}', **ns)
110 s = f.format('{stuff[slice(1,4)]}', **ns)
110 nt.assert_equal(s, 'ell')
111 nt.assert_equal(s, 'ell')
111
112
112 if sys.version_info >= (3, 4):
113 if sys.version_info >= (3, 4):
113 # String formatting has changed in Python 3.4, so this now works.
114 # String formatting has changed in Python 3.4, so this now works.
114 s = f.format("{a[:]}", a=[1, 2])
115 s = f.format("{a[:]}", a=[1, 2])
115 nt.assert_equal(s, "[1, 2]")
116 nt.assert_equal(s, "[1, 2]")
116 else:
117 else:
117 nt.assert_raises(SyntaxError, f.format, "{a[:]}")
118 nt.assert_raises(SyntaxError, f.format, "{a[:]}")
118
119
119 def test_eval_formatter():
120 def test_eval_formatter():
120 f = text.EvalFormatter()
121 f = text.EvalFormatter()
121 eval_formatter_check(f)
122 eval_formatter_check(f)
122 eval_formatter_no_slicing_check(f)
123 eval_formatter_no_slicing_check(f)
123
124
124 def test_full_eval_formatter():
125 def test_full_eval_formatter():
125 f = text.FullEvalFormatter()
126 f = text.FullEvalFormatter()
126 eval_formatter_check(f)
127 eval_formatter_check(f)
127 eval_formatter_slicing_check(f)
128 eval_formatter_slicing_check(f)
128
129
129 def test_dollar_formatter():
130 def test_dollar_formatter():
130 f = text.DollarFormatter()
131 f = text.DollarFormatter()
131 eval_formatter_check(f)
132 eval_formatter_check(f)
132 eval_formatter_slicing_check(f)
133 eval_formatter_slicing_check(f)
133
134
134 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
135 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
135 s = f.format("$n", **ns)
136 s = f.format("$n", **ns)
136 nt.assert_equal(s, "12")
137 nt.assert_equal(s, "12")
137 s = f.format("$n.real", **ns)
138 s = f.format("$n.real", **ns)
138 nt.assert_equal(s, "12")
139 nt.assert_equal(s, "12")
139 s = f.format("$n/{stuff[:5]}", **ns)
140 s = f.format("$n/{stuff[:5]}", **ns)
140 nt.assert_equal(s, "12/hello")
141 nt.assert_equal(s, "12/hello")
141 s = f.format("$n $$HOME", **ns)
142 s = f.format("$n $$HOME", **ns)
142 nt.assert_equal(s, "12 $HOME")
143 nt.assert_equal(s, "12 $HOME")
143 s = f.format("${foo}", foo="HOME")
144 s = f.format("${foo}", foo="HOME")
144 nt.assert_equal(s, "$HOME")
145 nt.assert_equal(s, "$HOME")
145
146
146
147
147 def test_long_substr():
148 def test_long_substr():
148 data = ['hi']
149 data = ['hi']
149 nt.assert_equal(text.long_substr(data), 'hi')
150 nt.assert_equal(text.long_substr(data), 'hi')
150
151
151
152
152 def test_long_substr2():
153 def test_long_substr2():
153 data = ['abc', 'abd', 'abf', 'ab']
154 data = ['abc', 'abd', 'abf', 'ab']
154 nt.assert_equal(text.long_substr(data), 'ab')
155 nt.assert_equal(text.long_substr(data), 'ab')
155
156
156 def test_long_substr_empty():
157 def test_long_substr_empty():
157 data = []
158 data = []
158 nt.assert_equal(text.long_substr(data), '')
159 nt.assert_equal(text.long_substr(data), '')
159
160
160 def test_strip_email():
161 def test_strip_email():
161 src = """\
162 src = """\
162 >> >>> def f(x):
163 >> >>> def f(x):
163 >> ... return x+1
164 >> ... return x+1
164 >> ...
165 >> ...
165 >> >>> zz = f(2.5)"""
166 >> >>> zz = f(2.5)"""
166 cln = """\
167 cln = """\
167 >>> def f(x):
168 >>> def f(x):
168 ... return x+1
169 ... return x+1
169 ...
170 ...
170 >>> zz = f(2.5)"""
171 >>> zz = f(2.5)"""
171 nt.assert_equal(text.strip_email_quotes(src), cln)
172 nt.assert_equal(text.strip_email_quotes(src), cln)
172
173
173
174
174 def test_strip_email2():
175 def test_strip_email2():
175 src = '> > > list()'
176 src = '> > > list()'
176 cln = 'list()'
177 cln = 'list()'
177 nt.assert_equal(text.strip_email_quotes(src), cln)
178 nt.assert_equal(text.strip_email_quotes(src), cln)
178
179
179 def test_LSString():
180 def test_LSString():
180 lss = text.LSString("abc\ndef")
181 lss = text.LSString("abc\ndef")
181 nt.assert_equal(lss.l, ['abc', 'def'])
182 nt.assert_equal(lss.l, ['abc', 'def'])
182 nt.assert_equal(lss.s, 'abc def')
183 nt.assert_equal(lss.s, 'abc def')
183 lss = text.LSString(os.getcwd())
184 lss = text.LSString(os.getcwd())
184 nt.assert_is_instance(lss.p[0], path.path)
185 nt.assert_is_instance(lss.p[0], path.path)
185
186
186 def test_SList():
187 def test_SList():
187 sl = text.SList(['a 11', 'b 1', 'a 2'])
188 sl = text.SList(['a 11', 'b 1', 'a 2'])
188 nt.assert_equal(sl.n, 'a 11\nb 1\na 2')
189 nt.assert_equal(sl.n, 'a 11\nb 1\na 2')
189 nt.assert_equal(sl.s, 'a 11 b 1 a 2')
190 nt.assert_equal(sl.s, 'a 11 b 1 a 2')
190 nt.assert_equal(sl.grep(lambda x: x.startswith('a')), text.SList(['a 11', 'a 2']))
191 nt.assert_equal(sl.grep(lambda x: x.startswith('a')), text.SList(['a 11', 'a 2']))
191 nt.assert_equal(sl.fields(0), text.SList(['a', 'b', 'a']))
192 nt.assert_equal(sl.fields(0), text.SList(['a', 'b', 'a']))
192 nt.assert_equal(sl.sort(field=1, nums=True), text.SList(['b 1', 'a 2', 'a 11']))
193 nt.assert_equal(sl.sort(field=1, nums=True), text.SList(['b 1', 'a 2', 'a 11']))
General Comments 0
You need to be logged in to leave comments. Login now