Completed
Push — master ( c54fdb...c9e533 )
by De
57s
created

RuntimeErrorTests   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
c 2
b 0
f 0
dl 0
loc 29
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A test_max_depth() 0 8 1
A test_dequeue_changed_during_iter() 0 4 1
A test_dict_size_changed_during_iter() 0 6 1
A test_set_changed_size_during_iter() 0 5 1
1
# -*- coding: utf-8
2
"""Unit tests for get_suggestions_for_exception."""
3
from didyoumean_internal import get_suggestions_for_exception, \
4
    STAND_MODULES, AVOID_REC_MESSAGE
5
import didyoumean_common_tests as common
6
import unittest2
7
import didyoumean_re as re
8
import warnings
9
import sys
10
import math
11
import os
12
import tempfile
13
from shutil import rmtree
14
15
16
this_is_a_global_list = []  # Value does not really matter but the type does
17
18
19
def func_gen(name='some_func', param='', body='pass', args=None):
20
    """Generate code corresponding to a function definition.
21
22
    Generate code for function definition (and eventually a call to it).
23
    Parameters are : name (with default), body (with default),
24
    parameters (with default) and arguments to call the functions with (if not
25
    provided or provided None, function call is not included in generated
26
    code).
27
    """
28
    func = "def {0}({1}):\n\t{2}\n".format(name, param, body)
29
    call = "" if args is None else "{0}({1})\n".format(name, args)
30
    return func + call
31
32
33
def my_generator():
34
    """Generate values for testing purposes.
35
36
    my_generator
37
    This is my generator, baby.
38
    """
39
    for i in range(5):
40
        yield i
41
42
43
def endlessly_recursive_func(n):
44
    """Call itself recursively with no end."""
45
    # http://stackoverflow.com/questions/871887/using-exec-with-recursive-functions
46
    return endlessly_recursive_func(n-1)
47
48
49
class FoobarClass():
50
    """Dummy class for testing purposes."""
51
52
    def __init__(self):
53
        """Constructor."""
54
        self.babar = 2
55
56
    @classmethod
57
    def this_is_cls_mthd(cls):
58
        """Just a class method."""
59
        return 5
60
61
    def nameerror_self(self):
62
        """Should be self.babar."""
63
        return babar
64
65
    def nameerror_self2(self):
66
        """Should be self.this_is_cls_mthd (or FoobarClass)."""
67
        return this_is_cls_mthd
68
69
    @classmethod
70
    def nameerror_cls(cls):
71
        """Should be cls.this_is_cls_mthd (or FoobarClass)."""
72
        return this_is_cls_mthd
73
74
    def some_method(self):
75
        """Method for testing purposes."""
76
        pass
77
78
    def some_method2(self, x):
79
        """Method for testing purposes."""
80
        pass
81
82
    def _some_semi_private_method(self):
83
        """Method for testing purposes."""
84
        pass
85
86
    def __some_private_method(self):
87
        """Method for testing purposes."""
88
        pass
89
90
    def some_method_missing_self_arg():
91
        """Method for testing purposes."""
92
        pass
93
94
    def some_method_missing_self_arg2(x):
95
        """Method for testing purposes."""
96
        pass
97
98
    @classmethod
99
    def some_cls_method_missing_cls():
100
        """Class method for testing purposes."""
101
        pass
102
103
    @classmethod
104
    def some_cls_method_missing_cls2(x):
105
        """Class method for testing purposes."""
106
        pass
107
108
109
# Logic to be able to have different tests on various version of Python
110
FIRST_VERSION = (0, 0)
111
LAST_VERSION = (10, 0)
112
ALL_VERSIONS = (FIRST_VERSION, LAST_VERSION)
113
INTERPRETERS = ['cython', 'pypy']
114
115
116
def from_version(version):
117
    """Create tuple describing a range of versions from a given version."""
118
    return (version, LAST_VERSION)
119
120
121
def up_to_version(version):
122
    """Create tuple describing a range of versions up to a given version."""
123
    return (FIRST_VERSION, version)
124
125
126
def version_in_range(version_range):
127
    """Test if current version is in a range version."""
128
    beg, end = version_range
129
    return beg <= sys.version_info < end
130
131
132
def interpreter_in(interpreters):
133
    """Test if current interpreter is in a list of interpreters."""
134
    is_pypy = hasattr(sys, "pypy_translation_info")
135
    interpreter = 'pypy' if is_pypy else 'cython'
136
    return interpreter in interpreters
137
138
139
def format_str(template, *args):
140
    """Format multiple string by using first arg as a template."""
141
    return [template.format(arg) for arg in args]
142
143
144
def listify(value, default):
145
    """Return list from value, using default value if value is None."""
146
    if value is None:
147
        value = default
148
    if not isinstance(value, list):
149
        value = [value]
150
    if default:
151
        assert all(v in default for v in value)
152
    return value
153
154
155
def no_exception(code):
156
    """Helper function to run code and check it works."""
157
    exec(code)
158
159
160
def get_exception(code):
161
    """Helper function to run code and get what it throws."""
162
    try:
163
        no_exception(code)
164
    except:
165
        return sys.exc_info()
166
    assert False, "No exception thrown running\n---\n{0}\n---".format(code)
167
168
169
# NameError for NameErrorTests
170
NAMEERROR = (NameError, re.NAMENOTDEFINED_RE)
171
NAMEERRORBEFOREREF = (NameError, re.VARREFBEFOREASSIGN_RE)
172
UNKNOWN_NAMEERROR = (NameError, None)
173
# UnboundLocalError for UnboundLocalErrorTests
174
UNBOUNDLOCAL = (UnboundLocalError, re.VARREFBEFOREASSIGN_RE)
175
UNKNOWN_UNBOUNDLOCAL = (UnboundLocalError, None)
176
# TypeError for TypeErrorTests
177
NBARGERROR = (TypeError, re.NB_ARG_RE)
178
MISSINGPOSERROR = (TypeError, re.MISSING_POS_ARG_RE)
179
UNHASHABLE = (TypeError, re.UNHASHABLE_RE)
180
UNSUBSCRIPTABLE = (TypeError, re.UNSUBSCRIPTABLE_RE)
181
NOATTRIBUTE_TYPEERROR = (TypeError, re.ATTRIBUTEERROR_RE)
182
UNEXPECTEDKWARG = (TypeError, re.UNEXPECTED_KEYWORDARG_RE)
183
UNEXPECTEDKWARG2 = (TypeError, re.UNEXPECTED_KEYWORDARG2_RE)
184
UNEXPECTEDKWARG3 = (TypeError, re.UNEXPECTED_KEYWORDARG3_RE)
185
UNSUPPORTEDOPERAND = (TypeError, re.UNSUPPORTED_OP_RE)
186
BADOPERANDUNARY = (TypeError, re.BAD_OPERAND_UNARY_RE)
187
OBJECTDOESNOTSUPPORT = (TypeError, re.OBJ_DOES_NOT_SUPPORT_RE)
188
CANNOTCONCAT = (TypeError, re.CANNOT_CONCAT_RE)
189
CANTCONVERT = (TypeError, re.CANT_CONVERT_RE)
190
MUSTBETYPENOTTYPE = (TypeError, re.MUST_BE_TYPE1_NOT_TYPE2_RE)
191
NOTCALLABLE = (TypeError, re.NOT_CALLABLE_RE)
192
DESCREXPECT = (TypeError, re.DESCRIPT_REQUIRES_TYPE_RE)
193
ARGNOTITERABLE = (TypeError, re.ARG_NOT_ITERABLE_RE)
194
MUSTCALLWITHINST = (TypeError, re.MUST_BE_CALLED_WITH_INST_RE)
195
OBJECTHASNOFUNC = (TypeError, re.OBJECT_HAS_NO_FUNC_RE)
196
UNKNOWN_TYPEERROR = (TypeError, None)
197
# ImportError for ImportErrorTests
198
NOMODULE = (ImportError, re.NOMODULE_RE)
199
CANNOTIMPORT = (ImportError, re.CANNOTIMPORT_RE)
200
UNKNOWN_IMPORTERROR = (ImportError, None)
201
# KeyError for KeyErrorTests
202
KEYERROR = (KeyError, None)
203
# IndexError for IndexErrorTests
204
OUTOFRANGE = (IndexError, re.INDEXOUTOFRANGE_RE)
205
# ValueError for ValueErrorTests
206
TOOMANYVALUES = (ValueError, re.TOO_MANY_VALUES_UNPACK_RE)
207
NEEDMOREVALUES = (ValueError, re.NEED_MORE_VALUES_RE)
208
EXPECTEDLENGTH = (ValueError, re.EXPECTED_LENGTH_RE)
209
MATHDOMAIN = (ValueError, re.MATH_DOMAIN_ERROR_RE)
210
ZEROLENERROR = (ValueError, re.ZERO_LEN_FIELD_RE)
211
INVALIDLITERAL = (ValueError, re.INVALID_LITERAL_RE)
212
TIMEDATAFORMAT = (ValueError, re.TIME_DATA_DOES_NOT_MATCH_FORMAT_RE)
213
# AttributeError for AttributeErrorTests
214
ATTRIBUTEERROR = (AttributeError, re.ATTRIBUTEERROR_RE)
215
MODATTRIBUTEERROR = (AttributeError, re.MODULEHASNOATTRIBUTE_RE)
216
UNKNOWN_ATTRIBUTEERROR = (AttributeError, None)
217
# SyntaxError for SyntaxErrorTests
218
INVALIDSYNTAX = (SyntaxError, re.INVALID_SYNTAX_RE)
219
INVALIDTOKEN = (SyntaxError, re.INVALID_TOKEN_RE)
220
NOBINDING = (SyntaxError, re.NO_BINDING_NONLOCAL_RE)
221
OUTSIDEFUNC = (SyntaxError, re.OUTSIDE_FUNCTION_RE)
222
MISSINGPARENT = (SyntaxError, re.MISSING_PARENT_RE)
223
INVALIDCOMP = (SyntaxError, re.INVALID_COMP_RE)
224
FUTUREFIRST = (SyntaxError, re.FUTURE_FIRST_RE)
225
FUTFEATNOTDEF = (SyntaxError, re.FUTURE_FEATURE_NOT_DEF_RE)
226
UNQUALIFIED_EXEC = (SyntaxError, re.UNQUALIFIED_EXEC_RE)
227
IMPORTSTAR = (SyntaxError, re.IMPORTSTAR_RE)
228
# MemoryError and OverflowError for MemoryErrorTests
229
MEMORYERROR = (MemoryError, '')
230
OVERFLOWERR = (OverflowError, re.RESULT_TOO_MANY_ITEMS_RE)
231
# IOError
232
NOFILE_IO = (common.NoFileIoError, re.NO_SUCH_FILE_RE)
233
NOFILE_OS = (common.NoFileOsError, re.NO_SUCH_FILE_RE)
234
NOTADIR_IO = (common.NotDirIoError, "^Not a directory$")
235
NOTADIR_OS = (common.NotDirOsError, "^Not a directory$")
236
ISADIR_IO = (common.IsDirIoError, "^Is a directory$")
237
ISADIR_OS = (common.IsDirOsError, "^Is a directory$")
238
DIRNOTEMPTY_OS = (OSError, "^Directory not empty$")
239
# RuntimeError
240
MAXRECURDEPTH = (RuntimeError, re.MAX_RECURSION_DEPTH_RE)
241
SIZECHANGEDDURINGITER = (RuntimeError, re.SIZE_CHANGED_DURING_ITER_RE)
242
243
244
class GetSuggestionsTests(unittest2.TestCase):
245
    """Generic class to test get_suggestions_for_exception.
246
247
    Many tests do not correspond to any handled exceptions but are
248
    kept because it is quite convenient to have a large panel of examples.
249
    Also, some correspond to example where suggestions could be added, those
250
    are flagged with a NICE_TO_HAVE comment.
251
    Finally, whenever it is easily possible, the code with the suggestions
252
    taken into account is usually tested too to ensure that the suggestion does
253
    work.
254
    """
255
256
    def runs(self, code, version_range=None, interpreters=None):
257
        """Helper function to run code.
258
259
        version_range and interpreters can be provided if the test depends on
260
        the used environment.
261
        """
262
        interpreters = listify(interpreters, INTERPRETERS)
263
        if version_range is None:
264
            version_range = ALL_VERSIONS
265
        if version_in_range(version_range) and interpreter_in(interpreters):
266
            no_exception(code)
267
268
    def throws(self, code, error_info,
269
               sugg=None, version_range=None, interpreters=None):
270
        """Run code and check it throws and relevant suggestions are provided.
271
272
        Helper function to run code, check that it throws, what it throws and
273
        that the exception leads to the expected suggestions.
274
        version_range and interpreters can be provided if the test depends on
275
        the used environment.
276
        """
277
        if version_range is None:
278
            version_range = ALL_VERSIONS
279
        interpreters = listify(interpreters, INTERPRETERS)
280
        sugg = sorted(listify(sugg, []))
281
        if version_in_range(version_range) and interpreter_in(interpreters):
282
            error_type, error_msg = error_info
283
            type_caught, value, traceback = get_exception(code)
284
            details = "Running following code :\n---\n{0}\n---".format(code)
285
            self.assertTrue(isinstance(value, type_caught))
286
            self.assertTrue(
287
                issubclass(type_caught, error_type),
288
                "{0} ({1}) not a subclass of {2}"
289
                .format(type_caught, value, error_type) + details)
290
            msg = next((a for a in value.args if isinstance(a, str)), '')
291
            if error_msg is not None:
292
                self.assertRegexpMatches(msg, error_msg)
293
            suggestions = sorted(
294
                get_suggestions_for_exception(value, traceback))
295
            self.assertEqual(suggestions, sugg, details)
296
297
298
class NameErrorTests(GetSuggestionsTests):
299
    """Class for tests related to NameError."""
300
301
    def test_local(self):
302
        """Should be 'foo'."""
303
        code = "foo = 0\n{0}"
304
        typo, sugg = "foob", "foo"
305
        bad_code, good_code = format_str(code, typo, sugg)
306
        self.throws(bad_code, NAMEERROR, "'" + sugg + "' (local)")
307
        self.runs(good_code)
308
309
    def test_1_arg(self):
310
        """Should be 'foo'."""
311
        typo, sugg = "foob", "foo"
312
        code = func_gen(param=sugg, body='{0}', args='1')
313
        bad_code, good_code = format_str(code, typo, sugg)
314
        self.throws(bad_code, NAMEERROR, "'" + sugg + "' (local)")
315
        self.runs(good_code)
316
317
    def test_n_args(self):
318
        """Should be 'fool' or 'foot'."""
319
        typo, sugg1, sugg2 = "foob", "foot", "fool"
320
        code = func_gen(param='fool, foot', body='{0}', args='1, 2')
321
        bad, good1, good2 = format_str(code, typo, sugg1, sugg2)
322
        self.throws(bad, NAMEERROR, ["'fool' (local)", "'foot' (local)"])
323
        self.runs(good1)
324
        self.runs(good2)
325
326
    def test_builtin(self):
327
        """Should be 'max'."""
328
        typo, sugg = 'maxi', 'max'
329
        self.throws(typo, NAMEERROR, "'" + sugg + "' (builtin)")
330
        self.runs(sugg)
331
332
    def test_keyword(self):
333
        """Should be 'pass'."""
334
        typo, sugg = 'passs', 'pass'
335
        self.throws(typo, NAMEERROR, "'" + sugg + "' (keyword)")
336
        self.runs(sugg)
337
338
    def test_global(self):
339
        """Should be this_is_a_global_list."""
340
        typo, sugg = 'this_is_a_global_lis', 'this_is_a_global_list'
341
        # just a way to say that this_is_a_global_list is needed in globals
342
        this_is_a_global_list
343
        self.assertFalse(sugg in locals())
344
        self.assertTrue(sugg in globals())
345
        self.throws(typo, NAMEERROR, "'" + sugg + "' (global)")
346
        self.runs(sugg)
347
348
    def test_name(self):
349
        """Should be '__name__'."""
350
        typo, sugg = '__name_', '__name__'
351
        self.throws(typo, NAMEERROR, "'" + sugg + "' (global)")
352
        self.runs(sugg)
353
354
    def test_decorator(self):
355
        """Should be classmethod."""
356
        typo, sugg = "class_method", "classmethod"
357
        code = "@{0}\n" + func_gen()
358
        bad_code, good_code = format_str(code, typo, sugg)
359
        self.throws(bad_code, NAMEERROR, "'" + sugg + "' (builtin)")
360
        self.runs(good_code)
361
362
    def test_import(self):
363
        """Should be math."""
364
        code = 'import math\n{0}'
365
        typo, sugg = 'maths', 'math'
366
        bad_code, good_code = format_str(code, typo, sugg)
367
        self.throws(bad_code, NAMEERROR, "'" + sugg + "' (local)")
368
        self.runs(good_code)
369
370
    def test_import2(self):
371
        """Should be my_imported_math."""
372
        code = 'import math as my_imported_math\n{0}'
373
        typo, sugg = 'my_imported_maths', 'my_imported_math'
374
        bad_code, good_code = format_str(code, typo, sugg)
375
        self.throws(bad_code, NAMEERROR, "'" + sugg + "' (local)")
376
        self.runs(good_code)
377
378
    def test_imported(self):
379
        """Should be math.pi."""
380
        code = 'import math\n{0}'
381
        typo, sugg = 'pi', 'math.pi'
382
        bad_code, good_code = format_str(code, typo, sugg)
383
        self.throws(bad_code, NAMEERROR, "'" + sugg + "'")
384
        self.runs(good_code)
385
386
    def test_imported_twice(self):
387
        """Should be math.pi."""
388
        code = 'import math\nimport math\n{0}'
389
        typo, sugg = 'pi', 'math.pi'
390
        bad_code, good_code = format_str(code, typo, sugg)
391
        self.throws(bad_code, NAMEERROR, "'" + sugg + "'")
392
        self.runs(good_code)
393
394
    def test_not_imported(self):
395
        """Should be random.choice after importing random."""
396
        # This test assumes that `module` is not imported
397
        module, attr = 'random', 'choice'
398
        self.assertFalse(module in locals())
399
        self.assertFalse(module in globals())
400
        self.assertTrue(module in STAND_MODULES)
401
        bad_code = attr
402
        good_code = 'from {0} import {1}\n{2}'.format(module, attr, bad_code)
403
        self.runs(good_code)
404
        self.throws(
405
            bad_code, NAMEERROR,
406
            "'{0}' from {1} (not imported)".format(attr, module))
407
408
    def test_enclosing_scope(self):
409
        """Test that variables from enclosing scope are suggested."""
410
        # NICE_TO_HAVE
411
        typo, sugg = 'foob', 'foo'
412
        code = 'def f():\n\tfoo = 0\n\tdef g():\n\t\t{0}\n\tg()\nf()'
413
        bad_code, good_code = format_str(code, typo, sugg)
414
        self.throws(bad_code, NAMEERROR)
415
        self.runs(good_code)
416
417
    def test_no_sugg(self):
418
        """No suggestion."""
419
        self.throws('a = ldkjhfnvdlkjhvgfdhgf', NAMEERROR)
420
421
    def test_free_var_before_assignment(self):
422
        """No suggestion but different error message."""
423
        code = 'def f():\n\tdef g():\n\t\treturn free_var' \
424
               '\n\tg()\n\tfree_var = 0\nf()'
425
        self.throws(code, NAMEERRORBEFOREREF)
426
427
    # For added/removed names, following functions with one name
428
    # per functions were added in the early stages of the project.
429
    # In the future, I'd like to have them replaced by something
430
    # a bit more concise using relevant data structure. In the
431
    # meantime, I am keeping both versions because safer is better.
432
    def test_removed_cmp(self):
433
        """Builtin cmp is removed."""
434
        # NICE_TO_HAVE
435
        code = 'cmp(1, 2)'
436
        version = (3, 0, 1)
437
        self.runs(code, up_to_version(version))
438
        self.throws(code, NAMEERROR, [], from_version(version))
439
440
    def test_removed_reduce(self):
441
        """Builtin reduce is removed - moved to functools."""
442
        code = 'reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])'
443
        version = (3, 0)
444
        self.runs(code, up_to_version(version))
445
        self.runs('from functools import reduce\n' + code,
446
                  from_version(version))
447
        self.throws(
448
            code,
449
            NAMEERROR,
450
            "'reduce' from functools (not imported)",
451
            from_version(version))
452
453
    def test_removed_apply(self):
454
        """Builtin apply is removed."""
455
        # NICE_TO_HAVE
456
        code = 'apply(sum, [[1, 2, 3]])'
457
        version = (3, 0)
458
        self.runs(code, up_to_version(version))
459
        self.throws(code, NAMEERROR, [], from_version(version))
460
461
    def test_removed_reload(self):
462
        """Builtin reload is removed.
463
464
        Moved to importlib.reload or imp.reload depending on version.
465
        """
466
        # NICE_TO_HAVE
467
        code = 'reload(math)'
468
        version = (3, 0)
469
        self.runs(code, up_to_version(version))
470
        self.throws(code, NAMEERROR, [], from_version(version))
471
472
    def test_removed_intern(self):
473
        """Builtin intern is removed - moved to sys."""
474
        code = 'intern("toto")'
475
        new_code = 'sys.intern("toto")'
476
        version = (3, 0)
477
        self.runs(code, up_to_version(version))
478
        self.throws(
479
            code, NAMEERROR,
480
            ["'iter' (builtin)", "'sys.intern'"],
481
            from_version(version))
482
        self.runs(new_code, from_version(version))
483
484
    def test_removed_execfile(self):
485
        """Builtin execfile is removed - use exec() and compile()."""
486
        # NICE_TO_HAVE
487
        code = 'execfile("some_filename")'
488
        version = (3, 0)
489
        # self.runs(code, up_to_version(version))
490
        self.throws(code, NAMEERROR, [], from_version(version))
491
492
    def test_removed_raw_input(self):
493
        """Builtin raw_input is removed - use input() instead."""
494
        code = 'i = raw_input("Prompt:")'
495
        version = (3, 0)
496
        # self.runs(code, up_to_version(version))
497
        self.throws(
498
            code, NAMEERROR, "'input' (builtin)", from_version(version))
499
500
    def test_removed_buffer(self):
501
        """Builtin buffer is removed - use memoryview instead."""
502
        # NICE_TO_HAVE
503
        code = 'buffer("abc")'
504
        version = (3, 0)
505
        self.runs(code, up_to_version(version))
506
        self.throws(code, NAMEERROR, [], from_version(version))
507
508
    def test_added_2_7(self):
509
        """Test for names added in 2.7."""
510
        version = (2, 7)
511
        for name in ['memoryview']:
512
            self.runs(name, from_version(version))
513
            self.throws(name, NAMEERROR, [], up_to_version(version))
514
515
    def test_removed_3_0(self):
516
        """Test for names removed in 3.0."""
517
        version = (3, 0)
518
        for name, suggs in {
519
                'StandardError': [],  # Exception
520
                'apply': [],
521
                'basestring': [],
522
                'buffer': [],
523
                'cmp': [],
524
                'coerce': [],
525
                'execfile': [],
526
                'file': ["'filter' (builtin)"],
527
                'intern': ["'iter' (builtin)", "'sys.intern'"],
528
                'long': [],
529
                'raw_input': ["'input' (builtin)"],
530
                'reduce': ["'reduce' from functools (not imported)"],
531
                'reload': [],
532
                'unichr': [],
533
                'unicode': ["'code' (local)"],
534
                'xrange': ["'range' (builtin)"],
535
                }.items():
536
            self.throws(name, NAMEERROR, suggs, from_version(version))
537
            self.runs(name, up_to_version(version))
538
539
    def test_added_3_0(self):
540
        """Test for names added in 3.0."""
541
        version = (3, 0)
542
        for name, suggs in {
543
                'ascii': [],
544
                'ResourceWarning': ["'FutureWarning' (builtin)"],
545
                '__build_class__': [],
546
                }.items():
547
            self.runs(name, from_version(version))
548
            self.throws(name, NAMEERROR, suggs, up_to_version(version))
549
550
    def test_added_3_3(self):
551
        """Test for names added in 3.3."""
552
        version = (3, 3)
553
        for name, suggs in {
554
                'BrokenPipeError': [],
555
                'ChildProcessError': [],
556
                'ConnectionAbortedError': [],
557
                'ConnectionError': ["'IndentationError' (builtin)"],
558
                'ConnectionRefusedError': [],
559
                'ConnectionResetError': [],
560
                'FileExistsError': [],
561
                'FileNotFoundError': [],
562
                'InterruptedError': [],
563
                'IsADirectoryError': [],
564
                'NotADirectoryError': [],
565
                'PermissionError': ["'ZeroDivisionError' (builtin)"],
566
                'ProcessLookupError': ["'LookupError' (builtin)"],
567
                'TimeoutError': [],
568
                '__loader__': [],
569
                }.items():
570
            self.runs(name, from_version(version))
571
            self.throws(name, NAMEERROR, suggs, up_to_version(version))
572
573
    def test_added_3_4(self):
574
        """Test for names added in 3.4."""
575
        version = (3, 4)
576
        for name, suggs in {
577
                '__spec__': [],
578
                }.items():
579
            self.runs(name, from_version(version))
580
            self.throws(name, NAMEERROR, suggs, up_to_version(version))
581
582
    def test_added_3_5(self):
583
        """Test for names added in 3.5."""
584
        version = (3, 5)
585
        for name, suggs in {
586
                'StopAsyncIteration': ["'StopIteration' (builtin)"],
587
                }.items():
588
            self.runs(name, from_version(version))
589
            self.throws(name, NAMEERROR, suggs, up_to_version(version))
590
591
    def test_import_sugg(self):
592
        """Should import module first."""
593
        module = 'collections'
594
        sugg = 'import {0}'.format(module)
595
        typo, good_code = module, sugg + '\n' + module
596
        self.assertFalse(module in locals())
597
        self.assertFalse(module in globals())
598
        self.assertTrue(module in STAND_MODULES)
599
        suggestions = (
600
            # module.module is suggested on Python 3.3 :-/
601
            ["'{0}' from {1} (not imported)".format(module, module)]
602
            if version_in_range(((3, 3), (3, 4))) else []) + \
603
            ['to {0} first'.format(sugg)]
604
        self.throws(typo, NAMEERROR, suggestions)
605
        self.runs(good_code)
606
607
    def test_attribute_hidden(self):
608
        """Should be math.pi but module math is hidden."""
609
        math  # just a way to say that math module is needed in globals
610
        self.assertFalse('math' in locals())
611
        self.assertTrue('math' in globals())
612
        code = 'math = ""\npi'
613
        self.throws(code, NAMEERROR, "'math.pi' (global hidden by local)")
614
615
    def test_self(self):
616
        """"Should be self.babar."""
617
        self.throws(
618
            'FoobarClass().nameerror_self()',
619
            NAMEERROR, "'self.babar'")
620
621
    def test_self2(self):
622
        """Should be self.this_is_cls_mthd."""
623
        self.throws(
624
            'FoobarClass().nameerror_self2()', NAMEERROR,
625
            ["'FoobarClass.this_is_cls_mthd'", "'self.this_is_cls_mthd'"])
626
627
    def test_cls(self):
628
        """Should be cls.this_is_cls_mthd."""
629
        self.throws(
630
            'FoobarClass().nameerror_cls()', NAMEERROR,
631
            ["'FoobarClass.this_is_cls_mthd'", "'cls.this_is_cls_mthd'"])
632
633
    def test_complex_numbers(self):
634
        """Should be 1j."""
635
        code = 'assert {0} ** 2 == -1'
636
        sugg = '1j'
637
        good_code, bad_code_i, bad_code_j = format_str(code, sugg, 'i', 'j')
638
        suggestion = "'" + sugg + "' (imaginary unit)"
639
        self.throws(bad_code_i, NAMEERROR, suggestion)
640
        self.throws(bad_code_j, NAMEERROR, suggestion)
641
        self.runs(good_code)
642
643
    def test_shell_commands(self):
644
        """Trying shell commands."""
645
        cmd, sugg = 'ls', 'os.listdir(os.getcwd())'
646
        self.throws(cmd, NAMEERROR, "'" + sugg + "'")
647
        self.runs(sugg)
648
        cmd, sugg = 'pwd', 'os.getcwd()'
649
        self.throws(cmd, NAMEERROR, "'" + sugg + "'")
650
        self.runs(sugg)
651
        cmd, sugg = 'cd', 'os.chdir(path)'
652
        self.throws(cmd, NAMEERROR, "'" + sugg + "'")
653
        self.runs(sugg.replace('path', 'os.getcwd()'))
654
        cmd = 'rm'
655
        sugg = "'os.remove(filename)', 'shutil.rmtree(dir)' for recursive"
656
        self.throws(cmd, NAMEERROR, sugg)
657
658
    def test_unmatched_msg(self):
659
        """Test that arbitrary strings are supported."""
660
        self.throws(
661
            'raise NameError("unmatched NAMEERROR")',
662
            UNKNOWN_NAMEERROR)
663
664
665
class UnboundLocalErrorTests(GetSuggestionsTests):
666
    """Class for tests related to UnboundLocalError."""
667
668
    def test_unbound_typo(self):
669
        """Should be foo."""
670
        code = 'def func():\n\tfoo = 1\n\t{0} +=1\nfunc()'
671
        typo, sugg = "foob", "foo"
672
        bad_code, good_code = format_str(code, typo, sugg)
673
        self.throws(bad_code, UNBOUNDLOCAL, "'" + sugg + "' (local)")
674
        self.runs(good_code)
675
676
    def test_unbound_global(self):
677
        """Should be global nb."""
678
        # NICE_TO_HAVE
679
        code = 'nb = 0\ndef func():\n\t{0}nb +=1\nfunc()'
680
        sugg = 'global nb'
681
        bad_code, good_code = format_str(code, "", sugg + "\n\t")
682
        self.throws(bad_code, UNBOUNDLOCAL)
683
        self.runs(good_code)  # this is to be run afterward :-/
684
685
    def test_unmatched_msg(self):
686
        """Test that arbitrary strings are supported."""
687
        self.throws(
688
            'raise UnboundLocalError("unmatched UNBOUNDLOCAL")',
689
            UNKNOWN_UNBOUNDLOCAL)
690
691
692
class AttributeErrorTests(GetSuggestionsTests):
693
    """Class for tests related to AttributeError."""
694
695
    def test_nonetype(self):
696
        """In-place methods like sort returns None.
697
698
        Might also happen if the functions misses a return.
699
        """
700
        # NICE_TO_HAVE
701
        code = '[].sort().append(4)'
702
        self.throws(code, ATTRIBUTEERROR)
703
704
    def test_method(self):
705
        """Should be 'append'."""
706
        code = '[0].{0}(1)'
707
        typo, sugg = 'appendh', 'append'
708
        bad_code, good_code = format_str(code, typo, sugg)
709
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'")
710
        self.runs(good_code)
711
712
    def test_builtin(self):
713
        """Should be 'max(lst)'."""
714
        bad_code, good_code = '[0].max()', 'max([0])'
715
        self.throws(bad_code, ATTRIBUTEERROR, "'max(list)'")
716
        self.runs(good_code)
717
718
    def test_builtin2(self):
719
        """Should be 'next(gen)'."""
720
        code = 'my_generator().next()'
721
        new_code = 'next(my_generator())'
722
        version = (3, 0)
723
        self.runs(code, up_to_version(version))
724
        self.throws(
725
            code, ATTRIBUTEERROR,
726
            "'next(generator)'",
727
            from_version(version))
728
        self.runs(new_code)
729
730
    def test_wrongmethod(self):
731
        """Should be 'lst.append(1)'."""
732
        code = '[0].{0}(1)'
733
        typo, sugg = 'add', 'append'
734
        bad_code, good_code = format_str(code, typo, sugg)
735
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'")
736
        self.runs(good_code)
737
738
    def test_wrongmethod2(self):
739
        """Should be 'lst.extend([4, 5, 6])'."""
740
        code = '[0].{0}([4, 5, 6])'
741
        typo, sugg = 'update', 'extend'
742
        bad_code, good_code = format_str(code, typo, sugg)
743
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'")
744
        self.runs(good_code)
745
746
    def test_hidden(self):
747
        """Accessing wrong string object."""
748
        # NICE_TO_HAVE
749
        code = 'import string\nstring = "a"\nascii = string.ascii_letters'
750
        self.throws(code, ATTRIBUTEERROR)
751
752
    def test_no_sugg(self):
753
        """No suggestion."""
754
        self.throws('[1, 2, 3].ldkjhfnvdlkjhvgfdhgf', ATTRIBUTEERROR)
755
756
    def test_from_module(self):
757
        """Should be math.pi."""
758
        code = 'import math\nmath.{0}'
759
        typo, sugg = 'pie', 'pi'
760
        version = (3, 5)
761
        bad_code, good_code = format_str(code, typo, sugg)
762
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'",
763
                    up_to_version(version))
764
        self.throws(bad_code, MODATTRIBUTEERROR, "'" + sugg + "'",
765
                    from_version(version))
766
        self.runs(good_code)
767
768
    def test_from_module2(self):
769
        """Should be math.pi."""
770
        code = 'import math\nm = math\nm.{0}'
771
        typo, sugg = 'pie', 'pi'
772
        version = (3, 5)
773
        bad_code, good_code = format_str(code, typo, sugg)
774
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'",
775
                    up_to_version(version))
776
        self.throws(bad_code, MODATTRIBUTEERROR, "'" + sugg + "'",
777
                    from_version(version))
778
        self.runs(good_code)
779
780
    def test_from_class(self):
781
        """Should be 'this_is_cls_mthd'."""
782
        code = 'FoobarClass().{0}()'
783
        typo, sugg = 'this_is_cls_mth', 'this_is_cls_mthd'
784
        bad_code, good_code = format_str(code, typo, sugg)
785
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'")
786
        self.runs(good_code)
787
788
    def test_from_class2(self):
789
        """Should be 'this_is_cls_mthd'."""
790
        code = 'FoobarClass.{0}()'
791
        typo, sugg = 'this_is_cls_mth', 'this_is_cls_mthd'
792
        bad_code, good_code = format_str(code, typo, sugg)
793
        self.throws(bad_code, ATTRIBUTEERROR, "'" + sugg + "'")
794
        self.runs(good_code)
795
796
    def test_private_attr(self):
797
        """Test that 'private' members are suggested with a warning message.
798
799
        Sometimes 'private' members are suggested but it's not ideal, a
800
        warning must be added to the suggestion.
801
        """
802
        code = 'FoobarClass().{0}'
803
        method = '__some_private_method'
804
        method2 = '_some_semi_private_method'
805
        typo, sugg, sugg2 = method, '_FoobarClass' + method, method2
806
        bad_code, bad_sugg, good_sugg = format_str(code, typo, sugg, sugg2)
807
        self.throws(
808
            bad_code,
809
            ATTRIBUTEERROR,
810
            ["'{0}' (but it is supposed to be private)".format(sugg),
811
             "'{0}'".format(sugg2)])
812
        self.runs(bad_sugg)
813
        self.runs(good_sugg)
814
815
    def test_get_on_nondict_cont(self):
816
        """Method get does not exist on all containers."""
817
        code = '{0}().get(0, None)'
818
        dictcode, tuplecode, listcode, setcode = \
819
            format_str(code, 'dict', 'tuple', 'list', 'set')
820
        self.runs(dictcode)
821
        self.throws(setcode, ATTRIBUTEERROR)
822
        for bad_code in tuplecode, listcode:
823
            self.throws(bad_code, ATTRIBUTEERROR,
824
                        "'obj[key]' with a len() check or "
825
                        "try: except: KeyError or IndexError")
826
827
    def test_removed_has_key(self):
828
        """Method has_key is removed from dict."""
829
        code = 'dict().has_key(1)'
830
        new_code = '1 in dict()'
831
        version = (3, 0)
832
        self.runs(code, up_to_version(version))
833
        self.throws(
834
            code,
835
            ATTRIBUTEERROR,
836
            "'key in dict' (has_key is removed)",
837
            from_version(version))
838
        self.runs(new_code)
839
840
    def test_removed_xreadlines(self):
841
        """Method xreadlines is removed."""
842
        # NICE_TO_HAVE
843
        code = "import os\nwith open(os.path.realpath(__file__)) as f:" \
844
            "\n\tf.{0}"
845
        old, sugg1, sugg2 = 'xreadlines', 'readline', 'readlines'
846
        old_code, new_code1, new_code2 = format_str(code, old, sugg1, sugg2)
847
        version = (3, 0)
848
        self.runs(old_code, up_to_version(version))
849
        self.throws(
850
            old_code,
851
            ATTRIBUTEERROR,
852
            ["'" + sugg1 + "'", "'" + sugg2 + "'", "'writelines'"],
853
            from_version(version))
854
        self.runs(new_code1)
855
        self.runs(new_code2)
856
857
    def test_removed_function_attributes(self):
858
        """Some functions attributes are removed."""
859
        # NICE_TO_HAVE
860
        version = (3, 0)
861
        code = func_gen() + 'some_func.{0}'
862
        attributes = [('func_name', '__name__', []),
863
                      ('func_doc', '__doc__', []),
864
                      ('func_defaults', '__defaults__', ["'__defaults__'"]),
865
                      ('func_dict', '__dict__', []),
866
                      ('func_closure', '__closure__', []),
867
                      ('func_globals', '__globals__', []),
868
                      ('func_code', '__code__', [])]
869
        for (old_att, new_att, sugg) in attributes:
870
            old_code, new_code = format_str(code, old_att, new_att)
871
            self.runs(old_code, up_to_version(version))
872
            self.throws(old_code, ATTRIBUTEERROR, sugg, from_version(version))
873
            self.runs(new_code)
874
875
    def test_removed_method_attributes(self):
876
        """Some methods attributes are removed."""
877
        # NICE_TO_HAVE
878
        version = (3, 0)
879
        code = 'FoobarClass().some_method.{0}'
880
        attributes = [('im_func', '__func__', []),
881
                      ('im_self', '__self__', []),
882
                      ('im_class', '__self__.__class__', ["'__class__'"])]
883
        for (old_att, new_att, sugg) in attributes:
884
            old_code, new_code = format_str(code, old_att, new_att)
885
            self.runs(old_code, up_to_version(version))
886
            self.throws(old_code, ATTRIBUTEERROR, sugg, from_version(version))
887
            self.runs(new_code)
888
889
    def test_join(self):
890
        """Test what happens when join is used incorrectly.
891
892
        This can be frustrating to call join on an iterable instead of a
893
        string.
894
        """
895
        code = "['a', 'b'].join('-')"
896
        self.throws(code, ATTRIBUTEERROR, "'my_string.join(list)'")
897 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
898
    def test_set_dict_comprehension(self):
899
        """{} creates a dict and not an empty set leading to errors."""
900
        # NICE_TO_HAVE
901
        version = (2, 7)
902
        for method in set(dir(set)) - set(dir(dict)):
903
            if not method.startswith('__'):  # boring suggestions
904
                code = "a = {0}\na." + method
905
                typo, dict1, dict2, sugg, set1 = format_str(
906
                    code, "{}", "dict()", "{0: 0}", "set()", "{0}")
907
                self.throws(typo, ATTRIBUTEERROR)
908
                self.throws(dict1, ATTRIBUTEERROR)
909
                self.throws(dict2, ATTRIBUTEERROR)
910
                self.runs(sugg)
911
                self.throws(set1, INVALIDSYNTAX, [], up_to_version(version))
912
                self.runs(set1, from_version(version))
913
914
    def test_unmatched_msg(self):
915
        """Test that arbitrary strings are supported."""
916
        self.throws(
917
            'raise AttributeError("unmatched ATTRIBUTEERROR")',
918
            UNKNOWN_ATTRIBUTEERROR)
919
920 View Code Duplication
    # TODO: Add sugg for situation where self/cls is the missing parameter
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
921
922
923
class TypeErrorTests(GetSuggestionsTests):
924
    """Class for tests related to TypeError."""
925
926
    def test_unhashable(self):
927
        """Test for UNHASHABLE exception."""
928
        # NICE_TO_HAVE : suggest hashable equivalent
929
        self.throws('s = set([list()])', UNHASHABLE)
930
        self.throws('s = set([dict()])', UNHASHABLE)
931
        self.throws('s = set([set()])', UNHASHABLE)
932
        self.runs('s = set([tuple()])')
933
        self.runs('s = set([frozenset()])')
934
935
    def test_not_sub(self):
936
        """Should be function call, not [] operator."""
937
        typo, sugg = '[2]', '(2)'
938
        code = func_gen(param='a') + 'some_func{0}'
939
        bad_code, good_code = format_str(code, typo, sugg)
940
        suggestion = "'function(value)'"
941
        # Only Python 2.7 with cpython has a different error message
942
        # (leading to more suggestions based on fuzzy matches)
943
        version1 = (2, 7)
944
        version2 = (3, 0)
945
        self.throws(bad_code, UNSUBSCRIPTABLE, suggestion,
946
                    ALL_VERSIONS, 'pypy')
947
        self.throws(bad_code, UNSUBSCRIPTABLE, suggestion,
948
                    up_to_version(version1), 'cython')
949
        self.throws(bad_code, UNSUBSCRIPTABLE, suggestion,
950
                    from_version(version2), 'cython')
951
        self.throws(bad_code, NOATTRIBUTE_TYPEERROR,
952
                    ["'__get__'", "'__getattribute__'", suggestion],
953
                    (version1, version2), 'cython')
954
        self.runs(good_code)
955
956
    def test_method_called_on_class(self):
957
        """Test where a method is called on a class and not an instance.
958
959
        Forgetting parenthesis makes the difference between using an
960
        instance and using a type.
961
        """
962
        # NICE_TO_HAVE
963
        wrong_type = (DESCREXPECT, MUSTCALLWITHINST, NBARGERROR)
964
        not_iterable = (ARGNOTITERABLE, ARGNOTITERABLE, ARGNOTITERABLE)
965
        version = (3, 0)
966
        for code, (err_cy, err_pyp, err_pyp3) in [
967
                ('set{0}.add(0)', wrong_type),
968
                ('list{0}.append(0)', wrong_type),
969
                ('0 in list{0}', not_iterable)]:
970
            bad_code, good_code = format_str(code, '', '()')
971
            self.runs(good_code)
972
            self.throws(bad_code, err_cy, [], ALL_VERSIONS, 'cython')
973
            self.throws(bad_code, err_pyp, [], up_to_version(version), 'pypy')
974
            self.throws(bad_code, err_pyp3, [], from_version(version), 'pypy')
975
976
    def test_set_operations(self):
977
        """+, +=, etc doesn't work on sets. A suggestion would be nice."""
978
        # NICE_TO_HAVE
979
        typo1 = 'set() + set()'
980
        typo2 = 's = set()\ns += set()'
981
        code1 = 'set() | set()'
982
        code2 = 'set().union(set())'
983
        code3 = 'set().update(set())'
984
        self.throws(typo1, UNSUPPORTEDOPERAND)
985
        self.throws(typo2, UNSUPPORTEDOPERAND)
986
        self.runs(code1)
987
        self.runs(code2)
988
        self.runs(code3)
989
990
    def test_dict_operations(self):
991
        """+, +=, etc doesn't work on dicts. A suggestion would be nice."""
992
        # NICE_TO_HAVE
993
        typo1 = 'dict() + dict()'
994
        typo2 = 'd = dict()\nd += dict()'
995
        typo3 = 'dict() & dict()'
996
        self.throws(typo1, UNSUPPORTEDOPERAND)
997
        self.throws(typo2, UNSUPPORTEDOPERAND)
998
        self.throws(typo3, UNSUPPORTEDOPERAND)
999
        code1 = 'dict().update(dict())'
1000
        self.runs(code1)
1001
1002
    def test_unsupported_operand_caret(self):
1003
        """Use '**' for power, not '^'."""
1004
        # NICE_TO_HAVE
1005
        code = '3.5 {0} 2'
1006
        bad_code, good_code = format_str(code, '^', '**')
1007
        self.runs(good_code)
1008
        self.throws(bad_code, UNSUPPORTEDOPERAND)
1009
1010
    def test_unary_operand_custom(self):
1011
        """Test unary operand errors on custom types."""
1012
        version = (3, 0)
1013
        ops = {
1014
            '+{0}': ('__pos__', "'__doc__'"),
1015
            '-{0}': ('__neg__', None),
1016
            '~{0}': ('__invert__', "'__init__'"),
1017
            'abs({0})': ('__abs__', None),
1018
        }
1019
        obj = 'FoobarClass()'
1020
        sugg = 'implement "{0}" on FoobarClass'
1021
        for op, suggestions in ops.items():
1022
            code = op.format(obj)
1023
            magic, sugg_attr = suggestions
1024
            sugg_unary = sugg.format(magic)
1025
            self.throws(code, ATTRIBUTEERROR, sugg_attr,
1026
                        up_to_version(version))
1027
            self.throws(code, BADOPERANDUNARY, sugg_unary,
1028
                        from_version(version))
1029
1030
    def test_unary_operand_builtin(self):
1031
        """Test unary operand errors on builtin types."""
1032
        ops = [
1033
            '+{0}',
1034
            '-{0}',
1035
            '~{0}',
1036
            'abs({0})',
1037
        ]
1038
        obj = 'set()'
1039
        for op in ops:
1040
            code = op.format(obj)
1041
            self.throws(code, BADOPERANDUNARY)
1042
1043
    def test_len_on_iterable(self):
1044
        """len() can't be called on iterable (weird but understandable)."""
1045
        code = 'len(my_generator())'
1046
        sugg = 'len(list(my_generator()))'
1047
        self.throws(code, OBJECTHASNOFUNC, "'len(list(generator))'")
1048
        self.runs(sugg)
1049
1050
    def test_nb_args(self):
1051
        """Should have 1 arg."""
1052
        typo, sugg = '1, 2', '1'
1053
        code = func_gen(param='a', args='{0}')
1054
        bad_code, good_code = format_str(code, typo, sugg)
1055
        self.throws(bad_code, NBARGERROR)
1056
        self.runs(good_code)
1057
1058
    def test_nb_args1(self):
1059
        """Should have 0 args."""
1060
        typo, sugg = '1', ''
1061
        code = func_gen(param='', args='{0}')
1062
        bad_code, good_code = format_str(code, typo, sugg)
1063
        self.throws(bad_code, NBARGERROR)
1064
        self.runs(good_code)
1065
1066
    def test_nb_args2(self):
1067
        """Should have 1 arg."""
1068
        typo, sugg = '', '1'
1069
        version = (3, 3)
1070
        code = func_gen(param='a', args='{0}')
1071
        bad_code, good_code = format_str(code, typo, sugg)
1072
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1073
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1074
        self.runs(good_code)
1075
1076
    def test_nb_args3(self):
1077
        """Should have 3 args."""
1078
        typo, sugg = '1', '1, 2, 3'
1079
        version = (3, 3)
1080
        code = func_gen(param='so, much, args', args='{0}')
1081
        bad_code, good_code = format_str(code, typo, sugg)
1082
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1083
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1084
        self.runs(good_code)
1085
1086
    def test_nb_args4(self):
1087
        """Should have 3 args."""
1088
        typo, sugg = '', '1, 2, 3'
1089
        version = (3, 3)
1090
        code = func_gen(param='so, much, args', args='{0}')
1091
        bad_code, good_code = format_str(code, typo, sugg)
1092
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1093
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1094
        self.runs(good_code)
1095
1096
    def test_nb_args5(self):
1097
        """Should have 3 args."""
1098
        typo, sugg = '1, 2', '1, 2, 3'
1099
        version = (3, 3)
1100
        code = func_gen(param='so, much, args', args='{0}')
1101
        bad_code, good_code = format_str(code, typo, sugg)
1102
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1103
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1104
        self.runs(good_code)
1105
1106
    def test_nb_args6(self):
1107
        """Should provide more args."""
1108
        # Amusing message: 'func() takes exactly 2 arguments (2 given)'
1109
        version = (3, 3)
1110
        code = func_gen(param='a, b, c=3', args='{0}')
1111
        bad_code, good_code1, good_code2 = format_str(
1112
            code,
1113
            'b=2, c=3',
1114
            'a=1, b=2, c=3',
1115
            '1, b=2, c=3')
1116
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1117
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1118
        self.runs(good_code1)
1119
        self.runs(good_code2)
1120
1121
    def test_nb_arg_missing_self(self):
1122
        """Arg 'self' is missing."""
1123
        # NICE_TO_HAVE
1124
        obj = 'FoobarClass()'
1125
        self.throws(obj + '.some_method_missing_self_arg()', NBARGERROR)
1126
        self.throws(obj + '.some_method_missing_self_arg2(42)', NBARGERROR)
1127
        self.runs(obj + '.some_method()')
1128
        self.runs(obj + '.some_method2(42)')
1129
1130
    def test_nb_arg_missing_cls(self):
1131
        """Arg 'cls' is missing."""
1132
        # NICE_TO_HAVE
1133
        for obj in ('FoobarClass()', 'FoobarClass'):
1134
            self.throws(obj + '.some_cls_method_missing_cls()', NBARGERROR)
1135
            self.throws(obj + '.some_cls_method_missing_cls2(42)', NBARGERROR)
1136
            self.runs(obj + '.this_is_cls_mthd()')
1137
1138
    def test_keyword_args(self):
1139
        """Should be param 'babar' not 'a' but it's hard to guess."""
1140
        typo, sugg = 'a', 'babar'
1141
        code = func_gen(param=sugg, args='{0}=1')
1142
        bad_code, good_code = format_str(code, typo, sugg)
1143
        self.throws(bad_code, UNEXPECTEDKWARG)
1144
        self.runs(good_code)
1145
1146
    def test_keyword_args2(self):
1147
        """Should be param 'abcdef' not 'abcdf'."""
1148
        typo, sugg = 'abcdf', 'abcdef'
1149
        code = func_gen(param=sugg, args='{0}=1')
1150
        bad_code, good_code = format_str(code, typo, sugg)
1151
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1152
        self.runs(good_code)
1153
1154
    def test_keyword_arg_method(self):
1155
        """Should be the same as previous test but on a method."""
1156
        code = 'class MyClass:\n\tdef func(self, a):' \
1157
               '\n\t\tpass\nMyClass().func({0}=1)'
1158
        bad_code, good_code = format_str(code, 'babar', 'a')
1159
        self.throws(bad_code, UNEXPECTEDKWARG)
1160
        self.runs(good_code)
1161
1162
    def test_keyword_arg_method2(self):
1163
        """Should be the same as previous test but on a method."""
1164
        typo, sugg = 'abcdf', 'abcdef'
1165
        code = 'class MyClass:\n\tdef func(self, ' + sugg + '):' \
1166
               '\n\t\tpass\nMyClass().func({0}=1)'
1167
        bad_code, good_code = format_str(code, typo, sugg)
1168
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1169
        self.runs(good_code)
1170
1171
    def test_keyword_arg_class_method(self):
1172
        """Should be the same as previous test but on a class method."""
1173
        code = 'class MyClass:\n\t@classmethod\n\tdef func(cls, a):' \
1174
               '\n\t\tpass\nMyClass.func({0}=1)'
1175
        bad_code, good_code = format_str(code, 'babar', 'a')
1176
        self.throws(bad_code, UNEXPECTEDKWARG)
1177
        self.runs(good_code)
1178
1179
    def test_keyword_arg_class_method2(self):
1180
        """Should be the same as previous test but on a class method."""
1181
        typo, sugg = 'abcdf', 'abcdef'
1182
        code = 'class MyClass:\n\t@classmethod ' \
1183
               '\n\tdef func(cls, ' + sugg + '):\n ' \
1184
               '\t\tpass\nMyClass.func({0}=1)'
1185
        bad_code, good_code = format_str(code, typo, sugg)
1186
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1187
        self.runs(good_code)
1188
1189
    def test_keyword_arg_multiples_instances(self):
1190
        """If multiple functions are found, suggestions should be unique."""
1191
        typo, sugg = 'abcdf', 'abcdef'
1192
        code = 'class MyClass:\n\tdef func(self, ' + sugg + '):' \
1193
               '\n\t\tpass\na = MyClass()\nb = MyClass()\na.func({0}=1)'
1194
        bad_code, good_code = format_str(code, typo, sugg)
1195
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1196
        self.runs(good_code)
1197
1198
    def test_keyword_arg_lambda(self):
1199
        """Test with lambda functions instead of usual function."""
1200
        typo, sugg = 'abcdf', 'abcdef'
1201
        code = 'f = lambda arg1, ' + sugg + ': None\nf(42, {0}=None)'
1202
        bad_code, good_code = format_str(code, typo, sugg)
1203
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1204
        self.runs(good_code)
1205
1206
    def test_keyword_arg_lambda_method(self):
1207
        """Test with lambda methods instead of usual methods."""
1208
        typo, sugg = 'abcdf', 'abcdef'
1209
        code = 'class MyClass:\n\tfunc = lambda self, ' + sugg + ': None' \
1210
               '\nMyClass().func({0}=1)'
1211
        bad_code, good_code = format_str(code, typo, sugg)
1212
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1213
        self.runs(good_code)
1214
1215
    def test_keyword_arg_other_objects_with_name(self):
1216
        """Mix of previous tests but with more objects defined.
1217
1218
        Non-function object with same same as the function tested are defined
1219
        to ensure that things do work fine.
1220
        """
1221
        code = 'func = "not_a_func"\nclass MyClass:\n\tdef func(self, a):' \
1222
               '\n\t\tpass\nMyClass().func({0}=1)'
1223
        bad_code, good_code = format_str(code, 'babar', 'a')
1224
        self.throws(bad_code, UNEXPECTEDKWARG)
1225
        self.runs(good_code)
1226
1227
    def test_keyword_builtin(self):
1228
        """A few builtins (like int()) have a different error message."""
1229
        # NICE_TO_HAVE
1230
        # 'max', 'input', 'len', 'abs', 'all', etc have a specific error
1231
        # message and are not relevant here
1232
        for builtin in ['int', 'float', 'bool', 'complex']:
1233
            code = builtin + '(this_doesnt_exist=2)'
1234
            self.throws(code, UNEXPECTEDKWARG2, [], ALL_VERSIONS, 'cython')
1235
            self.throws(code, UNEXPECTEDKWARG, [], ALL_VERSIONS, 'pypy')
1236
1237
    def test_keyword_builtin_print(self):
1238
        """Builtin "print" has a different error message."""
1239
        # It would be NICE_TO_HAVE suggestions on keyword arguments
1240
        v3 = (3, 0)
1241
        code = "c = 'string'\nb = print(c, end_='toto')"
1242
        self.throws(code, INVALIDSYNTAX, [], up_to_version(v3))
1243
        self.throws(code, UNEXPECTEDKWARG2, [], from_version(v3), 'cython')
1244
        self.throws(code, UNEXPECTEDKWARG3, [], from_version(v3), 'pypy')
1245
1246
    def test_no_implicit_str_conv(self):
1247
        """Trying to concatenate a non-string value to a string."""
1248
        # NICE_TO_HAVE
1249
        code = '{0} + " things"'
1250
        typo, sugg = '12', 'str(12)'
1251
        bad_code, good_code = format_str(code, typo, sugg)
1252
        self.throws(bad_code, UNSUPPORTEDOPERAND)
1253
        self.runs(good_code)
1254
1255
    def test_no_implicit_str_conv2(self):
1256
        """Trying to concatenate a non-string value to a string."""
1257
        # NICE_TO_HAVE
1258
        code = '"things " + {0}'
1259
        typo, sugg = '12', 'str(12)'
1260
        bad_code, good_code = format_str(code, typo, sugg)
1261
        version = (3, 0)
1262
        version2 = (3, 6)
1263
        self.throws(
1264
            bad_code, CANNOTCONCAT, [], up_to_version(version), 'cython')
1265
        self.throws(
1266
            bad_code, CANTCONVERT, [], (version, version2), 'cython')
1267
        self.throws(
1268
            bad_code, MUSTBETYPENOTTYPE, [], from_version(version2), 'cython')
1269
        self.throws(
1270
            bad_code, UNSUPPORTEDOPERAND, [], ALL_VERSIONS, 'pypy')
1271
        self.runs(good_code)
1272
1273
    def test_assignment_to_range(self):
1274
        """Trying to assign to range works on list, not on range."""
1275
        code = '{0}[2] = 1'
1276
        typo, sugg = 'range(4)', 'list(range(4))'
1277
        version = (3, 0)
1278
        bad_code, good_code = format_str(code, typo, sugg)
1279
        self.runs(good_code)
1280
        self.runs(bad_code, up_to_version(version))
1281
        self.throws(
1282
            bad_code,
1283
            OBJECTDOESNOTSUPPORT,
1284
            'convert to list to edit the list',
1285
            from_version(version))
1286
1287
    def test_assignment_to_string(self):
1288
        """Trying to assign to string does not work."""
1289
        code = "s = 'abc'\ns[1] = 'd'"
1290
        good_code = "s = 'abc'\nl = list(s)\nl[1] = 'd'\ns = ''.join(l)"
1291
        self.runs(good_code)
1292
        self.throws(
1293
            code,
1294
            OBJECTDOESNOTSUPPORT,
1295
            'convert to list to edit the list and use "join()" on the list')
1296
1297
    def test_deletion_from_string(self):
1298
        """Delete from string does not work."""
1299
        code = "s = 'abc'\ndel s[1]"
1300
        good_code = "s = 'abc'\nl = list(s)\ndel l[1]\ns = ''.join(l)"
1301 View Code Duplication
        self.runs(good_code)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1302
        self.throws(
1303
            code,
1304
            OBJECTDOESNOTSUPPORT,
1305
            'convert to list to edit the list and use "join()" on the list')
1306
1307
    def test_object_indexing(self):
1308
        """Index from object does not work if __getitem__ is not defined."""
1309
        version = (3, 0)
1310
        code = "{0}[0]"
1311
        good_code, set_code, custom_code = \
1312
            format_str(code, '"a_string"', "set()", "FoobarClass()")
1313
        self.runs(good_code)
1314
        sugg_for_iterable = 'convert to list first or use the iterator ' \
1315
            'protocol to get the different elements'
1316
        self.throws(set_code,
1317
                    OBJECTDOESNOTSUPPORT,
1318
                    sugg_for_iterable, ALL_VERSIONS, 'cython')
1319
        self.throws(set_code,
1320
                    UNSUBSCRIPTABLE,
1321
                    sugg_for_iterable, ALL_VERSIONS, 'pypy')
1322
        self.throws(custom_code,
1323
                    ATTRIBUTEERROR, [], up_to_version(version), 'pypy')
1324
        self.throws(custom_code,
1325
                    UNSUBSCRIPTABLE,
1326
                    'implement "__getitem__" on FoobarClass',
1327
                    from_version(version), 'pypy')
1328
        self.throws(custom_code,
1329
                    ATTRIBUTEERROR, [], up_to_version(version), 'cython')
1330
        self.throws(custom_code,
1331
                    OBJECTDOESNOTSUPPORT,
1332
                    'implement "__getitem__" on FoobarClass',
1333
                    from_version(version), 'cython')
1334
1335
    def test_not_callable(self):
1336
        """Sometimes, one uses parenthesis instead of brackets."""
1337
        typo, getitem = '(0)', '[0]'
1338
        for ex, sugg in {
1339
            '[0]': "'list[value]'",
1340
            '{0: 0}': "'dict[value]'",
1341
            '"a"': "'str[value]'",
1342
        }.items():
1343
            self.throws(ex + typo, NOTCALLABLE, sugg)
1344
            self.runs(ex + getitem)
1345
        for ex in ['1', 'set()']:
1346
            self.throws(ex + typo, NOTCALLABLE)
1347
1348
    def test_unmatched_msg(self):
1349
        """Test that arbitrary strings are supported."""
1350
        self.throws(
1351
            'raise TypeError("unmatched TYPEERROR")',
1352
            UNKNOWN_TYPEERROR)
1353
1354
1355
class ImportErrorTests(GetSuggestionsTests):
1356
    """Class for tests related to ImportError."""
1357
1358
    def test_no_module_no_sugg(self):
1359
        """No suggestion."""
1360
        self.throws('import fqslkdfjslkqdjfqsd', NOMODULE)
1361
1362
    def test_no_module(self):
1363
        """Should be 'math'."""
1364
        code = 'import {0}'
1365
        typo, sugg = 'maths', 'math'
1366
        self.assertTrue(sugg in STAND_MODULES)
1367
        bad_code, good_code = format_str(code, typo, sugg)
1368
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1369
        self.runs(good_code)
1370
1371
    def test_no_module2(self):
1372
        """Should be 'math'."""
1373
        code = 'from {0} import pi'
1374
        typo, sugg = 'maths', 'math'
1375
        self.assertTrue(sugg in STAND_MODULES)
1376
        bad_code, good_code = format_str(code, typo, sugg)
1377
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1378
        self.runs(good_code)
1379
1380
    def test_no_module3(self):
1381
        """Should be 'math'."""
1382
        code = 'import {0} as my_imported_math'
1383
        typo, sugg = 'maths', 'math'
1384
        self.assertTrue(sugg in STAND_MODULES)
1385
        bad_code, good_code = format_str(code, typo, sugg)
1386
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1387
        self.runs(good_code)
1388
1389
    def test_no_module4(self):
1390
        """Should be 'math'."""
1391
        code = 'from {0} import pi as three_something'
1392
        typo, sugg = 'maths', 'math'
1393
        self.assertTrue(sugg in STAND_MODULES)
1394
        bad_code, good_code = format_str(code, typo, sugg)
1395
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1396
        self.runs(good_code)
1397
1398
    def test_no_module5(self):
1399
        """Should be 'math'."""
1400
        code = '__import__("{0}")'
1401
        typo, sugg = 'maths', 'math'
1402
        self.assertTrue(sugg in STAND_MODULES)
1403
        bad_code, good_code = format_str(code, typo, sugg)
1404
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1405
        self.runs(good_code)
1406
1407
    def test_import_future_nomodule(self):
1408
        """Should be '__future__'."""
1409
        code = 'import {0}'
1410
        typo, sugg = '__future_', '__future__'
1411
        self.assertTrue(sugg in STAND_MODULES)
1412
        bad_code, good_code = format_str(code, typo, sugg)
1413
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1414
        self.runs(good_code)
1415
1416
    def test_no_name_no_sugg(self):
1417
        """No suggestion."""
1418
        self.throws('from math import fsfsdfdjlkf', CANNOTIMPORT)
1419
1420
    def test_wrong_import(self):
1421
        """Should be 'math'."""
1422
        code = 'from {0} import pi'
1423
        typo, sugg = 'itertools', 'math'
1424
        self.assertTrue(sugg in STAND_MODULES)
1425
        bad_code, good_code = format_str(code, typo, sugg)
1426
        self.throws(bad_code, CANNOTIMPORT, "'" + good_code + "'")
1427
        self.runs(good_code)
1428
1429
    def test_typo_in_method(self):
1430
        """Should be 'pi'."""
1431
        code = 'from math import {0}'
1432
        typo, sugg = 'pie', 'pi'
1433
        bad_code, good_code = format_str(code, typo, sugg)
1434
        self.throws(bad_code, CANNOTIMPORT, "'" + sugg + "'")
1435
        self.runs(good_code)
1436
1437
    def test_typo_in_method2(self):
1438
        """Should be 'pi'."""
1439
        code = 'from math import e, {0}, log'
1440
        typo, sugg = 'pie', 'pi'
1441
        bad_code, good_code = format_str(code, typo, sugg)
1442
        self.throws(bad_code, CANNOTIMPORT, "'" + sugg + "'")
1443
        self.runs(good_code)
1444
1445
    def test_typo_in_method3(self):
1446
        """Should be 'pi'."""
1447
        code = 'from math import {0} as three_something'
1448
        typo, sugg = 'pie', 'pi'
1449
        bad_code, good_code = format_str(code, typo, sugg)
1450
        self.throws(bad_code, CANNOTIMPORT, "'" + sugg + "'")
1451
        self.runs(good_code)
1452
1453
    def test_unmatched_msg(self):
1454
        """Test that arbitrary strings are supported."""
1455
        self.throws(
1456
            'raise ImportError("unmatched IMPORTERROR")',
1457
            UNKNOWN_IMPORTERROR)
1458
1459
    def test_module_removed(self):
1460
        """Sometimes, modules are deleted/moved/renamed."""
1461
        # NICE_TO_HAVE
1462
        version1 = (2, 7)  # result for 2.6 seems to vary
1463
        version2 = (3, 0)
1464
        code = 'import {0}'
1465
        lower, upper = format_str(code, 'tkinter', 'Tkinter')
1466
        self.throws(lower, NOMODULE, [], (version1, version2))
1467
        self.throws(upper, NOMODULE, [], from_version(version2))
1468
1469
1470
class LookupErrorTests(GetSuggestionsTests):
1471
    """Class for tests related to LookupError."""
1472
1473
1474
class KeyErrorTests(LookupErrorTests):
1475
    """Class for tests related to KeyError."""
1476
1477
    def test_no_sugg(self):
1478
        """No suggestion."""
1479
        self.throws('dict()["ffdsqmjklfqsd"]', KEYERROR)
1480
1481
1482
class IndexErrorTests(LookupErrorTests):
1483
    """Class for tests related to IndexError."""
1484
1485
    def test_no_sugg(self):
1486
        """No suggestion."""
1487
        self.throws('list()[2]', OUTOFRANGE)
1488
1489
1490
class SyntaxErrorTests(GetSuggestionsTests):
1491
    """Class for tests related to SyntaxError."""
1492
1493
    def test_no_error(self):
1494
        """No error."""
1495
        self.runs("1 + 2 == 2")
1496
1497
    def test_yield_return_out_of_func(self):
1498
        """yield/return needs to be in functions."""
1499
        sugg = "to indent it"
1500
        self.throws("yield 1", OUTSIDEFUNC, sugg)
1501
        self.throws("return 1", OUTSIDEFUNC, ["'sys.exit([arg])'", sugg])
1502
1503
    def test_print(self):
1504
        """print is a functions now and needs parenthesis."""
1505
        # NICE_TO_HAVE
1506
        code, new_code = 'print ""', 'print("")'
1507
        version = (3, 0)
1508
        version2 = (3, 4)
1509
        self.runs(code, up_to_version(version))
1510
        self.throws(code, INVALIDSYNTAX, [], (version, version2))
1511
        self.throws(code, INVALIDSYNTAX, [], from_version(version2))
1512
        self.runs(new_code)
1513
1514
    def test_exec(self):
1515
        """exec is a functions now and needs parenthesis."""
1516
        # NICE_TO_HAVE
1517
        code, new_code = 'exec "1"', 'exec("1")'
1518
        version = (3, 0)
1519
        version2 = (3, 4)
1520
        self.runs(code, up_to_version(version))
1521
        self.throws(code, INVALIDSYNTAX, [], (version, version2))
1522
        self.throws(code, INVALIDSYNTAX, [], from_version(version2))
1523
        self.runs(new_code)
1524
1525
    def test_old_comparison(self):
1526
        """<> comparison is removed, != always works."""
1527
        code = '1 {0} 2'
1528
        old, new = '<>', '!='
1529
        version = (3, 0)
1530
        old_code, new_code = format_str(code, old, new)
1531
        self.runs(old_code, up_to_version(version))
1532
        self.throws(
1533
            old_code,
1534
            INVALIDCOMP,
1535
            "'!='",
1536
            from_version(version),
1537
            'pypy')
1538
        self.throws(
1539
            old_code,
1540
            INVALIDSYNTAX,
1541
            "'!='",
1542
            from_version(version),
1543
            'cython')
1544
        self.runs(new_code)
1545
1546
    def test_missing_colon(self):
1547
        """Missing colon is a classic mistake."""
1548
        # NICE_TO_HAVE
1549
        code = "if True{0}\n\tpass"
1550
        bad_code, good_code = format_str(code, "", ":")
1551
        self.throws(bad_code, INVALIDSYNTAX)
1552
        self.runs(good_code)
1553
1554
    def test_missing_colon2(self):
1555
        """Missing colon is a classic mistake."""
1556
        # NICE_TO_HAVE
1557
        code = "class MyClass{0}\n\tpass"
1558
        bad_code, good_code = format_str(code, "", ":")
1559
        self.throws(bad_code, INVALIDSYNTAX)
1560
        self.runs(good_code)
1561
1562
    def test_simple_equal(self):
1563
        """'=' for comparison is a classic mistake."""
1564
        # NICE_TO_HAVE
1565
        code = "if 2 {0} 3:\n\tpass"
1566
        bad_code, good_code = format_str(code, "=", "==")
1567
        self.throws(bad_code, INVALIDSYNTAX)
1568
        self.runs(good_code)
1569
1570
    def test_keyword_as_identifier(self):
1571
        """Using a keyword as a variable name."""
1572
        # NICE_TO_HAVE
1573
        code = '{0} = 1'
1574
        bad_code, good_code = format_str(code, "from", "from_")
1575
        self.throws(bad_code, INVALIDSYNTAX)
1576
        self.runs(good_code)
1577
1578
    def test_increment(self):
1579
        """Trying to use '++' or '--'."""
1580
        # NICE_TO_HAVE
1581
        code = 'a = 0\na{0}'
1582
        # Adding pointless suffix to avoid wrong assumptions
1583
        for end in ('', '  ', ';', ' ;'):
1584
            code2 = code + end
1585
            for op in ('-', '+'):
1586
                typo, sugg = 2 * op, op + '=1'
1587
                bad_code, good_code = format_str(code + end, typo, sugg)
1588
                self.throws(bad_code, INVALIDSYNTAX)
1589
                self.runs(good_code)
1590
1591
    def test_wrong_bool_operator(self):
1592
        """Trying to use '&&' or '||'."""
1593
        code = 'True {0} False'
1594
        for typo, sugg in (('&&', 'and'), ('||', 'or')):
1595
            bad_code, good_code = format_str(code, typo, sugg)
1596
            self.throws(bad_code, INVALIDSYNTAX, "'" + sugg + "'")
1597
            self.runs(good_code)
1598
1599
    def test_import_future_not_first(self):
1600
        """Test what happens when import from __future__ is not first."""
1601
        code = 'a = 8/7\nfrom __future__ import division'
1602
        self.throws(code, FUTUREFIRST)
1603
1604
    def test_import_future_not_def(self):
1605
        """Should be 'division'."""
1606
        code = 'from __future__ import {0}'
1607
        typo, sugg = 'divisio', 'division'
1608
        bad_code, good_code = format_str(code, typo, sugg)
1609
        self.throws(bad_code, FUTFEATNOTDEF, "'" + sugg + "'")
1610
        self.runs(good_code)
1611
1612
    def test_unqualified_exec(self):
1613
        """Exec in nested functions."""
1614
        # NICE_TO_HAVE
1615
        version = (3, 0)
1616
        codes = [
1617
            "def func1():\n\tbar='1'\n\tdef func2():"
1618
            "\n\t\texec(bar)\n\tfunc2()\nfunc1()",
1619
            "def func1():\n\texec('1')\n\tdef func2():"
1620
            "\n\t\tTrue",
1621
        ]
1622
        for code in codes:
1623
            self.throws(code, UNQUALIFIED_EXEC, [], up_to_version(version))
1624
            self.runs(code, from_version(version))
1625
1626
    def test_import_star(self):
1627
        """'import *' in nested functions."""
1628
        # NICE_TO_HAVE
1629
        codes = [
1630
            "def func1():\n\tbar='1'\n\tdef func2():"
1631
            "\n\t\tfrom math import *\n\t\tTrue\n\tfunc2()\nfunc1()",
1632
            "def func1():\n\tfrom math import *"
1633
            "\n\tdef func2():\n\t\tTrue",
1634
        ]
1635
        with warnings.catch_warnings():
1636
            warnings.simplefilter("ignore", category=SyntaxWarning)
1637
            for code in codes:
1638
                self.throws(code, IMPORTSTAR, [])
1639
1640
    def test_unpack(self):
1641
        """Extended tuple unpacking does not work prior to Python 3."""
1642
        # NICE_TO_HAVE
1643
        version = (3, 0)
1644
        code = 'a, *b = (1, 2, 3)'
1645
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1646
        self.runs(code, from_version(version))
1647
1648
    def test_unpack2(self):
1649
        """Unpacking in function arguments was supported up to Python 3."""
1650
        # NICE_TO_HAVE
1651
        version = (3, 0)
1652
        code = 'def addpoints((x1, y1), (x2, y2)):\n\tpass'
1653
        self.runs(code, up_to_version(version))
1654
        self.throws(code, INVALIDSYNTAX, [], from_version(version))
1655
1656
    def test_nonlocal(self):
1657
        """nonlocal keyword is added in Python 3."""
1658
        # NICE_TO_HAVE
1659
        version = (3, 0)
1660
        code = 'def func():\n\tfoo = 1\n\tdef nested():\n\t\tnonlocal foo'
1661
        self.runs(code, from_version(version))
1662
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1663
1664
    def test_nonlocal2(self):
1665
        """nonlocal must be used only when binding exists."""
1666
        # NICE_TO_HAVE
1667
        version = (3, 0)
1668
        code = 'def func():\n\tdef nested():\n\t\tnonlocal foo'
1669
        self.throws(code, NOBINDING, [], from_version(version))
1670
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1671
1672
    def test_nonlocal3(self):
1673
        """nonlocal must be used only when binding to non-global exists."""
1674
        # NICE_TO_HAVE
1675 View Code Duplication
        version = (3, 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1676
        code = 'foo = 1\ndef func():\n\tdef nested():\n\t\tnonlocal foo'
1677
        self.throws(code, NOBINDING, [], from_version(version))
1678
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1679
1680
    def test_octal_literal(self):
1681
        """Syntax for octal liberals has changed."""
1682
        # NICE_TO_HAVE
1683
        version = (3, 0)
1684
        bad, good = '0720', '0o720'
1685
        self.runs(good)
1686
        self.runs(bad, up_to_version(version))
1687
        self.throws(bad, INVALIDTOKEN, [], from_version(version), 'cython')
1688
        self.throws(bad, INVALIDSYNTAX, [], from_version(version), 'pypy')
1689
1690
    def test_extended_unpacking(self):
1691
        """Extended iterable unpacking is added with Python 3."""
1692
        version = (3, 0)
1693
        code = '(a, *rest, b) = range(5)'
1694
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1695
        self.runs(code, from_version(version))
1696
1697
    def test_ellipsis(self):
1698
        """Triple dot (...) aka Ellipsis can be used anywhere in Python 3."""
1699
        version = (3, 0)
1700
        code = '...'
1701
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1702
        self.runs(code, from_version(version))
1703
1704
1705
class MemoryErrorTests(GetSuggestionsTests):
1706
    """Class for tests related to MemoryError."""
1707
1708
    def test_out_of_memory(self):
1709
        """Test what happens in case of MemoryError."""
1710
        code = '[0] * 999999999999999'
1711
        self.throws(code, MEMORYERROR)
1712
1713
    def test_out_of_memory_range(self):
1714
        """Test what happens in case of MemoryError."""
1715
        code = '{0}(999999999999999)'
1716
        typo, sugg = 'range', 'xrange'
1717
        bad_code, good_code = format_str(code, typo, sugg)
1718
        self.runs(bad_code, ALL_VERSIONS, 'pypy')
1719
        version = (2, 7)
1720
        version2 = (3, 0)
1721
        self.throws(
1722
            bad_code,
1723
            OVERFLOWERR, "'" + sugg + "'",
1724
            up_to_version(version),
1725
            'cython')
1726
        self.throws(
1727
            bad_code,
1728
            MEMORYERROR, "'" + sugg + "'",
1729
            (version, version2),
1730
            'cython')
1731
        self.runs(good_code, up_to_version(version2), 'cython')
1732
        self.runs(bad_code, from_version(version2), 'cython')
1733
1734
1735
class ValueErrorTests(GetSuggestionsTests):
1736
    """Class for tests related to ValueError."""
1737
1738
    def test_too_many_values(self):
1739
        """Unpack 4 values in 3 variables."""
1740
        code = 'a, b, c = [1, 2, 3, 4]'
1741
        version = (3, 0)
1742
        self.throws(code, EXPECTEDLENGTH, [], up_to_version(version), 'pypy')
1743
        self.throws(code, TOOMANYVALUES, [], from_version(version), 'pypy')
1744
        self.throws(code, TOOMANYVALUES, [], ALL_VERSIONS, 'cython')
1745
1746
    def test_not_enough_values(self):
1747
        """Unpack 2 values in 3 variables."""
1748
        code = 'a, b, c = [1, 2]'
1749
        version = (3, 0)
1750
        self.throws(code, EXPECTEDLENGTH, [], up_to_version(version), 'pypy')
1751
        self.throws(code, NEEDMOREVALUES, [], from_version(version), 'pypy')
1752
        self.throws(code, NEEDMOREVALUES, [], ALL_VERSIONS, 'cython')
1753
1754
    def test_conversion_fails(self):
1755
        """Conversion fails."""
1756
        self.throws('int("toto")', INVALIDLITERAL)
1757
1758
    def test_math_domain(self):
1759
        """Math function used out of its domain."""
1760
        code = 'import math\nlg = math.log(-1)'
1761
        self.throws(code, MATHDOMAIN)
1762
1763
    def test_zero_len_field_in_format(self):
1764
        """Format {} is not valid before Python 2.7."""
1765
        code = '"{0}".format(0)'
1766
        old, new = '{0}', '{}'
1767
        old_code, new_code = format_str(code, old, new)
1768
        version = (2, 7)
1769
        self.runs(old_code)
1770
        self.throws(new_code, ZEROLENERROR, '{0}', up_to_version(version))
1771
        self.runs(new_code, from_version(version))
1772
1773
    def test_timedata_does_not_match(self):
1774
        """Strptime arguments are in wrong order."""
1775
        code = 'import datetime\ndatetime.datetime.strptime({0}, {1})'
1776
        timedata, timeformat = '"30 Nov 00"', '"%d %b %y"'
1777
        good_code = code.format(*(timedata, timeformat))
1778
        bad_code = code.format(*(timeformat, timedata))
1779
        self.runs(good_code)
1780
        self.throws(bad_code, TIMEDATAFORMAT,
1781
                    ['to swap value and format parameters'])
1782
1783
1784
class RuntimeErrorTests(GetSuggestionsTests):
1785
    """Class for tests related to RuntimeError."""
1786
1787
    def test_max_depth(self):
1788
        """Reach maximum recursion depth."""
1789
        sys.setrecursionlimit(200)
1790
        code = 'endlessly_recursive_func(0)'
1791
        self.throws(code, MAXRECURDEPTH,
1792
                    ["increase the limit with `sys.setrecursionlimit(limit)`"
1793
                        " (current value is 200)",
1794
                     AVOID_REC_MESSAGE])
1795
1796
    def test_dict_size_changed_during_iter(self):
1797
        """Test size change during iteration."""
1798
        # NICE_TO_HAVE
1799
        code = 'd = dict(enumerate("notimportant"))' \
1800
            '\nfor e in d:\n\td.pop(e)'
1801
        self.throws(code, SIZECHANGEDDURINGITER)
1802
1803
    def test_set_changed_size_during_iter(self):
1804
        # NICE_TO_HAVE
1805
        code = 's = set("notimportant")' \
1806
            '\nfor e in s:\n\ts.pop()'
1807
        self.throws(code, SIZECHANGEDDURINGITER)
1808
1809
    def test_dequeue_changed_during_iter(self):
1810
        # NICE_TO_HAVE
1811
        # "deque mutated during iteration"
1812
        pass
1813
1814
1815
class IOErrorTests(GetSuggestionsTests):
1816
    """Class for tests related to IOError."""
1817
1818
    def test_no_such_file(self):
1819
        """File does not exist."""
1820
        code = 'with open("doesnotexist") as f:\n\tpass'
1821
        self.throws(code, NOFILE_IO)
1822
1823
    def test_no_such_file2(self):
1824
        """File does not exist."""
1825
        code = 'os.listdir("doesnotexist")'
1826
        self.throws(code, NOFILE_OS)
1827
1828
    def test_no_such_file_user(self):
1829
        """Suggestion when one needs to expanduser."""
1830
        code = 'os.listdir("{0}")'
1831
        typo, sugg = "~", os.path.expanduser("~")
1832
        bad_code, good_code = format_str(code, typo, sugg)
1833
        self.throws(
1834
            bad_code, NOFILE_OS,
1835
            "'" + sugg + "' (calling os.path.expanduser)")
1836
        self.runs(good_code)
1837
1838
    def test_no_such_file_vars(self):
1839
        """Suggestion when one needs to expandvars."""
1840
        code = 'os.listdir("{0}")'
1841
        key = 'HOME'
1842
        typo, sugg = "$" + key, os.path.expanduser("~")
1843
        original_home = os.environ.get('HOME')
1844
        os.environ[key] = sugg
1845
        bad_code, good_code = format_str(code, typo, sugg)
1846
        self.throws(
1847
            bad_code, NOFILE_OS,
1848
            "'" + sugg + "' (calling os.path.expandvars)")
1849
        self.runs(good_code)
1850
        if original_home is None:
1851
            del os.environ[key]
1852
        else:
1853
            os.environ[key] = original_home
1854
1855
    def create_tmp_dir_with_files(self, filelist):
1856
        """Create a temporary directory with files in it."""
1857
        tmpdir = tempfile.mkdtemp()
1858
        absfiles = [os.path.join(tmpdir, f) for f in filelist]
1859
        for name in absfiles:
1860
            open(name, 'a').close()
1861
        return (tmpdir, absfiles)
1862
1863
    def test_is_dir_empty(self):
1864
        """Suggestion when file is an empty directory."""
1865
        # Create empty temp dir
1866
        tmpdir, _ = self.create_tmp_dir_with_files([])
1867
        code = 'with open("{0}") as f:\n\tpass'
1868
        bad_code, _ = format_str(code, tmpdir, "TODO")
1869
        self.throws(
1870
            bad_code, ISADIR_IO, "to add content to {0} first".format(tmpdir))
1871
        rmtree(tmpdir)
1872
1873
    def test_is_dir_small(self):
1874
        """Suggestion when file is directory with a few files."""
1875
        # Create temp dir with a few files
1876
        nb_files = 3
1877
        files = sorted([str(i) + ".txt" for i in range(nb_files)])
1878
        tmpdir, absfiles = self.create_tmp_dir_with_files(files)
1879
        code = 'with open("{0}") as f:\n\tpass'
1880
        bad_code, good_code = format_str(code, tmpdir, absfiles[0])
1881
        self.throws(
1882
            bad_code, ISADIR_IO,
1883
            "any of the 3 files in directory ('0.txt', '1.txt', '2.txt')")
1884
        self.runs(good_code)
1885
        rmtree(tmpdir)
1886
1887
    def test_is_dir_big(self):
1888
        """Suggestion when file is directory with many files."""
1889
        # Create temp dir with many files
1890
        tmpdir = tempfile.mkdtemp()
1891
        nb_files = 30
1892
        files = sorted([str(i) + ".txt" for i in range(nb_files)])
1893
        tmpdir, absfiles = self.create_tmp_dir_with_files(files)
1894
        code = 'with open("{0}") as f:\n\tpass'
1895
        bad_code, good_code = format_str(code, tmpdir, absfiles[0])
1896
        self.throws(
1897
            bad_code, ISADIR_IO,
1898
            "any of the 30 files in directory "
1899
            "('0.txt', '1.txt', '10.txt', '11.txt', etc)")
1900
        self.runs(good_code)
1901
        rmtree(tmpdir)
1902
1903
    def test_is_not_dir(self):
1904
        """Suggestion when file is not a directory."""
1905
        code = 'with open("{0}") as f:\n\tpass'
1906
        code = 'os.listdir("{0}")'
1907
        typo, sugg = __file__, os.path.dirname(__file__)
1908
        bad_code, good_code = format_str(code, typo, sugg)
1909
        self.throws(
1910
            bad_code, NOTADIR_OS,
1911
            "'" + sugg + "' (calling os.path.dirname)")
1912
        self.runs(good_code)
1913
1914
    def test_dir_is_not_empty(self):
1915
        """Suggestion when directory is not empty."""
1916
        # NICE_TO_HAVE
1917
        nb_files = 3
1918
        files = sorted([str(i) + ".txt" for i in range(nb_files)])
1919
        tmpdir, _ = self.create_tmp_dir_with_files(files)
1920
        self.throws('os.rmdir("{0}")'.format(tmpdir), DIRNOTEMPTY_OS)
1921
        rmtree(tmpdir)  # this should be the suggestion
1922
1923
1924
class AnyErrorTests(GetSuggestionsTests):
1925
    """Class for tests not related to an error type in particular."""
1926
1927
    def test_wrong_except(self):
1928
        """Test where except is badly used and thus does not catch.
1929
1930
        Common mistake : "except Exc1, Exc2" doesn't catch Exc2.
1931
        Adding parenthesis solves the issue.
1932
        """
1933
        # NICE_TO_HAVE
1934
        version = (3, 0)
1935
        raised_exc, other_exc = KeyError, TypeError
1936
        raised, other = raised_exc.__name__, other_exc.__name__
1937
        code = "try:\n\traise {0}()\nexcept {{0}}:\n\tpass".format(raised)
1938
        typo = "{0}, {1}".format(other, raised)
1939
        sugg = "({0})".format(typo)
1940
        bad1, bad2, good1, good2 = format_str(code, typo, other, sugg, raised)
1941
        self.throws(bad1, (raised_exc, None), [], up_to_version(version))
1942
        self.throws(bad1, INVALIDSYNTAX, [], from_version(version))
1943
        self.throws(bad2, (raised_exc, None))
1944
        self.runs(good1)
1945
        self.runs(good2)
1946
1947
1948
if __name__ == '__main__':
1949
    print(sys.version_info)
1950
    unittest2.main()
1951