示例#1
0
    def test_document_validate_api(self):
        self.assertIsNone(xmlschema.validate(self.vh_xml_file))
        self.assertIsNone(
            xmlschema.validate(self.vh_xml_file, use_defaults=False))

        vh_2_file = self.casepath('examples/vehicles/vehicles-2_errors.xml')
        self.assertRaises(XMLSchemaValidationError, xmlschema.validate,
                          vh_2_file)

        try:
            xmlschema.validate(
                vh_2_file, namespaces={'vhx': "http://example.com/vehicles"})
        except XMLSchemaValidationError as err:
            path_line = str(err).splitlines()[-1]
        else:
            path_line = ''

        if sys.version_info >= (3, 6):
            self.assertEqual('Path: /vhx:vehicles/vhx:cars', path_line)
        else:
            self.assertTrue('Path: /vh:vehicles/vh:cars' == path_line
                            or 'Path: /vhx:vehicles/vhx:cars',
                            path_line)  # Due to unordered dicts

        # Issue #80
        vh_2_xt = ElementTree.parse(vh_2_file)
        self.assertRaises(XMLSchemaValidationError, xmlschema.validate,
                          vh_2_xt, self.vh_xsd_file)

        # Issue #145
        with open(self.vh_xml_file) as f:
            self.assertIsNone(xmlschema.validate(f, schema=self.vh_xsd_file))
def oscal_validator(oscal_schema, oscal_data):
    schema, stype = read_file(oscal_schema, _get_oscal_file_type(oscal_schema))
    data, ftype = read_file(oscal_data, _get_oscal_file_type(oscal_data))

    if ftype is 'json':
        validate(data, schema)
    if ftype is 'xml':
        xmlschema.validate(data, schema)
def oscal_validator(oscal_schema, oscal_data):
    schema, stype = read_file(oscal_schema, _get_oscal_file_type(oscal_schema))
    data, ftype = read_file(oscal_data, _get_oscal_file_type(oscal_data))

    if ftype == 'json' or ftype == 'yaml':
        # Yaml files are validated using the json schema
        validate(data, schema)
    if ftype == 'xml':
        xmlschema.validate(data, schema)
示例#4
0
def cli(xml_file, schema_file, verbose):
    """Validate an XML against an XSD SCHEMA."""
    xml_from_url = False

    try:
        xml_file, requested_url = xmlFromURL(xml_file, 'XML_FILE')
        if not xml_file.startswith('/'):
            xml_from_url = True

        xsd_resp, _ = xmlFromURL(schema_file, 'SCHEMA_FILE')
        if xsd_resp:
            schema_file = str(xsd_resp)

    except Exception as error:
        click.echo(error)
        return None

    try:
        xmlschema.validate(xml_file, schema=schema_file)
        # When validation succeeds
        if xml_from_url:
            click.echo(f"The XML from the URL:\n{requested_url}")
            click.secho("is valid.\n", fg='green')
        else:
            click.echo("The XML file: " +
                       click.format_filename(str(xml_file), shorten=True))
            click.secho("is valid.\n", fg='green')

    except xmlschema.validators.exceptions.XMLSchemaValidationError as err:
        # When validation does not succeed
        if xml_from_url:
            click.echo(f"The XML from the URL:\n{requested_url}")
            click.secho("is invalid.\n", fg='red')
        else:
            click.echo("The XML file: " +
                       click.format_filename(str(xml_file), shorten=True))
            click.secho("is invalid.\n", fg='red')
        if verbose:
            click.secho("Error:", bold=True)
            click.echo(err)

    except xmlschema.etree.ParseError as err:
        # If there is a syntax error with either file
        click.echo("Faulty XML or XSD file was given.\n")
        if verbose:
            click.echo(f"Error: {err}")

    except xmlschema.exceptions.XMLSchemaException as err:
        if not verbose:
            click.echo("\nValidation ran into an unexpected error." +
                       " Run command with --verbose option for more details\n")
        else:
            click.echo(f"Error: {err}")
示例#5
0
        def test_xml_instances(self):
            if group_tests[0]['source'].endswith('.xsd'):
                schema = group_tests[0]['source']
                schemas = group_tests[0]['sources']
            else:
                schema = None
                schemas = []

            for item in filter(lambda x: not x['source'].endswith('.xsd'), group_tests):
                source = item['source']
                rel_path = os.path.relpath(source)

                for version, expected in sorted(filter(lambda x: x[0] != 'source', item.items())):
                    schema_class = XMLSchema11 if version == '1.1' else XMLSchema10
                    if expected == 'invalid':
                        message = "instance %s should be invalid with XSD %s" % (rel_path, version)
                        with self.assertRaises((XMLSchemaException, ElementTree.ParseError),
                                               msg=message):
                            with warnings.catch_warnings():
                                warnings.simplefilter('ignore')
                                if not schemas:
                                    validate(source, schema=schema, cls=schema_class)
                                else:
                                    xs = schema_class(schemas[0], use_meta=use_meta,
                                                      use_fallback=use_fallback, build=False)
                                    for other in schemas[1:]:
                                        schema_class(other, global_maps=xs.maps,
                                                     use_fallback=use_fallback, build=False)
                                    xs.build()
                                    xs.validate(source)
                    else:
                        try:
                            with warnings.catch_warnings():
                                warnings.simplefilter('ignore')
                                if len(schemas) <= 1 and use_meta and use_fallback:
                                    validate(source, schema=schema, cls=schema_class)
                                else:
                                    xs = schema_class(schemas[0], use_meta=use_meta,
                                                      use_fallback=use_fallback, build=False)
                                    for other in schemas[1:]:
                                        schema_class(other, global_maps=xs.maps, build=False)
                                    xs.build()
                                    xs.validate(source)

                        except (XMLSchemaException, ElementTree.ParseError) as err:
                            error = "instance %s should be valid with XSD %s, but an error " \
                                    "is raised:\n\n%s" % (rel_path, version, str(err))
                        else:
                            error = None
                        self.assertIsNone(error)
示例#6
0
def test_can_create_xml_docs_from_csv():
    csv_file = "./test_data/metadata.csv"
    xsd_file = cvs_to_xsd(csv_file, xml_namespace="https://metadata.com", root_element="oai_dc")

    for xml_file in cvs_to_xml(csv_file, xml_namespace="https://metadata.com", root_element="oai_dc",
                               file_name_column="Identifier"):
        print(xmlschema.validate(xml_file, xsd_file))

    cmis_schema = "./test_data/CmisMetadata.xsd"
    cmis_file = cvs_to_cmis_xslt(csv_file, xml_namespace="https://metadata.com", root_element="oai_dc")

    search_schema = "./test_data/custom-indexer.xsd"
    search_file = csv_to_search_xml(csv_file, xml_namespace="https://metadata.com", root_element="oai_dc")

    xmlschema.validate(search_file, search_schema)
示例#7
0
def test_create_simple_package_with_parent():
    folder = client.folder(FOLDER_ID)
    package = simple_asset_package(preservation_file=file,
                                   parent_folder=folder)
    io_ref = os.path.basename(package).replace(".zip", "")
    with zipfile.ZipFile(package, "r") as zip_ref:
        zip_ref.extractall("./test_data/")
    folder = f"./test_data/{io_ref}"
    assert os.path.exists(folder)
    metadata = f"{folder}/metadata.xml"
    assert os.path.exists(metadata)
    xml_document = xml.etree.ElementTree.parse(metadata)
    ref = xml_document.find(f'.//{{{NS}}}InformationObject/{{{NS}}}Ref')
    assert ref.text == io_ref
    xmlschema.validate(metadata, './test_data/XIP-V6.0.xsd')
    shutil.rmtree(folder)
示例#8
0
        def test_xml_instances(self):
            if group_tests[0]['source'].endswith('.xsd'):
                schema = group_tests[0]['source']
            else:
                schema = None

            for item in filter(lambda x: not x['source'].endswith('.xsd'),
                               group_tests):
                source = item['source']
                rel_path = os.path.relpath(source)

                for version, expected in sorted(
                        filter(lambda x: x[0] != 'source', item.items())):
                    schema_class = XMLSchema11 if version == '1.1' else XMLSchema10
                    if expected == 'invalid':
                        message = "instance %s should be invalid with XSD %s" % (
                            rel_path, version)
                        with self.assertRaises(
                            (XMLSchemaException, ElementTree.ParseError),
                                msg=message):
                            with warnings.catch_warnings():
                                warnings.simplefilter('ignore')
                                validate(source,
                                         schema=schema,
                                         cls=schema_class)
                    else:
                        try:
                            with warnings.catch_warnings():
                                warnings.simplefilter('ignore')
                                validate(source,
                                         schema=schema,
                                         cls=schema_class)
                        except (XMLSchemaException,
                                ElementTree.ParseError) as err:
                            error = "instance %s should be valid with XSD %s, but an error " \
                                    "is raised:\n\n%s" % (rel_path, version, str(err))
                        else:
                            error = None
                        self.assertIsNone(error)
 def validate_XSD_file(self, xml_fileinput):
     """| Usage |
     This keyword is used to validate am xml file against the XSD
     
     | Arguments |
     
      'xml_fileinput' = Output xml file path.
      
      |XSD Validator | ${xml_fileinput}
     """
     if not os.path.exists(xml_fileinput):
         raise AssertionError("File not found error :" + xml_fileinput +
                              " doesnot exist")
     pprint(xmlschema.to_dict(xml_fileinput))
     print(xmlschema.validate(xml_fileinput))
示例#10
0
    def test_document_validate_api_lazy(self):
        source = xmlschema.XMLResource(self.col_xml_file, lazy=False)
        namespaces = source.get_namespaces()
        source.root[0].clear()  # Drop internal elements
        source.root[1].clear()
        xsd_element = self.col_schema.elements['collection']

        self.assertRaises(XMLSchemaValidationError,
                          xsd_element.decode,
                          source.root,
                          namespaces=namespaces)

        for _ in xsd_element.iter_decode(source.root,
                                         'strict',
                                         namespaces=namespaces,
                                         source=source,
                                         max_depth=1):
            del _

        self.assertIsNone(xmlschema.validate(self.col_xml_file, lazy=True))
示例#11
0
def Validate(xml_filepath, xsd_path):

    xmlschema_doc = etree.parse(xsd_path)
    xmlschema = etree.XMLSchema(xmlschema_doc)
    log_text = """<div class="jumbotron">
    <h1>Validation Result</h1>
    </div>
    """
    # parse xml
    try:
        xml_doc = etree.parse(xml_filepath)
        log_text += """<h3>XML Syntax validation : </h3>
            <div class="alert alert-success"> Okay </div>"""

    # check for file IO error
    except IOError:
        log_text += """<div class="alert alert-danger"> Invalid XML file </div>"""

    # check for XML syntax errors
    except etree.XMLSyntaxError as err:
        log_text += """<h2>XML Syntax Error</h2> <ul class="list-group">"""
        for error in err.error_log:
            log_text += "<li class=\"list-group-item\">" + "ERROR ON LINE " + str(
                error.line) + " " + str(
                    error.message.encode("utf-8")) + "</li>"
        log_text += "</ul>"
    except:
        log_text += 'Unknown error occurred .\n'

    # validate against schema
    try:
        xmlschema.assertValid(xml_doc)
        log_text += """<h3>XML Schema validation : </h3>
            <div class="alert alert-success"> Okay </div>"""

    except etree.DocumentInvalid as err:
        log_text += "<h3>XML Validation Error :</h3> <ul class=\"list-group\">"
        for error in err.error_log:
            log_text += "<li class=\"list-group-item\">" + "ERROR ON LINE " + str(
                error.line) + " " + str(
                    error.message.encode("utf-8")) + "</li>"
        log_text += "</ul>"

    except:
        log_text += 'Unknown error occurred .\n'

    result = xmlschema.validate(xml_doc)
    if (result):
        log_text += """<div class="alert alert-success"> <strong> Instance is valid :)</strong>
        </div>
        <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">Patient ID</span>
                    <input  id="patient_id" type="text" class="form-control" placeholder="Patient ID" aria-label="Username" 
                        aria-describedby="basic-addon1" required="true" name="patient_id"
                        pattern="[a-zA-Z0-9]{6,}$"title="Patient ID must have atleast 6 characters(only letters/numbers allowed)">
                </div>
                <br>
                <input type="submit" name="Save" value="Save" />
                <br><br>
        """

    else:
        log_text += """<div class="alert alert-danger"> <strong> Instance is invalid :(</strong>
        </div>"""

    log_text += "</form>"

    htmlheadString = """<!DOCTYPE html>
        <html>
            <head>
                <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
                <title>Validator Response</title>
            </head>
            <body style="margin-left: 30px;margin-right:30px">
        <form action="" method="post">
            {% csrf_token %}
        """

    buttonString = """<div>
        <form action="" method="post">
                {% csrf_token %}
                <input type="submit" name="Home" value="Home" />
                
            </form>
        </div>
        </body> </html>

    """
    source_code = htmlheadString + "\n" + log_text + "\n" + buttonString
    newfilepath = os.path.join(BASE_DIR, 'templates')
    newfilepath = os.path.join(newfilepath, 'validator_response.html')
    newfileobject = open(newfilepath, "w+")
    newfileobject.write(source_code)
    newfileobject.close()
示例#12
0
 def __compare_with_xml_schema(cls, xml_header_path):
     xsd_file_path = os.path.join(str(path), os.pardir, os.pardir,
                                  os.pardir, 'rec_to_nwb', 'data',
                                  'header_schema.xsd')
     xsd_schema = xmlschema.XMLSchema(xsd_file_path)
     xmlschema.validate(xml_header_path, xsd_schema)
示例#13
0
    for xml_file in args.xml_file:
        print("\nValidate XML file {!r} ...".format(xml_file))
        start_dt = datetime.datetime.now()

        try:
            if cert is not None:
                signed_xml_data = lxml.etree.parse(xml_file).getroot()
                signxml.XMLVerifier().verify(signed_xml_data, x509_cert=cert)

                elapsed_time = datetime.datetime.now() - start_dt
                print("XML signature validation: OK (elapsed time: {})".format(
                    elapsed_time))
                start_dt = datetime.datetime.now()
                xml_file = signed_xml_data

            xmlschema.validate(xml_file, schema=schema, lazy=args.lazy)

        except xmlschema.XMLSchemaValidationError as err:
            exit_code = 1
            print("XML schema validation: FAIL")
            if args.verbosity >= 2:
                print(err)

        except (signxml.InvalidDigest, signxml.InvalidSignature) as err:
            exit_code = 1
            print("XML signature validation: FAIL")
            if args.verbosity >= 2:
                print(err)
        else:
            elapsed_time = datetime.datetime.now() - start_dt
            print("XML schema validation: OK (elapsed time: {})".format(
示例#14
0
def validateXMLFiles():
    xmlschema.validate(article_training_data_loc, training_data_schema)
    xmlschema.validate(article_ground_truth_data_loc, ground_truth_schema)
示例#15
0
 def __compare_with_xml_schema(cls, xml_header_path):
     xsd_file_path = str(
         path) + '/../../../rec_to_nwb/data/header_schema.xsd'
     xsd_schema = xmlschema.XMLSchema(xsd_file_path)
     xmlschema.validate(xml_header_path, xsd_schema)