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

pyta-uoft / pyta / 14048343144

24 Mar 2025 11:53PM UTC coverage: 92.555% (-0.5%) from 93.089%
14048343144

Pull #1156

github

web-flow
Merge 11dc1a7b0 into 477f476ea
Pull Request #1156: Integrate Watchdog for Live Code Re-Checking

189 of 215 new or added lines in 3 files covered. (87.91%)

10 existing lines in 2 files now uncovered.

3344 of 3613 relevant lines covered (92.55%)

17.63 hits per line

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

94.16
/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 sys
20✔
10
import tokenize
20✔
11
from typing import IO, Any, AnyStr, Generator, Optional, Union
20✔
12

13
import pylint.config
20✔
14
import pylint.lint
20✔
15
import pylint.utils
20✔
16
from astroid import MANAGER, modutils
20✔
17
from pylint.exceptions import UnknownMessageError
20✔
18
from pylint.lint import PyLinter
20✔
19
from pylint.reporters import BaseReporter, MultiReporter
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
def setup_linter(
20✔
39
    local_config: Union[dict[str, Any], str],
40
    load_default_config: bool,
41
    output: Optional[Union[str, IO]],
42
) -> tuple[PyLinter, Union[BaseReporter, MultiReporter]]:
43
    """Set up the linter and reporter for the check."""
44
    linter = reset_linter(config=local_config, load_default_config=load_default_config)
20✔
45
    current_reporter = linter.reporter
20✔
46
    current_reporter.set_output(output)
20✔
47
    messages_config_path = linter.config.messages_config_path
20✔
48

49
    global PYLINT_PATCHED
50
    if not PYLINT_PATCHED:
20✔
51
        patch_all(linter.config.z3)
20✔
52
        PYLINT_PATCHED = True
20✔
53
    return linter, current_reporter
20✔
54

55

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

75
    if autoformat:
20✔
76
        run_autoformat(file_py, linter.config.autoformat_options, linter.config.max_line_length)
20✔
77

78
    if not is_any_file_checked:
20✔
79
        prev_output = current_reporter.out
20✔
80
        prev_should_close_out = current_reporter.should_close_out
20✔
81
        current_reporter = linter.reporter
20✔
82
        current_reporter.out = prev_output
20✔
83
        current_reporter.should_close_out = not linter.config.watch and prev_should_close_out
20✔
84

85
        # At this point, the only possible errors are those from parsing the config file
86
        # so print them, if there are any.
87
        if current_reporter.messages:
20✔
88
            current_reporter.print_messages()
20✔
89
    else:
90
        linter.set_reporter(current_reporter)
20✔
91

92
    # The current file was checked so update the flag
93
    is_any_file_checked = True
20✔
94

95
    module_name = os.path.splitext(os.path.basename(file_py))[0]
20✔
96
    if module_name in MANAGER.astroid_cache:  # Remove module from astroid cache
20✔
97
        del MANAGER.astroid_cache[module_name]
20✔
98
    linter.check([file_py])  # Lint !
20✔
99
    if linter.config.pyta_file_permission:
20✔
NEW
100
        f_paths.append(file_py)  # Appending paths for upload
×
101
    logging.debug(
20✔
102
        "File: {} was checked using the configuration file: {}".format(file_py, linter.config_file)
103
    )
104
    logging.debug(
20✔
105
        "File: {} was checked using the messages-config file: {}".format(
106
            file_py, linter.config.messages_config_path
107
        )
108
    )
109
    return is_any_file_checked, linter
20✔
110

111

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

135

136
def reset_linter(
20✔
137
    config: Optional[Union[dict, str]] = None,
138
    file_linted: Optional[AnyStr] = None,
139
    load_default_config: bool = True,
140
) -> PyLinter:
141
    """Construct a new linter. Register config and checker plugins.
142

143
    To determine which configuration to use:
144
    - If the option is enabled, load the default PythonTA config file,
145
    - If the config argument is a string, use the config found at that location,
146
    - Otherwise,
147
        - Try to use the config file at directory of the file being linted,
148
        - If the config argument is a dictionary, apply those options afterward.
149
    Do not re-use a linter object. Returns a new linter.
150
    """
151

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

257
    parent_dir_path = os.path.dirname(os.path.dirname(__file__))
20✔
258
    custom_checkers = [
20✔
259
        ("python_ta.checkers." + os.path.splitext(f)[0])
260
        for f in os.listdir(os.path.join(parent_dir_path, "checkers"))
261
        if f != "__init__.py" and os.path.splitext(f)[1] == ".py"
262
    ]
263

264
    # Register new options to a checker here to allow references to
265
    # options in `.pylintrc` config file.
266
    # Options stored in linter: `linter._all_options`, `linter._external_opts`
267
    linter = pylint.lint.PyLinter(options=new_checker_options)
20✔
268
    linter.load_default_plugins()  # Load checkers, reporters
20✔
269
    linter.load_plugin_modules(custom_checkers)
20✔
270
    linter.load_plugin_modules(["python_ta.transforms.setendings"])
20✔
271

272
    default_config_path = find_local_config(os.path.dirname(os.path.dirname(__file__)))
20✔
273
    set_config = load_config
20✔
274

275
    if load_default_config:
20✔
276
        load_config(linter, default_config_path)
20✔
277
        # If we do specify to load the default config, we just need to override the options later.
278
        set_config = override_config
20✔
279

280
    if isinstance(config, str) and config != "":
20✔
281
        set_config(linter, config)
20✔
282
    else:
283
        # If available, use config file at directory of the file being linted.
284
        pylintrc_location = None
20✔
285
        if file_linted:
20✔
286
            pylintrc_location = find_local_config(file_linted)
20✔
287

288
        # Load or override the options if there is a config file in the current directory.
289
        if pylintrc_location:
20✔
NEW
290
            set_config(linter, pylintrc_location)
×
291

292
        # Override part of the default config, with a dict of config options.
293
        # Note: these configs are overridden by config file in user's codebase
294
        # location.
295
        if isinstance(config, dict):
20✔
296
            for key in config:
20✔
297
                linter.set_option(key, config[key])
20✔
298

299
        # Override error messages
300
    messages_config_path = linter.config.messages_config_path
20✔
301
    messages_config_default_path = linter._option_dicts["messages-config-path"]["default"]
20✔
302
    use_pyta_error_messages = linter.config.use_pyta_error_messages
20✔
303
    messages_config = load_messages_config(
20✔
304
        messages_config_path, messages_config_default_path, use_pyta_error_messages
305
    )
306
    for error_id, new_msg in messages_config.items():
20✔
307
        # Create new message definition object according to configured error messages
308
        try:
20✔
309
            message = linter.msgs_store.get_message_definitions(error_id)
20✔
310
        except UnknownMessageError:
20✔
311
            logging.warning(f"{error_id} is not a valid error id.")
20✔
312
            continue
20✔
313

314
        for message_definition in message:
20✔
315
            message_definition.msg = new_msg
20✔
316
            # Mutate the message definitions of the linter object
317
            linter.msgs_store.register_message(message_definition)
20✔
318

319
    return linter
20✔
320

321

322
def get_valid_files_to_check(module_name: Union[list[str], str]) -> Generator[AnyStr, None, None]:
20✔
323
    """A generator for all valid files to check."""
324
    # Allow call to check with empty args
325
    if module_name == "":
20✔
326
        m = sys.modules["__main__"]
10✔
327
        spec = importlib.util.spec_from_file_location(m.__name__, m.__file__)
10✔
328
        module_name = [spec.origin]
10✔
329
    # Enforce API to expect 1 file or directory if type is list
330
    elif isinstance(module_name, str):
20✔
331
        module_name = [module_name]
20✔
332
    # Otherwise, enforce API to expect `module_name` type as list
333
    elif not isinstance(module_name, list):
20✔
334
        logging.error(
20✔
335
            "No checks run. Input to check, `{}`, has invalid type, must be a list of strings.".format(
336
                module_name
337
            )
338
        )
339
        return
20✔
340

341
    # Filter valid files to check
342
    for item in module_name:
20✔
343
        if not isinstance(item, str):  # Issue errors for invalid types
20✔
344
            logging.error(
20✔
345
                "No check run on file `{}`, with invalid type. Must be type: str.\n".format(item)
346
            )
347
        elif os.path.isdir(item):
20✔
348
            yield item
20✔
349
        elif not os.path.exists(os.path.expanduser(item)):
20✔
350
            try:
20✔
351
                # For files with dot notation, e.g., `examples.<filename>`
352
                filepath = modutils.file_from_modpath(item.split("."))
20✔
NEW
353
                if os.path.exists(filepath):
×
NEW
354
                    yield filepath
×
355
                else:
NEW
356
                    logging.error("Could not find the file called, `{}`\n".format(item))
×
357
            except ImportError:
20✔
358
                logging.error("Could not find the file called, `{}`\n".format(item))
20✔
359
        else:
360
            yield item  # Check other valid files.
20✔
361

362

363
def get_file_paths(rel_path: AnyStr) -> Generator[AnyStr, None, None]:
20✔
364
    """A generator for iterating python files within a directory.
365
    `rel_path` is a relative path to a file or directory.
366
    Returns paths to all files in a directory.
367
    """
368
    if not os.path.isdir(rel_path):
20✔
369
        yield rel_path  # Don't do anything; return the file name.
20✔
370
    else:
371
        for root, _, files in os.walk(rel_path):
20✔
372
            for filename in (f for f in files if f.endswith(".py")):
20✔
373
                yield os.path.join(root, filename)  # Format path, from root.
20✔
374

375

376
def verify_pre_check(filepath: AnyStr, allow_pylint_comments: bool) -> bool:
20✔
377
    """Check student code for certain issues.
378
    The additional allow_pylint_comments parameter indicates whether we want the user to be able to add comments
379
    beginning with pylint which can be used to locally disable checks.
380
    """
381
    # Make sure the program doesn't crash for students.
382
    # Could use some improvement for better logging and error reporting.
383
    try:
20✔
384
        # Check for inline "pylint:" comment, which may indicate a student
385
        # trying to disable a check.
386
        if allow_pylint_comments:
20✔
387
            return True
20✔
388
        with tokenize.open(os.path.expanduser(filepath)) as f:
20✔
389
            for tok_type, content, _, _, _ in tokenize.generate_tokens(f.readline):
20✔
390
                if tok_type != tokenize.COMMENT:
20✔
391
                    continue
20✔
392
                match = OPTION_PO.search(content)
20✔
393
                if match is not None:
20✔
394
                    logging.error(
20✔
395
                        'String "pylint:" found in comment. '
396
                        + "No check run on file `{}.`\n".format(filepath)
397
                    )
398
                    return False
20✔
399
    except IndentationError as e:
20✔
400
        logging.error(
20✔
401
            "python_ta could not check your code due to an "
402
            + "indentation error at line {}.".format(e.lineno)
403
        )
404
        return False
20✔
405
    except tokenize.TokenError as e:
20✔
406
        logging.error(
20✔
407
            "python_ta could not check your code due to a " + "syntax error in your file."
408
        )
409
        return False
20✔
410
    except UnicodeDecodeError:
20✔
411
        logging.error(
20✔
412
            "python_ta could not check your code due to an "
413
            + "invalid character. Please check the following lines "
414
            "in your file and all characters that are marked with a �."
415
        )
416
        with open(os.path.expanduser(filepath), encoding="utf-8", errors="replace") as f:
20✔
417
            for i, line in enumerate(f):
20✔
418
                if "�" in line:
20✔
419
                    logging.error(f"  Line {i + 1}: {line}")
20✔
420
        return False
20✔
421
    return True
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