Skip to content

Commit fec0298

Browse files
committed
tests, formatting fixes
1 parent e28d541 commit fec0298

3 files changed

Lines changed: 55 additions & 25 deletions

File tree

src/api.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
import pandas as pd
1414
import requests
1515
from cachetools import TTLCache, cached
16-
from geopy.geocoders import Nominatim
1716
from geopy.distance import great_circle
17+
from geopy.geocoders import Nominatim
1818

1919
from src import helper
2020
from src.open_meteo import openmeteo_client
@@ -37,7 +37,6 @@
3737
_ocean_lock = Lock()
3838

3939

40-
4140
@lru_cache(maxsize=128)
4241
def get_coordinates(args: tuple) -> list | str:
4342
"""
@@ -186,7 +185,12 @@ def ocean_information(
186185
params = {
187186
"latitude": lat,
188187
"longitude": long,
189-
"current": ["wave_height", "wave_direction", "wave_period", "sea_surface_temperature"],
188+
"current": [
189+
"wave_height",
190+
"wave_direction",
191+
"wave_period",
192+
"sea_surface_temperature",
193+
],
190194
"length_unit": unit,
191195
"timezone": "auto",
192196
"forecast_days": 3,
@@ -207,7 +211,12 @@ def ocean_information(
207211
current_wave_period = round(current.Variables(2).Value(), decimal)
208212
current_sea_surface_temperature = current.Variables(3).Value()
209213

210-
return [current_wave_height, current_wave_direction, current_wave_period, current_sea_surface_temperature]
214+
return [
215+
current_wave_height,
216+
current_wave_direction,
217+
current_wave_period,
218+
current_sea_surface_temperature,
219+
]
211220

212221

213222
@cached(ocean_history_cache, lock=_ocean_lock)
@@ -486,26 +495,26 @@ def get_hourly_forecast(
486495

487496
return curr_hour_data
488497

498+
489499
@cached(_tide_cache, lock=_ocean_lock)
490500
def get_tide_data(lat: float, long: float):
491501
"""
492502
Fetches tide data for the given cords
493503
"""
494-
station_id, station_distance = nearest_station(lat, long)
504+
station_id, _ = nearest_station(lat, long)
495505
begin = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y%m%d")
496506

497-
498507
url = "https://api.tidesandcurrents.noaa.gov/api/prod/datagetter"
499508
params = {
500509
"station": station_id,
501510
"product": "predictions",
502511
"datum": "MLLW",
503-
"interval": "hilo", # high/low only; omit for 6-min intervals
504-
"units": "english",
512+
"interval": "hilo", # high/low only; omit for 6-min intervals
513+
"units": "english",
505514
"time_zone": "gmt",
506515
"format": "json",
507516
"begin_date": begin,
508-
"range": 72, # hours
517+
"range": 72, # hours
509518
}
510519
r = requests.get(url, params=params, timeout=10)
511520
r.raise_for_status()
@@ -514,11 +523,14 @@ def get_tide_data(lat: float, long: float):
514523

515524
@lru_cache(maxsize=1)
516525
def _get_stations():
517-
url = "https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations.json"
526+
url = (
527+
"https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations.json"
528+
)
518529
r = requests.get(url, params={"type": "tidepredictions"}, timeout=10)
519530
r.raise_for_status()
520531
return r.json()["stations"]
521532

533+
522534
def nearest_station(lat: float, long: float) -> tuple[str, float]:
523535
"""
524536
returns the id of the nearest NOAA station in respect to the given cords
@@ -635,4 +647,4 @@ def separate_args_and_get_location(args: list) -> dict:
635647

636648

637649
if __name__ == "__main__":
638-
print(get_tide_data(40.741895, -73.989308))
650+
print(get_tide_data(40.741895, -73.989308))

src/helper.py

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from src import api, art
1212
from src.gpt import get_llm_client
1313

14-
1514
logger = logging.getLogger(__name__)
1615

1716
MAX_FORECAST_DAYS = 7
@@ -245,7 +244,7 @@ def print_ocean_data(arguments_dict, ocean_data_dict):
245244
]
246245

247246
for arg_key, data_key, label in mappings:
248-
if arguments_dict[arg_key]:
247+
if arguments_dict.get(arg_key) and data_key in ocean_data_dict:
249248
print(f"{label}{ocean_data_dict[data_key]}")
250249

251250
if arguments_dict.get("show_tide") and ocean_data_dict.get("Tide"):
@@ -257,8 +256,13 @@ def print_ocean_data(arguments_dict, ocean_data_dict):
257256
arrow = f"{color}{arrow}{art.colors['end']}"
258257
extreme = tide["next_extreme"]
259258
extreme_type = "High" if extreme["type"] == "H" else "Low"
260-
extreme_time = datetime.fromisoformat(extreme["time"]).strftime("%H:%M UTC")
261-
print(f"Tide: {tide['height_ft']} ft {arrow} | Next {extreme_type}: {extreme['height']:.2f} ft @ {extreme_time}")
259+
extreme_time = datetime.fromisoformat(extreme["time"]).strftime(
260+
"%H:%M UTC"
261+
)
262+
print(
263+
f"Tide: {tide['height_ft']} ft {arrow} | "
264+
f"Next {extreme_type}: {extreme['height']:.2f} ft @ {extreme_time}"
265+
)
262266

263267

264268
def print_forecast(ocean, forecast):
@@ -411,15 +415,21 @@ def get_gpt_response(surf_data):
411415
tide = surf_data["Tide"]
412416
extreme = tide["next_extreme"]
413417
extreme_type = "high" if extreme["type"] == "H" else "low"
414-
extreme_time = datetime.fromisoformat(extreme["time"]).strftime("%H:%M UTC")
418+
extreme_time = datetime.fromisoformat(extreme["time"]).strftime(
419+
"%H:%M UTC"
420+
)
415421
tide_desc = (
416-
f" The tide is currently {tide['direction']} at {tide['height_ft']} ft,"
417-
f" with the next {extreme_type} tide of {extreme['height']:.2f} ft at {extreme_time}."
422+
f" The tide is currently {tide['direction']} at"
423+
f" {tide['height_ft']} ft, with the next {extreme_type} tide"
424+
f" of {extreme['height']:.2f} ft at {extreme_time}."
418425
)
419426

420427
sea_temp_desc = ""
421428
if surf_data.get("Sea Surface Temperature") is not None:
422-
sea_temp_desc = f" The sea surface temperature is {surf_data['Sea Surface Temperature']} {unit_label}."
429+
sea_temp_desc = (
430+
f" The sea surface temperature is"
431+
f" {surf_data['Sea Surface Temperature']} {unit_label}."
432+
)
423433

424434
summary = (
425435
f"Today at {surf_data['Location']}, the surf height is "
@@ -434,19 +444,22 @@ def get_gpt_response(surf_data):
434444
logger.error("LLM request failed: %s", e)
435445
return "Unable to generate GPT response."
436446

447+
437448
def current_tide(lat: float, long: float) -> dict:
438449
predictions = api.get_tide_data(lat, long)["predictions"]
439450

440451
parsed = [
441452
{
442-
"time": datetime.strptime(p["t"], "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc),
453+
"time": datetime.strptime(p["t"], "%Y-%m-%d %H:%M").replace(
454+
tzinfo=timezone.utc
455+
),
443456
"height": float(p["v"]),
444457
"type": p["type"],
445458
}
446459
for p in predictions
447460
]
448461

449-
now = datetime.now(timezone.utc) # ← tz-aware UTC
462+
now = datetime.now(timezone.utc) # ← tz-aware UTC
450463

451464
prev = next_ = None
452465
for a, b in zip(parsed, parsed[1:]):
@@ -460,7 +473,8 @@ def current_tide(lat: float, long: float) -> dict:
460473
span = (next_["time"] - prev["time"]).total_seconds()
461474
elapsed = (now - prev["time"]).total_seconds()
462475
x = elapsed / span
463-
height = prev["height"] + (next_["height"] - prev["height"]) * (1 - cos(pi * x)) / 2
476+
delta = next_["height"] - prev["height"]
477+
height = prev["height"] + delta * (1 - cos(pi * x)) / 2
464478

465479
direction = "incoming" if next_["type"] == "H" else "outgoing"
466480

@@ -475,6 +489,5 @@ def current_tide(lat: float, long: float) -> dict:
475489
}
476490

477491

478-
479492
if __name__ == "__main__":
480-
print(current_tide(32.856132, -117.2175761))
493+
print(current_tide(32.856132, -117.2175761))

tests/test_api.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,12 @@ def test_ocean_information(mock_create_client):
126126
mock_var_3.Value.return_value = 20.0
127127

128128
mock_current = MagicMock()
129-
mock_current.Variables.side_effect = [mock_var_0, mock_var_1, mock_var_2, mock_var_3]
129+
mock_current.Variables.side_effect = [
130+
mock_var_0,
131+
mock_var_1,
132+
mock_var_2,
133+
mock_var_3,
134+
]
130135

131136
mock_response = MagicMock()
132137
mock_response.Current.return_value = mock_current

0 commit comments

Comments
 (0)