Python and JSON CI/CD

Some work to check the Python and JSON formatting.

Merge request reports

Loading
+50 −23
Changes for 103705/validation/validate_705.py: 50 added lines, 23 removed lines.
Original line number Diff line number Diff line
@@ -5,9 +5,11 @@ from pathlib import Path
import logging
import argparse


def handle_uri(u):
    print(u)


def load_json(path: str):
    with open(path) as f:
        return json.load(f)
@@ -16,9 +18,25 @@ def load_json(path : str):
if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument('-s','--schemadir', action="append", help="Directory containing supporting schema files to use for validation")
    parser.add_argument('-v', '--verbose', action="count", help="Verbose logging (can be specified multiple times)")
    parser.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin, help="Path to input file (if absent, stdin is used)")
    parser.add_argument(
        "-s",
        "--schemadir",
        action="append",
        help="Directory containing supporting schema files to use for validation",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        help="Verbose logging (can be specified multiple times)",
    )
    parser.add_argument(
        "-i",
        "--input",
        type=argparse.FileType("r"),
        default=sys.stdin,
        help="Path to input file (if absent, stdin is used)",
    )

    args = parser.parse_args()

@@ -36,20 +54,22 @@ if __name__ == "__main__":
    args.input.close()

    config = {
        'schema_include_dirs' : [
            '../schema/',
            '../../103280/',
        "schema_include_dirs": [
            "../schema/",
            "../../103280/",
        ],
        'main_schema_doc' : '../schema/response.schema.json'
        "main_schema_doc": "../schema/response.schema.json",
    }

    rootPath = Path(sys.argv[0]).parent
    main_schema = load_json(str(rootPath / config['main_schema_doc']))
    schema_dict = { main_schema['$id'] : main_schema }
    main_schema = load_json(str(rootPath / config["main_schema_doc"]))
    schema_dict = {main_schema["$id"]: main_schema}

    schema_paths = []
    for d in config['schema_include_dirs']:
        schema_paths += [f for f in (rootPath / Path(d)).rglob("*.schema.json")]
    for d in config["schema_include_dirs"]:
        schema_paths += [
            f for f in (rootPath / Path(d)).rglob("*.schema.json")
        ]
    logging.info(f"Core schema files loaded: {schema_paths}")
    if args.schemadir:
        for d in args.schemadir:
@@ -58,38 +78,45 @@ if __name__ == "__main__":
    else:
        logging.info(f"No CSP schema files loaded")
    schemas_json = [json.load(p.open()) for p in schema_paths]
    schema_dict = schema_dict | { s['$id'] : s for s in schemas_json }
    schema_dict = schema_dict | {s["$id"]: s for s in schemas_json}

    logging.info(f"Schema IDs loaded: {[k for k in schema_dict.keys()]}")

    logging.debug(f"Instance doc: {instance_doc}")
    logging.debug(f"Main schema: {main_schema}")

    resolver = RefResolver(None, 
                           referrer=None, 
                           store=schema_dict)
    resolver = RefResolver(None, referrer=None, store=schema_dict)

    logging.info("Performing ETSI validation")
    v = Draft202012Validator(main_schema, resolver=resolver)
    v.validate(instance_doc)

    logging.info("Building record type dictionary")
    type_dict = instance_doc['recordSetDescription']['recordTypes']
    type_dict = instance_doc["recordSetDescription"]["recordTypes"]
    logging.debug(type_dict)
    ref_dict = {k: {"$ref": v} for k, v in type_dict.items()}
    validator_dict = { k : Draft202012Validator(ref_dict[k], resolver=resolver) for k,v in ref_dict.items()}
    validator_dict = {
        k: Draft202012Validator(ref_dict[k], resolver=resolver)
        for k, v in ref_dict.items()
    }
    logging.debug(ref_dict)

    logging.info("Validating records")
    for r in instance_doc['recordSet']:
        type_key = r['type']
    for r in instance_doc["recordSet"]:
        type_key = r["type"]
        if type_key not in type_dict.keys():
            logging.error(f"Record {r['id']} has type {type_key}, not in recordType dict")
            logging.error(
                f"Record {r['id']} has type {type_key}, not in recordType dict"
            )
        type_ref = type_dict[type_key]
        type_schema_id = type_ref.split('#')[0]
        logging.info(f"Using {type_schema_id} to validate {type_ref} in record {r['id']}")
        type_schema_id = type_ref.split("#")[0]
        logging.info(
            f"Using {type_schema_id} to validate {type_ref} in record {r['id']}"
        )
        if not (type_key in validator_dict.keys()):
            logging.error(f'Type key {type_key} from type {type_ref} in record {r["id"]} not in validator dictionary')
            logging.error(
                f"Type key {type_key} from type {type_ref} in record {r['id']} not in validator dictionary"
            )
            print(ref_dict)
        v = validator_dict[type_key]
        v.validate(r)
+26 −10
Changes for 103705/validate.py: 26 added lines, 10 removed lines.
Original line number Diff line number Diff line
@@ -6,7 +6,6 @@ import logging
import argparse



# filename = sys.argv[1]

# def load_json (path):
@@ -38,20 +37,39 @@ import argparse
# validate(json_instance, ext_schema)
# print ("OK")


def handle_uri(u):
    print(u)


def load_json(path: str):
    with open(path) as f:
        return json.load(f)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument('-s','--schemadir', action="append", help="Directory containing supporting schema files to use for validation")
    parser.add_argument('-v', '--verbose', action="count", help="Verbose logging (can be specified multiple times)")
    parser.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin, help="Path to input file (if absent, stdin is used)")    
    parser.add_argument('schema', help="Primary schema to validate against")    
    parser.add_argument(
        "-s",
        "--schemadir",
        action="append",
        help="Directory containing supporting schema files to use for validation",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        help="Verbose logging (can be specified multiple times)",
    )
    parser.add_argument(
        "-i",
        "--input",
        type=argparse.FileType("r"),
        default=sys.stdin,
        help="Path to input file (if absent, stdin is used)",
    )
    parser.add_argument("schema", help="Primary schema to validate against")

    args = parser.parse_args()

@@ -68,7 +86,7 @@ if __name__ == "__main__":
    instance_doc = json.loads(args.input.read())
    args.input.close()
    main_schema = load_json(args.schema)
    schema_dict = { main_schema['$id'] : main_schema }
    schema_dict = {main_schema["$id"]: main_schema}

    if args.schemadir:
        schema_paths = []
@@ -77,16 +95,14 @@ if __name__ == "__main__":
        logging.info(f"Schema files loaded: {schema_paths}")

        schemas_json = [json.load(p.open()) for p in schema_paths]
        schema_dict = schema_dict | { s['$id'] : s for s in schemas_json }
        schema_dict = schema_dict | {s["$id"]: s for s in schemas_json}

    logging.info(f"Schema IDs loaded: {[k for k in schema_dict.keys()]}")

    logging.debug(f"Instance doc: {instance_doc}")
    logging.debug(f"Main schema: {main_schema}")

    resolver = RefResolver(None, 
                           referrer=None, 
                           store=schema_dict)
    resolver = RefResolver(None, referrer=None, store=schema_dict)

    v = Draft202012Validator(main_schema, resolver=resolver)

+11 −14
Changes for 103707/testing/validate_examples.py: 11 added lines, 14 removed lines.
Original line number Diff line number Diff line
@@ -3,39 +3,36 @@ import sys
from pathlib import Path
from pprint import pprint

if __name__ == '__main__':

if __name__ == "__main__":
    if sys.version_info <= (3, 5):
        sys.exit('ERROR: You need at least Python 3.5 to run this tool')
        sys.exit("ERROR: You need at least Python 3.5 to run this tool")

    try:
        from lxml import etree
    except ImportError:
        sys.exit('ERROR: You need to install the Python lxml library')
        sys.exit("ERROR: You need to install the Python lxml library")

    try:
        import xmlschema
    except ImportError:
        sys.exit('ERROR: You need to install the xml schema library')

        sys.exit("ERROR: You need to install the xml schema library")

    extraSchemas = [
        'examples/FooServiceSchema.xsd',
        'TS_103_280_v020301.xsd'
    ]
    extraSchemas = ["examples/FooServiceSchema.xsd", "TS_103_280_v020301.xsd"]

    locations = []
    for schemaFile in extraSchemas:
        xs = xmlschema.XMLSchema(schemaFile, validation='skip')
        xs = xmlschema.XMLSchema(schemaFile, validation="skip")
        locations.append((xs.default_namespace, str(Path(schemaFile))))

    coreSchema = xmlschema.XMLSchema('TS_103_707_v010201.xsd', locations=locations)
    coreSchema = xmlschema.XMLSchema(
        "TS_103_707_v010201.xsd", locations=locations
    )

    for schema in extraSchemas:
        newSchema = xmlschema.XMLSchema(schema)
        coreSchema.import_schema(newSchema.default_namespace, schema)

    examples = glob.glob('examples/*.xml')
    examples = glob.glob("examples/*.xml")
    for example in examples:
        try:
            coreSchema.validate(example)
@@ -43,4 +40,4 @@ if __name__ == '__main__':
        except Exception as ex:
            print("{0} failed validation: {1}".format(example, ex))

    print ('Done')
 No newline at end of file
    print("Done")
+67 −54
Changes for testing/asn_process.py: 67 added lines, 54 removed lines.
Original line number Diff line number Diff line
@@ -6,25 +6,31 @@ from shutil import which

from pycrate_asn1c.asnproc import *


def reconstrainInteger(filename):
    Path('temp.asn').write_text(Path(filename).read_text().replace("18446744073709551615", "65536"))
    return 'temp.asn'
    Path("temp.asn").write_text(
        Path(filename).read_text().replace("18446744073709551615", "65536")
    )
    return "temp.asn"


filesWithBigInts = [
    '102232-1/LI-PS-PDU.asn',
    '102232-3/IPAccessPDU.asn',
    '102232-4/L2AccessPDU.asn'
    "102232-1/LI-PS-PDU.asn",
    "102232-3/IPAccessPDU.asn",
    "102232-4/L2AccessPDU.asn",
]

asn1c_path = ""
change_path_to_unix = False


def fix_path(path):
    if change_path_to_unix:
        return "./" + path.replace("\\", "/")
    else:
        return path


def syntaxCheckASN(fileList):
    """
    Performs ASN syntax checking on a list of filenames (or pathlib Paths)
@@ -40,53 +46,58 @@ def syntaxCheckASN (fileList):
        try:
            if file.as_posix() in filesWithBigInts:
                newFile = reconstrainInteger(str(file))
                p = run([asn1c_path, '-E', fix_path(newFile)], capture_output=True)
                p = run(
                    [asn1c_path, "-E", fix_path(newFile)], capture_output=True
                )
                Path(newFile).unlink()
            else:
                p = run([asn1c_path, '-E', fix_path(str(file))], capture_output=True)
            if (p.returncode != 0):
                p = run(
                    [asn1c_path, "-E", fix_path(str(file))],
                    capture_output=True,
                )
            if p.returncode != 0:
                errorMessage = p.stderr.decode().splitlines()[0]
                if errorMessage.startswith('   Value "18446744073709551615" at line'):
                    results[str(file)] = { 'ok' : True}
                if errorMessage.startswith(
                    '   Value "18446744073709551615" at line'
                ):
                    results[str(file)] = {"ok": True}
                    continue
                results[str(file)] = {
                    'ok'   : False,
                    'code' : p.returncode,
                    'message'  : p.stderr.decode().splitlines()[0]
                    "ok": False,
                    "code": p.returncode,
                    "message": p.stderr.decode().splitlines()[0],
                }
            else:
                results[str(file)] = {
                    'ok'   : True
                }            
                results[str(file)] = {"ok": True}
        except Exception as ex:
            raise ex
            results[str(file)] = {
                'ok'   : False,
                'code' : -1,
                'message'  : f"{ex!r}"
                "ok": False,
                "code": -1,
                "message": f"{ex!r}",
            }
    return results


duplicateObjects = {
    '102232-1/LI-PS-PDU.asn' : [
        'CCPayload',
        'IRIPayload',
        'Location'
    ],
    'testing/mod1.asn' : [
        'ClashField'
    ]
    "102232-1/LI-PS-PDU.asn": ["CCPayload", "IRIPayload", "Location"],
    "testing/mod1.asn": ["ClashField"],
}


def fixDuplicateObjects(filename):
    stringContent = filename.read_text()
    for object in duplicateObjects[filename.as_posix()]:
        stringContent = stringContent.replace(f'{object} ::=', f'Native{object} ::=')
        stringContent = stringContent.replace(f'SEQUENCE OF {object}', f'SEQUENCE OF Native{object}')
        stringContent = stringContent.replace(
            f"{object} ::=", f"Native{object} ::="
        )
        stringContent = stringContent.replace(
            f"SEQUENCE OF {object}", f"SEQUENCE OF Native{object}"
        )
        # stringContent = sub(f"]\\w{object}", f"] Native{object}", stringContent)

    Path('temp.asn').write_text(stringContent)
    return 'temp.asn'
    Path("temp.asn").write_text(stringContent)
    return "temp.asn"


def compileAllTargets(compileTargets):
@@ -127,19 +138,18 @@ def compileAllTargets (compileTargets):
                logging.debug(f"  Loading {filename}")
            compile_text(fileTexts, filenames=fileNames)
            results[str(firstTarget)] = {
                'ok' : True,
                "ok": True,
            }
        except Exception as ex:
            results[str(firstTarget)] = {
                'ok'   : False,
                'code' : -1,
                'message'  : f"{ex!r}"
                "ok": False,
                "code": -1,
                "message": f"{ex!r}",
            }
            continue
    return results



def processResults(results, stageName):
    """
    Counts the number of errors and writes out the output per filename
@@ -149,7 +159,7 @@ def processResults (results, stageName):
    :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"]])
    logging.info(f"{errorCount} {stageName} errors encountered")

    print(f"{'-':-<60}")
@@ -157,9 +167,9 @@ def processResults (results, stageName):
    print(f"{'-':-<60}")
    for filename, result in results.items():
        print(f" {filename:.<55}{'..OK' if result['ok'] else 'FAIL'}")
        if not result['ok']:
            if isinstance(result['message'], list):
                for thing in result['message']:
        if not result["ok"]:
            if isinstance(result["message"], list):
                for thing in result["message"]:
                    print(f"    {thing['message']}")
            else:
                print(f"    {result['message']}")
@@ -171,40 +181,41 @@ def processResults (results, stageName):
    return errorCount


if __name__ == '__main__':
    logging.info ('Searching for ASN1C')
if __name__ == "__main__":
    logging.info("Searching for ASN1C")
    asn1c_path = which("asn1c")
    if asn1c_path is None:
        raise Exception("No asn1c executable found. Please install asn1c")
    logging.info(f"asn1c found at {asn1c_path}")
    if asn1c_path.lower().endswith("bat"):
        logging.info (f"asn1c is a batch file, so assume path separators need to be changed")
        logging.info(
            f"asn1c is a batch file, so assume path separators need to be changed"
        )
        change_path_to_unix = True


    logging.info('Searching for ASN.1 files')
    logging.info("Searching for ASN.1 files")
    fileList = list(Path(".").rglob("*.asn1")) + list(Path(".").rglob("*.asn"))
    logging.info(f'{len(fileList)} ASN.1 files found')
    logging.info(f"{len(fileList)} ASN.1 files found")
    for file in fileList:
        logging.debug(f'  {file}')
        logging.debug(f"  {file}")

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

    fileList = [file for file in fileList if file not in ignoredFiles]
    logging.info(f'{len(fileList)} files to process')
    logging.info(f"{len(fileList)} files to process")
    for file in fileList:
        logging.debug(f'  {file}')
        logging.debug(f"  {file}")

    if len(fileList) == 0:
        logging.warning("No files specified")
@@ -216,7 +227,9 @@ if __name__ == '__main__':
        exit(-1)

    logging.info("Getting compile targets")
    compileTargets = json.loads(Path('testing/asn_compile_targets.json').read_text())
    compileTargets = json.loads(
        Path("testing/asn_compile_targets.json").read_text()
    )
    logging.info(f"{len(compileTargets)} compile targets found")

    compileResults = compileAllTargets(compileTargets)
+12 −4
Changes for testing/merge_test.py: 12 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -8,18 +8,26 @@ crCommitBranch = os.environ.get("CI_COMMIT_REF_NAME", "NOTFOUND")
apiUrl = os.environ.get("CI_API_V4_URL", "https://forge.3gpp.org/rep/api/v4")
projectId = os.environ.get("CI_PROJECT_ID", "13")


def gapi(query):
    url = f"{apiUrl}/projects/{projectId}/{query}"
    r = requests.get(url)
    return json.loads(r.text)


def do(commandline):
    # print ("   Attempting: " + commandline)
    completedProc = subprocess.run(commandline, capture_output=True, shell=True)
    completedProc = subprocess.run(
        commandline, capture_output=True, shell=True
    )
    # print ("   STDOUT > " + ("empty" if completedProc.stdout is None else completedProc.stdout.decode('utf-8')))
    # print ("   STDERR > " + ("empty" if completedProc.stderr is None else completedProc.stderr.decode('utf-8')))
    # print (f"   Completed with code {completedProc.returncode}")
    return (completedProc.returncode == 0,  completedProc.stdout.decode('utf-8'))
    return (
        completedProc.returncode == 0,
        completedProc.stdout.decode("utf-8"),
    )


print("Searching for corresponding MR...")

@@ -41,13 +49,13 @@ print (f"Target branch is {mr['target_branch']}")
print("Searching for open MRs targeting same branch...")

mrs = gapi(f"merge_requests?target_branch={mr['target_branch']}&state=opened")
mrs = [m for m in mrs if m['reference'] != mr['reference']]
mrs = [m for m in mrs if m["reference"] != mr["reference"]]
print(f"{len(mrs)} MRs found")

mergeConflicts = {}

for mr in mrs:
    source_branch = mr['source_branch']
    source_branch = mr["source_branch"]
    print(source_branch)

    try:
Loading
Loading