Exemple #1
0
def path_parameter_match(
    part: str, vname: str, path_item: PathItem, operation: str, oas: OpenAPIObject,
) -> bool:
    """Matches part of a path against a path parameter with name vname

    Arguments:
        part {str} -- part of a path, ie an id
        vname {str} -- name of a parameter
        path_item {PathItem} -- a path item maybe containing the parameter
        operation {MethodNames} -- the name of the operation to check in case the parameter is in the operation
        oas {OpenAPIObject} -- the schema to traverse to find definitions

    Returns:
        bool -- Did we get a match
    """
    return reduce(
        lambda q, r: q
        and reduce(
            lambda a, b: a
            or valid_schema(
                b,
                {
                    **convert_from_openapi(r),
                    "definitions": make_definitions_from_spec(oas),
                },
            ),
            list(set([part, maybeJson(part)])),
            False,
        ),
        get_matching_parameters(vname, path_item, operation, oas),
        True,
    )
Exemple #2
0
def test_sateless_faker_4(mock_data_store):
    faker = StatefulFaker(mock_data_store)

    request = RequestBuilder.from_dict(
        dict(method="get", protocol="http", path="/", host="api.com"))

    schema = {
        "$id": "https://example.com/arrays.schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description":
        "A representation of a person, company, organization, or place",
        "type": "object",
        "properties": {
            "fruits": {
                "type": "array",
                "items": {
                    "type": "string"
                }
            },
            "vegetables": {
                "type": "array",
                "items": {
                    "$ref": "#/components/schemas/veggie"
                },
            },
        },
    }
    components = {
        "schemas": {
            "veggie": {
                "type": "object",
                "required": ["veggieName", "veggieLike"],
                "properties": {
                    "veggieName": {
                        "type": "string",
                        "description": "The name of the vegetable.",
                    },
                    "veggieLike": {
                        "type": "boolean",
                        "description": "Do I like this vegetable?",
                    },
                },
            }
        }
    }
    oai = spec(response_schema=schema, components=components)
    res = faker.process(
        "/",
        OpenAPISpecification(source="default",
                             api=oai,
                             definitions=make_definitions_from_spec(oai)),
        request,
    )

    schema["components"] = components
    assert valid_schema(res.bodyAsJson, schema)
Exemple #3
0
def test_reset():
    schema = {"$ref": "#/components/schemas/item"}

    components = {
        "schemas": {
            "item": {
                "type": "object",
                "required": ["foo", "baz"],
                "x-hmt-id-path": "itemId",
                "properties": {
                    "foo": {
                        "type": "number"
                    },
                    "bar": {
                        "type": "string"
                    },
                    "itemId": {
                        "type": "string"
                    },
                },
            }
        }
    }

    spec = spec_dict(path="/items/{id}",
                     response_schema=schema,
                     components=components,
                     method="get")
    spec["paths"]["/items/{id}"]["x-hmt-entity"] = "item"
    spec["paths"]["/items/{id}"]["get"]["x-hmt-operation"] = "read"
    spec["x-hmt-data"] = {
        "item": [{
            "foo": 10,
            "bar": "val",
            "itemId": "id123"
        }]
    }
    spec = convert_to_OpenAPIObject(spec)

    store = MockDataStore()
    store.add_mock(
        OpenAPISpecification(spec, "items", make_definitions_from_spec(spec)))

    assert 1 == len(store["items"].item)

    store["items"].item.insert({"foo": 10, "bar": "val1", "itemId": "id1234"})

    assert 2 == len(store["items"].item)
    assert "val1" == store["items"].item["id1234"]["bar"]

    store.reset()

    assert 1 == len(store["items"].item)
    assert "val" == store["items"].item["id123"]["bar"]
Exemple #4
0
def _json_schema_from_required_parameters(
    parameters: Sequence[Parameter], oai: OpenAPIObject
) -> Any:
    return {
        "type": "object",
        "properties": {
            param.name: convert_from_openapi(param.schema) for param in parameters
        },
        "required": [param.name for param in parameters if param.required],
        "additionalProperties": True,
        "definitions": make_definitions_from_spec(oai),
    }
Exemple #5
0
def load_spec(spec_source: str, is_http: bool) -> OpenAPISpecification:
    spec_text: str
    if is_http:
        try:
            response = requests.get(spec_source)
            spec_text = response.text
        except RequestException:
            raise Exception(f"Failed to load {spec_source}")
    else:
        with open(spec_source, encoding="utf8") as spec_file:
            spec_text = spec_file.read()

    spec = convert_to_openapi((json.loads if spec_source.endswith("json") else
                               yaml.safe_load)(spec_text))
    return OpenAPISpecification(spec, spec_source,
                                make_definitions_from_spec(spec))
Exemple #6
0
    def spew(
        self, request: Request, specs: Sequence[OpenAPISpecification]
    ) -> Sequence[OpenAPISpecification]:
        if len(self._endpoints) == 0:
            return specs

        req = HttpExchangeWriter.to_dict(request)
        cs = {spec.source: convert_from_openapi(spec.api) for spec in specs}
        for endpoint in self._endpoints:
            res = requests.post(endpoint, json={"request": req, "schemas": cs})
            cs = res.json()

        out = []
        for name, dict_spec in cs.items():
            spec = convert_to_openapi(dict_spec)
            out.append(
                OpenAPISpecification(
                    spec, name, definitions=make_definitions_from_spec(spec)))

        for spec in out:
            self._mock_data_store.add_mock(spec)

        return out