Commit bb0b260d authored by Luke Mewburn's avatar Luke Mewburn
Browse files

testing/asn: fix ruff issues

parent ba61583e
Loading
Loading
Loading
Loading
Loading
+87 −50
Changes for testing/asn/asn_process.py: 87 added lines, 50 removed lines.
Original line number Diff line number Diff line
#!/usr/bin/env python3

"""Tool to validate ASN.1 in the repository."""

# ruff: noqa: EM101 (raw-string-in-exception)
# ruff: noqa: N802 (invalid-function-name)
# ruff: noqa: N803 (invalid-argument-name)
# ruff: noqa: N806 (non-lowercase-variable-in-function)
# ruff: noqa: TRY003 (raise-vanilla-args)

import argparse
import json
import logging
@@ -7,14 +15,14 @@ import os
import shutil
import subprocess
import sys
import typing
from pathlib import Path
from time import perf_counter

import pycrate_asn1c.asnproc
import pycrate_asn1c.utils

import compat_asn1
import lint_asn1
import pycrate_asn1c.asnproc
import pycrate_asn1c.utils

# Note: requires python >= 3.10, pycrate >= 0.8.1, asn1c >= 0.9.29

@@ -24,7 +32,7 @@ asn1c_path = ""
change_path_to_unix = False


def filterIgnoredFiles(pathList, ignoreList):
def filterIgnoredFiles(pathList: list[Path], ignoreList: list[str]) -> list[Path]:
    """Return pathList with paths removed that contain substrings in ignoreList."""
    ignoredFiles = set()
    ignorePaths = [Path(x) for x in ignoreList]
@@ -37,43 +45,56 @@ def filterIgnoredFiles(pathList, ignoreList):

    logger.info(f"{len(ignoredFiles)} files ignored")

    result = [file for file in pathList if file not in ignoredFiles]
    return result
    return [file for file in pathList if file not in ignoredFiles]


def fix_path(path):
def fix_path(path: str) -> str:
    """Rewrite a file path for UNIX.

    Args:
        path: path to rewrite.

    Returns:
        Rewritten path.
    """
    if change_path_to_unix:
        return "./" + path.replace("\\", "/")
    else:
    return path


def getDependencies(asnFiles, fileName):
def getDependencies(asnFiles: dict[str, typing.Any], fileName: str) -> list[str]:
    """Return list of dependencies for fileName, and text of all files.

    :param asnFiles: dict; key is filename, value is dict with optional keys:
    Args:
        asnFiles: dict; key is filename, value is dict with optional keys:
            dependencies: list of dependencies.
    :returns: A list of dependencies with fileName first, and the text of all files.
        fileName: Filename we're getting the dependencies for.

    Returns:
        A list of dependencies with fileName first, and the text of all files.
    """
    fileNames = [fileName]
    fileNames.extend(asnFiles.get(fileName, {}).get("dependencies", []))
    return fileNames


def syntaxCheckASN(fileList):
    """
    Performs ASN syntax checking on a list of filenames (or pathlib Paths)
def syntaxCheckASN(fileList: list[Path]) -> dict[str, typing.Any]:
    """Performs ASN syntax checking on a list of pathlib Paths.

    Args:
        fileList: List of filenames (Pathlib Path)

    :param fileList: List of filenames (str or Pathlib Path)
    :returns: Dict with result, return code and message for each filename
    Returns:
        A dict of outcome against the first filename of each compile target.
        Return code and message are included for failures.

    Calls the open-source asn1c compiler with the "syntax only" option.
    As a result, asn1c must be available to run.
    Calls the open-source `asn1c` compiler with the "syntax only" option.
    As a result, `asn1c` must be available to run.
    """
    results = {}
    for file in fileList:
        try:
            p = subprocess.run(
            p = subprocess.run(  # noqa: S603 (subprocess-without-shell-equals-true)
                [str(asn1c_path), "-E", fix_path(str(file))],
                capture_output=True,
                check=False,
@@ -96,14 +117,16 @@ def syntaxCheckASN(fileList):
    return results


def compileAllTargets(asnFiles):
    """
    Attempts to compile a set of compile targets using the pycrate ASN.1 tools
def compileAllTargets(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]:
    """Attempts to compile a set of compile targets using the pycrate ASN.1 tools.

    :param asnFiles: dict; key is filename, value is dict with optional keys:
      compat_files:
    Args:
        asnFiles: dict; key is filename, value is dict with optional keys:
            dependencies: list of dependencies.
    :returns: A dict of outcome against the first filename of each compile target. Return code and message are included for failures.

    Returns:
        A dict of outcome against the first filename of each compile target.
        Return code and message are included for failures.

    For each compile target (list of filenames) the first filename is assumed
    to be the "primary" file. This doesn't have any relevance to the compilation,
@@ -137,19 +160,21 @@ def compileAllTargets(asnFiles):
    return results


def compatCheckFiles(asnFiles):
    """
    Attempts to check backwards compatibility using the pycrate ASN.1 tools.
def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]:
    """Attempts to check backwards compatibility using the pycrate ASN.1 tools.

    :param asnFiles: dict; key is filename, value is dict with optional keys:
    Args:
        asnFiles: dict; key is filename, value is dict with optional keys:
            dependencies: list of dependencies.
            compat_files: dict of filenames to check, value is list of expected errors.
    :returns: A dict of outcome against the first filename of each compile target. Return code and message are included for failures.

    Returns:
        A dict of outcome against the first filename of each compile target.
        Return code and message are included for failures.

    For each file in asnFiles:
      For each compat in file['compat_files']
         check file against compat, and the errors should match the value.

    """
    results = {}
    compatCheck = compat_asn1.CompatCheck()
@@ -194,19 +219,21 @@ def compatCheckFiles(asnFiles):
    return results


def compatCheckCommits(asnFiles):
    """
    Attempts to check backwards compatibility using the pycrate ASN.1 tools.
def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]:
    """Attempts to check backwards compatibility using the pycrate ASN.1 tools.

    :param asnFiles: dict; key is filename, value is dict with optional keys:
    Args:
        asnFiles: dict; key is filename, value is dict with optional keys:
            dependencies: list of dependencies.
            compat_commits: dict of commits to check, value is list of expected errors.
    :returns: A dict of outcome against the first filename of each compile target. Return code and message are included for failures.

    For each file in asnFiles:
    Returns:
        A dict of outcome against the first filename of each compile target.
        Return code and message are included for failures.

    For each file in `asnFiles`:
      For each compat in file['compat_commits']
         check file against revisions in compat, and the errors should match the value.

    """
    results = {}
    compatCheck = compat_asn1.CompatCheck()
@@ -263,16 +290,18 @@ def compatCheckCommits(asnFiles):
    return results


def processResults(results, stageName):
    """
    Counts the number of errors and writes out the output per filename
def processResults(results: dict[str, typing.Any], stageName: str) -> int:
    """Counts the number of errors and writes out the output per filename.

    Args:
        results: Dict of {filenames: status object}.
        stageName: Name to decorate the output with.

    :param results: List of filenames (str or Pathlib Path)
    :param stageName: Name to decorate the output with
    :returns: The number of files which had errors
    Returns:
        The number of files which had errors.
    """
    print()
    errorCount = sum([1 for r in results.values() if not r["ok"]])
    errorCount = sum(1 for r in results.values() if not r["ok"])
    logger.info(f"{errorCount} {stageName} errors encountered")

    print(f"{'-':-<60}")
@@ -294,7 +323,15 @@ def processResults(results, stageName):
    return errorCount


def main():
def main() -> int:  # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many-return-statements, too-many-statements)
    """Standalone main.

    Returns:
        Exit code.

    Raises:
        RuntimeError: If required tools aren't found.
    """
    loglevel = os.environ.get("LOGLEVEL", "WARNING").upper()
    logging.basicConfig(level=loglevel)
    pycrate_asn1c.utils.logger.setLevel(loglevel)
@@ -325,7 +362,7 @@ def main():
    times = []

    logger.info("Searching for ASN1C")
    global asn1c_path
    global asn1c_path  # noqa: PLW0603 (global-statement)
    asn1c_path = shutil.which("asn1c")
    if asn1c_path is None:
        raise RuntimeError("No asn1c executable found. Please install asn1c")
@@ -334,14 +371,14 @@ def main():
        logger.info(
            "asn1c is a batch file, so assume path separators need to be changed"
        )
        global change_path_to_unix
        global change_path_to_unix  # noqa: PLW0603 (global-statement)
        change_path_to_unix = True

    logger.info("Loading test_config.json")
    testConfig = json.loads(Path(args.config).read_text())

    logger.info("Searching for ASN.1 files")
    fileList = sorted(list(Path(".").rglob("*.asn1")) + list(Path(".").rglob("*.asn")))
    fileList = sorted(list(Path().rglob("*.asn1")) + list(Path().rglob("*.asn")))
    logger.info(f"{len(fileList)} ASN.1 files found")
    for file in fileList:
        logger.debug(f"  {file}")
@@ -415,7 +452,7 @@ def main():
        for t in times:
            print(f"  {t[0].ljust(30)}:  {t[1]:.2f} s")
        print(f"{'-':-<60}")
        print(f"Total time: {sum([x[1] for x in times]):.2f} s")
        print(f"Total time: {sum(x[1] for x in times):.2f} s")
        print(f"{'-':-<60}")
        print()

+3 −2
Changes for testing/asn/compat_asn1.py: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -7,7 +7,7 @@ import copy
import logging
import os
import pathlib
import subprocess  # noqa: S404 (suspicious-subprocess-import)
import subprocess
import sys

import pycrate_asn1c.asnobj as pa_asnobj
@@ -285,6 +285,7 @@ class CompatCheck:

        Args:
            asn_text: List of ASN.1 text strings for the module
            filenames: List of filenames, with a 1:1 relationship with asn_text.

        Returns:
            Parsed module.
@@ -531,7 +532,7 @@ class CompatCheck:
        fb_desc = repr_type_name(fb_type)
        logger.info(f"Comparing container OF {fa_desc} with {fb_desc}")

        # TODO: .name may end with "._item_"; removesuffix?
        # Note: .name may end with "._item_"; do we need removesuffix?

        if self._types_already_seen(fa_type=fa_type, fb_type=fb_type):
            return
+22 −1
Changes for testing/asn/lint_asn1.py: 22 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -3,6 +3,27 @@
NOTE: ASN.1 linting is not yet implemented.
"""

# ruff: noqa: ARG001 (unused-function-argument)
# ruff: noqa: INP001 (implicit-namespace-package)
# ruff: noqa: N802 (invalid-function-name)
# ruff: noqa: TC003 (typing-only-standard-library-import)

def lintASN1Files(fileList, testConfig):
import typing
from pathlib import Path


def lintASN1Files(
    file_list: list[Path],
    test_config: dict[str, typing.Any],
) -> dict[str, str]:
    """Lint all files in `file_list` per `test_config` configuration.

    Args:
        file_list: List of files to lint.
        test_config: dict with optional nested keys:
            asn1_files.FILENAME.lint_exceptions: list of expected errors.

    Returns:
        Error map, key is filename, value is object with describing fault.
    """
    return {}