def test_subscription_detail_with_domain_model_cache(test_client,
                                                     generic_subscription_1):
    # test with a subscription that has domain model and without
    subscription = SubscriptionModel.from_subscription(generic_subscription_1)
    extended_model = build_extendend_domain_model(subscription)
    etag = _generate_etag(extended_model)

    app_settings.CACHE_DOMAIN_MODELS = True

    to_redis(extended_model)

    response = test_client.get(
        URL("api/subscriptions/domain-model") / generic_subscription_1)

    cache = Redis(host=app_settings.CACHE_HOST, port=app_settings.CACHE_PORT)
    result = cache.get(f"domain:{generic_subscription_1}")
    cached_model = json_dumps(json_loads(result))
    cached_etag = cache.get(f"domain:etag:{generic_subscription_1}")
    assert cached_model == json_dumps(extended_model)
    assert cached_etag.decode("utf-8") == etag

    assert response.status_code == HTTPStatus.OK
    assert response.json()["subscription_id"] == generic_subscription_1
    app_settings.CACHE_DOMAIN_MODELS = False
    cache.delete(f"domain:{generic_subscription_1}")
示例#2
0
 async def disconnect(self,
                      websocket: WebSocket,
                      code: int = status.WS_1000_NORMAL_CLOSURE,
                      reason: Union[Dict, str, None] = None) -> None:
     if reason:
         await websocket.send_text(json_dumps(reason))
     await websocket.close(code=code)
def test_accept_ok():
    class Form(FormPage):
        accept: Accept

    validated_data = Form(accept="ACCEPTED").dict()

    expected = {"accept": True}
    assert expected == json_loads(json_dumps(validated_data))
示例#4
0
def test_deserialization_datetime():
    json_str = '{"end_date": "2019-12-06T19:25:22+00:00"}'
    dct = json_loads(json_str)
    assert "end_date" in dct
    assert dct["end_date"] == datetime(2019, 12, 6, 19, 25, 22, 0,
                                       timezone.utc)

    dct = {"end_date": datetime(2019, 12, 6, 19, 25, 22, 0, timezone.utc)}
    assert json_loads(json_dumps(dct)) == dct
示例#5
0
 async def broadcast_data(self, channels: List[str], data: Dict) -> None:
     try:
         for channel in channels:
             if channel in self.connections_by_pid:
                 for connection in self.connections_by_pid[channel]:
                     await connection.send_text(json_dumps(data))
                     if "close" in data and data["close"]:
                         await self.disconnect(connection)
     except (RuntimeError, ValueError):
         pass
示例#6
0
def test_post_process_yield():
    def input_form(state):

        user_input = yield TestForm
        return {**user_input.dict(), "extra": 234}

    validated_data = post_process(input_form, {"previous": True},
                                  [{
                                      "generic_select": "a"
                                  }])

    expected = {"generic_select": "a", "extra": 234}
    assert expected == json_loads(json_dumps(validated_data))
async def form_error_handler(request: Request,
                             exc: FormException) -> JSONResponse:
    if isinstance(exc, FormValidationError):
        return JSONResponse(
            {
                "type": type(exc).__name__,
                "detail": str(exc),
                "traceback": show_ex(exc),
                "title": "Form not valid",
                # We need to make sure the is nothing the default json.dumps cannot handle
                "validation_errors": json_loads(json_dumps(exc.errors)),
                "status": HTTPStatus.BAD_REQUEST,
            },
            status_code=HTTPStatus.BAD_REQUEST,
        )
    elif isinstance(exc, FormNotCompleteError):
        return JSONResponse(
            {
                "type": type(exc).__name__,
                "detail": str(exc),
                "traceback": show_ex(exc),
                # We need to make sure the is nothing the default json.dumps cannot handle
                "form": json_loads(json_dumps(exc.form)),
                "title": "Form not complete",
                "status": HTTPStatus.NOT_EXTENDED,
            },
            status_code=HTTPStatus.NOT_EXTENDED,
        )
    else:
        return JSONResponse(
            {
                "detail": str(exc),
                "title": "Internal Server Error",
                "status": HTTPStatus.INTERNAL_SERVER_ERROR,
                "type": type(exc).__name__,
            },
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
        )
示例#8
0
def to_redis(subscription: Dict[str, Any]) -> None:
    if caching_models_enabled():
        logger.info("Setting cache for subscription.",
                    subscription=subscription["subscription_id"])
        etag = _generate_etag(subscription)
        cache.set(f"domain:{subscription['subscription_id']}",
                  json_dumps(subscription),
                  ex=ONE_WEEK)
        cache.set(f"domain:etag:{subscription['subscription_id']}",
                  etag,
                  ex=ONE_WEEK)
    else:
        logger.warning("Caching disabled, not caching subscription",
                       subscription=subscription["subscription_id"])
示例#9
0
async def websocket_get_global_status(
    websocket: WebSocket, token: str = Query(...)) -> None:
    error = await websocket_manager.authorize(websocket, token)

    await websocket.accept()
    if error:
        await websocket_manager.disconnect(websocket, reason=error)
        return

    engine_settings = EngineSettingsTable.query.one()

    await websocket.send_text(
        json_dumps({
            "engine-status":
            generate_engine_status_response(engine_settings)
        }))

    channel = WS_CHANNELS.ENGINE_SETTINGS
    await websocket_manager.connect(websocket, channel)
示例#10
0
        def request(  # type: ignore
            self,
            method: str,
            url: str,
            data: Optional[DataType] = None,
            headers: Optional[typing.MutableMapping[str, str]] = None,
            json: typing.Any = None,
            **kwargs: Any,
        ) -> requests.Response:
            if json is not None:
                if headers is None:
                    headers = {}
                data = json_dumps(json).encode()
                headers["Content-Type"] = "application/json"

            return super().request(method,
                                   url,
                                   data=data,
                                   headers=headers,
                                   **kwargs)  # type: ignore
示例#11
0
def test_post_process_wizard():
    # Return if there is no form
    assert post_process(None, {}, []) == {}
    assert post_process([], {}, []) == {}

    def input_form(state):
        class TestForm1(FormPage):
            generic_select1: TestChoices

            class Config:
                title = "Some title"

        class TestForm2(FormPage):
            generic_select2: TestChoices

        class TestForm3(FormPage):
            generic_select3: TestChoices

        user_input_1 = yield TestForm1

        if user_input_1.generic_select1 == TestChoices.A:
            user_input_2 = yield TestForm2
        else:
            user_input_2 = yield TestForm3

        return {**user_input_1.dict(), **user_input_2.dict()}

    # Submit 1
    with pytest.raises(FormNotCompleteError) as error_info:
        post_process(input_form, {"previous": True}, [])

    assert error_info.value.form == {
        "title": "Some title",
        "type": "object",
        "additionalProperties": False,
        "definitions": {
            "TestChoices": {
                "description": "An enumeration.",
                "enum": ["a", "b"],
                "title": "TestChoices",
                "type": "string",
            }
        },
        "properties": {
            "generic_select1": {
                "$ref": "#/definitions/TestChoices"
            }
        },
        "required": ["generic_select1"],
    }

    # Submit 2
    with pytest.raises(FormNotCompleteError) as error_info:
        post_process(input_form, {"previous": True}, [{
            "generic_select1": "b"
        }])

    assert error_info.value.form == {
        "title": "unknown",
        "type": "object",
        "additionalProperties": False,
        "definitions": {
            "TestChoices": {
                "description": "An enumeration.",
                "enum": ["a", "b"],
                "title": "TestChoices",
                "type": "string",
            }
        },
        "properties": {
            "generic_select3": {
                "$ref": "#/definitions/TestChoices"
            }
        },
        "required": ["generic_select3"],
    }

    # Submit complete
    validated_data = post_process(input_form, {"previous": True},
                                  [{
                                      "generic_select1": "b"
                                  }, {
                                      "generic_select3": "a"
                                  }])

    expected = {"generic_select1": "b", "generic_select3": "a"}
    assert expected == json_loads(json_dumps(validated_data))

    # Submit overcomplete
    validated_data = post_process(input_form, {"previous": True},
                                  [{
                                      "generic_select1": "b"
                                  }, {
                                      "generic_select3": "a"
                                  }, {
                                      "to_much": True
                                  }])

    expected = {"generic_select1": "b", "generic_select3": "a"}
    assert expected == json_loads(json_dumps(validated_data))
示例#12
0
def test_serialization_datetime():
    json_str = json_dumps({"end_date": nowtz()})
    assert re.search(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00", json_str)
示例#13
0
 async def broadcast_data(self, channels: List[str], data: Dict) -> None:
     await self.pub_broadcast.connect()
     for channel in channels:
         await self.pub_broadcast.publish(channel, message=json_dumps(data))
     await self.pub_broadcast.disconnect()