Completed
Push — master ( 1cc01b...632e45 )
by De
51s
created

SyntaxErrorTests.test_octal_literal()   C

Complexity

Conditions 1

Size

Total Lines 9

Duplication

Lines 1
Ratio 11.11 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 1
loc 9
rs 6.2142
cc 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_moved_between_str_string(self):
890
        """Some methods have been moved from string to str."""
891
        # NICE_TO_HAVE
892
        version = (3, 0)
893
        code = 'import string\n{0}.maketrans'
894
        code_str, code_string = format_str(code, 'str', 'string')
895
        code_str2 = 'str.maketrans'  # No 'string' import
896
        self.throws(code_str, ATTRIBUTEERROR, [], up_to_version(version))
897 View Code Duplication
        self.throws(code_str2, ATTRIBUTEERROR, [], up_to_version(version))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
898
        self.runs(code_string, up_to_version(version))
899
        self.throws(code_string, ATTRIBUTEERROR, [], from_version(version))
900
        self.runs(code_str, from_version(version))
901
        self.runs(code_str2, from_version(version))
902
903
    def test_join(self):
904
        """Test what happens when join is used incorrectly.
905
906
        This can be frustrating to call join on an iterable instead of a
907
        string.
908
        """
909
        code = "['a', 'b'].join('-')"
910
        self.throws(code, ATTRIBUTEERROR, "'my_string.join(list)'")
911
912
    def test_set_dict_comprehension(self):
913
        """{} creates a dict and not an empty set leading to errors."""
914
        # NICE_TO_HAVE
915
        version = (2, 7)
916
        for method in set(dir(set)) - set(dir(dict)):
917
            if not method.startswith('__'):  # boring suggestions
918
                code = "a = {0}\na." + method
919
                typo, dict1, dict2, sugg, set1 = format_str(
920 View Code Duplication
                    code, "{}", "dict()", "{0: 0}", "set()", "{0}")
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
921
                self.throws(typo, ATTRIBUTEERROR)
922
                self.throws(dict1, ATTRIBUTEERROR)
923
                self.throws(dict2, ATTRIBUTEERROR)
924
                self.runs(sugg)
925
                self.throws(set1, INVALIDSYNTAX, [], up_to_version(version))
926
                self.runs(set1, from_version(version))
927
928
    def test_unmatched_msg(self):
929
        """Test that arbitrary strings are supported."""
930
        self.throws(
931
            'raise AttributeError("unmatched ATTRIBUTEERROR")',
932
            UNKNOWN_ATTRIBUTEERROR)
933
934
    # TODO: Add sugg for situation where self/cls is the missing parameter
935
936
937
class TypeErrorTests(GetSuggestionsTests):
938
    """Class for tests related to TypeError."""
939
940
    def test_unhashable(self):
941
        """Test for UNHASHABLE exception."""
942
        # NICE_TO_HAVE : suggest hashable equivalent
943
        self.throws('s = set([list()])', UNHASHABLE)
944
        self.throws('s = set([dict()])', UNHASHABLE)
945
        self.throws('s = set([set()])', UNHASHABLE)
946
        self.runs('s = set([tuple()])')
947
        self.runs('s = set([frozenset()])')
948
949
    def test_not_sub(self):
950
        """Should be function call, not [] operator."""
951
        typo, sugg = '[2]', '(2)'
952
        code = func_gen(param='a') + 'some_func{0}'
953
        bad_code, good_code = format_str(code, typo, sugg)
954
        suggestion = "'function(value)'"
955
        # Only Python 2.7 with cpython has a different error message
956
        # (leading to more suggestions based on fuzzy matches)
957
        version1 = (2, 7)
958
        version2 = (3, 0)
959
        self.throws(bad_code, UNSUBSCRIPTABLE, suggestion,
960
                    ALL_VERSIONS, 'pypy')
961
        self.throws(bad_code, UNSUBSCRIPTABLE, suggestion,
962
                    up_to_version(version1), 'cython')
963
        self.throws(bad_code, UNSUBSCRIPTABLE, suggestion,
964
                    from_version(version2), 'cython')
965
        self.throws(bad_code, NOATTRIBUTE_TYPEERROR,
966
                    ["'__get__'", "'__getattribute__'", suggestion],
967
                    (version1, version2), 'cython')
968
        self.runs(good_code)
969
970
    def test_method_called_on_class(self):
971
        """Test where a method is called on a class and not an instance.
972
973
        Forgetting parenthesis makes the difference between using an
974
        instance and using a type.
975
        """
976
        # NICE_TO_HAVE
977
        wrong_type = (DESCREXPECT, MUSTCALLWITHINST, NBARGERROR)
978
        not_iterable = (ARGNOTITERABLE, ARGNOTITERABLE, ARGNOTITERABLE)
979
        version = (3, 0)
980
        for code, (err_cy, err_pyp, err_pyp3) in [
981
                ('set{0}.add(0)', wrong_type),
982
                ('list{0}.append(0)', wrong_type),
983
                ('0 in list{0}', not_iterable)]:
984
            bad_code, good_code = format_str(code, '', '()')
985
            self.runs(good_code)
986
            self.throws(bad_code, err_cy, [], ALL_VERSIONS, 'cython')
987
            self.throws(bad_code, err_pyp, [], up_to_version(version), 'pypy')
988
            self.throws(bad_code, err_pyp3, [], from_version(version), 'pypy')
989
990
    def test_set_operations(self):
991
        """+, +=, etc doesn't work on sets. A suggestion would be nice."""
992
        # NICE_TO_HAVE
993
        typo1 = 'set() + set()'
994
        typo2 = 's = set()\ns += set()'
995
        code1 = 'set() | set()'
996
        code2 = 'set().union(set())'
997
        code3 = 'set().update(set())'
998
        self.throws(typo1, UNSUPPORTEDOPERAND)
999
        self.throws(typo2, UNSUPPORTEDOPERAND)
1000
        self.runs(code1)
1001
        self.runs(code2)
1002
        self.runs(code3)
1003
1004
    def test_dict_operations(self):
1005
        """+, +=, etc doesn't work on dicts. A suggestion would be nice."""
1006
        # NICE_TO_HAVE
1007
        typo1 = 'dict() + dict()'
1008
        typo2 = 'd = dict()\nd += dict()'
1009
        typo3 = 'dict() & dict()'
1010
        self.throws(typo1, UNSUPPORTEDOPERAND)
1011
        self.throws(typo2, UNSUPPORTEDOPERAND)
1012
        self.throws(typo3, UNSUPPORTEDOPERAND)
1013
        code1 = 'dict().update(dict())'
1014
        self.runs(code1)
1015
1016
    def test_unsupported_operand_caret(self):
1017
        """Use '**' for power, not '^'."""
1018
        # NICE_TO_HAVE
1019
        code = '3.5 {0} 2'
1020
        bad_code, good_code = format_str(code, '^', '**')
1021
        self.runs(good_code)
1022
        self.throws(bad_code, UNSUPPORTEDOPERAND)
1023
1024
    def test_unary_operand_custom(self):
1025
        """Test unary operand errors on custom types."""
1026
        version = (3, 0)
1027
        ops = {
1028
            '+{0}': ('__pos__', "'__doc__'"),
1029
            '-{0}': ('__neg__', None),
1030
            '~{0}': ('__invert__', "'__init__'"),
1031
            'abs({0})': ('__abs__', None),
1032
        }
1033
        obj = 'FoobarClass()'
1034
        sugg = 'implement "{0}" on FoobarClass'
1035
        for op, suggestions in ops.items():
1036
            code = op.format(obj)
1037
            magic, sugg_attr = suggestions
1038
            sugg_unary = sugg.format(magic)
1039
            self.throws(code, ATTRIBUTEERROR, sugg_attr,
1040
                        up_to_version(version))
1041
            self.throws(code, BADOPERANDUNARY, sugg_unary,
1042
                        from_version(version))
1043
1044
    def test_unary_operand_builtin(self):
1045
        """Test unary operand errors on builtin types."""
1046
        ops = [
1047
            '+{0}',
1048
            '-{0}',
1049
            '~{0}',
1050
            'abs({0})',
1051
        ]
1052
        obj = 'set()'
1053
        for op in ops:
1054
            code = op.format(obj)
1055
            self.throws(code, BADOPERANDUNARY)
1056
1057
    def test_len_on_iterable(self):
1058
        """len() can't be called on iterable (weird but understandable)."""
1059
        code = 'len(my_generator())'
1060
        sugg = 'len(list(my_generator()))'
1061
        self.throws(code, OBJECTHASNOFUNC, "'len(list(generator))'")
1062
        self.runs(sugg)
1063
1064
    def test_nb_args(self):
1065
        """Should have 1 arg."""
1066
        typo, sugg = '1, 2', '1'
1067
        code = func_gen(param='a', args='{0}')
1068
        bad_code, good_code = format_str(code, typo, sugg)
1069
        self.throws(bad_code, NBARGERROR)
1070
        self.runs(good_code)
1071
1072
    def test_nb_args1(self):
1073
        """Should have 0 args."""
1074
        typo, sugg = '1', ''
1075
        code = func_gen(param='', args='{0}')
1076
        bad_code, good_code = format_str(code, typo, sugg)
1077
        self.throws(bad_code, NBARGERROR)
1078
        self.runs(good_code)
1079
1080
    def test_nb_args2(self):
1081
        """Should have 1 arg."""
1082
        typo, sugg = '', '1'
1083
        version = (3, 3)
1084
        code = func_gen(param='a', args='{0}')
1085
        bad_code, good_code = format_str(code, typo, sugg)
1086
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1087
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1088
        self.runs(good_code)
1089
1090
    def test_nb_args3(self):
1091
        """Should have 3 args."""
1092
        typo, sugg = '1', '1, 2, 3'
1093
        version = (3, 3)
1094
        code = func_gen(param='so, much, args', args='{0}')
1095
        bad_code, good_code = format_str(code, typo, sugg)
1096
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1097
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1098
        self.runs(good_code)
1099
1100
    def test_nb_args4(self):
1101
        """Should have 3 args."""
1102
        typo, sugg = '', '1, 2, 3'
1103
        version = (3, 3)
1104
        code = func_gen(param='so, much, args', args='{0}')
1105
        bad_code, good_code = format_str(code, typo, sugg)
1106
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1107
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1108
        self.runs(good_code)
1109
1110
    def test_nb_args5(self):
1111
        """Should have 3 args."""
1112
        typo, sugg = '1, 2', '1, 2, 3'
1113
        version = (3, 3)
1114
        code = func_gen(param='so, much, args', args='{0}')
1115
        bad_code, good_code = format_str(code, typo, sugg)
1116
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1117
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1118
        self.runs(good_code)
1119
1120
    def test_nb_args6(self):
1121
        """Should provide more args."""
1122
        # Amusing message: 'func() takes exactly 2 arguments (2 given)'
1123
        version = (3, 3)
1124
        code = func_gen(param='a, b, c=3', args='{0}')
1125
        bad_code, good_code1, good_code2 = format_str(
1126
            code,
1127
            'b=2, c=3',
1128
            'a=1, b=2, c=3',
1129
            '1, b=2, c=3')
1130
        self.throws(bad_code, NBARGERROR, [], up_to_version(version))
1131
        self.throws(bad_code, MISSINGPOSERROR, [], from_version(version))
1132
        self.runs(good_code1)
1133
        self.runs(good_code2)
1134
1135
    def test_nb_arg_missing_self(self):
1136
        """Arg 'self' is missing."""
1137
        # NICE_TO_HAVE
1138
        obj = 'FoobarClass()'
1139
        self.throws(obj + '.some_method_missing_self_arg()', NBARGERROR)
1140
        self.throws(obj + '.some_method_missing_self_arg2(42)', NBARGERROR)
1141
        self.runs(obj + '.some_method()')
1142
        self.runs(obj + '.some_method2(42)')
1143
1144
    def test_nb_arg_missing_cls(self):
1145
        """Arg 'cls' is missing."""
1146
        # NICE_TO_HAVE
1147
        for obj in ('FoobarClass()', 'FoobarClass'):
1148
            self.throws(obj + '.some_cls_method_missing_cls()', NBARGERROR)
1149
            self.throws(obj + '.some_cls_method_missing_cls2(42)', NBARGERROR)
1150
            self.runs(obj + '.this_is_cls_mthd()')
1151
1152
    def test_keyword_args(self):
1153
        """Should be param 'babar' not 'a' but it's hard to guess."""
1154
        typo, sugg = 'a', 'babar'
1155
        code = func_gen(param=sugg, args='{0}=1')
1156
        bad_code, good_code = format_str(code, typo, sugg)
1157
        self.throws(bad_code, UNEXPECTEDKWARG)
1158
        self.runs(good_code)
1159
1160
    def test_keyword_args2(self):
1161
        """Should be param 'abcdef' not 'abcdf'."""
1162
        typo, sugg = 'abcdf', 'abcdef'
1163
        code = func_gen(param=sugg, args='{0}=1')
1164
        bad_code, good_code = format_str(code, typo, sugg)
1165
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1166
        self.runs(good_code)
1167
1168
    def test_keyword_arg_method(self):
1169
        """Should be the same as previous test but on a method."""
1170
        code = 'class MyClass:\n\tdef func(self, a):' \
1171
               '\n\t\tpass\nMyClass().func({0}=1)'
1172
        bad_code, good_code = format_str(code, 'babar', 'a')
1173
        self.throws(bad_code, UNEXPECTEDKWARG)
1174
        self.runs(good_code)
1175
1176
    def test_keyword_arg_method2(self):
1177
        """Should be the same as previous test but on a method."""
1178
        typo, sugg = 'abcdf', 'abcdef'
1179
        code = 'class MyClass:\n\tdef func(self, ' + sugg + '):' \
1180
               '\n\t\tpass\nMyClass().func({0}=1)'
1181
        bad_code, good_code = format_str(code, typo, sugg)
1182
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1183
        self.runs(good_code)
1184
1185
    def test_keyword_arg_class_method(self):
1186
        """Should be the same as previous test but on a class method."""
1187
        code = 'class MyClass:\n\t@classmethod\n\tdef func(cls, a):' \
1188
               '\n\t\tpass\nMyClass.func({0}=1)'
1189
        bad_code, good_code = format_str(code, 'babar', 'a')
1190
        self.throws(bad_code, UNEXPECTEDKWARG)
1191
        self.runs(good_code)
1192
1193
    def test_keyword_arg_class_method2(self):
1194
        """Should be the same as previous test but on a class method."""
1195
        typo, sugg = 'abcdf', 'abcdef'
1196
        code = 'class MyClass:\n\t@classmethod ' \
1197
               '\n\tdef func(cls, ' + sugg + '):\n ' \
1198
               '\t\tpass\nMyClass.func({0}=1)'
1199
        bad_code, good_code = format_str(code, typo, sugg)
1200
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1201
        self.runs(good_code)
1202
1203
    def test_keyword_arg_multiples_instances(self):
1204
        """If multiple functions are found, suggestions should be unique."""
1205
        typo, sugg = 'abcdf', 'abcdef'
1206
        code = 'class MyClass:\n\tdef func(self, ' + sugg + '):' \
1207
               '\n\t\tpass\na = MyClass()\nb = MyClass()\na.func({0}=1)'
1208
        bad_code, good_code = format_str(code, typo, sugg)
1209
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1210
        self.runs(good_code)
1211
1212
    def test_keyword_arg_lambda(self):
1213
        """Test with lambda functions instead of usual function."""
1214
        typo, sugg = 'abcdf', 'abcdef'
1215
        code = 'f = lambda arg1, ' + sugg + ': None\nf(42, {0}=None)'
1216
        bad_code, good_code = format_str(code, typo, sugg)
1217
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1218
        self.runs(good_code)
1219
1220
    def test_keyword_arg_lambda_method(self):
1221
        """Test with lambda methods instead of usual methods."""
1222
        typo, sugg = 'abcdf', 'abcdef'
1223
        code = 'class MyClass:\n\tfunc = lambda self, ' + sugg + ': None' \
1224
               '\nMyClass().func({0}=1)'
1225
        bad_code, good_code = format_str(code, typo, sugg)
1226
        self.throws(bad_code, UNEXPECTEDKWARG, "'" + sugg + "'")
1227
        self.runs(good_code)
1228
1229
    def test_keyword_arg_other_objects_with_name(self):
1230
        """Mix of previous tests but with more objects defined.
1231
1232
        Non-function object with same same as the function tested are defined
1233
        to ensure that things do work fine.
1234
        """
1235
        code = 'func = "not_a_func"\nclass MyClass:\n\tdef func(self, a):' \
1236
               '\n\t\tpass\nMyClass().func({0}=1)'
1237
        bad_code, good_code = format_str(code, 'babar', 'a')
1238
        self.throws(bad_code, UNEXPECTEDKWARG)
1239
        self.runs(good_code)
1240
1241
    def test_keyword_builtin(self):
1242
        """A few builtins (like int()) have a different error message."""
1243
        # NICE_TO_HAVE
1244
        # 'max', 'input', 'len', 'abs', 'all', etc have a specific error
1245
        # message and are not relevant here
1246
        for builtin in ['int', 'float', 'bool', 'complex']:
1247
            code = builtin + '(this_doesnt_exist=2)'
1248
            self.throws(code, UNEXPECTEDKWARG2, [], ALL_VERSIONS, 'cython')
1249
            self.throws(code, UNEXPECTEDKWARG, [], ALL_VERSIONS, 'pypy')
1250
1251
    def test_keyword_builtin_print(self):
1252
        """Builtin "print" has a different error message."""
1253
        # It would be NICE_TO_HAVE suggestions on keyword arguments
1254
        v3 = (3, 0)
1255
        code = "c = 'string'\nb = print(c, end_='toto')"
1256
        self.throws(code, INVALIDSYNTAX, [], up_to_version(v3))
1257
        self.throws(code, UNEXPECTEDKWARG2, [], from_version(v3), 'cython')
1258
        self.throws(code, UNEXPECTEDKWARG3, [], from_version(v3), 'pypy')
1259
1260
    def test_no_implicit_str_conv(self):
1261
        """Trying to concatenate a non-string value to a string."""
1262
        # NICE_TO_HAVE
1263
        code = '{0} + " things"'
1264
        typo, sugg = '12', 'str(12)'
1265
        bad_code, good_code = format_str(code, typo, sugg)
1266
        self.throws(bad_code, UNSUPPORTEDOPERAND)
1267
        self.runs(good_code)
1268
1269
    def test_no_implicit_str_conv2(self):
1270
        """Trying to concatenate a non-string value to a string."""
1271
        # NICE_TO_HAVE
1272
        code = '"things " + {0}'
1273
        typo, sugg = '12', 'str(12)'
1274
        bad_code, good_code = format_str(code, typo, sugg)
1275
        version = (3, 0)
1276
        version2 = (3, 6)
1277
        self.throws(
1278
            bad_code, CANNOTCONCAT, [], up_to_version(version), 'cython')
1279
        self.throws(
1280
            bad_code, CANTCONVERT, [], (version, version2), 'cython')
1281
        self.throws(
1282
            bad_code, MUSTBETYPENOTTYPE, [], from_version(version2), 'cython')
1283
        self.throws(
1284
            bad_code, UNSUPPORTEDOPERAND, [], ALL_VERSIONS, 'pypy')
1285
        self.runs(good_code)
1286
1287
    def test_assignment_to_range(self):
1288
        """Trying to assign to range works on list, not on range."""
1289
        code = '{0}[2] = 1'
1290
        typo, sugg = 'range(4)', 'list(range(4))'
1291
        version = (3, 0)
1292
        bad_code, good_code = format_str(code, typo, sugg)
1293
        self.runs(good_code)
1294
        self.runs(bad_code, up_to_version(version))
1295
        self.throws(
1296
            bad_code,
1297
            OBJECTDOESNOTSUPPORT,
1298
            'convert to list to edit the list',
1299
            from_version(version))
1300
1301 View Code Duplication
    def test_assignment_to_string(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1302
        """Trying to assign to string does not work."""
1303
        code = "s = 'abc'\ns[1] = 'd'"
1304
        good_code = "s = 'abc'\nl = list(s)\nl[1] = 'd'\ns = ''.join(l)"
1305
        self.runs(good_code)
1306
        self.throws(
1307
            code,
1308
            OBJECTDOESNOTSUPPORT,
1309
            'convert to list to edit the list and use "join()" on the list')
1310
1311
    def test_deletion_from_string(self):
1312
        """Delete from string does not work."""
1313
        code = "s = 'abc'\ndel s[1]"
1314
        good_code = "s = 'abc'\nl = list(s)\ndel l[1]\ns = ''.join(l)"
1315
        self.runs(good_code)
1316
        self.throws(
1317
            code,
1318
            OBJECTDOESNOTSUPPORT,
1319
            'convert to list to edit the list and use "join()" on the list')
1320
1321
    def test_object_indexing(self):
1322
        """Index from object does not work if __getitem__ is not defined."""
1323
        version = (3, 0)
1324
        code = "{0}[0]"
1325
        good_code, set_code, custom_code = \
1326
            format_str(code, '"a_string"', "set()", "FoobarClass()")
1327
        self.runs(good_code)
1328
        sugg_for_iterable = 'convert to list first or use the iterator ' \
1329
            'protocol to get the different elements'
1330
        self.throws(set_code,
1331
                    OBJECTDOESNOTSUPPORT,
1332
                    sugg_for_iterable, ALL_VERSIONS, 'cython')
1333
        self.throws(set_code,
1334
                    UNSUBSCRIPTABLE,
1335
                    sugg_for_iterable, ALL_VERSIONS, 'pypy')
1336
        self.throws(custom_code,
1337
                    ATTRIBUTEERROR, [], up_to_version(version), 'pypy')
1338
        self.throws(custom_code,
1339
                    UNSUBSCRIPTABLE,
1340
                    'implement "__getitem__" on FoobarClass',
1341
                    from_version(version), 'pypy')
1342
        self.throws(custom_code,
1343
                    ATTRIBUTEERROR, [], up_to_version(version), 'cython')
1344
        self.throws(custom_code,
1345
                    OBJECTDOESNOTSUPPORT,
1346
                    'implement "__getitem__" on FoobarClass',
1347
                    from_version(version), 'cython')
1348
1349
    def test_not_callable(self):
1350
        """Sometimes, one uses parenthesis instead of brackets."""
1351
        typo, getitem = '(0)', '[0]'
1352
        for ex, sugg in {
1353
            '[0]': "'list[value]'",
1354
            '{0: 0}': "'dict[value]'",
1355
            '"a"': "'str[value]'",
1356
        }.items():
1357
            self.throws(ex + typo, NOTCALLABLE, sugg)
1358
            self.runs(ex + getitem)
1359
        for ex in ['1', 'set()']:
1360
            self.throws(ex + typo, NOTCALLABLE)
1361
1362
    def test_unmatched_msg(self):
1363
        """Test that arbitrary strings are supported."""
1364
        self.throws(
1365
            'raise TypeError("unmatched TYPEERROR")',
1366
            UNKNOWN_TYPEERROR)
1367
1368
1369
class ImportErrorTests(GetSuggestionsTests):
1370
    """Class for tests related to ImportError."""
1371
1372
    def test_no_module_no_sugg(self):
1373
        """No suggestion."""
1374
        self.throws('import fqslkdfjslkqdjfqsd', NOMODULE)
1375
1376
    def test_no_module(self):
1377
        """Should be 'math'."""
1378
        code = 'import {0}'
1379
        typo, sugg = 'maths', 'math'
1380
        self.assertTrue(sugg in STAND_MODULES)
1381
        bad_code, good_code = format_str(code, typo, sugg)
1382
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1383
        self.runs(good_code)
1384
1385
    def test_no_module2(self):
1386
        """Should be 'math'."""
1387
        code = 'from {0} import pi'
1388
        typo, sugg = 'maths', 'math'
1389
        self.assertTrue(sugg in STAND_MODULES)
1390
        bad_code, good_code = format_str(code, typo, sugg)
1391
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1392
        self.runs(good_code)
1393
1394
    def test_no_module3(self):
1395
        """Should be 'math'."""
1396
        code = 'import {0} as my_imported_math'
1397
        typo, sugg = 'maths', 'math'
1398
        self.assertTrue(sugg in STAND_MODULES)
1399
        bad_code, good_code = format_str(code, typo, sugg)
1400
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1401
        self.runs(good_code)
1402
1403
    def test_no_module4(self):
1404
        """Should be 'math'."""
1405
        code = 'from {0} import pi as three_something'
1406
        typo, sugg = 'maths', 'math'
1407
        self.assertTrue(sugg in STAND_MODULES)
1408
        bad_code, good_code = format_str(code, typo, sugg)
1409
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1410
        self.runs(good_code)
1411
1412
    def test_no_module5(self):
1413
        """Should be 'math'."""
1414
        code = '__import__("{0}")'
1415
        typo, sugg = 'maths', 'math'
1416
        self.assertTrue(sugg in STAND_MODULES)
1417
        bad_code, good_code = format_str(code, typo, sugg)
1418
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1419
        self.runs(good_code)
1420
1421
    def test_import_future_nomodule(self):
1422
        """Should be '__future__'."""
1423
        code = 'import {0}'
1424
        typo, sugg = '__future_', '__future__'
1425
        self.assertTrue(sugg in STAND_MODULES)
1426
        bad_code, good_code = format_str(code, typo, sugg)
1427
        self.throws(bad_code, NOMODULE, "'" + sugg + "'")
1428
        self.runs(good_code)
1429
1430
    def test_no_name_no_sugg(self):
1431
        """No suggestion."""
1432
        self.throws('from math import fsfsdfdjlkf', CANNOTIMPORT)
1433
1434
    def test_wrong_import(self):
1435
        """Should be 'math'."""
1436
        code = 'from {0} import pi'
1437
        typo, sugg = 'itertools', 'math'
1438
        self.assertTrue(sugg in STAND_MODULES)
1439
        bad_code, good_code = format_str(code, typo, sugg)
1440
        self.throws(bad_code, CANNOTIMPORT, "'" + good_code + "'")
1441
        self.runs(good_code)
1442
1443
    def test_typo_in_method(self):
1444
        """Should be 'pi'."""
1445
        code = 'from math import {0}'
1446
        typo, sugg = 'pie', 'pi'
1447
        bad_code, good_code = format_str(code, typo, sugg)
1448
        self.throws(bad_code, CANNOTIMPORT, "'" + sugg + "'")
1449
        self.runs(good_code)
1450
1451
    def test_typo_in_method2(self):
1452
        """Should be 'pi'."""
1453
        code = 'from math import e, {0}, log'
1454
        typo, sugg = 'pie', 'pi'
1455
        bad_code, good_code = format_str(code, typo, sugg)
1456
        self.throws(bad_code, CANNOTIMPORT, "'" + sugg + "'")
1457
        self.runs(good_code)
1458
1459
    def test_typo_in_method3(self):
1460
        """Should be 'pi'."""
1461
        code = 'from math import {0} as three_something'
1462
        typo, sugg = 'pie', 'pi'
1463
        bad_code, good_code = format_str(code, typo, sugg)
1464
        self.throws(bad_code, CANNOTIMPORT, "'" + sugg + "'")
1465
        self.runs(good_code)
1466
1467
    def test_unmatched_msg(self):
1468
        """Test that arbitrary strings are supported."""
1469
        self.throws(
1470
            'raise ImportError("unmatched IMPORTERROR")',
1471
            UNKNOWN_IMPORTERROR)
1472
1473
    def test_module_removed(self):
1474
        """Sometimes, modules are deleted/moved/renamed."""
1475
        # NICE_TO_HAVE
1476
        version1 = (2, 7)  # result for 2.6 seems to vary
1477
        version2 = (3, 0)
1478
        code = 'import {0}'
1479
        lower, upper = format_str(code, 'tkinter', 'Tkinter')
1480
        self.throws(lower, NOMODULE, [], (version1, version2))
1481
        self.throws(upper, NOMODULE, [], from_version(version2))
1482
1483
1484
class LookupErrorTests(GetSuggestionsTests):
1485
    """Class for tests related to LookupError."""
1486
1487
1488
class KeyErrorTests(LookupErrorTests):
1489
    """Class for tests related to KeyError."""
1490
1491
    def test_no_sugg(self):
1492
        """No suggestion."""
1493
        self.throws('dict()["ffdsqmjklfqsd"]', KEYERROR)
1494
1495
1496
class IndexErrorTests(LookupErrorTests):
1497
    """Class for tests related to IndexError."""
1498
1499
    def test_no_sugg(self):
1500
        """No suggestion."""
1501
        self.throws('list()[2]', OUTOFRANGE)
1502
1503
1504
class SyntaxErrorTests(GetSuggestionsTests):
1505
    """Class for tests related to SyntaxError."""
1506
1507
    def test_no_error(self):
1508
        """No error."""
1509
        self.runs("1 + 2 == 2")
1510
1511
    def test_yield_return_out_of_func(self):
1512
        """yield/return needs to be in functions."""
1513
        sugg = "to indent it"
1514
        self.throws("yield 1", OUTSIDEFUNC, sugg)
1515
        self.throws("return 1", OUTSIDEFUNC, ["'sys.exit([arg])'", sugg])
1516
1517
    def test_print(self):
1518
        """print is a functions now and needs parenthesis."""
1519
        # NICE_TO_HAVE
1520
        code, new_code = 'print ""', 'print("")'
1521
        version = (3, 0)
1522
        version2 = (3, 4)
1523
        self.runs(code, up_to_version(version))
1524
        self.throws(code, INVALIDSYNTAX, [], (version, version2))
1525
        self.throws(code, INVALIDSYNTAX, [], from_version(version2))
1526
        self.runs(new_code)
1527
1528
    def test_exec(self):
1529
        """exec is a functions now and needs parenthesis."""
1530
        # NICE_TO_HAVE
1531
        code, new_code = 'exec "1"', 'exec("1")'
1532
        version = (3, 0)
1533
        version2 = (3, 4)
1534
        self.runs(code, up_to_version(version))
1535
        self.throws(code, INVALIDSYNTAX, [], (version, version2))
1536
        self.throws(code, INVALIDSYNTAX, [], from_version(version2))
1537
        self.runs(new_code)
1538
1539
    def test_old_comparison(self):
1540
        """<> comparison is removed, != always works."""
1541
        code = '1 {0} 2'
1542
        old, new = '<>', '!='
1543
        version = (3, 0)
1544
        old_code, new_code = format_str(code, old, new)
1545
        self.runs(old_code, up_to_version(version))
1546
        self.throws(
1547
            old_code,
1548
            INVALIDCOMP,
1549
            "'!='",
1550
            from_version(version),
1551
            'pypy')
1552
        self.throws(
1553
            old_code,
1554
            INVALIDSYNTAX,
1555
            "'!='",
1556
            from_version(version),
1557
            'cython')
1558
        self.runs(new_code)
1559
1560
    def test_missing_colon(self):
1561
        """Missing colon is a classic mistake."""
1562
        # NICE_TO_HAVE
1563
        code = "if True{0}\n\tpass"
1564
        bad_code, good_code = format_str(code, "", ":")
1565
        self.throws(bad_code, INVALIDSYNTAX)
1566
        self.runs(good_code)
1567
1568
    def test_missing_colon2(self):
1569
        """Missing colon is a classic mistake."""
1570
        # NICE_TO_HAVE
1571
        code = "class MyClass{0}\n\tpass"
1572
        bad_code, good_code = format_str(code, "", ":")
1573
        self.throws(bad_code, INVALIDSYNTAX)
1574
        self.runs(good_code)
1575
1576
    def test_simple_equal(self):
1577
        """'=' for comparison is a classic mistake."""
1578
        # NICE_TO_HAVE
1579
        code = "if 2 {0} 3:\n\tpass"
1580
        bad_code, good_code = format_str(code, "=", "==")
1581
        self.throws(bad_code, INVALIDSYNTAX)
1582
        self.runs(good_code)
1583
1584
    def test_keyword_as_identifier(self):
1585
        """Using a keyword as a variable name."""
1586
        # NICE_TO_HAVE
1587
        code = '{0} = 1'
1588
        bad_code, good_code = format_str(code, "from", "from_")
1589
        self.throws(bad_code, INVALIDSYNTAX)
1590
        self.runs(good_code)
1591
1592
    def test_increment(self):
1593
        """Trying to use '++' or '--'."""
1594
        # NICE_TO_HAVE
1595
        code = 'a = 0\na{0}'
1596
        # Adding pointless suffix to avoid wrong assumptions
1597
        for end in ('', '  ', ';', ' ;'):
1598
            code2 = code + end
1599
            for op in ('-', '+'):
1600
                typo, sugg = 2 * op, op + '=1'
1601
                bad_code, good_code = format_str(code + end, typo, sugg)
1602
                self.throws(bad_code, INVALIDSYNTAX)
1603
                self.runs(good_code)
1604
1605
    def test_wrong_bool_operator(self):
1606
        """Trying to use '&&' or '||'."""
1607
        code = 'True {0} False'
1608
        for typo, sugg in (('&&', 'and'), ('||', 'or')):
1609
            bad_code, good_code = format_str(code, typo, sugg)
1610
            self.throws(bad_code, INVALIDSYNTAX, "'" + sugg + "'")
1611
            self.runs(good_code)
1612
1613
    def test_import_future_not_first(self):
1614
        """Test what happens when import from __future__ is not first."""
1615
        code = 'a = 8/7\nfrom __future__ import division'
1616
        self.throws(code, FUTUREFIRST)
1617
1618
    def test_import_future_not_def(self):
1619
        """Should be 'division'."""
1620
        code = 'from __future__ import {0}'
1621
        typo, sugg = 'divisio', 'division'
1622
        bad_code, good_code = format_str(code, typo, sugg)
1623
        self.throws(bad_code, FUTFEATNOTDEF, "'" + sugg + "'")
1624
        self.runs(good_code)
1625
1626
    def test_unqualified_exec(self):
1627
        """Exec in nested functions."""
1628
        # NICE_TO_HAVE
1629
        version = (3, 0)
1630
        codes = [
1631
            "def func1():\n\tbar='1'\n\tdef func2():"
1632
            "\n\t\texec(bar)\n\tfunc2()\nfunc1()",
1633
            "def func1():\n\texec('1')\n\tdef func2():"
1634
            "\n\t\tTrue",
1635
        ]
1636
        for code in codes:
1637
            self.throws(code, UNQUALIFIED_EXEC, [], up_to_version(version))
1638
            self.runs(code, from_version(version))
1639
1640
    def test_import_star(self):
1641
        """'import *' in nested functions."""
1642
        # NICE_TO_HAVE
1643
        codes = [
1644
            "def func1():\n\tbar='1'\n\tdef func2():"
1645
            "\n\t\tfrom math import *\n\t\tTrue\n\tfunc2()\nfunc1()",
1646
            "def func1():\n\tfrom math import *"
1647
            "\n\tdef func2():\n\t\tTrue",
1648
        ]
1649
        with warnings.catch_warnings():
1650
            warnings.simplefilter("ignore", category=SyntaxWarning)
1651
            for code in codes:
1652
                self.throws(code, IMPORTSTAR, [])
1653
1654
    def test_unpack(self):
1655
        """Extended tuple unpacking does not work prior to Python 3."""
1656
        # NICE_TO_HAVE
1657
        version = (3, 0)
1658
        code = 'a, *b = (1, 2, 3)'
1659
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1660
        self.runs(code, from_version(version))
1661
1662
    def test_unpack2(self):
1663
        """Unpacking in function arguments was supported up to Python 3."""
1664
        # NICE_TO_HAVE
1665
        version = (3, 0)
1666
        code = 'def addpoints((x1, y1), (x2, y2)):\n\tpass'
1667
        self.runs(code, up_to_version(version))
1668
        self.throws(code, INVALIDSYNTAX, [], from_version(version))
1669
1670
    def test_nonlocal(self):
1671
        """nonlocal keyword is added in Python 3."""
1672
        # NICE_TO_HAVE
1673
        version = (3, 0)
1674
        code = 'def func():\n\tfoo = 1\n\tdef nested():\n\t\tnonlocal foo'
1675 View Code Duplication
        self.runs(code, from_version(version))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1676
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1677
1678
    def test_nonlocal2(self):
1679
        """nonlocal must be used only when binding exists."""
1680
        # NICE_TO_HAVE
1681
        version = (3, 0)
1682
        code = 'def func():\n\tdef nested():\n\t\tnonlocal foo'
1683
        self.throws(code, NOBINDING, [], from_version(version))
1684
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1685
1686
    def test_nonlocal3(self):
1687
        """nonlocal must be used only when binding to non-global exists."""
1688
        # NICE_TO_HAVE
1689
        version = (3, 0)
1690
        code = 'foo = 1\ndef func():\n\tdef nested():\n\t\tnonlocal foo'
1691
        self.throws(code, NOBINDING, [], from_version(version))
1692
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1693
1694
    def test_octal_literal(self):
1695
        """Syntax for octal liberals has changed."""
1696
        # NICE_TO_HAVE
1697
        version = (3, 0)
1698
        bad, good = '0720', '0o720'
1699
        self.runs(good)
1700
        self.runs(bad, up_to_version(version))
1701
        self.throws(bad, INVALIDTOKEN, [], from_version(version), 'cython')
1702
        self.throws(bad, INVALIDSYNTAX, [], from_version(version), 'pypy')
1703
1704
    def test_extended_unpacking(self):
1705
        """Extended iterable unpacking is added with Python 3."""
1706
        version = (3, 0)
1707
        code = '(a, *rest, b) = range(5)'
1708
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1709
        self.runs(code, from_version(version))
1710
1711
    def test_ellipsis(self):
1712
        """Triple dot (...) aka Ellipsis can be used anywhere in Python 3."""
1713
        version = (3, 0)
1714
        code = '...'
1715
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1716
        self.runs(code, from_version(version))
1717
1718
    def test_fstring(self):
1719
        """Fstring (see PEP 498) appeared in Python 3.6."""
1720
        # NICE_TO_HAVE
1721
        version = (3, 6)
1722
        code = 'f"toto"'
1723
        self.throws(code, INVALIDSYNTAX, [], up_to_version(version))
1724
        self.runs(code, from_version(version))
1725
1726
1727
class MemoryErrorTests(GetSuggestionsTests):
1728
    """Class for tests related to MemoryError."""
1729
1730
    def test_out_of_memory(self):
1731
        """Test what happens in case of MemoryError."""
1732
        code = '[0] * 999999999999999'
1733
        self.throws(code, MEMORYERROR)
1734
1735
    def test_out_of_memory_range(self):
1736
        """Test what happens in case of MemoryError."""
1737
        code = '{0}(999999999999999)'
1738
        typo, sugg = 'range', 'xrange'
1739
        bad_code, good_code = format_str(code, typo, sugg)
1740
        self.runs(bad_code, ALL_VERSIONS, 'pypy')
1741
        version = (2, 7)
1742
        version2 = (3, 0)
1743
        self.throws(
1744
            bad_code,
1745
            OVERFLOWERR, "'" + sugg + "'",
1746
            up_to_version(version),
1747
            'cython')
1748
        self.throws(
1749
            bad_code,
1750
            MEMORYERROR, "'" + sugg + "'",
1751
            (version, version2),
1752
            'cython')
1753
        self.runs(good_code, up_to_version(version2), 'cython')
1754
        self.runs(bad_code, from_version(version2), 'cython')
1755
1756
1757
class ValueErrorTests(GetSuggestionsTests):
1758
    """Class for tests related to ValueError."""
1759
1760
    def test_too_many_values(self):
1761
        """Unpack 4 values in 3 variables."""
1762
        code = 'a, b, c = [1, 2, 3, 4]'
1763
        version = (3, 0)
1764
        self.throws(code, EXPECTEDLENGTH, [], up_to_version(version), 'pypy')
1765
        self.throws(code, TOOMANYVALUES, [], from_version(version), 'pypy')
1766
        self.throws(code, TOOMANYVALUES, [], ALL_VERSIONS, 'cython')
1767
1768
    def test_not_enough_values(self):
1769
        """Unpack 2 values in 3 variables."""
1770
        code = 'a, b, c = [1, 2]'
1771
        version = (3, 0)
1772
        self.throws(code, EXPECTEDLENGTH, [], up_to_version(version), 'pypy')
1773
        self.throws(code, NEEDMOREVALUES, [], from_version(version), 'pypy')
1774
        self.throws(code, NEEDMOREVALUES, [], ALL_VERSIONS, 'cython')
1775
1776
    def test_conversion_fails(self):
1777
        """Conversion fails."""
1778
        self.throws('int("toto")', INVALIDLITERAL)
1779
1780
    def test_math_domain(self):
1781
        """Math function used out of its domain."""
1782
        code = 'import math\nlg = math.log(-1)'
1783
        self.throws(code, MATHDOMAIN)
1784
1785
    def test_zero_len_field_in_format(self):
1786
        """Format {} is not valid before Python 2.7."""
1787
        code = '"{0}".format(0)'
1788
        old, new = '{0}', '{}'
1789
        old_code, new_code = format_str(code, old, new)
1790
        version = (2, 7)
1791
        self.runs(old_code)
1792
        self.throws(new_code, ZEROLENERROR, '{0}', up_to_version(version))
1793
        self.runs(new_code, from_version(version))
1794
1795
    def test_timedata_does_not_match(self):
1796
        """Strptime arguments are in wrong order."""
1797
        code = 'import datetime\ndatetime.datetime.strptime({0}, {1})'
1798
        timedata, timeformat = '"30 Nov 00"', '"%d %b %y"'
1799
        good_code = code.format(*(timedata, timeformat))
1800
        bad_code = code.format(*(timeformat, timedata))
1801
        self.runs(good_code)
1802
        self.throws(bad_code, TIMEDATAFORMAT,
1803
                    ['to swap value and format parameters'])
1804
1805
1806
class RuntimeErrorTests(GetSuggestionsTests):
1807
    """Class for tests related to RuntimeError."""
1808
1809
    def test_max_depth(self):
1810
        """Reach maximum recursion depth."""
1811
        sys.setrecursionlimit(200)
1812
        code = 'endlessly_recursive_func(0)'
1813
        self.throws(code, MAXRECURDEPTH,
1814
                    ["increase the limit with `sys.setrecursionlimit(limit)`"
1815
                        " (current value is 200)",
1816
                     AVOID_REC_MESSAGE])
1817
1818
    def test_dict_size_changed_during_iter(self):
1819
        """Test size change during iteration (dict)."""
1820
        # NICE_TO_HAVE
1821
        code = 'd = dict(enumerate("notimportant"))' \
1822
            '\nfor e in d:\n\td.pop(e)'
1823
        self.throws(code, SIZECHANGEDDURINGITER)
1824
1825
    def test_set_changed_size_during_iter(self):
1826
        """Test size change during iteration (set)."""
1827
        # NICE_TO_HAVE
1828
        code = 's = set("notimportant")' \
1829
            '\nfor e in s:\n\ts.pop()'
1830
        self.throws(code, SIZECHANGEDDURINGITER)
1831
1832
    def test_dequeue_changed_during_iter(self):
1833
        """Test size change during iteration (dequeue)."""
1834
        # NICE_TO_HAVE
1835
        # "deque mutated during iteration"
1836
        pass
1837
1838
1839
class IOErrorTests(GetSuggestionsTests):
1840
    """Class for tests related to IOError."""
1841
1842
    def test_no_such_file(self):
1843
        """File does not exist."""
1844
        code = 'with open("doesnotexist") as f:\n\tpass'
1845
        self.throws(code, NOFILE_IO)
1846
1847
    def test_no_such_file2(self):
1848
        """File does not exist."""
1849
        code = 'os.listdir("doesnotexist")'
1850
        self.throws(code, NOFILE_OS)
1851
1852
    def test_no_such_file_user(self):
1853
        """Suggestion when one needs to expanduser."""
1854
        code = 'os.listdir("{0}")'
1855
        typo, sugg = "~", os.path.expanduser("~")
1856
        bad_code, good_code = format_str(code, typo, sugg)
1857
        self.throws(
1858
            bad_code, NOFILE_OS,
1859
            "'" + sugg + "' (calling os.path.expanduser)")
1860
        self.runs(good_code)
1861
1862
    def test_no_such_file_vars(self):
1863
        """Suggestion when one needs to expandvars."""
1864
        code = 'os.listdir("{0}")'
1865
        key = 'HOME'
1866
        typo, sugg = "$" + key, os.path.expanduser("~")
1867
        original_home = os.environ.get('HOME')
1868
        os.environ[key] = sugg
1869
        bad_code, good_code = format_str(code, typo, sugg)
1870
        self.throws(
1871
            bad_code, NOFILE_OS,
1872
            "'" + sugg + "' (calling os.path.expandvars)")
1873
        self.runs(good_code)
1874
        if original_home is None:
1875
            del os.environ[key]
1876
        else:
1877
            os.environ[key] = original_home
1878
1879
    def create_tmp_dir_with_files(self, filelist):
1880
        """Create a temporary directory with files in it."""
1881
        tmpdir = tempfile.mkdtemp()
1882
        absfiles = [os.path.join(tmpdir, f) for f in filelist]
1883
        for name in absfiles:
1884
            open(name, 'a').close()
1885
        return (tmpdir, absfiles)
1886
1887
    def test_is_dir_empty(self):
1888
        """Suggestion when file is an empty directory."""
1889
        # Create empty temp dir
1890
        tmpdir, _ = self.create_tmp_dir_with_files([])
1891
        code = 'with open("{0}") as f:\n\tpass'
1892
        bad_code, _ = format_str(code, tmpdir, "TODO")
1893
        self.throws(
1894
            bad_code, ISADIR_IO, "to add content to {0} first".format(tmpdir))
1895
        rmtree(tmpdir)
1896
1897
    def test_is_dir_small(self):
1898
        """Suggestion when file is directory with a few files."""
1899
        # Create temp dir with a few files
1900
        nb_files = 3
1901
        files = sorted([str(i) + ".txt" for i in range(nb_files)])
1902
        tmpdir, absfiles = self.create_tmp_dir_with_files(files)
1903
        code = 'with open("{0}") as f:\n\tpass'
1904
        bad_code, good_code = format_str(code, tmpdir, absfiles[0])
1905
        self.throws(
1906
            bad_code, ISADIR_IO,
1907
            "any of the 3 files in directory ('0.txt', '1.txt', '2.txt')")
1908
        self.runs(good_code)
1909
        rmtree(tmpdir)
1910
1911
    def test_is_dir_big(self):
1912
        """Suggestion when file is directory with many files."""
1913
        # Create temp dir with many files
1914
        tmpdir = tempfile.mkdtemp()
1915
        nb_files = 30
1916
        files = sorted([str(i) + ".txt" for i in range(nb_files)])
1917
        tmpdir, absfiles = self.create_tmp_dir_with_files(files)
1918
        code = 'with open("{0}") as f:\n\tpass'
1919
        bad_code, good_code = format_str(code, tmpdir, absfiles[0])
1920
        self.throws(
1921
            bad_code, ISADIR_IO,
1922
            "any of the 30 files in directory "
1923
            "('0.txt', '1.txt', '10.txt', '11.txt', etc)")
1924
        self.runs(good_code)
1925
        rmtree(tmpdir)
1926
1927
    def test_is_not_dir(self):
1928
        """Suggestion when file is not a directory."""
1929
        code = 'with open("{0}") as f:\n\tpass'
1930
        code = 'os.listdir("{0}")'
1931
        typo, sugg = __file__, os.path.dirname(__file__)
1932
        bad_code, good_code = format_str(code, typo, sugg)
1933
        self.throws(
1934
            bad_code, NOTADIR_OS,
1935
            "'" + sugg + "' (calling os.path.dirname)")
1936
        self.runs(good_code)
1937
1938
    def test_dir_is_not_empty(self):
1939
        """Suggestion when directory is not empty."""
1940
        # NICE_TO_HAVE
1941
        nb_files = 3
1942
        files = sorted([str(i) + ".txt" for i in range(nb_files)])
1943
        tmpdir, _ = self.create_tmp_dir_with_files(files)
1944
        self.throws('os.rmdir("{0}")'.format(tmpdir), DIRNOTEMPTY_OS)
1945
        rmtree(tmpdir)  # this should be the suggestion
1946
1947
1948
class AnyErrorTests(GetSuggestionsTests):
1949
    """Class for tests not related to an error type in particular."""
1950
1951
    def test_wrong_except(self):
1952
        """Test where except is badly used and thus does not catch.
1953
1954
        Common mistake : "except Exc1, Exc2" doesn't catch Exc2.
1955
        Adding parenthesis solves the issue.
1956
        """
1957
        # NICE_TO_HAVE
1958
        version = (3, 0)
1959
        raised_exc, other_exc = KeyError, TypeError
1960
        raised, other = raised_exc.__name__, other_exc.__name__
1961
        code = "try:\n\traise {0}()\nexcept {{0}}:\n\tpass".format(raised)
1962
        typo = "{0}, {1}".format(other, raised)
1963
        sugg = "({0})".format(typo)
1964
        bad1, bad2, good1, good2 = format_str(code, typo, other, sugg, raised)
1965
        self.throws(bad1, (raised_exc, None), [], up_to_version(version))
1966
        self.throws(bad1, INVALIDSYNTAX, [], from_version(version))
1967
        self.throws(bad2, (raised_exc, None))
1968
        self.runs(good1)
1969
        self.runs(good2)
1970
1971
1972
if __name__ == '__main__':
1973
    print(sys.version_info)
1974
    unittest2.main()
1975