• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pyta-uoft / pyta / 13865759664

14 Mar 2025 09:35PM UTC coverage: 93.04% (+0.07%) from 92.967%
13865759664

Pull #1161

github

web-flow
Merge be872aa19 into 2b00cbabf
Pull Request #1161: Update custom error message overriding

18 of 19 new or added lines in 3 files covered. (94.74%)

9 existing lines in 1 file now uncovered.

3275 of 3520 relevant lines covered (93.04%)

17.68 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.48
/python_ta/__init__.py
1
"""Python Teaching Assistant
2

3
The goal of this module is to provide automated feedback to students in our
4
introductory Python courses, using static analysis of their code.
5

6
To run the checker, call the check function on the name of the module to check.
7

8
> import python_ta
9
> python_ta.check_all('mymodule.py')
10

11
Or, put the following code in your Python module:
12

13
if __name__ == '__main__':
14
    import python_ta
15
    python_ta.check_all()
16
"""
17

18
from __future__ import annotations
20✔
19

20
__version__ = "2.10.2.dev"  # Version number
20✔
21
# First, remove underscore from builtins if it has been bound in the REPL.
22
# Must appear before other imports from pylint/python_ta.
23
import builtins
20✔
24
import subprocess
20✔
25

26
try:
20✔
27
    del builtins._
20✔
28
except AttributeError:
20✔
29
    pass
20✔
30

31

32
import importlib.util
20✔
33
import logging
20✔
34
import os
20✔
35
import sys
20✔
36
import tokenize
20✔
37
import webbrowser
20✔
38
from builtins import FileNotFoundError
20✔
39
from os import listdir
20✔
40
from typing import IO, Any, AnyStr, Generator, Optional, TextIO, Union
20✔
41

42
import pylint.config
20✔
43
import pylint.lint
20✔
44
import pylint.utils
20✔
45
from astroid import MANAGER, modutils
20✔
46
from pylint.lint import PyLinter
20✔
47
from pylint.utils.pragma_parser import OPTION_PO
20✔
48

49
from .config import (
20✔
50
    find_local_config,
51
    load_config,
52
    load_messages_config,
53
    override_config,
54
)
55
from .patches import patch_all
20✔
56
from .reporters import REPORTERS
20✔
57
from .reporters.core import PythonTaReporter
20✔
58
from .upload import upload_to_server
20✔
59
from .util.autoformat import run_autoformat
20✔
60

61
HELP_URL = "http://www.cs.toronto.edu/~david/pyta/checkers/index.html"
20✔
62

63

64
# Flag to determine if we've previously patched pylint
65
PYLINT_PATCHED = False
20✔
66

67

68
def check_errors(
20✔
69
    module_name: Union[list[str], str] = "",
70
    config: Union[dict[str, Any], str] = "",
71
    output: Optional[Union[str, IO]] = None,
72
    load_default_config: bool = True,
73
    autoformat: Optional[bool] = False,
74
) -> PythonTaReporter:
75
    """Check a module for errors, printing a report."""
76
    return _check(
20✔
77
        module_name=module_name,
78
        level="error",
79
        local_config=config,
80
        output=output,
81
        load_default_config=load_default_config,
82
        autoformat=autoformat,
83
    )
84

85

86
def check_all(
20✔
87
    module_name: Union[list[str], str] = "",
88
    config: Union[dict[str, Any], str] = "",
89
    output: Optional[Union[str, IO]] = None,
90
    load_default_config: bool = True,
91
    autoformat: Optional[bool] = False,
92
) -> PythonTaReporter:
93
    """Analyse one or more Python modules for code issues and display the results.
94

95
    Args:
96
        module_name:
97
            If an empty string (default), the module where this function is called is checked.
98
            If a non-empty string, it is interpreted as a path to a single Python module or a
99
            directory containing Python modules. If the latter, all Python modules in the directory
100
            are checked.
101
            If a list of strings, each string is interpreted as a path to a module or directory,
102
            and all modules across all paths are checked.
103
        config:
104
            If a string, a path to a configuration file to use.
105
            If a dictionary, a map of configuration options (each key is the name of an option).
106
        output:
107
            If a string, a path to a file to which the PythonTA report is written.
108
            If a typing.IO object, the report is written to this stream.
109
            If None, the report is written to standard out or automatically displayed in a
110
            web browser, depending on which reporter is used.
111
        load_default_config:
112
            If True (default), additional configuration passed with the ``config`` option is
113
            merged with the default PythonTA configuration file.
114
            If False, the default PythonTA configuration is not used.
115
        autoformat:
116
            If True, autoformat all modules using the black formatting tool before analyzing code.
117

118
    Returns:
119
        The ``PythonTaReporter`` object that generated the report.
120
    """
121
    return _check(
20✔
122
        module_name=module_name,
123
        level="all",
124
        local_config=config,
125
        output=output,
126
        load_default_config=load_default_config,
127
        autoformat=autoformat,
128
    )
129

130

131
def _check(
20✔
132
    module_name: Union[list[str], str] = "",
133
    level: str = "all",
134
    local_config: Union[dict[str, Any], str] = "",
135
    output: Optional[Union[str, IO]] = None,
136
    load_default_config: bool = True,
137
    autoformat: Optional[bool] = False,
138
) -> PythonTaReporter:
139
    """Check a module for problems, printing a report.
140

141
    The `module_name` can take several inputs:
142
      - string of a directory, or file to check (`.py` extension optional).
143
      - list of strings of directories or files -- can have multiple.
144
      - no argument -- checks the python file containing the function call.
145
    `level` is used to specify which checks should be made.
146
    `local_config` is a dict of config options or string (config file name).
147
    `output` is an absolute or relative path to a file, or a typing.IO object to capture pyta data
148
    output. If None, stdout is used.
149
    `load_default_config` is used to specify whether to load the default .pylintrc file that comes
150
    with PythonTA. It will load it by default.
151
    `autoformat` is used to specify whether the black formatting tool is run. It is not run by default.
152
    """
153
    # Configuring logger
154
    logging.basicConfig(format="[%(levelname)s] %(message)s", level=logging.INFO)
20✔
155

156
    linter = reset_linter(config=local_config, load_default_config=load_default_config)
20✔
157
    current_reporter = linter.reporter
20✔
158
    current_reporter.set_output(output)
20✔
159
    messages_config_path = linter.config.messages_config_path
20✔
160
    messages_config_default_path = linter._option_dicts["messages-config-path"]["default"]
20✔
161
    use_pyta_error_messages = linter.config.use_pyta_error_messages
20✔
162
    messages_config = load_messages_config(
20✔
163
        messages_config_path, messages_config_default_path, use_pyta_error_messages
164
    )
165

166
    global PYLINT_PATCHED
167
    if not PYLINT_PATCHED:
20✔
168
        patch_all(linter.config.z3)  # Monkeypatch pylint (override certain methods)
20✔
169
        PYLINT_PATCHED = True
20✔
170

171
    # Try to check file, issue error message for invalid files.
172
    try:
20✔
173
        # Flag indicating whether at least one file has been checked
174
        is_any_file_checked = False
20✔
175

176
        for locations in _get_valid_files_to_check(module_name):
20✔
177
            f_paths = []  # Paths to files for data submission
20✔
178
            errs = []  # Errors caught in files for data submission
20✔
179
            config = {}  # Configuration settings for data submission
20✔
180
            for file_py in get_file_paths(locations):
20✔
181
                allowed_pylint = linter.config.allow_pylint_comments
20✔
182
                if not _verify_pre_check(file_py, allowed_pylint):
20✔
UNCOV
183
                    continue  # Check the other files
×
184
                # Load config file in user location. Construct new linter each
185
                # time, so config options don't bleed to unintended files.
186
                # Reuse the same reporter each time to accumulate the results across different files.
187
                linter = reset_linter(
20✔
188
                    config=local_config,
189
                    file_linted=file_py,
190
                    load_default_config=load_default_config,
191
                )
192

193
                # Override error messages
194
                for error_id, new_msg in messages_config.items():
20✔
195
                    # Create new message definition object according to configured error messages
196
                    message = linter.msgs_store.get_message_definitions(error_id)
20✔
197
                    for message_definition in message:
20✔
198
                        message_definition.msg = new_msg
20✔
199
                        # Mutate the message definitions of the linter object
200
                        linter.msgs_store.register_message(message_definition)
20✔
201

202
                if autoformat:
20✔
203
                    run_autoformat(
20✔
204
                        file_py, linter.config.autoformat_options, linter.config.max_line_length
205
                    )
206

207
                if not is_any_file_checked:
20✔
208
                    prev_output = current_reporter.out
20✔
209
                    prev_should_close_out = current_reporter.should_close_out
20✔
210
                    current_reporter = linter.reporter
20✔
211
                    current_reporter.out = prev_output
20✔
212
                    current_reporter.should_close_out = prev_should_close_out
20✔
213

214
                    # At this point, the only possible errors are those from parsing the config file
215
                    # so print them, if there are any.
216
                    if current_reporter.messages:
20✔
217
                        current_reporter.print_messages()
20✔
218
                else:
219
                    linter.set_reporter(current_reporter)
20✔
220

221
                # The current file was checked so update the flag
222
                is_any_file_checked = True
20✔
223

224
                module_name = os.path.splitext(os.path.basename(file_py))[0]
20✔
225
                if module_name in MANAGER.astroid_cache:  # Remove module from astroid cache
20✔
226
                    del MANAGER.astroid_cache[module_name]
20✔
227
                linter.check([file_py])  # Lint !
20✔
228
                current_reporter.print_messages(level)
20✔
229
                if linter.config.pyta_file_permission:
20✔
UNCOV
230
                    f_paths.append(file_py)  # Appending paths for upload
×
231
                logging.debug(
20✔
232
                    "File: {} was checked using the configuration file: {}".format(
233
                        file_py, linter.config_file
234
                    )
235
                )
236
                logging.debug(
20✔
237
                    "File: {} was checked using the messages-config file: {}".format(
238
                        file_py, messages_config_path
239
                    )
240
                )
241
            if linter.config.pyta_error_permission:
20✔
UNCOV
242
                errs = list(current_reporter.messages.values())
×
243
            if (
20✔
244
                f_paths != [] or errs != []
245
            ):  # Only call upload_to_server() if there's something to upload
246
                # Checks if default configuration was used without changing options through the local_config argument
UNCOV
247
                if linter.config_file[-19:-10] != "python_ta" or local_config != "":
×
UNCOV
248
                    config = linter.config.__dict__
×
UNCOV
249
                upload_to_server(
×
250
                    errors=errs,
251
                    paths=f_paths,
252
                    config=config,
253
                    url=linter.config.pyta_server_address,
254
                    version=__version__,
255
                )
256
        # Only generate reports (display the webpage) if there were valid files to check
257
        if is_any_file_checked:
20✔
258
            linter.generate_reports()
20✔
259
        return current_reporter
20✔
260
    except Exception as e:
20✔
261
        logging.error(
20✔
262
            "Unexpected error encountered! Please report this to your instructor (and attach the code that caused the error)."
263
        )
264
        logging.error('Error message: "{}"'.format(e))
20✔
265
        raise e
20✔
266

267

268
def reset_linter(
20✔
269
    config: Optional[Union[dict, str]] = None,
270
    file_linted: Optional[AnyStr] = None,
271
    load_default_config: bool = True,
272
) -> PyLinter:
273
    """Construct a new linter. Register config and checker plugins.
274

275
    To determine which configuration to use:
276
    - If the option is enabled, load the default PythonTA config file,
277
    - If the config argument is a string, use the config found at that location,
278
    - Otherwise,
279
        - Try to use the config file at directory of the file being linted,
280
        - If the config argument is a dictionary, apply those options afterward.
281
    Do not re-use a linter object. Returns a new linter.
282
    """
283

284
    # Tuple of custom options. Note: 'type' must map to a value equal a key in the pylint/config/option.py `VALIDATORS` dict.
285
    new_checker_options = (
20✔
286
        (
287
            "server-port",
288
            {
289
                "default": 0,
290
                "type": "int",
291
                "metavar": "<port>",
292
                "help": "Port number for the HTML report server",
293
            },
294
        ),
295
        (
296
            "watch",
297
            {
298
                "default": False,
299
                "type": "yn",
300
                "metavar": "<yn>",
301
                "help": "Run the HTML report server in persistent mode",
302
            },
303
        ),
304
        (
305
            "pyta-number-of-messages",
306
            {
307
                "default": 0,  # If the value is 0, all messages are displayed.
308
                "type": "int",
309
                "metavar": "<number_messages>",
310
                "help": "The maximum number of occurrences of each check to report.",
311
            },
312
        ),
313
        (
314
            "pyta-template-file",
315
            {
316
                "default": "",
317
                "type": "string",
318
                "metavar": "<pyta_reporter>",
319
                "help": "HTML template file for the HTMLReporter.",
320
            },
321
        ),
322
        (
323
            "pyta-error-permission",
324
            {
325
                "default": False,
326
                "type": "yn",
327
                "metavar": "<yn>",
328
                "help": "Permission to anonymously submit errors",
329
            },
330
        ),
331
        (
332
            "pyta-file-permission",
333
            {
334
                "default": False,
335
                "type": "yn",
336
                "metavar": "<yn>",
337
                "help": "Permission to anonymously submit files and errors",
338
            },
339
        ),
340
        (
341
            "pyta-server-address",
342
            {
343
                "default": "http://127.0.0.1:5000",
344
                "type": "string",
345
                "metavar": "<server-url>",
346
                "help": "Server address to submit anonymous data",
347
            },
348
        ),
349
        (
350
            "messages-config-path",
351
            {
352
                "default": os.path.join(
353
                    os.path.dirname(__file__), "config", "messages_config.toml"
354
                ),
355
                "type": "string",
356
                "metavar": "<messages_config>",
357
                "help": "Path to patch config toml file.",
358
            },
359
        ),
360
        (
361
            "allow-pylint-comments",
362
            {
363
                "default": False,
364
                "type": "yn",
365
                "metavar": "<yn>",
366
                "help": "Allows or disallows 'pylint:' comments",
367
            },
368
        ),
369
        (
370
            "use-pyta-error-messages",
371
            {
372
                "default": True,
373
                "type": "yn",
374
                "metavar": "<yn>",
375
                "help": "Overwrite the default pylint error messages with PythonTA's messages",
376
            },
377
        ),
378
        (
379
            "autoformat-options",
380
            {
381
                "default": ["skip-string-normalization"],
382
                "type": "csv",
383
                "metavar": "<autoformatter options>",
384
                "help": "List of command-line arguments for black",
385
            },
386
        ),
387
    )
388

389
    parent_dir_path = os.path.dirname(__file__)
20✔
390
    custom_checkers = [
20✔
391
        ("python_ta.checkers." + os.path.splitext(f)[0])
392
        for f in listdir(parent_dir_path + "/checkers")
393
        if f != "__init__.py" and os.path.splitext(f)[1] == ".py"
394
    ]
395

396
    # Register new options to a checker here to allow references to
397
    # options in `.pylintrc` config file.
398
    # Options stored in linter: `linter._all_options`, `linter._external_opts`
399
    linter = pylint.lint.PyLinter(options=new_checker_options)
20✔
400
    linter.load_default_plugins()  # Load checkers, reporters
20✔
401
    linter.load_plugin_modules(custom_checkers)
20✔
402
    linter.load_plugin_modules(["python_ta.transforms.setendings"])
20✔
403

404
    default_config_path = find_local_config(os.path.dirname(__file__))
20✔
405
    set_config = load_config
20✔
406

407
    if load_default_config:
20✔
408
        load_config(linter, default_config_path)
20✔
409
        # If we do specify to load the default config, we just need to override the options later.
410
        set_config = override_config
20✔
411

412
    if isinstance(config, str) and config != "":
20✔
413
        set_config(linter, config)
20✔
414
    else:
415
        # If available, use config file at directory of the file being linted.
416
        pylintrc_location = None
20✔
417
        if file_linted:
20✔
418
            pylintrc_location = find_local_config(file_linted)
20✔
419

420
        # Load or override the options if there is a config file in the current directory.
421
        if pylintrc_location:
20✔
NEW
422
            set_config(linter, pylintrc_location)
×
423

424
        # Override part of the default config, with a dict of config options.
425
        # Note: these configs are overridden by config file in user's codebase
426
        # location.
427
        if isinstance(config, dict):
20✔
428
            for key in config:
20✔
429
                linter.set_option(key, config[key])
20✔
430

431
    return linter
20✔
432

433

434
def get_file_paths(rel_path: AnyStr) -> Generator[AnyStr, None, None]:
20✔
435
    """A generator for iterating python files within a directory.
436
    `rel_path` is a relative path to a file or directory.
437
    Returns paths to all files in a directory.
438
    """
439
    if not os.path.isdir(rel_path):
20✔
440
        yield rel_path  # Don't do anything; return the file name.
20✔
441
    else:
442
        for root, _, files in os.walk(rel_path):
20✔
443
            for filename in (f for f in files if f.endswith(".py")):
20✔
444
                yield os.path.join(root, filename)  # Format path, from root.
20✔
445

446

447
def _verify_pre_check(filepath: AnyStr, allow_pylint_comments: bool) -> bool:
20✔
448
    """Check student code for certain issues.
449
    The additional allow_pylint_comments parameter indicates whether we want the user to be able to add comments
450
    beginning with pylint which can be used to locally disable checks.
451
    """
452
    # Make sure the program doesn't crash for students.
453
    # Could use some improvement for better logging and error reporting.
454
    try:
20✔
455
        # Check for inline "pylint:" comment, which may indicate a student
456
        # trying to disable a check.
457
        if allow_pylint_comments:
20✔
458
            return True
20✔
459
        with tokenize.open(os.path.expanduser(filepath)) as f:
20✔
460
            for tok_type, content, _, _, _ in tokenize.generate_tokens(f.readline):
20✔
461
                if tok_type != tokenize.COMMENT:
20✔
462
                    continue
20✔
463
                match = OPTION_PO.search(content)
20✔
464
                if match is not None:
20✔
465
                    logging.error(
20✔
466
                        'String "pylint:" found in comment. '
467
                        + "No check run on file `{}.`\n".format(filepath)
468
                    )
469
                    return False
20✔
470
    except IndentationError as e:
20✔
471
        logging.error(
20✔
472
            "python_ta could not check your code due to an "
473
            + "indentation error at line {}.".format(e.lineno)
474
        )
475
        return False
20✔
476
    except tokenize.TokenError as e:
20✔
477
        logging.error(
20✔
478
            "python_ta could not check your code due to a " + "syntax error in your file."
479
        )
480
        return False
20✔
481
    except UnicodeDecodeError:
20✔
482
        logging.error(
20✔
483
            "python_ta could not check your code due to an "
484
            + "invalid character. Please check the following lines "
485
            "in your file and all characters that are marked with a �."
486
        )
487
        with open(os.path.expanduser(filepath), encoding="utf-8", errors="replace") as f:
20✔
488
            for i, line in enumerate(f):
20✔
489
                if "�" in line:
20✔
490
                    logging.error(f"  Line {i + 1}: {line}")
20✔
491
        return False
20✔
492
    return True
20✔
493

494

495
def _get_valid_files_to_check(module_name: Union[list[str], str]) -> Generator[AnyStr, None, None]:
20✔
496
    """A generator for all valid files to check."""
497
    # Allow call to check with empty args
498
    if module_name == "":
20✔
499
        m = sys.modules["__main__"]
10✔
500
        spec = importlib.util.spec_from_file_location(m.__name__, m.__file__)
10✔
501
        module_name = [spec.origin]
10✔
502
    # Enforce API to expect 1 file or directory if type is list
503
    elif isinstance(module_name, str):
20✔
504
        module_name = [module_name]
20✔
505
    # Otherwise, enforce API to expect `module_name` type as list
506
    elif not isinstance(module_name, list):
20✔
507
        logging.error(
20✔
508
            "No checks run. Input to check, `{}`, has invalid type, must be a list of strings.".format(
509
                module_name
510
            )
511
        )
512
        return
20✔
513

514
    # Filter valid files to check
515
    for item in module_name:
20✔
516
        if not isinstance(item, str):  # Issue errors for invalid types
20✔
517
            logging.error(
20✔
518
                "No check run on file `{}`, with invalid type. Must be type: str.\n".format(item)
519
            )
520
        elif os.path.isdir(item):
20✔
521
            yield item
20✔
522
        elif not os.path.exists(os.path.expanduser(item)):
20✔
523
            try:
20✔
524
                # For files with dot notation, e.g., `examples.<filename>`
525
                filepath = modutils.file_from_modpath(item.split("."))
20✔
UNCOV
526
                if os.path.exists(filepath):
×
UNCOV
527
                    yield filepath
×
528
                else:
UNCOV
529
                    logging.error("Could not find the file called, `{}`\n".format(item))
×
530
            except ImportError:
20✔
531
                logging.error("Could not find the file called, `{}`\n".format(item))
20✔
532
        else:
533
            yield item  # Check other valid files.
20✔
534

535

536
def doc(msg_id: str) -> None:
20✔
537
    """Open the PythonTA documentation page for the given error message id.
538

539
    Args:
540
        msg_id: The five-character error code, e.g. ``"E0401"``.
541
    """
542
    msg_url = HELP_URL + "#" + msg_id.lower()
20✔
543
    print("Opening {} in a browser.".format(msg_url))
20✔
544
    webbrowser.open(msg_url)
20✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc