Loading testing/asn/asn_process.py +26 −31 Changes for testing/asn/asn_process.py: 26 added lines, 31 removed lines. Original line number Diff line number Diff line Loading @@ -8,7 +8,6 @@ # ruff: noqa: N806 (non-lowercase-variable-in-function) import argparse import json import logging import os import shutil Loading @@ -22,8 +21,9 @@ import compat_asn1 import lint_asn1 import pycrate_asn1c.asnproc import pycrate_asn1c.utils import test_config # Note: requires python >= 3.10, pycrate >= 0.8.1, asn1c >= 0.9.29 # Note: requires python >= 3.14, pycrate >= 0.8.1, asn1c >= 0.9.29 logger = logging.getLogger(__name__) Loading @@ -31,13 +31,14 @@ asn1c_path = "" change_path_to_unix = False def filterIgnoredFiles(pathList: list[Path], ignoreList: list[str]) -> list[Path]: def filterIgnoredFiles( pathList: list[Path], ignoreList: test_config.PathList ) -> list[Path]: """Return pathList with paths removed that contain substrings in ignoreList.""" ignoredFiles = set() ignorePaths = [Path(x) for x in ignoreList] for path in pathList: for ignorePath in ignorePaths: for ignorePath in ignoreList: if path == ignorePath or ignorePath in path.parents: logger.debug(f"Ignoring {path} due to {ignorePath}") ignoredFiles.add(path) Loading @@ -61,19 +62,18 @@ def fix_path(path: str) -> str: return path def getDependencies(asnFiles: dict[str, typing.Any], fileName: str) -> list[str]: def getDependencies(asnFiles: test_config.Asn1FilesDict, fileName: Path) -> list[Path]: """Return list of dependencies for fileName, and text of all files. Args: asnFiles: dict; key is filename, value is dict with optional keys: dependencies: list of dependencies. asnFiles: Asn1FilesDict dict. 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", [])) fileNames.extend(asnFiles.get(fileName, test_config.Asn1FileEntry).dependencies) return fileNames Loading Loading @@ -116,12 +116,11 @@ def syntaxCheckASN(fileList: list[Path]) -> dict[str, typing.Any]: return results def compileAllTargets(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: def compileAllTargets(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]: """Attempts to compile a set of compile targets using the pycrate ASN.1 tools. Args: asnFiles: dict; key is filename, value is dict with optional keys: dependencies: list of dependencies. asnFiles: Asn1FilesDict dict. Returns: A dict of outcome against the first filename of each compile target. Loading Loading @@ -159,13 +158,11 @@ def compileAllTargets(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: return results def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: def compatCheckFiles(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]: """Attempts to check backwards compatibility using the pycrate ASN.1 tools. 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. asnFiles: Asn1FilesDict dict. Returns: A dict of outcome against the first filename of each compile target. Loading @@ -180,11 +177,13 @@ def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: for target, config in asnFiles.items(): logger.info(f"Compatibility checking {target}") try: compatFiles = config.get("compat_files", {}) compatFiles = config.compat_files if not compatFiles: continue errors = [] logger.info(f"Check {target} against {' '.join(compatFiles.keys())}") logger.info( f"Check {target} against {' '.join(str(k) for k in compatFiles)}" ) targetDeps = getDependencies(asnFiles, target) for compatName, compatExceptions in compatFiles.items(): compatDeps = getDependencies(asnFiles, compatName) Loading Loading @@ -218,13 +217,11 @@ def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: return results def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: def compatCheckCommits(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]: """Attempts to check backwards compatibility using the pycrate ASN.1 tools. 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. asnFiles: Asn1FilesDict dict. Returns: A dict of outcome against the first filename of each compile target. Loading @@ -239,14 +236,14 @@ def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any] for target, config in asnFiles.items(): logger.info(f"Compatibility commit checking {target}") try: compatCommits = config.get("compat_commits", {}) compatCommits = config.compat_commits if not compatCommits: continue errors = [] logger.info( f"Check {target} against commits {' '.join(compatCommits.keys())}" ) targetDeps = asnFiles.get(target, {}).get("dependencies", []) targetDeps = asnFiles.get(target, test_config.Asn1FileEntry).dependencies for commitExpr, compatExceptions in compatCommits.items(): commitIds = commitExpr.split("..", maxsplit=1) if len(commitIds) == 1: Loading @@ -255,7 +252,7 @@ def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any] compareErrors = compatCheck.compare_commits( commit1=commitIds[0], commit2=commitIds[1], asn_file=target, asn1_file=target, dependencies=targetDeps, ) except Exception as ex: Loading Loading @@ -374,7 +371,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- change_path_to_unix = True logger.info("Loading test_config.json") testConfig = json.loads(Path(args.config).read_text()) testConfig = test_config.parse_json_file(Path(args.config)) logger.info("Searching for ASN.1 files") fileList = sorted(list(Path().rglob("*.asn1")) + list(Path().rglob("*.asn"))) Loading @@ -382,9 +379,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- for file in fileList: logger.debug(f" {file}") parseFileList = filterIgnoredFiles( fileList, testConfig.get("asn1_parse_ignore", {}) ) parseFileList = filterIgnoredFiles(fileList, testConfig.asn1_parse_ignore) logger.info(f"{len(parseFileList)} files to parse") for file in parseFileList: logger.debug(f" {file}") Loading @@ -401,7 +396,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- return 1 logger.info("Compiling ASN.1 files") asnFiles = testConfig.get("asn1_files", {}) asnFiles = testConfig.asn1_files logger.info(f"{len(asnFiles)} compile targets found") start_time = perf_counter() compileResults = compileAllTargets(asnFiles) Loading @@ -412,7 +407,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- retval = 0 # Checks now don't prevent subsequent checks from running logger.info("Linting files") lintFileList = filterIgnoredFiles(fileList, testConfig.get("asn1_lint_ignore", {})) lintFileList = filterIgnoredFiles(fileList, testConfig.asn1_lint_ignore) logger.info(f"{len(lintFileList)} files to lint") for file in lintFileList: logger.debug(f" {file}") Loading testing/asn/compat_asn1.py +76 −39 Changes for testing/asn/compat_asn1.py: 76 added lines, 39 removed lines. Original line number Diff line number Diff line Loading @@ -17,7 +17,7 @@ import pycrate_asn1c.utils # ruff: noqa: SLF001 (private-member-access) # Note: requires python >= 3.10, pycrate >= 0.8.1 # Note: requires python >= 3.14, pycrate >= 0.8.1 TYPE_CONTAINER_OF = (pa_asnobj.TYPE_SEQ_OF, pa_asnobj.TYPE_SET_OF) Loading Loading @@ -232,7 +232,11 @@ class CompatCheck: logger.info(f"Test Failure: {message}") self._errors.append(message) def _read_commit(self, commit: str, filename: str) -> str: def _read_commit( self, commit: str, filename: pathlib.Path, ) -> str: """Read file `filename` as at git commit `commit`, return text contents. Args: Loading @@ -259,7 +263,10 @@ class CompatCheck: ) return bytes_to_utf8(p.stdout) def _read_file(self, filename: str) -> str: def _read_file( self, filename: pathlib.Path, ) -> str: """Read file `filename` as UTF-8, and return text contents. Args: Loading @@ -273,57 +280,66 @@ class CompatCheck: """ logger.debug(f"Reading file '{filename}'") try: filepath = pathlib.Path(filename) filepath = filename return filepath.read_text(encoding="utf-8") except Exception as ex: raise CompatCheckError(f"Error reading '{filename}': {ex}") from ex def _parse_asn1_text( self, asn_text: list[str], filenames: list[str] self, asn1_text: list[str], asn1_files: list[pathlib.Path], ) -> pa_asnobj.ASN1Dict: """Parse `asn_text` using pycrate, returning the module object. """Parse `asn1_text` using pycrate compile_text(), returning the module object. Args: asn_text: List of ASN.1 text strings for the module filenames: List of filenames, with a 1:1 relationship with asn_text. asn1_text: List of ASN.1 text strings for the module asn1_files: List of filenames, with a 1:1 relationship with asn1_text. Returns: Parsed module. """ logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn_text)}'") logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn1_text)}'") pycrate_asn1c.asnproc.GLOBAL.clear() pycrate_asn1c.asnproc.compile_text(text=asn_text, filenames=filenames) filenames = [str(filename) for filename in asn1_files] pycrate_asn1c.asnproc.compile_text(text=asn1_text, filenames=filenames) return copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD) def _parse_asn1_commit( self, commit: str, asn_file: str, dependencies: list[str] self, commit: str, asn1_file: pathlib.Path, dependencies: list[pathlib.Path], ) -> pa_asnobj.ASN1Dict: """Parse `asn_file` as at git commit `commit` as ASN.1 using pycrate. """Parse `asn1_file` as at git commit `commit` as ASN.1 using pycrate. Args: commit: git commit. asn_file: File to parse. asn1_file: File to parse. dependencies: Optional list of dependencies. Returns: Parsed module object. """ logger.info(f"Parsing {asn_file} as at git commit {commit}") cachekey = (commit, asn_file, tuple(dependencies)) logger.info(f"Parsing {asn1_file} as at git commit {commit}") cachekey = (commit, asn1_file, tuple(dependencies)) if (cached_parse := self._cache_commits.get(cachekey, None)) is not None: logger.info(f"Parse cache hit with key {cachekey}") return cached_parse asn_text = [] asn_text.append(self._read_commit(commit=commit, filename=asn_file)) filenames = [asn_file] asn1_text: list[str] = [] asn1_text.append(self._read_commit(commit=commit, filename=asn1_file)) filenames: list[pathlib.Path] = [asn1_file] for filename in dependencies: asn_text.append(self._read_file(filename)) asn1_text.append(self._read_file(filename)) filenames.append(filename) parse = self._parse_asn1_text(asn_text=asn_text, filenames=filenames) parse = self._parse_asn1_text(asn1_text=asn1_text, asn1_files=filenames) self._cache_commits[cachekey] = parse return parse def _parse_asn1_files(self, asn1_files: list[str]) -> pa_asnobj.ASN1Dict: def _parse_asn1_files( self, asn1_files: list[pathlib.Path], ) -> pa_asnobj.ASN1Dict: """Parse `asn1_files` as ASN.1 using pycrate, returning the module object. Args: Loading @@ -332,17 +348,20 @@ class CompatCheck: Returns: Parsed module. """ logger.info(f"Parsing {' '.join(asn1_files)}") logger.info(f"Parsing {' '.join(str(f) for f in asn1_files)}") cachekey = tuple(asn1_files) if (cached_parse := self._cache_files.get(cachekey, None)) is not None: logger.info(f"Parse cache hit with key {cachekey}") return cached_parse asn_text = [self._read_file(filename) for filename in asn1_files] parse = self._parse_asn1_text(asn_text=asn_text, filenames=asn1_files) asn1_text = [self._read_file(filename) for filename in asn1_files] parse = self._parse_asn1_text(asn1_text=asn1_text, asn1_files=asn1_files) self._cache_files[cachekey] = parse return parse def _container_to_tag_dict(self, container: pa_asnobj.ASN1Dict) -> dict: def _container_to_tag_dict( self, container: pa_asnobj.ASN1Dict, ) -> dict: """Convert `container` to dict indexed on tag, value is type. Args: Loading Loading @@ -386,7 +405,10 @@ class CompatCheck: self._seen.add(seenkey) return False def _decode_constraints(self, asnobj: pa_asnobj.ASN1Obj) -> str: def _decode_constraints( self, asnobj: pa_asnobj.ASN1Obj, ) -> str: """Return representation of any constraints and defaults of `asnobj`. Args: Loading Loading @@ -423,7 +445,9 @@ class CompatCheck: return coding def _compare_constraints( self, fa_type: pa_asnobj.ASN1Obj, fb_type: pa_asnobj.ASN1Obj self, fa_type: pa_asnobj.ASN1Obj, fb_type: pa_asnobj.ASN1Obj, ) -> None: """Compare ASN.1 constraints of `fa_type` and `fb_type`.""" fa_desc = repr_type_name(fa_type) Loading Loading @@ -653,7 +677,9 @@ class CompatCheck: logger.debug(f"Unimplemented check of type '{fa_type['type']}'") def _compare_modules( self, fa_modules: pa_asnobj.ASN1Dict, fb_modules: pa_asnobj.ASN1Dict self, fa_modules: pa_asnobj.ASN1Dict, fb_modules: pa_asnobj.ASN1Dict, ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between modules. Loading Loading @@ -711,39 +737,47 @@ class CompatCheck: return self._errors def compare_commits( self, commit1: str, commit2: str, asn_file: str, dependencies: list[str] self, commit1: str, commit2: str, asn1_file: pathlib.Path, dependencies: list[pathlib.Path], ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between commits. Checks `asn_file` at git commit `commit1` and `asn_file` at git commit Checks `asn1_file` at git commit `commit1` and `asn1_file` at git commit `commit2`, using optional list of dependencies in `dependencies` at git commit HEAD. Args: commit1: First git commit. commit2: Second git commit. asn_file: File to check. asn1_file: File to check. dependencies: List of files to check. Returns: List of error messages (if any). """ logger.info( f"Comparing file {asn_file} between git commit {commit1} and {commit2}" f"Comparing file {asn1_file} between git commit {commit1} and {commit2}" ) self._clear() fa_modules = self._parse_asn1_commit( commit=commit1, asn_file=asn_file, dependencies=dependencies commit=commit1, asn1_file=asn1_file, dependencies=dependencies ) fb_modules = self._parse_asn1_commit( commit=commit2, asn_file=asn_file, dependencies=dependencies commit=commit2, asn1_file=asn1_file, dependencies=dependencies ) return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules) def compare_files(self, a_files: list[str], b_files: list[str]) -> list[str]: def compare_files( self, a_files: list[pathlib.Path], b_files: list[pathlib.Path], ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between files. Args: Loading Loading @@ -793,17 +827,20 @@ usage: %(prog)s -h argparser.add_argument( "file1", metavar="FILE1", type=pathlib.Path, help="first ASN.1 specification to check", ) argparser.add_argument( "file2", metavar="FILE2", type=pathlib.Path, nargs="?", help="second ASN.1 specification to check (if not using -1)", ) argparser.add_argument( "dependencies", metavar="DEPENDENCIES", type=pathlib.Path, nargs=argparse.REMAINDER, help="optional dependencies for FILE1 and FILE2", ) Loading @@ -822,7 +859,7 @@ usage: %(prog)s -h compat_check.compare_commits( commit1=args.commit1, commit2=args.commit2, asn_file=args.file1, asn1_file=args.file1, dependencies=args.dependencies, ) ) Loading @@ -831,8 +868,8 @@ usage: %(prog)s -h argparser.error("FILE2 is required") if args.commit2 is not None: argparser.error("-2 COMMIT2 provided without -1 COMMIT1") a_files = [args.file1] b_files = [args.file2] a_files: list[pathlib.Path] = [args.file1] b_files: list[pathlib.Path] = [args.file2] a_files.extend(args.dependencies) b_files.extend(args.dependencies) compat_errors.extend( Loading @@ -848,7 +885,7 @@ usage: %(prog)s -h else: print(f"File 1: {args.file1}") print(f"File 2: {args.file2}") print(f"Dependencies: {' '.join(args.dependencies)}") print(f"Dependencies: {' '.join(str(p) for p in args.dependencies)}") print("Errors:") for error in compat_errors: print(f" {error}") Loading testing/asn/lint_asn1.py +6 −4 Changes for testing/asn/lint_asn1.py: 6 added lines, 4 removed lines. Original line number Diff line number Diff line Loading @@ -6,15 +6,17 @@ 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: TC002 (typing-only-third-party-import) # ruff: noqa: TC003 (typing-only-standard-library-import) import typing from pathlib import Path import pathlib import test_config def lintASN1Files( file_list: list[Path], test_config: dict[str, typing.Any], file_list: list[pathlib.Path], test_config: test_config.TestConfig, ) -> dict[str, str]: """Lint all files in `file_list` per `test_config` configuration. Loading testing/asn/test_config.py +x+114 Changes for testing/asn/test_config.py: 114 added lines, 0 removed lines. Original line number Diff line number Diff line #!/usr/bin/env python3 """Testing tools configuration handling.""" import json import pathlib import sys import pydantic type ErrorList = list[str] type CompatCommitsDict = dict[str, ErrorList] type CompatFilesDict = dict[pathlib.Path, ErrorList] type PathList = list[pathlib.Path] class Asn1FileEntry(pydantic.BaseModel): """Configuration for asn1_files.FILENAME. object.""" compat_commits: CompatCommitsDict = pydantic.Field( default_factory=dict, description="Dict of commit specs to expected compat_asn1.py error messages", ) compat_files: CompatFilesDict = pydantic.Field( default_factory=dict, description=( "Dict of filenames to compare against FILENAME " "for expected compat_asn1.py error messages" ), ) dependencies: PathList = pydantic.Field( default_factory=list, description=( "List of filenames containing ASN.1 dependencies " "required to parse FILENAME." ), ) lint_exceptions: ErrorList = pydantic.Field( default_factory=list, description="List of expected lint_asn1.py error messages.", ) type Asn1FilesDict = dict[pathlib.Path, Asn1FileEntry] class TestConfig(pydantic.BaseModel): """Top-level configuration, parsed from TESTCONFIG.JSON. See https://forge.3gpp.org/rep/sa3/li/-/wikis/Process/Testing-tools """ asn1_files: Asn1FilesDict = pydantic.Field( default_factory=dict, description="Dict of ASN.1 filenames to per-file configuration.", ) asn1_lint_ignore: PathList = pydantic.Field( default_factory=list, description="Paths in the repository to exclude from lint_asn1.py.", ) asn1_parse_ignore: PathList = pydantic.Field( default_factory=list, description="Paths in the repository to exclude from checking with asn1c.", ) def parse_json_file(path: pathlib.Path) -> TestConfig: """Parse JSON file into internal data structures. Args: path: Path to JSON file to parse. Returns: Validated dictionary. Raises: RuntimeError: Parse or validation error. """ try: with pathlib.Path.open(path) as fp: config = fp.read() except Exception as exc: raise RuntimeError(f"{path}: {exc}") from exc try: testconfig = TestConfig.model_validate_json(config, strict=True) except pydantic.ValidationError as exc: msgs = [] for error in exc.errors(): location = ".".join(str(loc) for loc in error["loc"]) msgs.append(f"Field '{location}': {error['msg']}") raise RuntimeError(f"{path}: {'; '.join(msgs)}") from exc return testconfig def main() -> None: """Dump JSON Schema from TestConfig.""" config = TestConfig() schema = config.model_json_schema() sys.stdout.write(json.dumps(schema, indent=2, sort_keys=True)) sys.stdout.write("\n") if __name__ == "__main__": main() # pragma: no cover Loading
testing/asn/asn_process.py +26 −31 Changes for testing/asn/asn_process.py: 26 added lines, 31 removed lines. Original line number Diff line number Diff line Loading @@ -8,7 +8,6 @@ # ruff: noqa: N806 (non-lowercase-variable-in-function) import argparse import json import logging import os import shutil Loading @@ -22,8 +21,9 @@ import compat_asn1 import lint_asn1 import pycrate_asn1c.asnproc import pycrate_asn1c.utils import test_config # Note: requires python >= 3.10, pycrate >= 0.8.1, asn1c >= 0.9.29 # Note: requires python >= 3.14, pycrate >= 0.8.1, asn1c >= 0.9.29 logger = logging.getLogger(__name__) Loading @@ -31,13 +31,14 @@ asn1c_path = "" change_path_to_unix = False def filterIgnoredFiles(pathList: list[Path], ignoreList: list[str]) -> list[Path]: def filterIgnoredFiles( pathList: list[Path], ignoreList: test_config.PathList ) -> list[Path]: """Return pathList with paths removed that contain substrings in ignoreList.""" ignoredFiles = set() ignorePaths = [Path(x) for x in ignoreList] for path in pathList: for ignorePath in ignorePaths: for ignorePath in ignoreList: if path == ignorePath or ignorePath in path.parents: logger.debug(f"Ignoring {path} due to {ignorePath}") ignoredFiles.add(path) Loading @@ -61,19 +62,18 @@ def fix_path(path: str) -> str: return path def getDependencies(asnFiles: dict[str, typing.Any], fileName: str) -> list[str]: def getDependencies(asnFiles: test_config.Asn1FilesDict, fileName: Path) -> list[Path]: """Return list of dependencies for fileName, and text of all files. Args: asnFiles: dict; key is filename, value is dict with optional keys: dependencies: list of dependencies. asnFiles: Asn1FilesDict dict. 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", [])) fileNames.extend(asnFiles.get(fileName, test_config.Asn1FileEntry).dependencies) return fileNames Loading Loading @@ -116,12 +116,11 @@ def syntaxCheckASN(fileList: list[Path]) -> dict[str, typing.Any]: return results def compileAllTargets(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: def compileAllTargets(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]: """Attempts to compile a set of compile targets using the pycrate ASN.1 tools. Args: asnFiles: dict; key is filename, value is dict with optional keys: dependencies: list of dependencies. asnFiles: Asn1FilesDict dict. Returns: A dict of outcome against the first filename of each compile target. Loading Loading @@ -159,13 +158,11 @@ def compileAllTargets(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: return results def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: def compatCheckFiles(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]: """Attempts to check backwards compatibility using the pycrate ASN.1 tools. 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. asnFiles: Asn1FilesDict dict. Returns: A dict of outcome against the first filename of each compile target. Loading @@ -180,11 +177,13 @@ def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: for target, config in asnFiles.items(): logger.info(f"Compatibility checking {target}") try: compatFiles = config.get("compat_files", {}) compatFiles = config.compat_files if not compatFiles: continue errors = [] logger.info(f"Check {target} against {' '.join(compatFiles.keys())}") logger.info( f"Check {target} against {' '.join(str(k) for k in compatFiles)}" ) targetDeps = getDependencies(asnFiles, target) for compatName, compatExceptions in compatFiles.items(): compatDeps = getDependencies(asnFiles, compatName) Loading Loading @@ -218,13 +217,11 @@ def compatCheckFiles(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: return results def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any]: def compatCheckCommits(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]: """Attempts to check backwards compatibility using the pycrate ASN.1 tools. 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. asnFiles: Asn1FilesDict dict. Returns: A dict of outcome against the first filename of each compile target. Loading @@ -239,14 +236,14 @@ def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any] for target, config in asnFiles.items(): logger.info(f"Compatibility commit checking {target}") try: compatCommits = config.get("compat_commits", {}) compatCommits = config.compat_commits if not compatCommits: continue errors = [] logger.info( f"Check {target} against commits {' '.join(compatCommits.keys())}" ) targetDeps = asnFiles.get(target, {}).get("dependencies", []) targetDeps = asnFiles.get(target, test_config.Asn1FileEntry).dependencies for commitExpr, compatExceptions in compatCommits.items(): commitIds = commitExpr.split("..", maxsplit=1) if len(commitIds) == 1: Loading @@ -255,7 +252,7 @@ def compatCheckCommits(asnFiles: dict[str, typing.Any]) -> dict[str, typing.Any] compareErrors = compatCheck.compare_commits( commit1=commitIds[0], commit2=commitIds[1], asn_file=target, asn1_file=target, dependencies=targetDeps, ) except Exception as ex: Loading Loading @@ -374,7 +371,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- change_path_to_unix = True logger.info("Loading test_config.json") testConfig = json.loads(Path(args.config).read_text()) testConfig = test_config.parse_json_file(Path(args.config)) logger.info("Searching for ASN.1 files") fileList = sorted(list(Path().rglob("*.asn1")) + list(Path().rglob("*.asn"))) Loading @@ -382,9 +379,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- for file in fileList: logger.debug(f" {file}") parseFileList = filterIgnoredFiles( fileList, testConfig.get("asn1_parse_ignore", {}) ) parseFileList = filterIgnoredFiles(fileList, testConfig.asn1_parse_ignore) logger.info(f"{len(parseFileList)} files to parse") for file in parseFileList: logger.debug(f" {file}") Loading @@ -401,7 +396,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- return 1 logger.info("Compiling ASN.1 files") asnFiles = testConfig.get("asn1_files", {}) asnFiles = testConfig.asn1_files logger.info(f"{len(asnFiles)} compile targets found") start_time = perf_counter() compileResults = compileAllTargets(asnFiles) Loading @@ -412,7 +407,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many- retval = 0 # Checks now don't prevent subsequent checks from running logger.info("Linting files") lintFileList = filterIgnoredFiles(fileList, testConfig.get("asn1_lint_ignore", {})) lintFileList = filterIgnoredFiles(fileList, testConfig.asn1_lint_ignore) logger.info(f"{len(lintFileList)} files to lint") for file in lintFileList: logger.debug(f" {file}") Loading
testing/asn/compat_asn1.py +76 −39 Changes for testing/asn/compat_asn1.py: 76 added lines, 39 removed lines. Original line number Diff line number Diff line Loading @@ -17,7 +17,7 @@ import pycrate_asn1c.utils # ruff: noqa: SLF001 (private-member-access) # Note: requires python >= 3.10, pycrate >= 0.8.1 # Note: requires python >= 3.14, pycrate >= 0.8.1 TYPE_CONTAINER_OF = (pa_asnobj.TYPE_SEQ_OF, pa_asnobj.TYPE_SET_OF) Loading Loading @@ -232,7 +232,11 @@ class CompatCheck: logger.info(f"Test Failure: {message}") self._errors.append(message) def _read_commit(self, commit: str, filename: str) -> str: def _read_commit( self, commit: str, filename: pathlib.Path, ) -> str: """Read file `filename` as at git commit `commit`, return text contents. Args: Loading @@ -259,7 +263,10 @@ class CompatCheck: ) return bytes_to_utf8(p.stdout) def _read_file(self, filename: str) -> str: def _read_file( self, filename: pathlib.Path, ) -> str: """Read file `filename` as UTF-8, and return text contents. Args: Loading @@ -273,57 +280,66 @@ class CompatCheck: """ logger.debug(f"Reading file '{filename}'") try: filepath = pathlib.Path(filename) filepath = filename return filepath.read_text(encoding="utf-8") except Exception as ex: raise CompatCheckError(f"Error reading '{filename}': {ex}") from ex def _parse_asn1_text( self, asn_text: list[str], filenames: list[str] self, asn1_text: list[str], asn1_files: list[pathlib.Path], ) -> pa_asnobj.ASN1Dict: """Parse `asn_text` using pycrate, returning the module object. """Parse `asn1_text` using pycrate compile_text(), returning the module object. Args: asn_text: List of ASN.1 text strings for the module filenames: List of filenames, with a 1:1 relationship with asn_text. asn1_text: List of ASN.1 text strings for the module asn1_files: List of filenames, with a 1:1 relationship with asn1_text. Returns: Parsed module. """ logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn_text)}'") logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn1_text)}'") pycrate_asn1c.asnproc.GLOBAL.clear() pycrate_asn1c.asnproc.compile_text(text=asn_text, filenames=filenames) filenames = [str(filename) for filename in asn1_files] pycrate_asn1c.asnproc.compile_text(text=asn1_text, filenames=filenames) return copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD) def _parse_asn1_commit( self, commit: str, asn_file: str, dependencies: list[str] self, commit: str, asn1_file: pathlib.Path, dependencies: list[pathlib.Path], ) -> pa_asnobj.ASN1Dict: """Parse `asn_file` as at git commit `commit` as ASN.1 using pycrate. """Parse `asn1_file` as at git commit `commit` as ASN.1 using pycrate. Args: commit: git commit. asn_file: File to parse. asn1_file: File to parse. dependencies: Optional list of dependencies. Returns: Parsed module object. """ logger.info(f"Parsing {asn_file} as at git commit {commit}") cachekey = (commit, asn_file, tuple(dependencies)) logger.info(f"Parsing {asn1_file} as at git commit {commit}") cachekey = (commit, asn1_file, tuple(dependencies)) if (cached_parse := self._cache_commits.get(cachekey, None)) is not None: logger.info(f"Parse cache hit with key {cachekey}") return cached_parse asn_text = [] asn_text.append(self._read_commit(commit=commit, filename=asn_file)) filenames = [asn_file] asn1_text: list[str] = [] asn1_text.append(self._read_commit(commit=commit, filename=asn1_file)) filenames: list[pathlib.Path] = [asn1_file] for filename in dependencies: asn_text.append(self._read_file(filename)) asn1_text.append(self._read_file(filename)) filenames.append(filename) parse = self._parse_asn1_text(asn_text=asn_text, filenames=filenames) parse = self._parse_asn1_text(asn1_text=asn1_text, asn1_files=filenames) self._cache_commits[cachekey] = parse return parse def _parse_asn1_files(self, asn1_files: list[str]) -> pa_asnobj.ASN1Dict: def _parse_asn1_files( self, asn1_files: list[pathlib.Path], ) -> pa_asnobj.ASN1Dict: """Parse `asn1_files` as ASN.1 using pycrate, returning the module object. Args: Loading @@ -332,17 +348,20 @@ class CompatCheck: Returns: Parsed module. """ logger.info(f"Parsing {' '.join(asn1_files)}") logger.info(f"Parsing {' '.join(str(f) for f in asn1_files)}") cachekey = tuple(asn1_files) if (cached_parse := self._cache_files.get(cachekey, None)) is not None: logger.info(f"Parse cache hit with key {cachekey}") return cached_parse asn_text = [self._read_file(filename) for filename in asn1_files] parse = self._parse_asn1_text(asn_text=asn_text, filenames=asn1_files) asn1_text = [self._read_file(filename) for filename in asn1_files] parse = self._parse_asn1_text(asn1_text=asn1_text, asn1_files=asn1_files) self._cache_files[cachekey] = parse return parse def _container_to_tag_dict(self, container: pa_asnobj.ASN1Dict) -> dict: def _container_to_tag_dict( self, container: pa_asnobj.ASN1Dict, ) -> dict: """Convert `container` to dict indexed on tag, value is type. Args: Loading Loading @@ -386,7 +405,10 @@ class CompatCheck: self._seen.add(seenkey) return False def _decode_constraints(self, asnobj: pa_asnobj.ASN1Obj) -> str: def _decode_constraints( self, asnobj: pa_asnobj.ASN1Obj, ) -> str: """Return representation of any constraints and defaults of `asnobj`. Args: Loading Loading @@ -423,7 +445,9 @@ class CompatCheck: return coding def _compare_constraints( self, fa_type: pa_asnobj.ASN1Obj, fb_type: pa_asnobj.ASN1Obj self, fa_type: pa_asnobj.ASN1Obj, fb_type: pa_asnobj.ASN1Obj, ) -> None: """Compare ASN.1 constraints of `fa_type` and `fb_type`.""" fa_desc = repr_type_name(fa_type) Loading Loading @@ -653,7 +677,9 @@ class CompatCheck: logger.debug(f"Unimplemented check of type '{fa_type['type']}'") def _compare_modules( self, fa_modules: pa_asnobj.ASN1Dict, fb_modules: pa_asnobj.ASN1Dict self, fa_modules: pa_asnobj.ASN1Dict, fb_modules: pa_asnobj.ASN1Dict, ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between modules. Loading Loading @@ -711,39 +737,47 @@ class CompatCheck: return self._errors def compare_commits( self, commit1: str, commit2: str, asn_file: str, dependencies: list[str] self, commit1: str, commit2: str, asn1_file: pathlib.Path, dependencies: list[pathlib.Path], ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between commits. Checks `asn_file` at git commit `commit1` and `asn_file` at git commit Checks `asn1_file` at git commit `commit1` and `asn1_file` at git commit `commit2`, using optional list of dependencies in `dependencies` at git commit HEAD. Args: commit1: First git commit. commit2: Second git commit. asn_file: File to check. asn1_file: File to check. dependencies: List of files to check. Returns: List of error messages (if any). """ logger.info( f"Comparing file {asn_file} between git commit {commit1} and {commit2}" f"Comparing file {asn1_file} between git commit {commit1} and {commit2}" ) self._clear() fa_modules = self._parse_asn1_commit( commit=commit1, asn_file=asn_file, dependencies=dependencies commit=commit1, asn1_file=asn1_file, dependencies=dependencies ) fb_modules = self._parse_asn1_commit( commit=commit2, asn_file=asn_file, dependencies=dependencies commit=commit2, asn1_file=asn1_file, dependencies=dependencies ) return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules) def compare_files(self, a_files: list[str], b_files: list[str]) -> list[str]: def compare_files( self, a_files: list[pathlib.Path], b_files: list[pathlib.Path], ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between files. Args: Loading Loading @@ -793,17 +827,20 @@ usage: %(prog)s -h argparser.add_argument( "file1", metavar="FILE1", type=pathlib.Path, help="first ASN.1 specification to check", ) argparser.add_argument( "file2", metavar="FILE2", type=pathlib.Path, nargs="?", help="second ASN.1 specification to check (if not using -1)", ) argparser.add_argument( "dependencies", metavar="DEPENDENCIES", type=pathlib.Path, nargs=argparse.REMAINDER, help="optional dependencies for FILE1 and FILE2", ) Loading @@ -822,7 +859,7 @@ usage: %(prog)s -h compat_check.compare_commits( commit1=args.commit1, commit2=args.commit2, asn_file=args.file1, asn1_file=args.file1, dependencies=args.dependencies, ) ) Loading @@ -831,8 +868,8 @@ usage: %(prog)s -h argparser.error("FILE2 is required") if args.commit2 is not None: argparser.error("-2 COMMIT2 provided without -1 COMMIT1") a_files = [args.file1] b_files = [args.file2] a_files: list[pathlib.Path] = [args.file1] b_files: list[pathlib.Path] = [args.file2] a_files.extend(args.dependencies) b_files.extend(args.dependencies) compat_errors.extend( Loading @@ -848,7 +885,7 @@ usage: %(prog)s -h else: print(f"File 1: {args.file1}") print(f"File 2: {args.file2}") print(f"Dependencies: {' '.join(args.dependencies)}") print(f"Dependencies: {' '.join(str(p) for p in args.dependencies)}") print("Errors:") for error in compat_errors: print(f" {error}") Loading
testing/asn/lint_asn1.py +6 −4 Changes for testing/asn/lint_asn1.py: 6 added lines, 4 removed lines. Original line number Diff line number Diff line Loading @@ -6,15 +6,17 @@ 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: TC002 (typing-only-third-party-import) # ruff: noqa: TC003 (typing-only-standard-library-import) import typing from pathlib import Path import pathlib import test_config def lintASN1Files( file_list: list[Path], test_config: dict[str, typing.Any], file_list: list[pathlib.Path], test_config: test_config.TestConfig, ) -> dict[str, str]: """Lint all files in `file_list` per `test_config` configuration. Loading
testing/asn/test_config.py +x+114 Changes for testing/asn/test_config.py: 114 added lines, 0 removed lines. Original line number Diff line number Diff line #!/usr/bin/env python3 """Testing tools configuration handling.""" import json import pathlib import sys import pydantic type ErrorList = list[str] type CompatCommitsDict = dict[str, ErrorList] type CompatFilesDict = dict[pathlib.Path, ErrorList] type PathList = list[pathlib.Path] class Asn1FileEntry(pydantic.BaseModel): """Configuration for asn1_files.FILENAME. object.""" compat_commits: CompatCommitsDict = pydantic.Field( default_factory=dict, description="Dict of commit specs to expected compat_asn1.py error messages", ) compat_files: CompatFilesDict = pydantic.Field( default_factory=dict, description=( "Dict of filenames to compare against FILENAME " "for expected compat_asn1.py error messages" ), ) dependencies: PathList = pydantic.Field( default_factory=list, description=( "List of filenames containing ASN.1 dependencies " "required to parse FILENAME." ), ) lint_exceptions: ErrorList = pydantic.Field( default_factory=list, description="List of expected lint_asn1.py error messages.", ) type Asn1FilesDict = dict[pathlib.Path, Asn1FileEntry] class TestConfig(pydantic.BaseModel): """Top-level configuration, parsed from TESTCONFIG.JSON. See https://forge.3gpp.org/rep/sa3/li/-/wikis/Process/Testing-tools """ asn1_files: Asn1FilesDict = pydantic.Field( default_factory=dict, description="Dict of ASN.1 filenames to per-file configuration.", ) asn1_lint_ignore: PathList = pydantic.Field( default_factory=list, description="Paths in the repository to exclude from lint_asn1.py.", ) asn1_parse_ignore: PathList = pydantic.Field( default_factory=list, description="Paths in the repository to exclude from checking with asn1c.", ) def parse_json_file(path: pathlib.Path) -> TestConfig: """Parse JSON file into internal data structures. Args: path: Path to JSON file to parse. Returns: Validated dictionary. Raises: RuntimeError: Parse or validation error. """ try: with pathlib.Path.open(path) as fp: config = fp.read() except Exception as exc: raise RuntimeError(f"{path}: {exc}") from exc try: testconfig = TestConfig.model_validate_json(config, strict=True) except pydantic.ValidationError as exc: msgs = [] for error in exc.errors(): location = ".".join(str(loc) for loc in error["loc"]) msgs.append(f"Field '{location}': {error['msg']}") raise RuntimeError(f"{path}: {'; '.join(msgs)}") from exc return testconfig def main() -> None: """Dump JSON Schema from TestConfig.""" config = TestConfig() schema = config.model_json_schema() sys.stdout.write(json.dumps(schema, indent=2, sort_keys=True)) sys.stdout.write("\n") if __name__ == "__main__": main() # pragma: no cover