Example #1
0
def test_sateless_faker_3(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/geographical-location.schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#",
        "title": "Longitude and Latitude Values",
        "description": "A geographical coordinate.",
        "required": ["latitude", "longitude"],
        "type": "object",
        "properties": {
            "latitude": {"type": "number", "minimum": -90.0, "maximum": 90.0},
            "longitude": {"type": "number", "minimum": -180.0, "maximum": 180.0},
        },
    }
    res = faker.process(
        OpenAPISpecification(source="default", api=spec(response_schema=schema)),
        request,
    )

    assert valid_schema(res.bodyAsJson, schema)
Example #2
0
def test_sateless_faker_2(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/person.schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#",
        "title": "Person",
        "type": "object",
        "properties": {
            "firstName": {"type": "string", "description": "The person's first name."},
            "lastName": {"type": "string", "description": "The person's last name."},
            "age": {
                "description": "Age in years which must be equal to or greater than zero.",
                "type": "integer",
                "minimum": 0.0,
            },
        },
    }
    res = faker.process(
        OpenAPISpecification(source="default", api=spec(response_schema=schema)),
        request,
    )

    assert valid_schema(res.bodyAsJson, schema)
Example #3
0
def test_sateless_faker_1(mock_data_store):
    faker = StatefulFaker(mock_data_store)

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

    schema = {
        "type": "array",
        "items": {
            "type": "object",
            "required": ["foo", "baz"],
            "properties": {
                "foo": {"type": "number"},
                "bar": {"type": "string"},
                "baz": {"type": "string"},
            },
        },
    }
    res = faker.process(
        OpenAPISpecification(source="default", api=spec(response_schema=schema)),
        request,
    )

    assert valid_schema(res.bodyAsJson, schema)
Example #4
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)
Example #5
0
def test_fake_array(mock_data_store):
    faker = StatefulFaker(mock_data_store)

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

    schema = {"type": "array", "items": {"$ref": "#/components/schemas/item"}}

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

    spec = spec_dict(
        path="/items", response_schema=schema, components=components, method="get"
    )
    spec["paths"]["/items"]["x-hmt-entity"] = "item"
    spec["paths"]["/items"]["get"]["x-hmt-operation"] = "read"

    spec = convert_to_OpenAPIObject(spec)
    mock_data_store.add_mock(OpenAPISpecification(spec, "default"))

    schema["components"] = components
    spec = OpenAPISpecification(source="default", api=spec)

    res = faker.process(spec, request)

    assert valid_schema(res.bodyAsJson, schema)
    assert 0 == len(res.bodyAsJson)

    mock_data_store["default"].item.insert({"foo": 10, "bar": "val", "itemId": "id123"})
    res = faker.process(spec, request)

    assert valid_schema(res.bodyAsJson, schema)
    assert 1 == len(res.bodyAsJson)

    mock_data_store["default"].item.insert(
        {"foo": 10, "bar": "val", "itemId": "id1234"}
    )
    res = faker.process(spec, request)

    assert valid_schema(res.bodyAsJson, schema)
    assert 2 == len(res.bodyAsJson)
Example #6
0
 def __init__(
     self,
     specs: Sequence[OpenAPISpecification],
     mock_data_store: MockDataStore,
     callback_manager: CallbackManager,
     rest_middleware_manager: RestMiddlewareManager,
 ):
     self._specs = specs
     self._mock_data_store = mock_data_store
     self._callback_manager = callback_manager
     self._rest_middleware_manager = rest_middleware_manager
     self._faker = StatefulFaker(self._mock_data_store)
Example #7
0
def test_sateless_faker_5(mock_data_store):
    faker = StatefulFaker(mock_data_store)

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

    schema = {"type": "array"}
    res = faker.process(
        OpenAPISpecification(source="default", api=spec(response_schema=schema)),
        request,
    )

    assert valid_schema(res.bodyAsJson, schema)
Example #8
0
def test_insert(mock_data_store):
    faker = StatefulFaker(mock_data_store)

    request_schema = {
        "type": "object",
        "properties": {"item": {"$ref": "#/components/schemas/item"}},
    }

    response_schema = {"$ref": "#/components/schemas/item"}

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

    spec = spec_dict(
        path="/items",
        request_schema=request_schema,
        response_schema=response_schema,
        components=components,
        method="post",
    )
    spec["paths"]["/items"]["x-hmt-entity"] = "item"
    spec["paths"]["/items"]["post"]["x-hmt-operation"] = "insert"

    spec = convert_to_OpenAPIObject(spec)
    mock_data_store.add_mock(OpenAPISpecification(spec, "default"))

    schema = response_schema
    schema["components"] = components
    spec = OpenAPISpecification(source="default", api=spec)

    request = RequestBuilder.from_dict(
        dict(
            method="post",
            protocol="http",
            path="/items",
            host="api.com",
            bodyAsJson={"item": {"foo": 10, "bar": "val"}},
        )
    )
    res = faker.process(spec, request)

    assert valid_schema(res.bodyAsJson, schema)
    assert res.bodyAsJson["itemId"] is not None
    assert 10 == res.bodyAsJson["foo"]

    assert 1 == len(mock_data_store["default"].item)
    assert "val" == mock_data_store["default"].item[res.bodyAsJson["itemId"]]["bar"]

    request = RequestBuilder.from_dict(
        dict(
            method="post",
            protocol="http",
            path="/items",
            host="api.com",
            bodyAsJson={"item": {"foo": 20, "bar": "val1", "itemId": "id123"}},
        )
    )
    res = faker.process(spec, request)

    assert valid_schema(res.bodyAsJson, schema)
    assert "id123" == res.bodyAsJson["itemId"]
    assert 20 == res.bodyAsJson["foo"]

    assert 2 == len(mock_data_store["default"].item)
    assert "val1" == mock_data_store["default"].item[res.bodyAsJson["itemId"]]["bar"]

    request = RequestBuilder.from_dict(
        dict(
            method="post",
            protocol="http",
            path="/items",
            host="api.com",
            bodyAsJson={"item": {"foo": 30, "itemId": "id123"}},
        )
    )
    res = faker.process(spec, request)

    assert 2 == len(mock_data_store["default"].item)
    assert "bar" not in mock_data_store["default"].item[res.bodyAsJson["itemId"]]
    assert 30 == mock_data_store["default"].item[res.bodyAsJson["itemId"]]["foo"]
Example #9
0
class RequestProcessor:
    _specs: Sequence[OpenAPISpecification]

    def __init__(
        self,
        specs: Sequence[OpenAPISpecification],
        mock_data_store: MockDataStore,
        callback_manager: CallbackManager,
        rest_middleware_manager: RestMiddlewareManager,
    ):
        self._specs = specs
        self._mock_data_store = mock_data_store
        self._callback_manager = callback_manager
        self._rest_middleware_manager = rest_middleware_manager
        self._faker = StatefulFaker(self._mock_data_store)

    def match_error(self, msg: str, req: Request):
        json_resp = {
            "message":
            "%s. Here is the full request: host=%s, path=%s, method=%s." %
            (msg, req.host, req.path, req.method.value)
        }
        return Response(
            statusCode=501,
            body=json.dumps(json_resp),
            bodyAsJson=json_resp,
            headers={},
            timestamp=None,
        )

    def _match_response(self, spec: OpenAPISpecification, request: Request):
        try:
            return self._faker.process(spec, request)
        except FakerException as e:
            return self.match_error(str(e), request)

    def process(self, request: Request) -> Response:
        if request.method.value is None:
            method_error = "Could not find a method %s for path %s on hostname %s." % (
                request.method.value,
                request.path,
                request.host,
            )
            return self.match_error(method_error, request)

        specs = self._rest_middleware_manager.spew(request, self._specs)

        logger.debug("Matching to security schemes of %d specs", len(specs))
        maybe_security_response = match_to_security_schemes(
            request, [spec.api for spec in specs])

        if maybe_security_response is not None:
            logger.debug("Matched to security scheme, returning response.")
            return maybe_security_response

        match = match_request_to_openapi(request, specs)

        if len(match) == 0:
            return self._callback_manager(
                request,
                self.match_error(
                    "Could not find an open API schema for the host %s." %
                    request.host,
                    request,
                ),
                self._mock_data_store.default,
            )

        spec = random.choice(match)
        if spec.api.paths is None or len(spec.api.paths.items()) == 0:
            path_error = "Could not find a path %s on hostname %s." % (
                request.path,
                request.host,
            )
            return self.match_error(path_error, request)

        storage = self._mock_data_store[spec.source]
        response = self._match_response(spec, request)
        return self._callback_manager(request, response, storage)