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

pyta-uoft / pyta / 14200587856

01 Apr 2025 04:09PM UTC coverage: 92.587% (+0.03%) from 92.557%
14200587856

Pull #1164

github

web-flow
Merge dbce74df4 into a4b858faf
Pull Request #1164: Fix issue with inline comments in docstring assertions

0 of 1 new or added line in 1 file covered. (0.0%)

11 existing lines in 3 files now uncovered.

3360 of 3629 relevant lines covered (92.59%)

17.64 hits per line

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

94.27
/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, Optional, Union
20✔
13

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

23
from python_ta import __version__
20✔
24

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

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

38

39
def setup_linter(
20✔
40
    local_config: Union[dict[str, Any], str],
41
    load_default_config: bool,
42
    output: Optional[Union[str, IO]],
43
) -> tuple[PyLinter, Union[BaseReporter, MultiReporter]]:
44
    """Set up the linter and reporter for the check."""
45
    linter = reset_linter(config=local_config, load_default_config=load_default_config)
20✔
46
    current_reporter = linter.reporter
20✔
47
    current_reporter.set_output(output)
20✔
48
    messages_config_path = linter.config.messages_config_path
20✔
49

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

56

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

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

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

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

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

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

112

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

136

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

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

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

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

265
    custom_reporters = [
20✔
266
        ("python_ta.reporters." + os.path.splitext(f)[0])
267
        for f in os.listdir(parent_dir_path + "/reporters")
268
        if f not in ["__init__.py", "stat_reporter.py"] and re.match(r".*_reporter\.py$", f)
269
    ]
270

271
    # Register new options to a checker here to allow references to
272
    # options in `.pylintrc` config file.
273
    # Options stored in linter: `linter._all_options`, `linter._external_opts`
274
    linter = pylint.lint.PyLinter(options=new_checker_options)
20✔
275
    linter.load_default_plugins()  # Load checkers, reporters
20✔
276
    linter.load_plugin_modules(custom_checkers)
20✔
277
    linter.load_plugin_modules(custom_reporters)
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
    if load_default_config:
20✔
284
        load_config(linter, default_config_path)
20✔
285
        # If we do specify to load the default config, we just need to override the options later.
286
        set_config = override_config
20✔
287

288
    if isinstance(config, str) and config != "":
20✔
289
        set_config(linter, config)
20✔
290
    else:
291
        # If available, use config file at directory of the file being linted.
292
        pylintrc_location = None
20✔
293
        if file_linted:
20✔
294
            pylintrc_location = find_local_config(file_linted)
20✔
295

296
        # Load or override the options if there is a config file in the current directory.
297
        if pylintrc_location:
20✔
UNCOV
298
            set_config(linter, pylintrc_location)
×
299

300
        # Override part of the default config, with a dict of config options.
301
        # Note: these configs are overridden by config file in user's codebase
302
        # location.
303
        if isinstance(config, dict):
20✔
304
            for key in config:
20✔
305
                linter.set_option(key, config[key])
20✔
306

307
        # Override error messages
308
    messages_config_path = linter.config.messages_config_path
20✔
309
    messages_config_default_path = linter._option_dicts["messages-config-path"]["default"]
20✔
310
    use_pyta_error_messages = linter.config.use_pyta_error_messages
20✔
311
    messages_config = load_messages_config(
20✔
312
        messages_config_path, messages_config_default_path, use_pyta_error_messages
313
    )
314
    for error_id, new_msg in messages_config.items():
20✔
315
        # Create new message definition object according to configured error messages
316
        try:
20✔
317
            message = linter.msgs_store.get_message_definitions(error_id)
20✔
318
        except UnknownMessageError:
20✔
319
            logging.warning(f"{error_id} is not a valid error id.")
20✔
320
            continue
20✔
321

322
        for message_definition in message:
20✔
323
            message_definition.msg = new_msg
20✔
324
            # Mutate the message definitions of the linter object
325
            linter.msgs_store.register_message(message_definition)
20✔
326

327
    return linter
20✔
328

329

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

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

370

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

383

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