services/weather.py asks Open-Meteo for 7 days, the next 24 hours and the details (mph for Fahrenheit); older answers without them still read. The widget's layout, the details it adds and the place's name; up to 7 days. Plan 6R.18, F-116. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
158 lines
9.8 KiB
Python
158 lines
9.8 KiB
Python
"""Signage widgets (plan step 5.4c): logo, name, date, clock, message of the day, QR code and
|
|
weather on menu and text slides; the message changes on every screen at once; the weather comes
|
|
from the internet and is simply hidden (null) when it can't be fetched."""
|
|
import asyncio
|
|
import time
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
|
from tests.test_media import jpeg, media_dir, mp4, up # noqa: F401 (fixture + helpers)
|
|
from tests.test_signage import playlist, slide
|
|
|
|
FORECAST = {"current": {"time": "2026-11-17T12:00", "temperature_2m": 17.4, "weather_code": 2, "is_day": 1},
|
|
"daily": {"time": ["2026-11-17", "2026-11-18"], "temperature_2m_max": [19.0, 16.5],
|
|
"temperature_2m_min": [9.1, 8.0], "weather_code": [2, 61]}}
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _fresh_weather():
|
|
from services import weather
|
|
weather.reset()
|
|
yield
|
|
weather.reset()
|
|
|
|
|
|
@pytest.fixture
|
|
def sent(monkeypatch):
|
|
import routers.signage as sg
|
|
got = []
|
|
monkeypatch.setattr(sg, "broadcast_sync", lambda kind, data, **kw: got.append((kind, kw.get("device_ids"))))
|
|
return got
|
|
|
|
|
|
@pytest.fixture
|
|
def tv(client, owner_h, pair):
|
|
token, r = pair("signage", "TV")
|
|
p = playlist(client, owner_h, "Window")
|
|
client.put(f"/api/signage/screens/{r.json()['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
|
return {"h": {"X-Xenia-Device": token}, "id": r.json()["id"], "playlist": p["id"]}
|
|
|
|
|
|
@pytest.fixture
|
|
def internet(monkeypatch):
|
|
"""Open-Meteo answered by a fake: `internet["up"] = False` cuts the line."""
|
|
from services import weather
|
|
state = {"up": True, "calls": []}
|
|
|
|
def handler(request):
|
|
state["calls"].append(str(request.url))
|
|
if not state["up"]:
|
|
raise httpx.ConnectError("no internet")
|
|
if "geocoding" in str(request.url):
|
|
return httpx.Response(200, json={"results": [{"name": "Kalavryta", "country": "Greece", "admin1": "West Greece",
|
|
"latitude": 38.03, "longitude": 22.11}]})
|
|
return httpx.Response(200, json=FORECAST)
|
|
real = httpx.AsyncClient
|
|
monkeypatch.setattr(weather.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
|
|
return state
|
|
|
|
|
|
def test_widgets_on_slides(client, owner_h, tv, monkeypatch):
|
|
from services import cloud_sync
|
|
monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com")
|
|
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
|
|
logo, video = up(client, owner_h, jpeg(400, 200)).json(), up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json()
|
|
widgets = [{"kind": "logo", "position": "top-left", "media_id": logo["id"]}, {"kind": "clock", "position": "top-right", "clock_seconds": True},
|
|
{"kind": "date", "position": "bottom-left"}, {"kind": "message", "position": "bottom-bar"},
|
|
{"kind": "qr", "position": "bottom-right", "qr_caption": "Order online"}, {"kind": "weather", "weather_days": 3}]
|
|
s = slide(client, owner_h, tv["playlist"], "text", content={"title": "Welcome", "widgets": widgets})
|
|
got = next(x for x in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"] if x["id"] == s["id"])
|
|
ws = got["content"]["widgets"]
|
|
assert [w["kind"] for w in ws] == ["logo", "clock", "date", "message", "qr", "weather"]
|
|
assert ws[4]["link"] == "https://menu.example.com/order/taverna-1"
|
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["media"][str(logo["id"])]["kind"] == "image"
|
|
slide(client, owner_h, tv["playlist"], "menu", content={"select": "all", "widgets": [{"kind": "name", "position": "top-bar", "size": "large"}]})
|
|
url = f"/api/signage/playlists/{tv['playlist']}/slides"
|
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "logo", "media_id": video["id"]}]}})) == "media.not_a_picture"
|
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "logo", "position": "middle"}]}})) == "signage.content_invalid"
|
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "disco"}]}})) == "signage.content_invalid"
|
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "qr", "qr_target": "custom", "qr_url": "ftp://x"}]}})) == "signage.content_invalid"
|
|
# a logo in a widget is protected in the library
|
|
assert client.delete(f"/api/media/{logo['id']}", headers=owner_h).status_code == 409
|
|
|
|
|
|
def test_the_message_of_the_day_reaches_every_screen(client, owner_h, tv, pair, sent):
|
|
_, other = pair("signage", "TV 2")
|
|
r = client.put("/api/signage/message", headers=owner_h, json={"text": " Today: fresh fish! "})
|
|
assert r.json() == {"text": "Today: fresh fish!"}
|
|
assert sent == [("signage.changed", sorted([tv["id"], other.json()["id"]]))]
|
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["message"] == "Today: fresh fish!"
|
|
client.put("/api/signage/message", headers=owner_h, json={"text": ""})
|
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["message"] is None
|
|
assert client.get("/api/signage/message", headers=owner_h).json() == {"text": None}
|
|
|
|
|
|
def test_the_weather_shows_with_internet_and_hides_without(client, owner_h, tv, internet, sent, db):
|
|
from services import weather
|
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"] is None # no place yet
|
|
places = client.get("/api/signage/weather/places?q=Kalav", headers=owner_h).json()
|
|
assert places[0]["name"] == "Kalavryta" and places[0]["latitude"] == 38.03
|
|
r = client.put("/api/signage/weather/place", headers=owner_h, json={"name": "Kalavryta", "latitude": 38.03, "longitude": 22.11})
|
|
assert r.status_code == 200 and r.json()["weather"]["temperature"] == 17.4 and r.json()["error"] is None
|
|
assert ("signage.changed", [tv["id"]]) in sent
|
|
w = client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"]
|
|
assert w["place"] == "Kalavryta" and w["code"] == 2 and [d["max"] for d in w["days"]] == [19.0, 16.5] and w["units"] == "celsius"
|
|
# 6R.18: an answer without the detailed fields still reads (they are None)
|
|
assert w["feels_like"] is None and w["days"][0]["sunrise"] is None and w["hours"] == [] and w["wind_unit"] == "km/h"
|
|
# the internet goes: the last forecast stays while it is fresh, then the widget hides
|
|
internet["up"] = False
|
|
sent.clear()
|
|
assert asyncio.run(weather.refresh(db)) is False
|
|
assert client.get("/api/signage/weather", headers=owner_h).json()["error"] == "ConnectError"
|
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"] is not None
|
|
assert weather.current(db, now=time.time() + weather.STALE_S + 1) is None
|
|
assert err(client.get("/api/signage/weather/places?q=Patra", headers=owner_h)) == "signage.weather_offline"
|
|
# forgetting the place hides it at once
|
|
internet["up"] = True
|
|
client.delete("/api/signage/weather/place", headers=owner_h)
|
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"] is None
|
|
|
|
|
|
def test_fahrenheit_and_a_new_place(client, owner_h, internet):
|
|
client.put("/api/signage/weather/place", headers=owner_h, json={"name": "Patra", "latitude": 38.24, "longitude": 21.73, "units": "fahrenheit"})
|
|
assert "temperature_unit=fahrenheit" in internet["calls"][-1]
|
|
assert client.put("/api/signage/weather/place", headers=owner_h, json={"name": "X", "latitude": 99, "longitude": 0}).status_code == 422
|
|
|
|
|
|
def test_who_may(client, make_user, login):
|
|
waiter = login(make_user(role="waiter"))
|
|
assert client.put("/api/signage/message", headers=waiter, json={"text": "x"}).status_code == 403
|
|
assert client.get("/api/signage/weather", headers=waiter).status_code == 403
|
|
|
|
|
|
def test_the_detailed_weather(monkeypatch):
|
|
"""6R.18: humidity, feels like, wind, rain chance, sunrise / sunset, UV and the next 24 hours."""
|
|
import asyncio
|
|
import httpx
|
|
from services import weather
|
|
hours = [f"2026-11-17T{h:02d}:00" for h in range(24)] + [f"2026-11-18T{h:02d}:00" for h in range(24)]
|
|
answer = {"current": {"time": "2026-11-17T12:15", "temperature_2m": 17.4, "weather_code": 2, "is_day": 1, "apparent_temperature": 15.9,
|
|
"relative_humidity_2m": 62, "wind_speed_10m": 12.3, "wind_direction_10m": 200, "precipitation": 0},
|
|
"daily": {"time": ["2026-11-17", "2026-11-18"], "temperature_2m_max": [19.0, 16.5], "temperature_2m_min": [9.1, 8.0],
|
|
"weather_code": [2, 61], "precipitation_probability_max": [10, 80], "wind_speed_10m_max": [20, 35], "uv_index_max": [3.2, 1.0],
|
|
"sunrise": ["2026-11-17T07:12", "2026-11-18T07:13"], "sunset": ["2026-11-17T17:08", "2026-11-18T17:07"]},
|
|
"hourly": {"time": hours, "temperature_2m": list(range(48)), "weather_code": [0] * 48, "precipitation_probability": [5] * 48, "is_day": [1] * 48}}
|
|
seen = {}
|
|
|
|
def handler(req):
|
|
seen.update(dict(req.url.params))
|
|
return httpx.Response(200, json=answer)
|
|
c = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
|
w = asyncio.run(weather.fetch({"name": "X", "latitude": 1, "longitude": 2, "units": "fahrenheit"}, c))
|
|
assert seen["forecast_days"] == "7" and seen["wind_speed_unit"] == "mph" and "hourly" in seen
|
|
assert w["feels_like"] == 15.9 and w["humidity"] == 62 and w["wind"] == 12.3 and w["wind_unit"] == "mph"
|
|
assert w["days"][1] == {"date": "2026-11-18", "max": 16.5, "min": 8.0, "code": 61, "rain": 80, "wind": 35, "uv": 1.0, "sunrise": "07:13", "sunset": "17:07"}
|
|
assert len(w["hours"]) == 24 and w["hours"][0]["time"] == "12:00" and w["hours"][0]["temp"] == 12 and w["hours"][-1]["time"] == "11:00"
|