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

pyta-uoft / pyta / 15523487723

08 Jun 2025 11:12PM UTC coverage: 92.886% (-0.07%) from 92.959%
15523487723

Pull #1183

github

web-flow
Merge c11a9bd9b into 0539d23be
Pull Request #1183: Loaded python-ta reporter modules dynamically

25 of 26 new or added lines in 1 file covered. (96.15%)

8 existing lines in 5 files now uncovered.

3421 of 3683 relevant lines covered (92.89%)

17.55 hits per line

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

96.65
/python_ta/check/helpers.py
1
"""Helper functions for PythonTA's checking and reporting processes.
2
These functions are designed to support the main checking workflow by
3
modularizing core operations like file validation, linting, and result uploads.
4
"""
5

6
import importlib.util
20✔
7
import logging
20✔
8
import os
20✔
9
import re
20✔
10
import sys
20✔
11
import tokenize
20✔
12
from typing import IO, Any, AnyStr, Generator, Literal, Optional, Union
20✔
13

14
from astroid import MANAGER, modutils
20✔
15
from pylint.exceptions import UnknownMessageError
20✔
16
from pylint.lint import PyLinter
20✔
17
from pylint.lint.pylinter import _load_reporter_by_class
20✔
18
from pylint.reporters import BaseReporter, MultiReporter
20✔
19
from pylint.reporters.json_reporter import JSONReporter
20✔
20
from pylint.utils.pragma_parser import OPTION_PO
20✔
21

22
from python_ta import __version__
20✔
23

24
from ..config import (
20✔
25
    find_local_config,
26
    load_config,
27
    load_messages_config,
28
    override_config,
29
)
30
from ..patches import patch_all
20✔
31
from ..upload import upload_to_server
20✔
32
from ..util.autoformat import run_autoformat
20✔
33

34
# Flag to determine if we've previously patched pylint
35
PYLINT_PATCHED = False
20✔
36

37

38
class PytaPyLinter(PyLinter):
20✔
39
    """Extension PyLinter that supports dynamic loading of pyta-* reporters."""
40

41
    def _load_reporters(self, reporter_names: str) -> None:
20✔
42
        """Override the default behaviour to return if a pyta-* reporter is already set"""
43
        return
20✔
44

45

46
def setup_linter(
20✔
47
    local_config: Union[dict[str, Any], str],
48
    load_default_config: bool,
49
    output: Optional[Union[str, IO]],
50
) -> tuple[PyLinter, Union[BaseReporter, MultiReporter]]:
51
    """Set up the linter and reporter for the check."""
52
    linter = reset_linter(config=local_config, load_default_config=load_default_config)
20✔
53
    current_reporter = linter.reporter
20✔
54
    current_reporter.set_output(output)
20✔
55
    messages_config_path = linter.config.messages_config_path
20✔
56

57
    global PYLINT_PATCHED
58
    if not PYLINT_PATCHED:
20✔
59
        patch_all(linter.config.z3)
20✔
60
        PYLINT_PATCHED = True
20✔
61
    return linter, current_reporter
20✔
62

63

64
def check_file(
20✔
65
    file_py: AnyStr,
66
    local_config: Union[dict[str, Any], str],
67
    load_default_config: bool,
68
    autoformat: Optional[bool],
69
    is_any_file_checked: bool,
70
    current_reporter: Union[BaseReporter, MultiReporter],
71
    f_paths: list,
72
) -> tuple[bool, PyLinter]:
73
    """Perform linting on a single Python file using the provided linter and configuration"""
74
    # Load config file in user location. Construct new linter each
75
    # time, so config options don't bleed to unintended files.
76
    # Reuse the same reporter each time to accumulate the results across different files.
77
    linter = reset_linter(
20✔
78
        config=local_config,
79
        file_linted=file_py,
80
        load_default_config=load_default_config,
81
    )
82

83
    if autoformat:
20✔
84
        run_autoformat(file_py, linter.config.autoformat_options, linter.config.max_line_length)
20✔
85

86
    if not is_any_file_checked:
20✔
87
        prev_output = current_reporter.out
20✔
88
        prev_should_close_out = current_reporter.should_close_out
20✔
89
        current_reporter = linter.reporter
20✔
90
        current_reporter.out = prev_output
20✔
91
        current_reporter.should_close_out = not linter.config.watch and prev_should_close_out
20✔
92

93
        # At this point, the only possible errors are those from parsing the config file
94
        # so print them, if there are any.
95
        if current_reporter.messages:
20✔
96
            current_reporter.print_messages()
20✔
97
    else:
98
        linter.set_reporter(current_reporter)
20✔
99

100
    # The current file was checked so update the flag
101
    is_any_file_checked = True
20✔
102

103
    module_name = os.path.splitext(os.path.basename(file_py))[0]
20✔
104
    if module_name in MANAGER.astroid_cache:  # Remove module from astroid cache
20✔
105
        del MANAGER.astroid_cache[module_name]
20✔
106
    linter.check([file_py])  # Lint !
20✔
107
    if linter.config.pyta_file_permission:
20✔
UNCOV
108
        f_paths.append(file_py)  # Appending paths for upload
×
109
    logging.debug(
20✔
110
        "File: {} was checked using the configuration file: {}".format(file_py, linter.config_file)
111
    )
112
    logging.debug(
20✔
113
        "File: {} was checked using the messages-config file: {}".format(
114
            file_py, linter.config.messages_config_path
115
        )
116
    )
117
    return is_any_file_checked, linter
20✔
118

119

120
def upload_linter_results(
20✔
121
    linter: PyLinter,
122
    current_reporter: Union[BaseReporter, MultiReporter],
123
    f_paths: list,
124
    local_config: Union[dict[str, Any], str],
125
) -> None:
126
    """Upload linter results and configuration data to the specified server if permissions allow."""
127
    config = {}  # Configuration settings for data submission
20✔
128
    errs = []  # Errors caught in files for data submission
20✔
129
    if linter.config.pyta_error_permission:
20✔
UNCOV
130
        errs = list(current_reporter.messages.values())
×
131
    if f_paths != [] or errs != []:  # Only call upload_to_server() if there's something to upload
20✔
132
        # Checks if default configuration was used without changing options through the local_config argument
133
        if linter.config_file[-19:-10] != "python_ta" or local_config != "":
×
134
            config = linter.config.__dict__
×
UNCOV
135
        upload_to_server(
×
136
            errors=errs,
137
            paths=f_paths,
138
            config=config,
139
            url=linter.config.pyta_server_address,
140
            version=__version__,
141
        )
142

143

144
def reset_linter(
20✔
145
    config: Optional[Union[dict, str]] = None,
146
    file_linted: Optional[AnyStr] = None,
147
    load_default_config: bool = True,
148
) -> PyLinter:
149
    """Construct a new linter. Register config and checker plugins.
150

151
    To determine which configuration to use:
152
    - If the option is enabled, load the default PythonTA config file,
153
    - If the config argument is a string, use the config found at that location,
154
    - Otherwise,
155
        - Try to use the config file at directory of the file being linted,
156
        - If the config argument is a dictionary, apply those options afterward.
157
    Do not re-use a linter object. Returns a new linter.
158
    """
159

160
    # Tuple of custom options. Note: 'type' must map to a value equal a key in the pylint/config/option.py `VALIDATORS` dict.
161
    new_checker_options = (
20✔
162
        (
163
            "server-port",
164
            {
165
                "default": 0,
166
                "type": "int",
167
                "metavar": "<port>",
168
                "help": "Port number for the HTML report server",
169
            },
170
        ),
171
        (
172
            "watch",
173
            {
174
                "default": False,
175
                "type": "yn",
176
                "metavar": "<yn>",
177
                "help": "Run the HTML report server in persistent mode",
178
            },
179
        ),
180
        (
181
            "pyta-number-of-messages",
182
            {
183
                "default": 0,  # If the value is 0, all messages are displayed.
184
                "type": "int",
185
                "metavar": "<number_messages>",
186
                "help": "The maximum number of occurrences of each check to report.",
187
            },
188
        ),
189
        (
190
            "pyta-template-file",
191
            {
192
                "default": "",
193
                "type": "string",
194
                "metavar": "<pyta_reporter>",
195
                "help": "HTML template file for the HTMLReporter.",
196
            },
197
        ),
198
        (
199
            "pyta-error-permission",
200
            {
201
                "default": False,
202
                "type": "yn",
203
                "metavar": "<yn>",
204
                "help": "Permission to anonymously submit errors",
205
            },
206
        ),
207
        (
208
            "pyta-file-permission",
209
            {
210
                "default": False,
211
                "type": "yn",
212
                "metavar": "<yn>",
213
                "help": "Permission to anonymously submit files and errors",
214
            },
215
        ),
216
        (
217
            "pyta-server-address",
218
            {
219
                "default": "http://127.0.0.1:5000",
220
                "type": "string",
221
                "metavar": "<server-url>",
222
                "help": "Server address to submit anonymous data",
223
            },
224
        ),
225
        (
226
            "messages-config-path",
227
            {
228
                "default": os.path.join(
229
                    os.path.dirname(os.path.dirname(__file__)), "config", "messages_config.toml"
230
                ),
231
                "type": "string",
232
                "metavar": "<messages_config>",
233
                "help": "Path to patch config toml file.",
234
            },
235
        ),
236
        (
237
            "allow-pylint-comments",
238
            {
239
                "default": False,
240
                "type": "yn",
241
                "metavar": "<yn>",
242
                "help": "Allows or disallows 'pylint:' comments",
243
            },
244
        ),
245
        (
246
            "use-pyta-error-messages",
247
            {
248
                "default": True,
249
                "type": "yn",
250
                "metavar": "<yn>",
251
                "help": "Overwrite the default pylint error messages with PythonTA's messages",
252
            },
253
        ),
254
        (
255
            "autoformat-options",
256
            {
257
                "default": ["skip-string-normalization"],
258
                "type": "csv",
259
                "metavar": "<autoformatter options>",
260
                "help": "List of command-line arguments for black",
261
            },
262
        ),
263
    )
264

265
    parent_dir_path = os.path.dirname(os.path.dirname(__file__))
20✔
266
    custom_checkers = [
20✔
267
        ("python_ta.checkers." + os.path.splitext(f)[0])
268
        for f in os.listdir(os.path.join(parent_dir_path, "checkers"))
269
        if f != "__init__.py" and os.path.splitext(f)[1] == ".py"
270
    ]
271

272
    # Register new options to a checker here to allow references to
273
    # options in `.pylintrc` config file.
274
    # Options stored in linter: `linter._all_options`, `linter._external_opts`
275
    linter = PytaPyLinter(options=new_checker_options, reporter=JSONReporter())
20✔
276
    linter.load_default_plugins()  # Load checkers, reporters
20✔
277
    linter.load_plugin_modules(custom_checkers)
20✔
278
    linter.load_plugin_modules(["python_ta.transforms.setendings"])
20✔
279

280
    default_config_path = find_local_config(os.path.dirname(os.path.dirname(__file__)))
20✔
281
    set_config = load_config
20✔
282

283
    output_format_override = None
20✔
284
    if isinstance(config, str) and config != "":
20✔
285
        with open(config) as f:
20✔
286
            for line in f:
20✔
287
                if "output-format" in line and not line.strip().startswith("#"):
20✔
288
                    match = re.search(r"output-format\s*=\s*(\S+)", line)
20✔
289
                    if match:
20✔
290
                        output_format_override = match.group(1).strip()
20✔
291
                        break
20✔
292
    elif isinstance(config, dict) and config.get("output-format"):
20✔
293
        output_format_override = config.get("output-format")
20✔
294

295
    reporter_class_path = _get_reporter_class_path(output_format_override)
20✔
296
    reporter_class = _load_reporter_by_class(reporter_class_path)
20✔
297
    linter.set_reporter(reporter_class())
20✔
298

299
    if load_default_config:
20✔
300
        load_config(linter, default_config_path)
20✔
301
        # If we do specify to load the default config, we just need to override the options later.
302
        set_config = override_config
20✔
303
        if default_config_path in linter.reporter.messages:
20✔
304
            del linter.reporter.messages[default_config_path]
20✔
305

306
    if isinstance(config, str) and config != "":
20✔
307
        set_config(linter, config)
20✔
308
    else:
309
        # If available, use config file at directory of the file being linted.
310
        pylintrc_location = None
20✔
311
        if file_linted:
20✔
312
            pylintrc_location = find_local_config(file_linted)
20✔
313

314
        # Load or override the options if there is a config file in the current directory.
315
        if pylintrc_location:
20✔
NEW
UNCOV
316
            set_config(linter, pylintrc_location)
×
317

318
        # Override part of the default config, with a dict of config options.
319
        # Note: these configs are overridden by config file in user's codebase
320
        # location.
321
        if isinstance(config, dict):
20✔
322
            for key in config:
20✔
323
                linter.set_option(key, config[key])
20✔
324

325
    # Override error messages
326
    messages_config_path = linter.config.messages_config_path
20✔
327
    messages_config_default_path = linter._option_dicts["messages-config-path"]["default"]
20✔
328
    use_pyta_error_messages = linter.config.use_pyta_error_messages
20✔
329
    messages_config = load_messages_config(
20✔
330
        messages_config_path, messages_config_default_path, use_pyta_error_messages
331
    )
332
    for error_id, new_msg in messages_config.items():
20✔
333
        # Create new message definition object according to configured error messages
334
        try:
20✔
335
            message = linter.msgs_store.get_message_definitions(error_id)
20✔
336
        except UnknownMessageError:
20✔
337
            logging.warning(f"{error_id} is not a valid error id.")
20✔
338
            continue
20✔
339

340
        for message_definition in message:
20✔
341
            message_definition.msg = new_msg
20✔
342
            # Mutate the message definitions of the linter object
343
            linter.msgs_store.register_message(message_definition)
20✔
344
    return linter
20✔
345

346

347
def get_valid_files_to_check(module_name: Union[list[str], str]) -> Generator[AnyStr, None, None]:
20✔
348
    """A generator for all valid files to check."""
349
    # Allow call to check with empty args
350
    if module_name == "":
20✔
351
        m = sys.modules["__main__"]
10✔
352
        spec = importlib.util.spec_from_file_location(m.__name__, m.__file__)
10✔
353
        module_name = [spec.origin]
10✔
354
    # Enforce API to expect 1 file or directory if type is list
355
    elif isinstance(module_name, str):
20✔
356
        module_name = [module_name]
20✔
357
    # Otherwise, enforce API to expect `module_name` type as list
358
    elif not isinstance(module_name, list):
20✔
359
        logging.error(
20✔
360
            "No checks run. Input to check, `{}`, has invalid type, must be a list of strings.".format(
361
                module_name
362
            )
363
        )
364
        return
20✔
365

366
    # Filter valid files to check
367
    for item in module_name:
20✔
368
        if not isinstance(item, str):  # Issue errors for invalid types
20✔
369
            logging.error(
20✔
370
                "No check run on file `{}`, with invalid type. Must be type: str.\n".format(item)
371
            )
372
        elif os.path.isdir(item):
20✔
373
            yield item
20✔
374
        elif not os.path.exists(os.path.expanduser(item)):
20✔
375
            try:
20✔
376
                # For files with dot notation, e.g., `examples.<filename>`
377
                yield modutils.file_from_modpath(item.split("."))
20✔
378
            except ImportError:
20✔
379
                logging.error("Could not find the file called, `{}`\n".format(item))
20✔
380
        else:
381
            yield item  # Check other valid files.
20✔
382

383

384
def get_file_paths(rel_path: AnyStr) -> Generator[AnyStr, None, None]:
20✔
385
    """A generator for iterating python files within a directory.
386
    `rel_path` is a relative path to a file or directory.
387
    Returns paths to all files in a directory.
388
    """
389
    if not os.path.isdir(rel_path):
20✔
390
        yield rel_path  # Don't do anything; return the file name.
20✔
391
    else:
392
        for root, _, files in os.walk(rel_path):
20✔
393
            for filename in (f for f in files if f.endswith(".py")):
20✔
394
                yield os.path.join(root, filename)  # Format path, from root.
20✔
395

396

397
def verify_pre_check(
20✔
398
    filepath: AnyStr,
399
    allow_pylint_comments: bool,
400
    on_verify_fail: Literal["log", "raise"] = "log",
401
) -> bool:
402
    """Check student code for certain issues.
403

404
    Precondition: `filepath` variable must be a valid file path.
405

406
    - `filepath` corresponds to the file path of the file that needs to be checked.
407
    - `allow_pylint_comments` parameter indicates whether we want the user to be able to add comments
408
       beginning with pylint which can be used to locally disable checks.
409
    - `on_verify_fail` determines how to handle files that cannot be checked. In the event that a file cannot be
410
       checked, if `on_verify_fail="raise"`, then an error is raised. However, if 'on_verify_fail="log"' (default), then
411
       False is returned.
412
    """
413
    # Make sure the program doesn't crash for students.
414
    # Could use some improvement for better logging and error reporting.
415
    try:
20✔
416
        # Check for inline "pylint:" comment, which may indicate a student
417
        # trying to disable a check.
418
        if allow_pylint_comments:
20✔
419
            return True
20✔
420
        with tokenize.open(os.path.expanduser(filepath)) as f:
20✔
421
            for tok_type, content, _, _, _ in tokenize.generate_tokens(f.readline):
20✔
422
                if tok_type != tokenize.COMMENT:
20✔
423
                    continue
20✔
424
                match = OPTION_PO.search(content)
20✔
425
                if match is not None:
20✔
426
                    logging.error(
20✔
427
                        'String "pylint:" found in comment. '
428
                        + "No check run on file `{}.`\n".format(filepath)
429
                    )
430
                    return False
20✔
431
    except IndentationError as e:
20✔
432
        logging.error(
20✔
433
            "python_ta could not check your code due to an "
434
            + "indentation error at line {}.".format(e.lineno)
435
        )
436
        if on_verify_fail == "raise":
20✔
437
            raise
20✔
438
        return False
20✔
439
    except tokenize.TokenError as e:
20✔
440
        logging.error(
20✔
441
            "python_ta could not check your code due to a " + "syntax error in your file."
442
        )
443
        if on_verify_fail == "raise":
20✔
444
            raise
20✔
445
        return False
20✔
446
    except UnicodeDecodeError as e:
20✔
447
        logging.error(
20✔
448
            "python_ta could not check your code due to an "
449
            + "invalid character. Please check the following lines "
450
            "in your file and all characters that are marked with a �."
451
        )
452
        with open(os.path.expanduser(filepath), encoding="utf-8", errors="replace") as f:
20✔
453
            for i, line in enumerate(f):
20✔
454
                if "�" in line:
20✔
455
                    logging.error(f"  Line {i + 1}: {line}")
20✔
456
        if on_verify_fail == "raise":
20✔
457
            raise
20✔
458
        return False
20✔
459
    return True
20✔
460

461

462
def _get_reporter_class_path(reporter_name: str) -> str:
20✔
463
    """Return the fully qualified class path for a given PyTA reporter name. Defaults to pyta-html"""
464
    reporter_map = {
20✔
465
        "pyta-html": "python_ta.reporters.html_reporter.HTMLReporter",
466
        "pyta-plain": "python_ta.reporters.plain_reporter.PlainReporter",
467
        "pyta-color": "python_ta.reporters.color_reporter.ColorReporter",
468
        "pyta-json": "python_ta.reporters.json_reporter.JSONReporter",
469
    }
470
    return reporter_map.get(reporter_name, "python_ta.reporters.html_reporter.HTMLReporter")
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