Example #1
0
def test_json_encoder_raises(hass):
    """Test the JSON encoder raises on unsupported types."""
    ha_json_enc = JSONEncoder()

    # Default method raises TypeError if non HA object
    with pytest.raises(TypeError):
        ha_json_enc.default(1)
def test_json_encoder(hass):
    """Test the JSON Encoder."""
    ha_json_enc = JSONEncoder()
    state = core.State('test.test', 'hello')

    assert ha_json_enc.default(state) == state.as_dict()

    # Default method raises TypeError if non HA object
    with pytest.raises(TypeError):
        ha_json_enc.default(1)

    now = dt_util.utcnow()
    assert ha_json_enc.default(now) == now.isoformat()
def _encode(value: Any) -> Any:
    """Little helper to JSON encode a value."""
    try:
        return JSONEncoder.default(
            None,  # type: ignore
            value,
        )
    except TypeError:
        return value
Example #4
0
    def default(self, o: Any) -> Any:
        """Convert timedelta objects.

        Hand other objects to the Home Assistant JSONEncoder.
        """
        if isinstance(o, timedelta):
            return o.total_seconds()

        return JSONEncoder.default(self, o)
Example #5
0
async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
    """Activate Azure EH component."""
    config = yaml_config[DOMAIN]

    event_hub_address = (
        f"amqps://{config[CONF_EVENT_HUB_NAMESPACE]}"
        f".servicebus.windows.net/{config[CONF_EVENT_HUB_INSTANCE_NAME]}"
    )
    entities_filter = config[CONF_FILTER]

    client = EventHubClientAsync(
        event_hub_address,
        debug=True,
        username=config[CONF_EVENT_HUB_SAS_POLICY],
        password=config[CONF_EVENT_HUB_SAS_KEY],
    )
    async_sender = client.add_async_sender()
    await client.run_async()

    encoder = JSONEncoder()

    async def async_send_to_event_hub(event: Event):
        """Send states to Event Hub."""
        state = event.data.get("new_state")
        if (
            state is None
            or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE)
            or not entities_filter(state.entity_id)
        ):
            return

        event_data = EventData(
            json.dumps(obj=state.as_dict(), default=encoder.encode).encode("utf-8")
        )
        await async_sender.send(event_data)

    async def async_shutdown(event: Event):
        """Shut down the client."""
        await client.stop_async()

    hass.bus.async_listen(EVENT_STATE_CHANGED, async_send_to_event_hub)
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_shutdown)

    return True
def test_json_encoder(hass):
    """Test the JSON Encoder."""
    ha_json_enc = JSONEncoder()
    state = core.State("test.test", "hello")

    assert ha_json_enc.default(state) == state.as_dict()

    # Default method raises TypeError if non HA object
    with pytest.raises(TypeError):
        ha_json_enc.default(1)

    now = dt_util.utcnow()
    assert ha_json_enc.default(now) == now.isoformat()
Example #7
0
def test_json_encoder(hass):
    """Test the JSON Encoder."""
    ha_json_enc = JSONEncoder()
    state = core.State("test.test", "hello")

    # Test serializing a datetime
    now = dt_util.utcnow()
    assert ha_json_enc.default(now) == now.isoformat()

    # Test serializing a set()
    data = {"milk", "beer"}
    assert sorted(ha_json_enc.default(data)) == sorted(data)

    # Test serializing an object which implements as_dict
    assert ha_json_enc.default(state) == state.as_dict()

    # Default method raises TypeError if non HA object
    with pytest.raises(TypeError):
        ha_json_enc.default(1)
Example #8
0
def _encode(value):
    """Little helper to JSON encode a value."""
    try:
        return JSONEncoder.default(None, value)
    except TypeError:
        return value