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

pyta-uoft / pyta / 15523442578

08 Jun 2025 11:06PM UTC coverage: 92.888% (-0.07%) from 92.959%
15523442578

Pull #1183

github

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

24 of 24 new or added lines in 1 file covered. (100.0%)

9 existing lines in 5 files now uncovered.

3422 of 3684 relevant lines covered (92.89%)

17.55 hits per line

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

96.67
/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
    output_format = None
20✔
42

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

47

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

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

65

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

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

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

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

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

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

121

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

145

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

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

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

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

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

282
    default_config_path = find_local_config(os.path.dirname(os.path.dirname(__file__)))
20✔
283
    set_config = load_config
20✔
284

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

297
    reporter_class_path = _get_reporter_class_path(output_format_override)
20✔
298
    reporter_class = _load_reporter_by_class(reporter_class_path)
20✔
299
    linter.set_reporter(reporter_class())
20✔
300

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

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

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

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

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

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

348

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

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

385

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

398

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

406
    Precondition: `filepath` variable must be a valid file path.
407

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

463

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