##// END OF EJS Templates
Merge pull request #13098 from Carreau/less-nose-II...
Matthias Bussonnier -
r26735:8dddfe2f merge
parent child Browse files
Show More
@@ -56,7 +56,7 b' def pyfile(fname):'
56
56
57
57
58 def match_pyfiles(f1, f2):
58 def match_pyfiles(f1, f2):
59 nt.assert_equal(pyfile(f1), pyfile(f2))
59 assert pyfile(f1) == pyfile(f2)
60
60
61
61
62 def test_find_file():
62 def test_find_file():
@@ -76,7 +76,7 b' def test_find_file_decorated1():'
76 "My docstring"
76 "My docstring"
77
77
78 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
78 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
79 nt.assert_equal(f.__doc__, "My docstring")
79 assert f.__doc__ == "My docstring"
80
80
81
81
82 def test_find_file_decorated2():
82 def test_find_file_decorated2():
@@ -92,7 +92,7 b' def test_find_file_decorated2():'
92 "My docstring 2"
92 "My docstring 2"
93
93
94 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
94 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
95 nt.assert_equal(f.__doc__, "My docstring 2")
95 assert f.__doc__ == "My docstring 2"
96
96
97
97
98 def test_find_file_magic():
98 def test_find_file_magic():
@@ -167,41 +167,46 b' class SerialLiar(object):'
167
167
168 def test_info():
168 def test_info():
169 "Check that Inspector.info fills out various fields as expected."
169 "Check that Inspector.info fills out various fields as expected."
170 i = inspector.info(Call, oname='Call')
170 i = inspector.info(Call, oname="Call")
171 nt.assert_equal(i['type_name'], 'type')
171 assert i["type_name"] == "type"
172 expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
172 expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
173 nt.assert_equal(i['base_class'], expted_class)
173 assert i["base_class"] == expted_class
174 nt.assert_regex(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>")
174 nt.assert_regex(
175 i["string_form"],
176 "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>",
177 )
175 fname = __file__
178 fname = __file__
176 if fname.endswith(".pyc"):
179 if fname.endswith(".pyc"):
177 fname = fname[:-1]
180 fname = fname[:-1]
178 # case-insensitive comparison needed on some filesystems
181 # case-insensitive comparison needed on some filesystems
179 # e.g. Windows:
182 # e.g. Windows:
180 nt.assert_equal(i['file'].lower(), compress_user(fname).lower())
183 assert i["file"].lower() == compress_user(fname).lower()
181 nt.assert_equal(i['definition'], None)
184 assert i["definition"] == None
182 nt.assert_equal(i['docstring'], Call.__doc__)
185 assert i["docstring"] == Call.__doc__
183 nt.assert_equal(i['source'], None)
186 assert i["source"] == None
184 nt.assert_true(i['isclass'])
187 nt.assert_true(i["isclass"])
185 nt.assert_equal(i['init_definition'], "Call(x, y=1)")
188 assert i["init_definition"] == "Call(x, y=1)"
186 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
189 assert i["init_docstring"] == Call.__init__.__doc__
187
190
188 i = inspector.info(Call, detail_level=1)
191 i = inspector.info(Call, detail_level=1)
189 nt.assert_not_equal(i['source'], None)
192 nt.assert_not_equal(i["source"], None)
190 nt.assert_equal(i['docstring'], None)
193 assert i["docstring"] == None
191
194
192 c = Call(1)
195 c = Call(1)
193 c.__doc__ = "Modified instance docstring"
196 c.__doc__ = "Modified instance docstring"
194 i = inspector.info(c)
197 i = inspector.info(c)
195 nt.assert_equal(i['type_name'], 'Call')
198 assert i["type_name"] == "Call"
196 nt.assert_equal(i['docstring'], "Modified instance docstring")
199 assert i["docstring"] == "Modified instance docstring"
197 nt.assert_equal(i['class_docstring'], Call.__doc__)
200 assert i["class_docstring"] == Call.__doc__
198 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
201 assert i["init_docstring"] == Call.__init__.__doc__
199 nt.assert_equal(i['call_docstring'], Call.__call__.__doc__)
202 assert i["call_docstring"] == Call.__call__.__doc__
203
200
204
201 def test_class_signature():
205 def test_class_signature():
202 info = inspector.info(HasSignature, 'HasSignature')
206 info = inspector.info(HasSignature, "HasSignature")
203 nt.assert_equal(info['init_definition'], "HasSignature(test)")
207 assert info["init_definition"] == "HasSignature(test)"
204 nt.assert_equal(info['init_docstring'], HasSignature.__init__.__doc__)
208 assert info["init_docstring"] == HasSignature.__init__.__doc__
209
205
210
206 def test_info_awkward():
211 def test_info_awkward():
207 # Just test that this doesn't throw an error.
212 # Just test that this doesn't throw an error.
@@ -231,8 +236,9 b' def f_kwarg(pos, *, kwonly):'
231 pass
236 pass
232
237
233 def test_definition_kwonlyargs():
238 def test_definition_kwonlyargs():
234 i = inspector.info(f_kwarg, oname='f_kwarg') # analysis:ignore
239 i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore
235 nt.assert_equal(i['definition'], "f_kwarg(pos, *, kwonly)")
240 assert i["definition"] == "f_kwarg(pos, *, kwonly)"
241
236
242
237 def test_getdoc():
243 def test_getdoc():
238 class A(object):
244 class A(object):
@@ -253,9 +259,9 b' def test_getdoc():'
253 b = B()
259 b = B()
254 c = C()
260 c = C()
255
261
256 nt.assert_equal(oinspect.getdoc(a), "standard docstring")
262 assert oinspect.getdoc(a) == "standard docstring"
257 nt.assert_equal(oinspect.getdoc(b), "custom docstring")
263 assert oinspect.getdoc(b) == "custom docstring"
258 nt.assert_equal(oinspect.getdoc(c), "standard docstring")
264 assert oinspect.getdoc(c) == "standard docstring"
259
265
260
266
261 def test_empty_property_has_no_source():
267 def test_empty_property_has_no_source():
@@ -299,15 +305,17 b' def test_property_docstring_is_in_info_for_detail_level_0():'
299 """This is `foobar` property."""
305 """This is `foobar` property."""
300 pass
306 pass
301
307
302 ip.user_ns['a_obj'] = A()
308 ip.user_ns["a_obj"] = A()
303 nt.assert_equal(
309 assert (
304 'This is `foobar` property.',
310 "This is `foobar` property."
305 ip.object_inspect('a_obj.foobar', detail_level=0)['docstring'])
311 == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"]
312 )
306
313
307 ip.user_ns['a_cls'] = A
314 ip.user_ns["a_cls"] = A
308 nt.assert_equal(
315 assert (
309 'This is `foobar` property.',
316 "This is `foobar` property."
310 ip.object_inspect('a_cls.foobar', detail_level=0)['docstring'])
317 == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"]
318 )
311
319
312
320
313 def test_pdef():
321 def test_pdef():
@@ -404,7 +412,7 b' def test_render_signature_short():'
404 signature(short_fun),
412 signature(short_fun),
405 short_fun.__name__,
413 short_fun.__name__,
406 )
414 )
407 nt.assert_equal(sig, 'short_fun(a=1)')
415 assert sig == "short_fun(a=1)"
408
416
409
417
410 def test_render_signature_long():
418 def test_render_signature_long():
@@ -15,9 +15,6 b''
15 # Stdlib imports
15 # Stdlib imports
16 import time
16 import time
17
17
18 # Third-party imports
19 import nose.tools as nt
20
21 # Our own imports
18 # Our own imports
22 from IPython.lib import backgroundjobs as bg
19 from IPython.lib import backgroundjobs as bg
23
20
@@ -49,18 +46,18 b' def test_result():'
49 jobs = bg.BackgroundJobManager()
46 jobs = bg.BackgroundJobManager()
50 j = jobs.new(sleeper)
47 j = jobs.new(sleeper)
51 j.join()
48 j.join()
52 nt.assert_equal(j.result['interval'], t_short)
49 assert j.result["interval"] == t_short
53
50
54
51
55 def test_flush():
52 def test_flush():
56 """Test job control"""
53 """Test job control"""
57 jobs = bg.BackgroundJobManager()
54 jobs = bg.BackgroundJobManager()
58 j = jobs.new(sleeper)
55 j = jobs.new(sleeper)
59 j.join()
56 j.join()
60 nt.assert_equal(len(jobs.completed), 1)
57 assert len(jobs.completed) == 1
61 nt.assert_equal(len(jobs.dead), 0)
58 assert len(jobs.dead) == 0
62 jobs.flush()
59 jobs.flush()
63 nt.assert_equal(len(jobs.completed), 0)
60 assert len(jobs.completed) == 0
64
61
65
62
66 def test_dead():
63 def test_dead():
@@ -68,10 +65,10 b' def test_dead():'
68 jobs = bg.BackgroundJobManager()
65 jobs = bg.BackgroundJobManager()
69 j = jobs.new(crasher)
66 j = jobs.new(crasher)
70 j.join()
67 j.join()
71 nt.assert_equal(len(jobs.completed), 0)
68 assert len(jobs.completed) == 0
72 nt.assert_equal(len(jobs.dead), 1)
69 assert len(jobs.dead) == 1
73 jobs.flush()
70 jobs.flush()
74 nt.assert_equal(len(jobs.dead), 0)
71 assert len(jobs.dead) == 0
75
72
76
73
77 def test_longer():
74 def test_longer():
@@ -81,8 +78,8 b' def test_longer():'
81 # job as running, but not so long that it makes the test suite noticeably
78 # job as running, but not so long that it makes the test suite noticeably
82 # slower.
79 # slower.
83 j = jobs.new(sleeper, 0.1)
80 j = jobs.new(sleeper, 0.1)
84 nt.assert_equal(len(jobs.running), 1)
81 assert len(jobs.running) == 1
85 nt.assert_equal(len(jobs.completed), 0)
82 assert len(jobs.completed) == 0
86 j.join()
83 j.join()
87 nt.assert_equal(len(jobs.running), 0)
84 assert len(jobs.running) == 0
88 nt.assert_equal(len(jobs.completed), 1)
85 assert len(jobs.completed) == 1
@@ -59,8 +59,9 b' def test_existing_path_FileLink():'
59 tf = NamedTemporaryFile()
59 tf = NamedTemporaryFile()
60 fl = display.FileLink(tf.name)
60 fl = display.FileLink(tf.name)
61 actual = fl._repr_html_()
61 actual = fl._repr_html_()
62 expected = "<a href='%s' target='_blank'>%s</a><br>" % (tf.name,tf.name)
62 expected = "<a href='%s' target='_blank'>%s</a><br>" % (tf.name, tf.name)
63 nt.assert_equal(actual,expected)
63 assert actual == expected
64
64
65
65 def test_existing_path_FileLink_repr():
66 def test_existing_path_FileLink_repr():
66 """FileLink: Calling repr() functions as expected on existing filepath
67 """FileLink: Calling repr() functions as expected on existing filepath
@@ -69,7 +70,8 b' def test_existing_path_FileLink_repr():'
69 fl = display.FileLink(tf.name)
70 fl = display.FileLink(tf.name)
70 actual = repr(fl)
71 actual = repr(fl)
71 expected = tf.name
72 expected = tf.name
72 nt.assert_equal(actual,expected)
73 assert actual == expected
74
73
75
74 def test_error_on_directory_to_FileLink():
76 def test_error_on_directory_to_FileLink():
75 """FileLink: Raises error when passed directory
77 """FileLink: Raises error when passed directory
@@ -111,7 +113,8 b' def test_existing_path_FileLinks():'
111 (tf1.name.replace("\\","/"),split(tf1.name)[1])]
113 (tf1.name.replace("\\","/"),split(tf1.name)[1])]
112 expected.sort()
114 expected.sort()
113 # We compare the sorted list of links here as that's more reliable
115 # We compare the sorted list of links here as that's more reliable
114 nt.assert_equal(actual,expected)
116 assert actual == expected
117
115
118
116 def test_existing_path_FileLinks_alt_formatter():
119 def test_existing_path_FileLinks_alt_formatter():
117 """FileLinks: Calling _repr_html_ functions as expected w/ an alt formatter
120 """FileLinks: Calling _repr_html_ functions as expected w/ an alt formatter
@@ -128,7 +131,8 b' def test_existing_path_FileLinks_alt_formatter():'
128 expected = ["hello","world"]
131 expected = ["hello","world"]
129 expected.sort()
132 expected.sort()
130 # We compare the sorted list of links here as that's more reliable
133 # We compare the sorted list of links here as that's more reliable
131 nt.assert_equal(actual,expected)
134 assert actual == expected
135
132
136
133 def test_existing_path_FileLinks_repr():
137 def test_existing_path_FileLinks_repr():
134 """FileLinks: Calling repr() functions as expected on existing directory """
138 """FileLinks: Calling repr() functions as expected on existing directory """
@@ -142,8 +146,9 b' def test_existing_path_FileLinks_repr():'
142 expected = ['%s/' % td, ' %s' % split(tf1.name)[1],' %s' % split(tf2.name)[1]]
146 expected = ['%s/' % td, ' %s' % split(tf1.name)[1],' %s' % split(tf2.name)[1]]
143 expected.sort()
147 expected.sort()
144 # We compare the sorted list of links here as that's more reliable
148 # We compare the sorted list of links here as that's more reliable
145 nt.assert_equal(actual,expected)
149 assert actual == expected
146
150
151
147 def test_existing_path_FileLinks_repr_alt_formatter():
152 def test_existing_path_FileLinks_repr_alt_formatter():
148 """FileLinks: Calling repr() functions as expected w/ alt formatter
153 """FileLinks: Calling repr() functions as expected w/ alt formatter
149 """
154 """
@@ -159,8 +164,9 b' def test_existing_path_FileLinks_repr_alt_formatter():'
159 expected = ["hello","world"]
164 expected = ["hello","world"]
160 expected.sort()
165 expected.sort()
161 # We compare the sorted list of links here as that's more reliable
166 # We compare the sorted list of links here as that's more reliable
162 nt.assert_equal(actual,expected)
167 assert actual == expected
163
168
169
164 def test_error_on_file_to_FileLinks():
170 def test_error_on_file_to_FileLinks():
165 """FileLinks: Raises error when passed file
171 """FileLinks: Raises error when passed file
166 """
172 """
@@ -178,11 +184,11 b' def test_recursive_FileLinks():'
178 fl = display.FileLinks(td)
184 fl = display.FileLinks(td)
179 actual = str(fl)
185 actual = str(fl)
180 actual = actual.split('\n')
186 actual = actual.split('\n')
181 nt.assert_equal(len(actual), 4, actual)
187 assert len(actual) == 4, actual
182 fl = display.FileLinks(td, recursive=False)
188 fl = display.FileLinks(td, recursive=False)
183 actual = str(fl)
189 actual = str(fl)
184 actual = actual.split('\n')
190 actual = actual.split('\n')
185 nt.assert_equal(len(actual), 2, actual)
191 assert len(actual) == 2, actual
186
192
187 def test_audio_from_file():
193 def test_audio_from_file():
188 path = pjoin(dirname(__file__), 'test.wav')
194 path = pjoin(dirname(__file__), 'test.wav')
@@ -194,13 +200,13 b' class TestAudioDataWithNumpy(TestCase):'
194 def test_audio_from_numpy_array(self):
200 def test_audio_from_numpy_array(self):
195 test_tone = get_test_tone()
201 test_tone = get_test_tone()
196 audio = display.Audio(test_tone, rate=44100)
202 audio = display.Audio(test_tone, rate=44100)
197 nt.assert_equal(len(read_wav(audio.data)), len(test_tone))
203 assert len(read_wav(audio.data)) == len(test_tone)
198
204
199 @skipif_not_numpy
205 @skipif_not_numpy
200 def test_audio_from_list(self):
206 def test_audio_from_list(self):
201 test_tone = get_test_tone()
207 test_tone = get_test_tone()
202 audio = display.Audio(list(test_tone), rate=44100)
208 audio = display.Audio(list(test_tone), rate=44100)
203 nt.assert_equal(len(read_wav(audio.data)), len(test_tone))
209 assert len(read_wav(audio.data)) == len(test_tone)
204
210
205 @skipif_not_numpy
211 @skipif_not_numpy
206 def test_audio_from_numpy_array_without_rate_raises(self):
212 def test_audio_from_numpy_array_without_rate_raises(self):
@@ -212,7 +218,7 b' class TestAudioDataWithNumpy(TestCase):'
212 for scale in [1, 0.5, 2]:
218 for scale in [1, 0.5, 2]:
213 audio = display.Audio(get_test_tone(scale), rate=44100)
219 audio = display.Audio(get_test_tone(scale), rate=44100)
214 actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
220 actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
215 nt.assert_equal(actual_max_value, expected_max_value)
221 assert actual_max_value == expected_max_value
216
222
217 @skipif_not_numpy
223 @skipif_not_numpy
218 def test_audio_data_without_normalization(self):
224 def test_audio_data_without_normalization(self):
@@ -223,7 +229,7 b' class TestAudioDataWithNumpy(TestCase):'
223 expected_max_value = int(max_int16 * test_tone_max_abs)
229 expected_max_value = int(max_int16 * test_tone_max_abs)
224 audio = display.Audio(test_tone, rate=44100, normalize=False)
230 audio = display.Audio(test_tone, rate=44100, normalize=False)
225 actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
231 actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
226 nt.assert_equal(actual_max_value, expected_max_value)
232 assert actual_max_value == expected_max_value
227
233
228 def test_audio_data_without_normalization_raises_for_invalid_data(self):
234 def test_audio_data_without_normalization_raises_for_invalid_data(self):
229 nt.assert_raises(
235 nt.assert_raises(
@@ -2,8 +2,6 b''
2 import sys
2 import sys
3 from unittest import mock
3 from unittest import mock
4
4
5 import nose.tools as nt
6
7 from IPython import get_ipython
5 from IPython import get_ipython
8 from IPython.lib import editorhooks
6 from IPython.lib import editorhooks
9
7
@@ -20,15 +18,15 b' def test_install_editor():'
20 with mock.patch('subprocess.Popen', fake_popen):
18 with mock.patch('subprocess.Popen', fake_popen):
21 get_ipython().hooks.editor('the file', 64)
19 get_ipython().hooks.editor('the file', 64)
22
20
23 nt.assert_equal(len(called), 1)
21 assert len(called) == 1
24 args = called[0]['args']
22 args = called[0]["args"]
25 kwargs = called[0]['kwargs']
23 kwargs = called[0]["kwargs"]
26
24
27 nt.assert_equal(kwargs, {'shell': True})
25 assert kwargs == {"shell": True}
28
26
29 if sys.platform.startswith('win'):
27 if sys.platform.startswith("win"):
30 expected = ['foo', '-l', '64', '-f', 'the file']
28 expected = ["foo", "-l", "64", "-f", "the file"]
31 else:
29 else:
32 expected = "foo -l 64 -f 'the file'"
30 expected = "foo -l 64 -f 'the file'"
33 cmd = args[0]
31 cmd = args[0]
34 nt.assert_equal(cmd, expected)
32 assert cmd == expected
@@ -25,7 +25,7 b' def test_check_latex_to_png_dvipng_fails_when_no_cmd(command):'
25 raise FindCmdError
25 raise FindCmdError
26
26
27 with patch.object(latextools, "find_cmd", mock_find_cmd):
27 with patch.object(latextools, "find_cmd", mock_find_cmd):
28 assert latextools.latex_to_png_dvipng("whatever", True) == None
28 assert latextools.latex_to_png_dvipng("whatever", True) is None
29
29
30
30
31 @contextmanager
31 @contextmanager
@@ -81,7 +81,7 b' def test_indentation():'
81 gotoutput = pretty.pretty(MyList(range(count)))
81 gotoutput = pretty.pretty(MyList(range(count)))
82 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
82 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
83
83
84 nt.assert_equal(gotoutput, expectedoutput)
84 assert gotoutput == expectedoutput
85
85
86
86
87 def test_dispatch():
87 def test_dispatch():
@@ -92,7 +92,7 b' def test_dispatch():'
92 gotoutput = pretty.pretty(MyDict())
92 gotoutput = pretty.pretty(MyDict())
93 expectedoutput = "MyDict(...)"
93 expectedoutput = "MyDict(...)"
94
94
95 nt.assert_equal(gotoutput, expectedoutput)
95 assert gotoutput == expectedoutput
96
96
97
97
98 def test_callability_checking():
98 def test_callability_checking():
@@ -103,7 +103,7 b' def test_callability_checking():'
103 gotoutput = pretty.pretty(Dummy2())
103 gotoutput = pretty.pretty(Dummy2())
104 expectedoutput = "Dummy1(...)"
104 expectedoutput = "Dummy1(...)"
105
105
106 nt.assert_equal(gotoutput, expectedoutput)
106 assert gotoutput == expectedoutput
107
107
108
108
109 @pytest.mark.parametrize(
109 @pytest.mark.parametrize(
@@ -135,7 +135,7 b' def test_sets(obj, expected_output):'
135 Test that set and frozenset use Python 3 formatting.
135 Test that set and frozenset use Python 3 formatting.
136 """
136 """
137 got_output = pretty.pretty(obj)
137 got_output = pretty.pretty(obj)
138 nt.assert_equal(got_output, expected_output)
138 assert got_output == expected_output
139
139
140
140
141 @skip_without('xxlimited')
141 @skip_without('xxlimited')
@@ -145,22 +145,24 b' def test_pprint_heap_allocated_type():'
145 """
145 """
146 import xxlimited
146 import xxlimited
147 output = pretty.pretty(xxlimited.Null)
147 output = pretty.pretty(xxlimited.Null)
148 nt.assert_equal(output, 'xxlimited.Null')
148 assert output == "xxlimited.Null"
149
149
150
150 def test_pprint_nomod():
151 def test_pprint_nomod():
151 """
152 """
152 Test that pprint works for classes with no __module__.
153 Test that pprint works for classes with no __module__.
153 """
154 """
154 output = pretty.pretty(NoModule)
155 output = pretty.pretty(NoModule)
155 nt.assert_equal(output, 'NoModule')
156 assert output == "NoModule"
156
157
158
157 def test_pprint_break():
159 def test_pprint_break():
158 """
160 """
159 Test that p.break_ produces expected output
161 Test that p.break_ produces expected output
160 """
162 """
161 output = pretty.pretty(Breaking())
163 output = pretty.pretty(Breaking())
162 expected = "TG: Breaking(\n ):"
164 expected = "TG: Breaking(\n ):"
163 nt.assert_equal(output, expected)
165 assert output == expected
164
166
165 def test_pprint_break_repr():
167 def test_pprint_break_repr():
166 """
168 """
@@ -168,11 +170,11 b' def test_pprint_break_repr():'
168 """
170 """
169 output = pretty.pretty([[BreakingRepr()]])
171 output = pretty.pretty([[BreakingRepr()]])
170 expected = "[[Breaking(\n )]]"
172 expected = "[[Breaking(\n )]]"
171 nt.assert_equal(output, expected)
173 assert output == expected
172
174
173 output = pretty.pretty([[BreakingRepr()]*2])
175 output = pretty.pretty([[BreakingRepr()]*2])
174 expected = "[[Breaking(\n ),\n Breaking(\n )]]"
176 expected = "[[Breaking(\n ),\n Breaking(\n )]]"
175 nt.assert_equal(output, expected)
177 assert output == expected
176
178
177 def test_bad_repr():
179 def test_bad_repr():
178 """Don't catch bad repr errors"""
180 """Don't catch bad repr errors"""
@@ -258,7 +260,7 b" ClassWithMeta = MetaClass('ClassWithMeta')"
258
260
259 def test_metaclass_repr():
261 def test_metaclass_repr():
260 output = pretty.pretty(ClassWithMeta)
262 output = pretty.pretty(ClassWithMeta)
261 nt.assert_equal(output, "[CUSTOM REPR FOR CLASS ClassWithMeta]")
263 assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]"
262
264
263
265
264 def test_unicode_repr():
266 def test_unicode_repr():
@@ -271,9 +273,9 b' def test_unicode_repr():'
271
273
272 c = C()
274 c = C()
273 p = pretty.pretty(c)
275 p = pretty.pretty(c)
274 nt.assert_equal(p, u)
276 assert p == u
275 p = pretty.pretty([c])
277 p = pretty.pretty([c])
276 nt.assert_equal(p, u'[%s]' % u)
278 assert p == u"[%s]" % u
277
279
278
280
279 def test_basic_class():
281 def test_basic_class():
@@ -290,10 +292,11 b' def test_basic_class():'
290 printer.flush()
292 printer.flush()
291 output = stream.getvalue()
293 output = stream.getvalue()
292
294
293 nt.assert_equal(output, '%s.MyObj' % __name__)
295 assert output == "%s.MyObj" % __name__
294 nt.assert_true(type_pprint_wrapper.called)
296 nt.assert_true(type_pprint_wrapper.called)
295
297
296
298
299 # TODO : pytest.mark.parametrise once nose is gone.
297 def test_collections_defaultdict():
300 def test_collections_defaultdict():
298 # Create defaultdicts with cycles
301 # Create defaultdicts with cycles
299 a = defaultdict()
302 a = defaultdict()
@@ -311,9 +314,10 b' def test_collections_defaultdict():'
311 (b, "defaultdict(list, {'key': defaultdict(...)})"),
314 (b, "defaultdict(list, {'key': defaultdict(...)})"),
312 ]
315 ]
313 for obj, expected in cases:
316 for obj, expected in cases:
314 nt.assert_equal(pretty.pretty(obj), expected)
317 assert pretty.pretty(obj) == expected
315
318
316
319
320 # TODO : pytest.mark.parametrise once nose is gone.
317 def test_collections_ordereddict():
321 def test_collections_ordereddict():
318 # Create OrderedDict with cycle
322 # Create OrderedDict with cycle
319 a = OrderedDict()
323 a = OrderedDict()
@@ -335,9 +339,10 b' def test_collections_ordereddict():'
335 (a, "OrderedDict([('key', OrderedDict(...))])"),
339 (a, "OrderedDict([('key', OrderedDict(...))])"),
336 ]
340 ]
337 for obj, expected in cases:
341 for obj, expected in cases:
338 nt.assert_equal(pretty.pretty(obj), expected)
342 assert pretty.pretty(obj) == expected
339
343
340
344
345 # TODO : pytest.mark.parametrise once nose is gone.
341 def test_collections_deque():
346 def test_collections_deque():
342 # Create deque with cycle
347 # Create deque with cycle
343 a = deque()
348 a = deque()
@@ -369,8 +374,10 b' def test_collections_deque():'
369 (a, 'deque([deque(...)])'),
374 (a, 'deque([deque(...)])'),
370 ]
375 ]
371 for obj, expected in cases:
376 for obj, expected in cases:
372 nt.assert_equal(pretty.pretty(obj), expected)
377 assert pretty.pretty(obj) == expected
373
378
379
380 # TODO : pytest.mark.parametrise once nose is gone.
374 def test_collections_counter():
381 def test_collections_counter():
375 class MyCounter(Counter):
382 class MyCounter(Counter):
376 pass
383 pass
@@ -380,8 +387,9 b' def test_collections_counter():'
380 (MyCounter(a=1), "MyCounter({'a': 1})"),
387 (MyCounter(a=1), "MyCounter({'a': 1})"),
381 ]
388 ]
382 for obj, expected in cases:
389 for obj, expected in cases:
383 nt.assert_equal(pretty.pretty(obj), expected)
390 assert pretty.pretty(obj) == expected
384
391
392 # TODO : pytest.mark.parametrise once nose is gone.
385 def test_mappingproxy():
393 def test_mappingproxy():
386 MP = types.MappingProxyType
394 MP = types.MappingProxyType
387 underlying_dict = {}
395 underlying_dict = {}
@@ -424,9 +432,10 b' def test_mappingproxy():'
424 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
432 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
425 ]
433 ]
426 for obj, expected in cases:
434 for obj, expected in cases:
427 nt.assert_equal(pretty.pretty(obj), expected)
435 assert pretty.pretty(obj) == expected
428
436
429
437
438 # TODO : pytest.mark.parametrise once nose is gone.
430 def test_simplenamespace():
439 def test_simplenamespace():
431 SN = types.SimpleNamespace
440 SN = types.SimpleNamespace
432
441
@@ -444,7 +453,7 b' def test_simplenamespace():'
444 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
453 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
445 ]
454 ]
446 for obj, expected in cases:
455 for obj, expected in cases:
447 nt.assert_equal(pretty.pretty(obj), expected)
456 assert pretty.pretty(obj) == expected
448
457
449
458
450 def test_pretty_environ():
459 def test_pretty_environ():
@@ -452,7 +461,7 b' def test_pretty_environ():'
452 # reindent to align with 'environ' prefix
461 # reindent to align with 'environ' prefix
453 dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
462 dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
454 env_repr = pretty.pretty(os.environ)
463 env_repr = pretty.pretty(os.environ)
455 nt.assert_equal(env_repr, 'environ' + dict_indented)
464 assert env_repr == "environ" + dict_indented
456
465
457
466
458 def test_function_pretty():
467 def test_function_pretty():
@@ -460,8 +469,9 b' def test_function_pretty():'
460 # posixpath is a pure python module, its interface is consistent
469 # posixpath is a pure python module, its interface is consistent
461 # across Python distributions
470 # across Python distributions
462 import posixpath
471 import posixpath
463 nt.assert_equal(pretty.pretty(posixpath.join), '<function posixpath.join(a, *p)>')
472
464
473 assert pretty.pretty(posixpath.join) == "<function posixpath.join(a, *p)>"
474
465 # custom function
475 # custom function
466 def meaning_of_life(question=None):
476 def meaning_of_life(question=None):
467 if question:
477 if question:
@@ -489,4 +499,4 b' def test_custom_repr():'
489 oc = OrderedCounter("abracadabra")
499 oc = OrderedCounter("abracadabra")
490 nt.assert_in("OrderedCounter(OrderedDict", pretty.pretty(oc))
500 nt.assert_in("OrderedCounter(OrderedDict", pretty.pretty(oc))
491
501
492 nt.assert_equal(pretty.pretty(MySet()), 'mine')
502 assert pretty.pretty(MySet()) == "mine"
@@ -1,26 +1,27 b''
1 # coding: utf-8
1 # coding: utf-8
2 from IPython.lib import passwd
2 from IPython.lib import passwd
3 from IPython.lib.security import passwd_check, salt_len
3 from IPython.lib.security import passwd_check, salt_len
4 import nose.tools as nt
5
4
6 def test_passwd_structure():
5 def test_passwd_structure():
7 p = passwd('passphrase')
6 p = passwd("passphrase")
8 algorithm, salt, hashed = p.split(':')
7 algorithm, salt, hashed = p.split(":")
9 nt.assert_equal(algorithm, 'sha1')
8 assert algorithm == "sha1"
10 nt.assert_equal(len(salt), salt_len)
9 assert len(salt) == salt_len
11 nt.assert_equal(len(hashed), 40)
10 assert len(hashed) == 40
12
11
13 def test_roundtrip():
12 def test_roundtrip():
14 p = passwd('passphrase')
13 p = passwd("passphrase")
15 nt.assert_equal(passwd_check(p, 'passphrase'), True)
14 assert passwd_check(p, "passphrase") is True
15
16
16
17 def test_bad():
17 def test_bad():
18 p = passwd('passphrase')
18 p = passwd('passphrase')
19 nt.assert_equal(passwd_check(p, p), False)
19 assert passwd_check(p, p) is False
20 nt.assert_equal(passwd_check(p, 'a:b:c:d'), False)
20 assert passwd_check(p, "a:b:c:d") is False
21 nt.assert_equal(passwd_check(p, 'a:b'), False)
21 assert passwd_check(p, "a:b") is False
22
22
23
23 def test_passwd_check_unicode():
24 def test_passwd_check_unicode():
24 # GH issue #4524
25 # GH issue #4524
25 phash = u'sha1:23862bc21dd3:7a415a95ae4580582e314072143d9c382c491e4f'
26 phash = u'sha1:23862bc21dd3:7a415a95ae4580582e314072143d9c382c491e4f'
26 assert passwd_check(phash, u"Ε‚e¢ŧ←↓→") No newline at end of file
27 assert passwd_check(phash, u"Ε‚e¢ŧ←↓→")
@@ -15,7 +15,6 b''
15
15
16 import sys
16 import sys
17
17
18 import nose.tools as nt
19 import pytest
18 import pytest
20
19
21 from IPython.testing.decorators import skip_iptest_but_not_pytest
20 from IPython.testing.decorators import skip_iptest_but_not_pytest
@@ -75,18 +74,18 b' def test_rich_output_empty(method_mime):'
75 """RichOutput with no args"""
74 """RichOutput with no args"""
76 rich = capture.RichOutput()
75 rich = capture.RichOutput()
77 method, mime = method_mime
76 method, mime = method_mime
78 nt.assert_equal(getattr(rich, method)(), None)
77 assert getattr(rich, method)() is None
79
78
80 def test_rich_output():
79 def test_rich_output():
81 """test RichOutput basics"""
80 """test RichOutput basics"""
82 data = basic_data
81 data = basic_data
83 metadata = basic_metadata
82 metadata = basic_metadata
84 rich = capture.RichOutput(data=data, metadata=metadata)
83 rich = capture.RichOutput(data=data, metadata=metadata)
85 nt.assert_equal(rich._repr_html_(), data["text/html"])
84 assert rich._repr_html_() == data["text/html"]
86 nt.assert_equal(rich._repr_png_(), (data["image/png"], metadata["image/png"]))
85 assert rich._repr_png_() == (data["image/png"], metadata["image/png"])
87 nt.assert_equal(rich._repr_latex_(), None)
86 assert rich._repr_latex_() is None
88 nt.assert_equal(rich._repr_javascript_(), None)
87 assert rich._repr_javascript_() is None
89 nt.assert_equal(rich._repr_svg_(), None)
88 assert rich._repr_svg_() is None
90
89
91
90
92 @skip_iptest_but_not_pytest
91 @skip_iptest_but_not_pytest
@@ -96,7 +95,7 b' def test_rich_output_no_metadata(method_mime):'
96 data = full_data
95 data = full_data
97 rich = capture.RichOutput(data=data)
96 rich = capture.RichOutput(data=data)
98 method, mime = method_mime
97 method, mime = method_mime
99 nt.assert_equal(getattr(rich, method)(), data[mime])
98 assert getattr(rich, method)() == data[mime]
100
99
101
100
102 @skip_iptest_but_not_pytest
101 @skip_iptest_but_not_pytest
@@ -107,7 +106,7 b' def test_rich_output_metadata(method_mime):'
107 metadata = full_metadata
106 metadata = full_metadata
108 rich = capture.RichOutput(data=data, metadata=metadata)
107 rich = capture.RichOutput(data=data, metadata=metadata)
109 method, mime = method_mime
108 method, mime = method_mime
110 nt.assert_equal(getattr(rich, method)(), (data[mime], metadata[mime]))
109 assert getattr(rich, method)() == (data[mime], metadata[mime])
111
110
112 def test_rich_output_display():
111 def test_rich_output_display():
113 """test RichOutput.display
112 """test RichOutput.display
@@ -119,10 +118,10 b' def test_rich_output_display():'
119 rich = capture.RichOutput(data=data)
118 rich = capture.RichOutput(data=data)
120 with capture.capture_output() as cap:
119 with capture.capture_output() as cap:
121 rich.display()
120 rich.display()
122 nt.assert_equal(len(cap.outputs), 1)
121 assert len(cap.outputs) == 1
123 rich2 = cap.outputs[0]
122 rich2 = cap.outputs[0]
124 nt.assert_equal(rich2.data, rich.data)
123 assert rich2.data == rich.data
125 nt.assert_equal(rich2.metadata, rich.metadata)
124 assert rich2.metadata == rich.metadata
126
125
127 def test_capture_output():
126 def test_capture_output():
128 """capture_output works"""
127 """capture_output works"""
@@ -131,8 +130,8 b' def test_capture_output():'
131 print(hello_stdout, end="")
130 print(hello_stdout, end="")
132 print(hello_stderr, end="", file=sys.stderr)
131 print(hello_stderr, end="", file=sys.stderr)
133 rich.display()
132 rich.display()
134 nt.assert_equal(hello_stdout, cap.stdout)
133 assert hello_stdout == cap.stdout
135 nt.assert_equal(hello_stderr, cap.stderr)
134 assert hello_stderr == cap.stderr
136
135
137
136
138 def test_capture_output_no_stdout():
137 def test_capture_output_no_stdout():
@@ -142,9 +141,9 b' def test_capture_output_no_stdout():'
142 print(hello_stdout, end="")
141 print(hello_stdout, end="")
143 print(hello_stderr, end="", file=sys.stderr)
142 print(hello_stderr, end="", file=sys.stderr)
144 rich.display()
143 rich.display()
145 nt.assert_equal("", cap.stdout)
144 assert "" == cap.stdout
146 nt.assert_equal(hello_stderr, cap.stderr)
145 assert hello_stderr == cap.stderr
147 nt.assert_equal(len(cap.outputs), 1)
146 assert len(cap.outputs) == 1
148
147
149
148
150 def test_capture_output_no_stderr():
149 def test_capture_output_no_stderr():
@@ -155,9 +154,9 b' def test_capture_output_no_stderr():'
155 print(hello_stdout, end="")
154 print(hello_stdout, end="")
156 print(hello_stderr, end="", file=sys.stderr)
155 print(hello_stderr, end="", file=sys.stderr)
157 rich.display()
156 rich.display()
158 nt.assert_equal(hello_stdout, cap.stdout)
157 assert hello_stdout == cap.stdout
159 nt.assert_equal("", cap.stderr)
158 assert "" == cap.stderr
160 nt.assert_equal(len(cap.outputs), 1)
159 assert len(cap.outputs) == 1
161
160
162
161
163 def test_capture_output_no_display():
162 def test_capture_output_no_display():
@@ -167,6 +166,6 b' def test_capture_output_no_display():'
167 print(hello_stdout, end="")
166 print(hello_stdout, end="")
168 print(hello_stderr, end="", file=sys.stderr)
167 print(hello_stderr, end="", file=sys.stderr)
169 rich.display()
168 rich.display()
170 nt.assert_equal(hello_stdout, cap.stdout)
169 assert hello_stdout == cap.stdout
171 nt.assert_equal(hello_stderr, cap.stderr)
170 assert hello_stderr == cap.stderr
172 nt.assert_equal(cap.outputs, [])
171 assert cap.outputs == []
@@ -113,7 +113,7 b' def test_get_home_dir_1():'
113 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
113 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
114
114
115 home_dir = path.get_home_dir()
115 home_dir = path.get_home_dir()
116 nt.assert_equal(home_dir, unfrozen)
116 assert home_dir == unfrozen
117
117
118
118
119 @skip_if_not_win32
119 @skip_if_not_win32
@@ -127,7 +127,7 b' def test_get_home_dir_2():'
127 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
127 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
128
128
129 home_dir = path.get_home_dir(True)
129 home_dir = path.get_home_dir(True)
130 nt.assert_equal(home_dir, unfrozen)
130 assert home_dir == unfrozen
131
131
132
132
133 @skip_win32_py38
133 @skip_win32_py38
@@ -137,7 +137,7 b' def test_get_home_dir_3():'
137 env["HOME"] = HOME_TEST_DIR
137 env["HOME"] = HOME_TEST_DIR
138 home_dir = path.get_home_dir(True)
138 home_dir = path.get_home_dir(True)
139 # get_home_dir expands symlinks
139 # get_home_dir expands symlinks
140 nt.assert_equal(home_dir, os.path.realpath(env["HOME"]))
140 assert home_dir == os.path.realpath(env["HOME"])
141
141
142
142
143 @with_environment
143 @with_environment
@@ -181,7 +181,7 b' def test_get_home_dir_8():'
181 with patch.object(wreg, 'OpenKey', return_value=key()), \
181 with patch.object(wreg, 'OpenKey', return_value=key()), \
182 patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]):
182 patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]):
183 home_dir = path.get_home_dir()
183 home_dir = path.get_home_dir()
184 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
184 assert home_dir == abspath(HOME_TEST_DIR)
185
185
186 @with_environment
186 @with_environment
187 def test_get_xdg_dir_0():
187 def test_get_xdg_dir_0():
@@ -195,7 +195,7 b' def test_get_xdg_dir_0():'
195 env.pop('IPYTHONDIR', None)
195 env.pop('IPYTHONDIR', None)
196 env.pop('XDG_CONFIG_HOME', None)
196 env.pop('XDG_CONFIG_HOME', None)
197
197
198 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
198 assert path.get_xdg_dir() == os.path.join("somewhere", ".config")
199
199
200
200
201 @with_environment
201 @with_environment
@@ -208,7 +208,7 b' def test_get_xdg_dir_1():'
208 env.pop('IPYTHON_DIR', None)
208 env.pop('IPYTHON_DIR', None)
209 env.pop('IPYTHONDIR', None)
209 env.pop('IPYTHONDIR', None)
210 env.pop('XDG_CONFIG_HOME', None)
210 env.pop('XDG_CONFIG_HOME', None)
211 nt.assert_equal(path.get_xdg_dir(), None)
211 assert path.get_xdg_dir() is None
212
212
213 @with_environment
213 @with_environment
214 def test_get_xdg_dir_2():
214 def test_get_xdg_dir_2():
@@ -224,7 +224,7 b' def test_get_xdg_dir_2():'
224 if not os.path.exists(cfgdir):
224 if not os.path.exists(cfgdir):
225 os.makedirs(cfgdir)
225 os.makedirs(cfgdir)
226
226
227 nt.assert_equal(path.get_xdg_dir(), cfgdir)
227 assert path.get_xdg_dir() == cfgdir
228
228
229 @with_environment
229 @with_environment
230 def test_get_xdg_dir_3():
230 def test_get_xdg_dir_3():
@@ -240,7 +240,7 b' def test_get_xdg_dir_3():'
240 if not os.path.exists(cfgdir):
240 if not os.path.exists(cfgdir):
241 os.makedirs(cfgdir)
241 os.makedirs(cfgdir)
242
242
243 nt.assert_equal(path.get_xdg_dir(), None)
243 assert path.get_xdg_dir() is None
244
244
245 def test_filefind():
245 def test_filefind():
246 """Various tests for filefind"""
246 """Various tests for filefind"""
@@ -263,13 +263,13 b' def test_get_long_path_name_win32():'
263 # Test to see if the short path evaluates correctly.
263 # Test to see if the short path evaluates correctly.
264 short_path = os.path.join(tmpdir, 'THISIS~1')
264 short_path = os.path.join(tmpdir, 'THISIS~1')
265 evaluated_path = path.get_long_path_name(short_path)
265 evaluated_path = path.get_long_path_name(short_path)
266 nt.assert_equal(evaluated_path.lower(), long_path.lower())
266 assert evaluated_path.lower() == long_path.lower()
267
267
268
268
269 @dec.skip_win32
269 @dec.skip_win32
270 def test_get_long_path_name():
270 def test_get_long_path_name():
271 p = path.get_long_path_name('/usr/local')
271 p = path.get_long_path_name("/usr/local")
272 nt.assert_equal(p,'/usr/local')
272 assert p == "/usr/local"
273
273
274
274
275 class TestRaiseDeprecation(unittest.TestCase):
275 class TestRaiseDeprecation(unittest.TestCase):
@@ -300,18 +300,18 b' class TestRaiseDeprecation(unittest.TestCase):'
300 @with_environment
300 @with_environment
301 def test_get_py_filename():
301 def test_get_py_filename():
302 os.chdir(TMP_TEST_DIR)
302 os.chdir(TMP_TEST_DIR)
303 with make_tempfile('foo.py'):
303 with make_tempfile("foo.py"):
304 nt.assert_equal(path.get_py_filename('foo.py'), 'foo.py')
304 assert path.get_py_filename("foo.py") == "foo.py"
305 nt.assert_equal(path.get_py_filename('foo'), 'foo.py')
305 assert path.get_py_filename("foo") == "foo.py"
306 with make_tempfile('foo'):
306 with make_tempfile("foo"):
307 nt.assert_equal(path.get_py_filename('foo'), 'foo')
307 assert path.get_py_filename("foo") == "foo"
308 nt.assert_raises(IOError, path.get_py_filename, 'foo.py')
308 nt.assert_raises(IOError, path.get_py_filename, "foo.py")
309 nt.assert_raises(IOError, path.get_py_filename, 'foo')
309 nt.assert_raises(IOError, path.get_py_filename, "foo")
310 nt.assert_raises(IOError, path.get_py_filename, 'foo.py')
310 nt.assert_raises(IOError, path.get_py_filename, "foo.py")
311 true_fn = 'foo with spaces.py'
311 true_fn = "foo with spaces.py"
312 with make_tempfile(true_fn):
312 with make_tempfile(true_fn):
313 nt.assert_equal(path.get_py_filename('foo with spaces'), true_fn)
313 assert path.get_py_filename("foo with spaces") == true_fn
314 nt.assert_equal(path.get_py_filename('foo with spaces.py'), true_fn)
314 assert path.get_py_filename("foo with spaces.py") == true_fn
315 nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"')
315 nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"')
316 nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'")
316 nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'")
317
317
@@ -361,8 +361,7 b' class TestShellGlob(unittest.TestCase):'
361 def check_match(self, patterns, matches):
361 def check_match(self, patterns, matches):
362 with self.in_tempdir():
362 with self.in_tempdir():
363 # glob returns unordered list. that's why sorted is required.
363 # glob returns unordered list. that's why sorted is required.
364 nt.assert_equal(sorted(path.shellglob(patterns)),
364 assert sorted(path.shellglob(patterns)) == sorted(matches)
365 sorted(matches))
366
365
367 def common_cases(self):
366 def common_cases(self):
368 return [
367 return [
@@ -397,12 +396,13 b' class TestShellGlob(unittest.TestCase):'
397 yield (self.check_match, patterns, matches)
396 yield (self.check_match, patterns, matches)
398
397
399
398
399 # TODO : pytest.mark.parametrise once nose is gone.
400 def test_unescape_glob():
400 def test_unescape_glob():
401 nt.assert_equal(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?')
401 assert path.unescape_glob(r"\*\[\!\]\?") == "*[!]?"
402 nt.assert_equal(path.unescape_glob(r'\\*'), r'\*')
402 assert path.unescape_glob(r"\\*") == r"\*"
403 nt.assert_equal(path.unescape_glob(r'\\\*'), r'\*')
403 assert path.unescape_glob(r"\\\*") == r"\*"
404 nt.assert_equal(path.unescape_glob(r'\\a'), r'\a')
404 assert path.unescape_glob(r"\\a") == r"\a"
405 nt.assert_equal(path.unescape_glob(r'\a'), r'\a')
405 assert path.unescape_glob(r"\a") == r"\a"
406
406
407
407
408 @onlyif_unicode_paths
408 @onlyif_unicode_paths
@@ -431,17 +431,19 b' class TestLinkOrCopy(unittest.TestCase):'
431 return os.path.join(self.tempdir.name, *args)
431 return os.path.join(self.tempdir.name, *args)
432
432
433 def assert_inode_not_equal(self, a, b):
433 def assert_inode_not_equal(self, a, b):
434 nt.assert_not_equal(os.stat(a).st_ino, os.stat(b).st_ino,
434 assert (
435 "%r and %r do reference the same indoes" %(a, b))
435 os.stat(a).st_ino != os.stat(b).st_ino
436 ), "%r and %r do reference the same indoes" % (a, b)
436
437
437 def assert_inode_equal(self, a, b):
438 def assert_inode_equal(self, a, b):
438 nt.assert_equal(os.stat(a).st_ino, os.stat(b).st_ino,
439 assert (
439 "%r and %r do not reference the same indoes" %(a, b))
440 os.stat(a).st_ino == os.stat(b).st_ino
441 ), "%r and %r do not reference the same indoes" % (a, b)
440
442
441 def assert_content_equal(self, a, b):
443 def assert_content_equal(self, a, b):
442 with open(a) as a_f:
444 with open(a) as a_f:
443 with open(b) as b_f:
445 with open(b) as b_f:
444 nt.assert_equal(a_f.read(), b_f.read())
446 assert a_f.read() == b_f.read()
445
447
446 @skip_win32
448 @skip_win32
447 def test_link_successful(self):
449 def test_link_successful(self):
@@ -489,4 +491,4 b' class TestLinkOrCopy(unittest.TestCase):'
489 path.link_or_copy(self.src, dst)
491 path.link_or_copy(self.src, dst)
490 path.link_or_copy(self.src, dst)
492 path.link_or_copy(self.src, dst)
491 self.assert_inode_equal(self.src, dst)
493 self.assert_inode_equal(self.src, dst)
492 nt.assert_equal(sorted(os.listdir(self.tempdir.name)), ['src', 'target'])
494 assert sorted(os.listdir(self.tempdir.name)) == ["src", "target"]
@@ -66,7 +66,8 b' def test_find_cmd_fail():'
66 """Make sure that FindCmdError is raised if we can't find the cmd."""
66 """Make sure that FindCmdError is raised if we can't find the cmd."""
67 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
67 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
68
68
69
69
70 # TODO: move to pytest.mark.parametrize once nose gone
70 @dec.skip_win32
71 @dec.skip_win32
71 def test_arg_split():
72 def test_arg_split():
72 """Ensure that argument lines are correctly split like in a shell."""
73 """Ensure that argument lines are correctly split like in a shell."""
@@ -80,8 +81,10 b' def test_arg_split():'
80 ['something "with quotes"', ['something', '"with quotes"']],
81 ['something "with quotes"', ['something', '"with quotes"']],
81 ]
82 ]
82 for argstr, argv in tests:
83 for argstr, argv in tests:
83 nt.assert_equal(arg_split(argstr), argv)
84 assert arg_split(argstr) == argv
84
85
86
87 # TODO: move to pytest.mark.parametrize once nose gone
85 @dec.skip_if_not_win32
88 @dec.skip_if_not_win32
86 def test_arg_split_win32():
89 def test_arg_split_win32():
87 """Ensure that argument lines are correctly split like in a shell."""
90 """Ensure that argument lines are correctly split like in a shell."""
@@ -92,7 +95,7 b' def test_arg_split_win32():'
92 ['something "with quotes"', ['something', 'with quotes']],
95 ['something "with quotes"', ['something', 'with quotes']],
93 ]
96 ]
94 for argstr, argv in tests:
97 for argstr, argv in tests:
95 nt.assert_equal(arg_split(argstr), argv)
98 assert arg_split(argstr) == argv
96
99
97
100
98 class SubProcessTestCase(tt.TempFileMixin):
101 class SubProcessTestCase(tt.TempFileMixin):
@@ -32,31 +32,31 b' def test_columnize():'
32 items = [l*size for l in 'abcd']
32 items = [l*size for l in 'abcd']
33
33
34 out = text.columnize(items, displaywidth=80)
34 out = text.columnize(items, displaywidth=80)
35 nt.assert_equal(out, 'aaaaa bbbbb ccccc ddddd\n')
35 assert out == "aaaaa bbbbb ccccc ddddd\n"
36 out = text.columnize(items, displaywidth=25)
36 out = text.columnize(items, displaywidth=25)
37 nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
37 assert out == "aaaaa ccccc\nbbbbb ddddd\n"
38 out = text.columnize(items, displaywidth=12)
38 out = text.columnize(items, displaywidth=12)
39 nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
39 assert out == "aaaaa ccccc\nbbbbb ddddd\n"
40 out = text.columnize(items, displaywidth=10)
40 out = text.columnize(items, displaywidth=10)
41 nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\nddddd\n')
41 assert out == "aaaaa\nbbbbb\nccccc\nddddd\n"
42
42
43 out = text.columnize(items, row_first=True, displaywidth=80)
43 out = text.columnize(items, row_first=True, displaywidth=80)
44 nt.assert_equal(out, 'aaaaa bbbbb ccccc ddddd\n')
44 assert out == "aaaaa bbbbb ccccc ddddd\n"
45 out = text.columnize(items, row_first=True, displaywidth=25)
45 out = text.columnize(items, row_first=True, displaywidth=25)
46 nt.assert_equal(out, 'aaaaa bbbbb\nccccc ddddd\n')
46 assert out == "aaaaa bbbbb\nccccc ddddd\n"
47 out = text.columnize(items, row_first=True, displaywidth=12)
47 out = text.columnize(items, row_first=True, displaywidth=12)
48 nt.assert_equal(out, 'aaaaa bbbbb\nccccc ddddd\n')
48 assert out == "aaaaa bbbbb\nccccc ddddd\n"
49 out = text.columnize(items, row_first=True, displaywidth=10)
49 out = text.columnize(items, row_first=True, displaywidth=10)
50 nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\nddddd\n')
50 assert out == "aaaaa\nbbbbb\nccccc\nddddd\n"
51
51
52 out = text.columnize(items, displaywidth=40, spread=True)
52 out = text.columnize(items, displaywidth=40, spread=True)
53 nt.assert_equal(out, 'aaaaa bbbbb ccccc ddddd\n')
53 assert out == "aaaaa bbbbb ccccc ddddd\n"
54 out = text.columnize(items, displaywidth=20, spread=True)
54 out = text.columnize(items, displaywidth=20, spread=True)
55 nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
55 assert out == "aaaaa ccccc\nbbbbb ddddd\n"
56 out = text.columnize(items, displaywidth=12, spread=True)
56 out = text.columnize(items, displaywidth=12, spread=True)
57 nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
57 assert out == "aaaaa ccccc\nbbbbb ddddd\n"
58 out = text.columnize(items, displaywidth=10, spread=True)
58 out = text.columnize(items, displaywidth=10, spread=True)
59 nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\nddddd\n')
59 assert out == "aaaaa\nbbbbb\nccccc\nddddd\n"
60
60
61
61
62 def test_columnize_random():
62 def test_columnize_random():
@@ -77,38 +77,43 b' def test_columnize_random():'
77 print("size of each element :\n %s" % rand_len)
77 print("size of each element :\n %s" % rand_len)
78 assert False, "row_first={0}".format(row_first)
78 assert False, "row_first={0}".format(row_first)
79
79
80
81 # TODO: pytest mark.parametrize once nose removed.
80 def test_columnize_medium():
82 def test_columnize_medium():
81 """Test with inputs than shouldn't be wider than 80"""
83 """Test with inputs than shouldn't be wider than 80"""
82 size = 40
84 size = 40
83 items = [l*size for l in 'abc']
85 items = [l*size for l in 'abc']
84 for row_first in [True, False]:
86 for row_first in [True, False]:
85 out = text.columnize(items, row_first=row_first, displaywidth=80)
87 out = text.columnize(items, row_first=row_first, displaywidth=80)
86 nt.assert_equal(out, '\n'.join(items+['']), "row_first={0}".format(row_first))
88 assert out == "\n".join(items + [""]), "row_first={0}".format(row_first)
89
87
90
91 # TODO: pytest mark.parametrize once nose removed.
88 def test_columnize_long():
92 def test_columnize_long():
89 """Test columnize with inputs longer than the display window"""
93 """Test columnize with inputs longer than the display window"""
90 size = 11
94 size = 11
91 items = [l*size for l in 'abc']
95 items = [l*size for l in 'abc']
92 for row_first in [True, False]:
96 for row_first in [True, False]:
93 out = text.columnize(items, row_first=row_first, displaywidth=size-1)
97 out = text.columnize(items, row_first=row_first, displaywidth=size - 1)
94 nt.assert_equal(out, '\n'.join(items+['']), "row_first={0}".format(row_first))
98 assert out == "\n".join(items + [""]), "row_first={0}".format(row_first)
99
95
100
96 def eval_formatter_check(f):
101 def eval_formatter_check(f):
97 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"cafΓ©", b="cafΓ©")
102 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"cafΓ©", b="cafΓ©")
98 s = f.format("{n} {n//4} {stuff.split()[0]}", **ns)
103 s = f.format("{n} {n//4} {stuff.split()[0]}", **ns)
99 nt.assert_equal(s, "12 3 hello")
104 assert s == "12 3 hello"
100 s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns)
105 s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns)
101 nt.assert_equal(s, "12 6 4 3 2 2 1")
106 assert s == "12 6 4 3 2 2 1"
102 s = f.format('{[n//i for i in range(1,8)]}', **ns)
107 s = f.format('{[n//i for i in range(1,8)]}', **ns)
103 nt.assert_equal(s, "[12, 6, 4, 3, 2, 2, 1]")
108 assert s == "[12, 6, 4, 3, 2, 2, 1]"
104 s = f.format("{stuff!s}", **ns)
109 s = f.format("{stuff!s}", **ns)
105 nt.assert_equal(s, ns['stuff'])
110 assert s == ns["stuff"]
106 s = f.format("{stuff!r}", **ns)
111 s = f.format("{stuff!r}", **ns)
107 nt.assert_equal(s, repr(ns['stuff']))
112 assert s == repr(ns["stuff"])
108
113
109 # Check with unicode:
114 # Check with unicode:
110 s = f.format("{u}", **ns)
115 s = f.format("{u}", **ns)
111 nt.assert_equal(s, ns['u'])
116 assert s == ns["u"]
112 # This decodes in a platform dependent manner, but it shouldn't error out
117 # This decodes in a platform dependent manner, but it shouldn't error out
113 s = f.format("{b}", **ns)
118 s = f.format("{b}", **ns)
114
119
@@ -117,25 +122,25 b' def eval_formatter_check(f):'
117 def eval_formatter_slicing_check(f):
122 def eval_formatter_slicing_check(f):
118 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
123 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
119 s = f.format(" {stuff.split()[:]} ", **ns)
124 s = f.format(" {stuff.split()[:]} ", **ns)
120 nt.assert_equal(s, " ['hello', 'there'] ")
125 assert s == " ['hello', 'there'] "
121 s = f.format(" {stuff.split()[::-1]} ", **ns)
126 s = f.format(" {stuff.split()[::-1]} ", **ns)
122 nt.assert_equal(s, " ['there', 'hello'] ")
127 assert s == " ['there', 'hello'] "
123 s = f.format("{stuff[::2]}", **ns)
128 s = f.format("{stuff[::2]}", **ns)
124 nt.assert_equal(s, ns['stuff'][::2])
129 assert s == ns["stuff"][::2]
125
130
126 nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
131 nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
127
132
128 def eval_formatter_no_slicing_check(f):
133 def eval_formatter_no_slicing_check(f):
129 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
134 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
130
135
131 s = f.format('{n:x} {pi**2:+f}', **ns)
136 s = f.format('{n:x} {pi**2:+f}', **ns)
132 nt.assert_equal(s, "c +9.869604")
137 assert s == "c +9.869604"
133
138
134 s = f.format('{stuff[slice(1,4)]}', **ns)
139 s = f.format("{stuff[slice(1,4)]}", **ns)
135 nt.assert_equal(s, 'ell')
140 assert s == "ell"
136
141
137 s = f.format("{a[:]}", a=[1, 2])
142 s = f.format("{a[:]}", a=[1, 2])
138 nt.assert_equal(s, "[1, 2]")
143 assert s == "[1, 2]"
139
144
140 def test_eval_formatter():
145 def test_eval_formatter():
141 f = text.EvalFormatter()
146 f = text.EvalFormatter()
@@ -154,15 +159,15 b' def test_dollar_formatter():'
154
159
155 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
160 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
156 s = f.format("$n", **ns)
161 s = f.format("$n", **ns)
157 nt.assert_equal(s, "12")
162 assert s == "12"
158 s = f.format("$n.real", **ns)
163 s = f.format("$n.real", **ns)
159 nt.assert_equal(s, "12")
164 assert s == "12"
160 s = f.format("$n/{stuff[:5]}", **ns)
165 s = f.format("$n/{stuff[:5]}", **ns)
161 nt.assert_equal(s, "12/hello")
166 assert s == "12/hello"
162 s = f.format("$n $$HOME", **ns)
167 s = f.format("$n $$HOME", **ns)
163 nt.assert_equal(s, "12 $HOME")
168 assert s == "12 $HOME"
164 s = f.format("${foo}", foo="HOME")
169 s = f.format("${foo}", foo="HOME")
165 nt.assert_equal(s, "$HOME")
170 assert s == "$HOME"
166
171
167
172
168 def test_strip_email():
173 def test_strip_email():
@@ -176,25 +181,25 b' def test_strip_email():'
176 ... return x+1
181 ... return x+1
177 ...
182 ...
178 >>> zz = f(2.5)"""
183 >>> zz = f(2.5)"""
179 nt.assert_equal(text.strip_email_quotes(src), cln)
184 assert text.strip_email_quotes(src) == cln
180
185
181
186
182 def test_strip_email2():
187 def test_strip_email2():
183 src = '> > > list()'
188 src = '> > > list()'
184 cln = 'list()'
189 cln = 'list()'
185 nt.assert_equal(text.strip_email_quotes(src), cln)
190 assert text.strip_email_quotes(src) == cln
186
191
187 def test_LSString():
192 def test_LSString():
188 lss = text.LSString("abc\ndef")
193 lss = text.LSString("abc\ndef")
189 nt.assert_equal(lss.l, ['abc', 'def'])
194 assert lss.l == ["abc", "def"]
190 nt.assert_equal(lss.s, 'abc def')
195 assert lss.s == "abc def"
191 lss = text.LSString(os.getcwd())
196 lss = text.LSString(os.getcwd())
192 nt.assert_is_instance(lss.p[0], Path)
197 nt.assert_is_instance(lss.p[0], Path)
193
198
194 def test_SList():
199 def test_SList():
195 sl = text.SList(['a 11', 'b 1', 'a 2'])
200 sl = text.SList(["a 11", "b 1", "a 2"])
196 nt.assert_equal(sl.n, 'a 11\nb 1\na 2')
201 assert sl.n == "a 11\nb 1\na 2"
197 nt.assert_equal(sl.s, 'a 11 b 1 a 2')
202 assert sl.s == "a 11 b 1 a 2"
198 nt.assert_equal(sl.grep(lambda x: x.startswith('a')), text.SList(['a 11', 'a 2']))
203 assert sl.grep(lambda x: x.startswith("a")) == text.SList(["a 11", "a 2"])
199 nt.assert_equal(sl.fields(0), text.SList(['a', 'b', 'a']))
204 assert sl.fields(0) == text.SList(["a", "b", "a"])
200 nt.assert_equal(sl.sort(field=1, nums=True), text.SList(['b 1', 'a 2', 'a 11']))
205 assert 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