Skip to content

Commit

Permalink
refactor(test): add fixtures for bewegungsdaten
Browse files Browse the repository at this point in the history
Clean up imports
  • Loading branch information
DarwinsBuddy committed Nov 12, 2024
1 parent 1414e74 commit ef0b6ff
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 45 deletions.
1 change: 0 additions & 1 deletion custom_components/wnsm/statistics_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from datetime import timedelta, timezone, datetime
from decimal import Decimal
from operator import itemgetter
from zoneinfo import ZoneInfo

from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.models import (
Expand Down
69 changes: 36 additions & 33 deletions tests/it/__init__.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import datetime as dt
import json
import os
import random
import sys
import json
from datetime import datetime, timedelta
from importlib.resources import files
from urllib import parse
from urllib.parse import urlencode

import pytest
import requests
from requests_mock import Mocker
import urllib3

from test_resources import post_data_matcher
from importlib.resources import files
import datetime as dt
from urllib import parse

# necessary for pytest-cov to measure coverage
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../../custom_components')
from wnsm import api # noqa: E402
from wnsm.api.constants import Resolution, ValueType, AnlageType, RoleType # noqa: E402
from wnsm.api.constants import ValueType, AnlageType, RoleType # noqa: E402


def _dt_string(datetime_string):
Expand Down Expand Up @@ -272,47 +274,48 @@ def history_response(zp: str, wrong_zp: bool = False, wrong_obis_code: bool = Fa
"zaehlpunkt": zp
}

def delta(i: str, n: int=0) -> timedelta:
return {
"h": timedelta(hours=n),
"d": timedelta(days=n),
"qh": timedelta(minutes=15 * n)
}[i.lower()]

def bewegungsdaten_value(ts: datetime, interval: str, i: int = 0) -> dict:
t = ts.replace(minute=0, second=0, microsecond=0)
return {
"wert": round(random.gauss(0.045,0.015), 3),
"zeitpunktVon": (t + delta(interval, i)).strftime('%Y-%m-%dT%H:%M:%SZ'),
"zeitpunktBis": (t + delta(interval, i+1)).strftime('%Y-%m-%dT%H:%M:%SZ'),
"geschaetzt": False
}

def bewegungsdaten(count=24, timestamp=None, interval='h'):
if timestamp is None:
timestamp = datetime.now().replace(minute=0, second=0, microsecond=0)
return [bewegungsdaten_value(timestamp, interval, i) for i in list(range(0,count))]


def bewegungsdaten_response(customer_id: str, zp: str,
granularity: ValueType = ValueType.QUARTER_HOUR, anlagetype: AnlageType = AnlageType.CONSUMING,
wrong_zp: bool = False, empty_values: bool = False):
wrong_zp: bool = False, values_count: int = 10):
if (granularity == ValueType.QUARTER_HOUR):
t1 = "2022-08-07T00:00:00Z"
t2 = "2022-08-07T00:15:00Z"
t3 = "2022-08-07T00:30:00Z"
gran = "QH"
if(anlagetype == AnlageType.CONSUMING):
rolle = "V002"
else:
rolle = "E002"
else:
t1 = "2022-08-07T00:00:00Z"
t2 = "2022-08-08T00:00:00Z"
t3 = "2022-08-09T00:00:00Z"
gran = "D"
if(anlagetype == AnlageType.CONSUMING):
rolle = "V001"
else:
rolle = "V002"
if wrong_zp:
zp = zp + "9"
if empty_values:
values = []
else:
values = [
{
"wert": 0.041,
"zeitpunktVon": t1,
"zeitpunktBis": t2,
"geschaetzt": False
},
{
"wert": 0.034,
"zeitpunktVon": t2,
"zeitpunktBis": t3,
"geschaetzt": False
}
]


values = [] if values_count == 0 else bewegungsdaten(count=values_count, timestamp=datetime(2022,8,7,0,0,0), interval=gran)

return {
"descriptor": {
"geschaeftspartnernummer": customer_id,
Expand Down Expand Up @@ -506,7 +509,7 @@ def expect_history(requests_mock: Mocker, customer_id: str, zp: str,
@pytest.mark.usefixtures("requests_mock")
def expect_bewegungsdaten(requests_mock: Mocker, customer_id: str, zp: str, dateFrom: dt.datetime, dateTo: dt.datetime,
granularity:ValueType = ValueType.QUARTER_HOUR, anlagetype: AnlageType = AnlageType.CONSUMING,
wrong_zp: bool = False, empty_values: bool = False):
wrong_zp: bool = False, values_count=10):
if anlagetype== AnlageType.FEEDING:
if granularity == ValueType.DAY:
rolle = RoleType.DAILY_FEEDING.value
Expand All @@ -531,4 +534,4 @@ def expect_bewegungsdaten(requests_mock: Mocker, customer_id: str, zp: str, date
"Authorization": f"Bearer {ACCESS_TOKEN}",
"Accept": "application/json"
},
json=bewegungsdaten_response(customer_id, zp, granularity, anlagetype, wrong_zp, empty_values))
json=bewegungsdaten_response(customer_id, zp, granularity, anlagetype, wrong_zp, values_count))
24 changes: 13 additions & 11 deletions tests/it/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
from wnsm.api.errors import SmartmeterConnectionError, SmartmeterLoginError, SmartmeterQueryError
import wnsm.api.constants as const

COUNT = 10

logger = logging.getLogger(__name__)

@pytest.mark.usefixtures("requests_mock")
Expand Down Expand Up @@ -244,12 +246,12 @@ def test_bewegungsdaten_quarterly_hour_consuming(requests_mock: Mocker):
dateTo = dt.datetime(2023, 5, 1, 23, 59, 59, 999999)
zpn = z["zaehlpunkte"][0]['zaehlpunktnummer']
expect_login(requests_mock)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.QUARTER_HOUR)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.QUARTER_HOUR, values_count=COUNT)
expect_zaehlpunkte(requests_mock, [enabled(zaehlpunkt())])

hist = smartmeter().login().bewegungsdaten(None, dateFrom, dateTo)

assert 2 == len(hist['values'])
assert 10 == len(hist['values'])

@pytest.mark.usefixtures("requests_mock")
def test_bewegungsdaten_daily_consuming(requests_mock: Mocker):
Expand All @@ -258,12 +260,12 @@ def test_bewegungsdaten_daily_consuming(requests_mock: Mocker):
dateTo = dt.datetime(2023, 5, 1, 23, 59, 59, 999999)
zpn = z["zaehlpunkte"][0]['zaehlpunktnummer']
expect_login(requests_mock)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.DAY)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.DAY, values_count=COUNT)
expect_zaehlpunkte(requests_mock, [enabled(zaehlpunkt())])

hist = smartmeter().login().bewegungsdaten(None, dateFrom, dateTo, const.ValueType.DAY)

assert 2 == len(hist['values'])
assert 10 == len(hist['values'])

@pytest.mark.usefixtures("requests_mock")
def test_bewegungsdaten_quarterly_hour_feeding(requests_mock: Mocker):
Expand All @@ -272,12 +274,12 @@ def test_bewegungsdaten_quarterly_hour_feeding(requests_mock: Mocker):
dateTo = dt.datetime(2023, 5, 1, 23, 59, 59, 999999)
zpn = z["zaehlpunkte"][0]['zaehlpunktnummer']
expect_login(requests_mock)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.QUARTER_HOUR, const.AnlageType.FEEDING)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.QUARTER_HOUR, const.AnlageType.FEEDING, values_count=COUNT)
expect_zaehlpunkte(requests_mock, [enabled(zaehlpunkt_feeding())])

hist = smartmeter().login().bewegungsdaten(None, dateFrom, dateTo)

assert 2 == len(hist['values'])
assert 10 == len(hist['values'])

@pytest.mark.usefixtures("requests_mock")
def test_bewegungsdaten_daily_feeding(requests_mock: Mocker):
Expand All @@ -286,12 +288,12 @@ def test_bewegungsdaten_daily_feeding(requests_mock: Mocker):
dateTo = dt.datetime(2023, 5, 1, 23, 59, 59, 999999)
zpn = z["zaehlpunkte"][0]['zaehlpunktnummer']
expect_login(requests_mock)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.DAY, const.AnlageType.FEEDING)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, const.ValueType.DAY, const.AnlageType.FEEDING, values_count=COUNT)
expect_zaehlpunkte(requests_mock, [enabled(zaehlpunkt_feeding())])

hist = smartmeter().login().bewegungsdaten(None, dateFrom, dateTo, const.ValueType.DAY)

assert 2 == len(hist['values'])
assert 10 == len(hist['values'])

@pytest.mark.usefixtures("requests_mock")
def test_bewegungsdaten_no_dates_given(requests_mock: Mocker):
Expand All @@ -300,12 +302,12 @@ def test_bewegungsdaten_no_dates_given(requests_mock: Mocker):
dateFrom = dateTo - relativedelta(years=3)
zpn = z["zaehlpunkte"][0]['zaehlpunktnummer']
expect_login(requests_mock)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, values_count=COUNT)
expect_zaehlpunkte(requests_mock, [enabled(zaehlpunkt())])

hist = smartmeter().login().bewegungsdaten()

assert 2 == len(hist['values'])
assert 10 == len(hist['values'])

@pytest.mark.usefixtures("requests_mock")
def test_bewegungsdaten_wrong_zp(requests_mock: Mocker):
Expand All @@ -314,7 +316,7 @@ def test_bewegungsdaten_wrong_zp(requests_mock: Mocker):
dateTo = dt.datetime(2023, 5, 1, 23, 59, 59, 999999)
zpn = z["zaehlpunkte"][0]['zaehlpunktnummer']
expect_login(requests_mock)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, wrong_zp = True)
expect_bewegungsdaten(requests_mock, z["geschaeftspartner"], zpn, dateFrom, dateTo, wrong_zp = True, values_count=COUNT)
expect_zaehlpunkte(requests_mock, [enabled(zaehlpunkt())])
with pytest.raises(SmartmeterQueryError) as exc_info:
smartmeter().login().bewegungsdaten(None, dateFrom, dateTo)
Expand Down

0 comments on commit ef0b6ff

Please sign in to comment.