Skip to content

Commit

Permalink
add test relays
Browse files Browse the repository at this point in the history
  • Loading branch information
steersbob committed Dec 4, 2023
1 parent 60d69c8 commit 0d6a598
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 100 deletions.
4 changes: 2 additions & 2 deletions brewblox_history/app_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def init_logging(debug: bool):
datefmt = '%Y/%m/%d %H:%M:%S'

logging.basicConfig(level=level, format=format, datefmt=datefmt)
# logging.captureWarnings(True)
logging.captureWarnings(True)

logging.getLogger('gmqtt').setLevel(unimportant_level)
logging.getLogger('httpx').setLevel(unimportant_level)
Expand All @@ -36,7 +36,7 @@ async def lifespan(app: FastAPI):
yield


def create_app():
def create_app() -> FastAPI:
config = utils.get_config()
init_logging(config.debug)

Expand Down
1 change: 0 additions & 1 deletion brewblox_history/redis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# import json
import logging
from contextlib import asynccontextmanager
from contextvars import ContextVar
Expand Down
97 changes: 0 additions & 97 deletions test/_test_relays.py

This file was deleted.

99 changes: 99 additions & 0 deletions test/test_relays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""
Tests brewblox_history.relays
"""

import asyncio
from contextlib import AsyncExitStack
from unittest.mock import AsyncMock, Mock, call

import pytest
from fastapi import FastAPI
from httpx import AsyncClient

from brewblox_history import mqtt, relays, victoria
from brewblox_history.models import HistoryEvent, ServiceConfig

TESTED = relays.__name__


@pytest.fixture
def m_victoria(mocker):
m = Mock()
m.write = AsyncMock()
victoria.CV.set(m)
return m


@pytest.fixture
def app(m_victoria):
mqtt.setup()
relays.setup()
app = FastAPI()
return app


@pytest.fixture
async def lifespan(app):
async with AsyncExitStack() as stack:
# Prevents test hangups if the connection fails
async with asyncio.timeout(5):
await stack.enter_async_context(mqtt.lifespan())
yield


async def test_mqtt_relay(client: AsyncClient, config: ServiceConfig, m_victoria: Mock):
topic = 'brewcast/history'
recv = []
recv_done = asyncio.Event()
mqtt_client = mqtt.CV.get()

@mqtt_client.subscribe(config.history_topic + '/#')
async def on_history_message(client, topic, payload, qos, properties):
recv.append(payload)
if len(recv) >= 5:
recv_done.set()

data = {
'nest': {
'ed': {
'values': [
'val',
'var',
True,
]
}
}
}

nested_empty_data = {
'nest': {
'ed': {
'empty': {},
'data': [],
}
}
}

flat_data = {
'nest/ed/values/0': 'val',
'nest/ed/values/1': 'var',
'nest/ed/values/2': True,
}

flat_value = {
'single/text': 'value',
}

mqtt_client.publish(topic, {'key': 'm', 'data': data})
mqtt_client.publish(topic, {'key': 'm', 'data': flat_value})
mqtt_client.publish(topic, {'key': 'm', 'data': nested_empty_data})
mqtt_client.publish(topic, {'pancakes': 'yummy'})
mqtt_client.publish(topic, {'key': 'm', 'data': 'no'})

await asyncio.wait_for(recv_done.wait(), timeout=5)

assert m_victoria.write.await_args_list == [
call(HistoryEvent(key='m', data=flat_data)),
call(HistoryEvent(key='m', data=flat_value)),
call(HistoryEvent(key='m', data={})),
]
7 changes: 7 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Tests brewblox_history.utils
"""

import logging
from datetime import datetime, timedelta, timezone

import pytest
Expand All @@ -11,6 +12,12 @@
TESTED = utils.__name__


def test_duplicate_filter(caplog: pytest.LogCaptureFixture):
logger = logging.getLogger('test_duplicate')
logger.addFilter(utils.DuplicateFilter())
len_start = len(caplog.records)


def test_parse_duration():
assert utils.parse_duration('2h10m') == timedelta(hours=2, minutes=10)
assert utils.parse_duration('10') == timedelta(seconds=10)
Expand Down
13 changes: 13 additions & 0 deletions test/test_victoria.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,16 @@ async def handler(request: Request) -> Response:
'service f1=1.0',
'service f1=2.0,f2=3.0',
]


async def test_write_exc(client: AsyncClient,
url: str,
httpx_mock: HTTPXMock):
vic = victoria.CV.get()

httpx_mock.add_exception(url=f'{url}/write',
method='POST',
exception=RuntimeError('dummy error'))

# Write errors are swallowed
await vic.write(HistoryEvent(key='service', data={'f1': 1}))

0 comments on commit 0d6a598

Please sign in to comment.