132 lines
6.3 KiB
Python
132 lines
6.3 KiB
Python
import http.client
|
|
import json
|
|
import threading
|
|
import unittest
|
|
from datetime import datetime, timedelta, timezone
|
|
from http.client import IncompleteRead
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from app.belki.weather import FALLBACK, WeatherCache, parse_metar
|
|
from app.main import BelkiHTTPServer, Handler
|
|
|
|
|
|
class MetarTests(unittest.TestCase):
|
|
def test_weather_and_intensity(self):
|
|
cases = {
|
|
"CAVOK": ("leaves", 1), "-RA": ("rain", 1), "RA": ("rain", 2),
|
|
"+RA": ("rain", 3), "SHRA": ("rain", 3), "-SHRA": ("rain", 1),
|
|
"-DZ": ("rain", 1), "FZRA": ("rain", 2), "SN": ("snow", 2),
|
|
"+SHSN": ("snow", 3), "BLSN": ("snow", 3), "-SHSN": ("snow", 1),
|
|
"RASN": ("mixed", 2), "-RA SN": ("mixed", 2), "BR FG": ("leaves", 1),
|
|
"VCSH VCSN VCRA": ("leaves", 1),
|
|
"CAVOK TEMPO +SHSN": ("leaves", 1),
|
|
"-RA BECMG +SN": ("rain", 1),
|
|
"CAVOK RMK SN RA": ("leaves", 1),
|
|
}
|
|
for weather, expected in cases.items():
|
|
with self.subTest(weather=weather):
|
|
result = parse_metar(f"METAR ULLI 181630Z 34003MPS {weather}")
|
|
self.assertEqual((result["mode"], result["intensity"]), expected)
|
|
|
|
def test_wind_units_gusts_and_calm(self):
|
|
for token, expected in [("34003MPS", 3), ("VRB05G15MPS", 15), ("27010G20KT", 10.29),
|
|
("12036KMH", 10), ("00000KT", 0), ("/////KT", 0), ("270199KT", 60)]:
|
|
with self.subTest(token=token):
|
|
self.assertAlmostEqual(parse_metar(f"ULLI {token} CAVOK TEMPO 27050MPS")["wind_mps"], expected, places=2)
|
|
|
|
|
|
class WeatherCacheTests(unittest.TestCase):
|
|
def payload(self, age=0):
|
|
return {"found": True, "item": {"station_id": "ULLI", "raw_metar": "METAR ULLI 181630Z 27010G15MPS +SHSN",
|
|
"observation_time": (datetime.now(timezone.utc) - timedelta(seconds=age)).isoformat()}}
|
|
|
|
def opener(self, payload):
|
|
response = MagicMock()
|
|
response.__enter__.return_value.read.return_value = json.dumps(payload).encode()
|
|
return response
|
|
|
|
def test_caches_result_and_bounds_upstream_request(self):
|
|
cache = WeatherCache()
|
|
with patch("app.belki.weather.urlopen", return_value=self.opener(self.payload())) as opened:
|
|
first = cache.get()
|
|
self.assertEqual(first, {"mode": "snow", "intensity": 3, "wind_mps": 15})
|
|
first["mode"] = "rain"
|
|
self.assertEqual(cache.get()["mode"], "snow")
|
|
opened.assert_called_once()
|
|
self.assertEqual(opened.call_args.kwargs["timeout"], 3)
|
|
self.assertEqual(opened.return_value.__enter__.return_value.read.call_args.args, (65_537,))
|
|
|
|
def test_invalid_stale_future_and_absent_reports_fall_back(self):
|
|
invalid = [self.payload(7201), self.payload(-601), {"found": False, "item": None}, [],
|
|
{"found": True, "item": {"station_id": "UUDD"}}]
|
|
for payload in invalid:
|
|
with self.subTest(payload=payload), patch("app.belki.weather.urlopen", return_value=self.opener(payload)) as opened:
|
|
cache = WeatherCache()
|
|
self.assertEqual(cache.get(), FALLBACK)
|
|
self.assertEqual(cache.get(), FALLBACK)
|
|
opened.assert_called_once()
|
|
|
|
def test_network_error_resets_previous_weather_and_is_cached(self):
|
|
cache = WeatherCache()
|
|
with patch("app.belki.weather.urlopen", return_value=self.opener(self.payload())):
|
|
self.assertEqual(cache.get()["mode"], "snow")
|
|
cache._expires = 0
|
|
with patch("app.belki.weather.urlopen", side_effect=TimeoutError) as opened:
|
|
self.assertEqual(cache.get(), FALLBACK)
|
|
self.assertEqual(cache.get(), FALLBACK)
|
|
opened.assert_called_once()
|
|
|
|
def test_concurrent_cold_reader_does_not_wait(self):
|
|
cache = WeatherCache()
|
|
cache._lock.acquire()
|
|
try:
|
|
with patch("app.belki.weather.urlopen") as opened:
|
|
self.assertEqual(cache.get(), FALLBACK)
|
|
opened.assert_not_called()
|
|
finally:
|
|
cache._lock.release()
|
|
|
|
|
|
def test_bounded_malformed_and_interrupted_responses_fall_back(self):
|
|
for body in (b"x" * 65_537, b"not json", b"null"):
|
|
response = MagicMock()
|
|
response.__enter__.return_value.read.return_value = body
|
|
with self.subTest(size=len(body)), patch("app.belki.weather.urlopen", return_value=response):
|
|
self.assertEqual(WeatherCache().get(), FALLBACK)
|
|
with patch("app.belki.weather.urlopen", side_effect=IncompleteRead(b"partial")):
|
|
self.assertEqual(WeatherCache().get(), FALLBACK)
|
|
|
|
def test_success_and_failure_refresh_intervals(self):
|
|
cache = WeatherCache()
|
|
with patch("app.belki.weather.time.monotonic", return_value=100), patch("app.belki.weather.urlopen", return_value=self.opener(self.payload())):
|
|
cache.get()
|
|
self.assertEqual(cache._expires, 400)
|
|
with patch("app.belki.weather.time.monotonic", return_value=401), patch("app.belki.weather.urlopen", side_effect=TimeoutError):
|
|
self.assertEqual(cache.get(), FALLBACK)
|
|
self.assertEqual(cache._expires, 461)
|
|
|
|
|
|
class WeatherHttpTests(unittest.TestCase):
|
|
def test_public_weather_and_shared_assets(self):
|
|
server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
thread.start()
|
|
connection = http.client.HTTPConnection(*server.server_address, timeout=5)
|
|
try:
|
|
with patch("app.main.weather_cache.get", return_value=FALLBACK):
|
|
connection.request("GET", "/api/weather/ulli")
|
|
response = connection.getresponse()
|
|
self.assertEqual(response.status, 200)
|
|
self.assertEqual(json.loads(response.read()), FALLBACK)
|
|
for path, mime in [("effect.js", "javascript"), ("effect.css", "text/css")]:
|
|
connection.request("GET", f"/api/weather/{path}")
|
|
response = connection.getresponse()
|
|
self.assertEqual(response.status, 200)
|
|
self.assertIn(mime, response.getheader("Content-Type"))
|
|
self.assertTrue(response.read())
|
|
finally:
|
|
connection.close()
|
|
server.shutdown()
|
|
server.server_close()
|
|
thread.join()
|