Commit 96ece814 authored by Luke Mewburn's avatar Luke Mewburn Committed by Luke Mewburn
Browse files

asn_process: use common test_config.json

Implement common testing/test_config.json to be used by various checks.
Contents is a JSON object with keys:
  asn_files:    Dict with key as filename, value is object with
                various optional keys:
                  dependencies: List of filenames with dependencies.
                                Replaces asn_compile_targets.json.
  asn1_parse_ignore: List of globs to ignore. Replaces asn_ignore.txt.

Add -c CONFIG to allow different test_config.json to be used.

(Based on similar functionality in the SA3LI asn_process.py).
parent 3543b734
Loading
Loading
Loading
Loading
−35

File deleted.

−2

File deleted.

−1

File deleted.

+67 −37
Changes for testing/asn/asn_process.py: 67 added lines, 37 removed lines.
Original line number Diff line number Diff line
#!/usr/bin/env python3

import argparse
import json
import logging
import os
@@ -21,17 +22,34 @@ def reconstrainInteger(filename):
    return "temp.asn"


filesWithBigInts = [
filesWithBigInts = {
    "102232-1/LI-PS-PDU.asn",
    "102232-2/EmailPDU.asn",
    "102232-3/IPAccessPDU.asn",
    "102232-4/L2AccessPDU.asn",
]
}

asn1c_path = ""
change_path_to_unix = False


def filterIgnoredFiles(pathList, ignoreList):
    """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:
            if path == ignorePath or ignorePath in path.parents:
                logger.debug(f"Ignoring {path} due to {ignorePath}")
                ignoredFiles.add(path)

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

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


def fix_path(path):
    if change_path_to_unix:
        return "./" + path.replace("\\", "/")
@@ -39,6 +57,18 @@ def fix_path(path):
        return path


def getDependencies(asnFiles, fileName):
    """Return list of dependencies for fileName, and text of all files.

    :param 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.
    """
    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)
@@ -84,11 +114,13 @@ def syntaxCheckASN(fileList):
    return results


def compileAllTargets(compileTargets):
def compileAllTargets(asnFiles):
    """
    Attempts to compile a set of compile targets using the pycrate ASN.1 tools

    :param compileTargets: list of compile targets, each of which is a list of filenames
    :param asnFiles: dict; key is filename, value is dict with optional keys:
      compat_files:
      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.

    For each compile target (list of filenames) the first filename is assumed
@@ -103,24 +135,22 @@ def compileAllTargets(compileTargets):
    we can't use it.
    """
    results = {}
    for target in compileTargets:
        firstTarget = target[0]
        logger.debug(f"Compiling {firstTarget}")
    for target in asnFiles:
        logger.debug(f"Compiling {target}")
        try:
            fileTexts = []
            fileNames = []
            fileNames = getDependencies(asnFiles, target)
            pycrate_asn1c.asnproc.GLOBAL.clear()
            for filename in target:
            for filename in fileNames:
                pFile = Path(filename)
                fileTexts.append(pFile.read_text())
                fileNames.append(filename)
                logger.debug(f"  Loading {filename}")
            pycrate_asn1c.asnproc.compile_text(fileTexts, filenames=fileNames)
            results[str(firstTarget)] = {
            results[str(target)] = {
                "ok": True,
            }
        except Exception as ex:  # noqa: BLE001 (blind-except)
            results[str(firstTarget)] = {"ok": False, "code": -1, "message": f"{ex!r}"}
            results[str(target)] = {"ok": False, "code": -1, "message": f"{ex!r}"}
            continue
    return results

@@ -161,6 +191,18 @@ def main():
    logging.basicConfig(level=loglevel)
    pycrate_asn1c.utils.logger.setLevel(loglevel)

    argparser = argparse.ArgumentParser()
    argparser.add_argument(
        "-c",
        "--config",
        help="Configuration file to use (default is test_config.json)",
        default="testing/test_config.json",
    )
    args = argparser.parse_args()
    if not Path(args.config).exists():
        argparser.error(f"Could not find config file {args.config}")
    logger.debug(f"Loading config from {args.config}")

    logger.info("Searching for ASN1C")
    global asn1c_path
    asn1c_path = shutil.which("asn1c")
@@ -174,46 +216,34 @@ def main():
        global change_path_to_unix
        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")))
    logger.info(f"{len(fileList)} ASN.1 files found")
    for file in fileList:
        logger.debug(f"  {file}")

    ignoreList = Path("testing/asn/asn_ignore.txt").read_text().splitlines()
    ignoredFiles = []
    for ignore in ignoreList:
        logger.debug(f"Ignoring pattern {ignore}")
        for file in fileList:
            if ignore in str(file):
                ignoredFiles.append(file)
                logger.debug(f" Ignoring {file!s} as contains {ignore}")
    ignoredFiles = list(set(ignoredFiles))
    logger.info(f"{len(ignoredFiles)} files ignored")
    for file in ignoredFiles:
        logger.debug(f"  {file}")

    fileList = [file for file in fileList if file not in ignoredFiles]
    logger.info(f"{len(fileList)} files to process")
    for file in fileList:
    parseFileList = filterIgnoredFiles(fileList, testConfig["asn1_parse_ignore"])
    logger.info(f"{len(parseFileList)} files to parse")
    for file in parseFileList:
        logger.debug(f"  {file}")

    if len(fileList) == 0:
    if len(parseFileList) == 0:
        logger.warning("No files specified")
        return 1

    logger.info("Parsing ASN1 files")
    parseResults = syntaxCheckASN(fileList)
    logger.info("Parsing ASN.1 files")
    parseResults = syntaxCheckASN(parseFileList)
    if processResults(parseResults, "Parsing") > 0:
        return 1

    logger.info("Getting compile targets")
    compileTargets = json.loads(
        Path("testing/asn/asn_compile_targets.json").read_text()
    )
    logger.info(f"{len(compileTargets)} compile targets found")
    logger.info("Compiling ASN.1 files")
    asnFiles = testConfig["asn1_files"]
    logger.info(f"{len(asnFiles)} compile targets found")

    compileResults = compileAllTargets(compileTargets)
    compileResults = compileAllTargets(asnFiles)
    if processResults(compileResults, "Compiling") > 0:
        return 1

+39
Changes for testing/test_config.json: 39 added lines, 0 removed lines.
Original line number Diff line number Diff line
{
  "asn1_files": {
    "./102232-1/LI-PS-PDU.asn": {
      "dependencies": [
        "./103280/TS_103_280.asn1",
        "./testing/deps/33128/TS33128Payloads.asn",
        "./testing/deps/33108/Three3gppHI1Notifications.asn",
        "./testing/deps/33108/UMTSHI2Operations.asn",
        "./testing/deps/33108/UMTSHI3PS.asn",
        "./testing/deps/33108/EpsHI3PS.asn",
        "./testing/deps/33108/ConfHI3IMS.asn",
        "./testing/deps/33108/VoipHI3IMS.asn",
        "./testing/deps/33108/GCSEHI3.asn",
        "./testing/deps/33108/CSVoiceHI3IP.asn",
        "./testing/deps/33108/UMTSCSHI2Operations.asn",
        "./testing/deps/33108/EpsHI2Operations.asn",
        "./testing/deps/33108/ConfHI2Operations.asn",
        "./testing/deps/33108/ProSeHI2Operations.asn",
        "./testing/deps/33108/GCSEHI2Operations.asn",
        "./testing/deps/101671/HI1NotificationOperations,ver7.asn",
        "./testing/deps/101671/HI2Operations,ver18.asn",
        "./testing/deps/101909/TS101909201.asn",
        "./testing/deps/101909/TS101909202.asn",
        "./testing/deps/101909/PCESP.asn",
        "./testing/deps/301040/06132v203_C01.asn",
        "./103462/ILHIPDU.asn",
        "./102232-2/EmailPDU.asn",
        "./102232-3/IPAccessPDU.asn",
        "./102232-4/L2AccessPDU.asn",
        "./102232-5/IPMultimediaPDU.asn",
        "./102232-6/PstnIsdnPDU.asn"
      ]
    },
    "./102657/RDMessage.asn": {}
  },
  "asn1_parse_ignore": [
    "testing/deps/"
  ]
}