示例#1
0
def test_auto_bad():
    with pytest.raises(TypeError):  # NOTE TypeError
        decoder.to_dict(b'')
    with pytest.raises(TypeError):
        decoder.to_dict(b'[]')
    with pytest.raises(TypeError):
        decoder.to_dict(b'/\\')
    with pytest.raises(ValueError):
        decoder.to_dict(YAML, 'json')
    with pytest.raises(ValueError):
        decoder.to_dict(YAML, ctype='application/json')
示例#2
0
def validate(doc, schemas):
    """
        Validate a document agasint schemas.
        Schemas is a dict of name and schema pairs.
    """

    # required by jsonschema package
    if not isinstance(doc, dict):
        doc = decoder.to_dict(doc)

    try:  # validate agasint every schema
        for name, schema in schemas.items():
            jsonschema.validate(doc, schema)

    except jsonschema.ValidationError as err:
        _ = (
            f"Failed {name} validation at "
            f"{err.path} - {err.message}. "
            # show path first, message can
            # sometimes be very very long
        )
        raise ValueError(_) from err

    except Exception as err:
        _ = (
            f"Unexpected Validation Error: "
            f"{type(err).__name__} - {err}"
        )
        raise ValueError(_) from err
示例#3
0
 def test_json(self):
     '''
     [POST] with JSON body
     '''
     headers = {'Content-type': 'application/yaml', 'Accept': 'text/plain'}
     self.request("/api/validate/",
                  method='POST',
                  json=decoder.to_dict(MYGENE_RAW))
     self.request("/api/validate/",
                  method='POST',
                  data=MYGENE_RAW,
                  headers=headers)
     self.request("/api/validate/", method='POST', data=MYGENE_RAW)
     with open(os.path.join(dirname, './validate/openapi-pass.json'),
               'rb') as file:
         self.request("/api/validate/", method='POST', data=file.read())
     with open(os.path.join(dirname, './validate/swagger-pass.json'),
               'rb') as file:
         self.request("/api/validate/", method='POST', data=file.read())
     with open(os.path.join(dirname, './validate/x-translator-pass.json'),
               'rb') as file:
         self.request("/api/validate/", method='POST', data=file.read())
     with open(os.path.join(dirname, './validate/x-translator-fail-1.yml'),
               'rb') as file:
         self.request("/api/validate/",
                      method='POST',
                      data=file.read(),
                      expect=400)
     with open(os.path.join(dirname, './validate/x-translator-fail-2.yml'),
               'rb') as file:
         self.request("/api/validate/",
                      method='POST',
                      data=file.read(),
                      expect=400)
示例#4
0
def test_javascript():
    # intentionally test this because
    # we rely on it in the application
    doc = decoder.to_dict(SWAGGER)
    assert doc["id"] == "http://swagger.io/v2/schema.json#"
    assert doc["type"] == "object"
    assert "$schema" in doc
    assert "required" in doc
示例#5
0
def download_mapping(url):

    response = requests.get(url)
    response.raise_for_status()

    return decoder.to_dict(stream=response.content,
                           ext=file_extension(url),
                           ctype=response.headers.get("Content-Type"))
示例#6
0
    def transform_hit(self, path, doc, options):

        if path == '':
            doc.pop('_index')
            doc.pop('_type', None)  # not available by default on es7
            doc.pop('sort', None)  # added when using sort
            doc.pop('_node', None)  # added when using explain
            doc.pop('_shard', None)  # added when using explain

            # OVERRIDE STARTS HERE

            if "_raw" in doc:
                _raw = b64decode(doc.pop('_raw'))
                _raw = decoder.decompress(_raw)
                _raw = decoder.to_dict(_raw)
                doc.update(_raw)

            if options.raw == 0:
                for key in list(doc.keys()):
                    if key.startswith('_'):
                        doc.pop(key)

            if isinstance(doc.get('paths'), list):
                doc['paths'] = {
                    item['path']: item.get('pathitem', {})
                    for item in doc['paths']
                }

            # NOTE
            # Root field filtering in transform stage (if necessary)
            # ---------------------------------------------------------------
            # if options._source:
            #     fields = {field.split('.')[0] for field in options._source}
            #     for key in list(doc.keys()):
            #         if key not in fields:
            #             doc.pop(key)

            # field ordering
            if not options.sorted:

                if 'openapi' in doc:
                    _doc = OpenAPI(doc)
                    _doc.order()
                    # meta fields appear first
                    for key in list(doc.keys()):
                        if not key.startswith('_'):
                            doc.pop(key)
                    doc.update(_doc)

                elif 'swagger' in doc:
                    _doc = Swagger(doc)
                    _doc.order()
                    # meta fields appear first
                    for key in list(doc.keys()):
                        if not key.startswith('_'):
                            doc.pop(key)
                    doc.update(_doc)
示例#7
0
    def raw(self, value):

        if not value:
            raise ControllerError("Empty value.")
        try:
            self._data = decoder.to_dict(value)
        except (ValueError, TypeError) as err:
            raise ControllerError(str(err)) from err
        else:  # dict conversion success
            self._raw = value

        # update the timestamps
        self.last_updated = datetime.now(timezone.utc)
        if not self.date_created:
            self.date_created = self.last_updated
示例#8
0
def test_auto_good():
    _ok(decoder.to_dict(YAML))
    _ok(decoder.to_dict(JSON))
    _ok(decoder.to_dict(JSTS))  # NOTE Javascript Only Supported Here

    _ok(decoder.to_dict(JSON, 'json'))
    _ok(decoder.to_dict(JSON, ctype='application/json'))
    _ok(decoder.to_dict(JSON, ctype='application/JSON'))
    _ok(decoder.to_dict(JSON, 'json', 'application/json'))
    _ok(decoder.to_dict(JSON, ctype='application/json; charset=utf-8'))

    _ok(decoder.to_dict(YAML, 'yml'))
    _ok(decoder.to_dict(YAML, 'yaml'))
    _ok(decoder.to_dict(YAML, ctype='application/yaml'))
    _ok(decoder.to_dict(YAML, ctype='application/YAML'))
    _ok(decoder.to_dict(YAML, 'yaml', 'application/yaml'))
    _ok(decoder.to_dict(YAML, ctype='application/yaml; charset=utf-8'))