Skip to content

Commit

Permalink
Add tests for BelAQI and fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
jdejaegh committed Jun 23, 2024
1 parent 95fa6dd commit ee5304e
Show file tree
Hide file tree
Showing 7 changed files with 407 additions and 21 deletions.
2 changes: 0 additions & 2 deletions src/open_irceline/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ async def _api_wrapper(self, url: str, querystring: dict = None, headers: dict =
:param querystring: dict to build the query string
:return: response from the client
"""

if headers is None:
headers = dict()
if 'User-Agent' not in headers:
Expand Down Expand Up @@ -228,7 +227,6 @@ async def get_data(self,
except IrcelineApiError:
# retry for the day before
yesterday = timestamp - timedelta(days=1)
print('here')
url = f"{forecast_base_url}/BE_{feature}_{yesterday.strftime('%Y%m%d')}_d{d}.csv"
try:
r: ClientResponse = await self._api_cached_wrapper(url)
Expand Down
38 changes: 27 additions & 11 deletions src/open_irceline/belaqi.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ def belaqi_index(pm10: float, pm25: float, o3: float, no2: float) -> BelAqiIndex
:param no2: NO2 max 1-hourly mean per day (or latest hourly mean for real-time) (µg/m³)
:return: BelAQI index from 1 to 10 (Value of BelAqiIndex enum)
"""
if pm10 is None or pm25 is None or o3 is None or no2 is None:
raise ValueError("All the components should be valued (at lest one is None here)")

if pm10 < 0 or pm25 < 0 or o3 < 0 or no2 < 0:
raise ValueError("All the components should have a positive value")
Expand Down Expand Up @@ -62,6 +64,7 @@ async def belaqi_index_actual(rio_client: IrcelineRioClient, position: Tuple[flo
timestamp: datetime | None = None) -> BelAqiIndex:
"""
Get current BelAQI index value for the given position using the rio_client
Raise ValueError if one or more components are not available
:param rio_client: client for the RIO WFS service
:param position: position for which to get the data
:param timestamp: desired time for the data (now if None)
Expand All @@ -71,21 +74,27 @@ async def belaqi_index_actual(rio_client: IrcelineRioClient, position: Tuple[flo
timestamp = datetime.utcnow()
components = await rio_client.get_data(
timestamp=timestamp,
features=[RioFeature.PM10_24HMEAN, RioFeature.PM25_24HMEAN, RioFeature.O3_HMEAN, RioFeature.NO2_HMEAN],
features=[RioFeature.PM10_24HMEAN,
RioFeature.PM25_24HMEAN,
RioFeature.O3_HMEAN,
RioFeature.NO2_HMEAN],
position=position
)

return belaqi_index(components[RioFeature.PM10_24HMEAN].get('value', -1),
components[RioFeature.PM25_24HMEAN].get('value', -1),
components[RioFeature.O3_HMEAN].get('value', -1),
components[RioFeature.NO2_HMEAN].get('value', -1))
return belaqi_index(
components.get(RioFeature.PM10_24HMEAN, {}).get('value', -1),
components.get(RioFeature.PM25_24HMEAN, {}).get('value', -1),
components.get(RioFeature.O3_HMEAN, {}).get('value', -1),
components.get(RioFeature.NO2_HMEAN, {}).get('value', -1)
)


async def belaqi_index_forecast(forecast_client: IrcelineForecastClient, position: Tuple[float, float],
timestamp: date | None = None) -> Dict[date, BelAqiIndex]:
timestamp: date | None = None) -> Dict[date, BelAqiIndex | None]:
"""
Get forecasted BelAQI index value for the given position using the forecast_client.
Data is downloaded for the given day and the four next days
Value is None for the date if one or more components cannot be downloaded
:param forecast_client: client for the forecast data
:param position: position for which to get the data
:param timestamp: day at which the forecast are issued
Expand All @@ -95,17 +104,24 @@ async def belaqi_index_forecast(forecast_client: IrcelineForecastClient, positio
timestamp = date.today()
components = await forecast_client.get_data(
timestamp=timestamp,
features=[ForecastFeature.PM10_DMEAN, ForecastFeature.PM25_DMEAN, ForecastFeature.O3_MAXHMEAN,
features=[ForecastFeature.PM10_DMEAN,
ForecastFeature.PM25_DMEAN,
ForecastFeature.O3_MAXHMEAN,
ForecastFeature.NO2_MAXHMEAN],
position=position
)

result = dict()

for _, day in components.keys():
result[day] = belaqi_index(components[(ForecastFeature.PM10_DMEAN, day)].get('value', -1),
components[(ForecastFeature.PM25_DMEAN, day)].get('value', -1),
components[(ForecastFeature.O3_MAXHMEAN, day)].get('value', -1),
components[(ForecastFeature.NO2_MAXHMEAN, day)].get('value', -1))
try:
result[day] = belaqi_index(
components.get((ForecastFeature.PM10_DMEAN, day), {}).get('value', -1),
components.get((ForecastFeature.PM25_DMEAN, day), {}).get('value', -1),
components.get((ForecastFeature.O3_MAXHMEAN, day), {}).get('value', -1),
components.get((ForecastFeature.NO2_MAXHMEAN, day), {}).get('value', -1)
)
except ValueError:
result[day] = None

return result
2 changes: 1 addition & 1 deletion src/open_irceline/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __setitem__(self, key, value):
super().__setitem__(key, value)
self.move_to_end(key)
if len(self) > self._size:
print('drop', self.popitem(False)[0])
self.popitem(False)

def __getitem__(self, key):
self.move_to_end(key)
Expand Down
3 changes: 1 addition & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@
import aiohttp



def get_api_data(fixture: str, plain=False) -> str | dict:
with open(f'tests/fixtures/{fixture}', 'r') as file:
if plain:
return file.read()
return json.load(file)


def get_mock_session_json(json_file=None, text_file=None):
def get_mock_session(json_file=None, text_file=None):
# Create the mock response
mock_response = Mock()
if json_file is not None:
Expand Down
Loading

0 comments on commit ee5304e

Please sign in to comment.