feat: tik op het regenblok voor de Buienradar-animatie
Het regenblok linksonder opent een overlay met de geanimeerde regenradar van Buienradar (550x512, tijd in het beeld), naast de regencijfers die we al hebben: vandaag, de 3 vorige dagen en het maandtotaal. Sluit na 20 seconden of bij een tik, net als het uuroverzicht. Het beeld loopt via onze eigen /api/radar.php in plaats van een <img> rechtstreeks naar Buienradar: de spec wil alles lokaal geserveerd, de iPad praat zo nooit met een derde partij, we cachen 4 minuten (de radar ververst elke 5) en de servicewerker kan het laatste beeld offline bewaren. Bij een storing komt het laatst opgehaalde beeld terug; pas als er niets is, een nette melding in plaats van een leeg vlak. Bronvermelding staat in de overlay, zoals Buienradar vraagt. Verder: de overlay-machinerie (20s-timer, balk, sluiten) staat nu een keer in plaats van per overlay, Http kan optioneel redirects volgen (de beeld-API leidt door naar een CDN), en alle /api/-paden zijn in de servicewerker network-first met een cachesleutel zonder querystring. Servicewerker naar v7. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Weerscherm\Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Weerscherm\BuienradarClient;
|
||||
use Weerscherm\UpstreamException;
|
||||
|
||||
final class BuienradarClientTest extends TestCase
|
||||
{
|
||||
private const GIF = "GIF89a\x01\x00\x01\x00fake-animatie";
|
||||
|
||||
public function testFetchesTheAnimatedRadarImage(): void
|
||||
{
|
||||
$http = (new FakeHttp())->queue(200, self::GIF);
|
||||
|
||||
$bytes = (new BuienradarClient($http))->rainRadar();
|
||||
|
||||
self::assertSame(self::GIF, $bytes);
|
||||
self::assertSame('https://image.buienradar.nl/2.0/image/animation/RadarmapRainNL', $http->requests[0]['url']);
|
||||
self::assertSame(['w' => 550, 'h' => 512], $http->requests[0]['params']);
|
||||
}
|
||||
|
||||
public function testErrorStatusIsUpstreamException(): void
|
||||
{
|
||||
$http = (new FakeHttp())->queue(503, '');
|
||||
|
||||
$this->expectException(UpstreamException::class);
|
||||
$this->expectExceptionMessage('HTTP 503');
|
||||
(new BuienradarClient($http))->rainRadar();
|
||||
}
|
||||
|
||||
public function testNonGifResponseIsUpstreamException(): void
|
||||
{
|
||||
// Bijvoorbeeld een foutpagina of een redirect die als HTML binnenkomt.
|
||||
$http = (new FakeHttp())->queue(200, '<!doctype html><title>Oeps</title>');
|
||||
|
||||
$this->expectException(UpstreamException::class);
|
||||
$this->expectExceptionMessage('geen GIF');
|
||||
(new BuienradarClient($http))->rainRadar();
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ final class ConfigTest extends TestCase
|
||||
|
||||
self::assertSame('Europe/Berlin', $config->get('timezone'));
|
||||
self::assertSame('fixture', $config->get('data_source'));
|
||||
self::assertSame(['stations' => 300, 'measure' => 900, 'pressure' => 900, 'forecast' => 3600], $config->get('cache_ttl'));
|
||||
self::assertSame(['stations' => 300, 'measure' => 900, 'pressure' => 900, 'forecast' => 3600, 'radar' => 240], $config->get('cache_ttl'));
|
||||
self::assertSame([], $config->get('indoor_modules'));
|
||||
self::assertNull($config->get('netatmo_device_id'));
|
||||
}
|
||||
@@ -39,7 +39,7 @@ final class ConfigTest extends TestCase
|
||||
$config = Config::load($this->file);
|
||||
|
||||
self::assertSame('Europe/Amsterdam', $config->get('timezone'));
|
||||
self::assertSame(['stations' => 60, 'measure' => 900, 'pressure' => 900, 'forecast' => 3600], $config->get('cache_ttl'));
|
||||
self::assertSame(['stations' => 60, 'measure' => 900, 'pressure' => 900, 'forecast' => 3600, 'radar' => 240], $config->get('cache_ttl'));
|
||||
}
|
||||
|
||||
public function testUnknownKeyReturnsGivenDefault(): void
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Weerscherm\Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Weerscherm\BuienradarClient;
|
||||
use Weerscherm\RadarService;
|
||||
use Weerscherm\UpstreamException;
|
||||
|
||||
final class RadarServiceTest extends TestCase
|
||||
{
|
||||
private const NOW = 1_800_000_000;
|
||||
private const GIF = "GIF89a\x01\x00\x01\x00vers";
|
||||
private const OLD_GIF = "GIF89a\x01\x00\x01\x00oud";
|
||||
|
||||
private string $dir;
|
||||
private string $file;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->dir = sys_get_temp_dir() . '/weerscherm-radar-' . uniqid();
|
||||
$this->file = $this->dir . '/radar.gif';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
array_map('unlink', glob($this->dir . '/*') ?: []);
|
||||
@rmdir($this->dir);
|
||||
}
|
||||
|
||||
private function service(FakeHttp $http, int $ttl = 240): RadarService
|
||||
{
|
||||
return new RadarService(
|
||||
new BuienradarClient($http),
|
||||
$this->file,
|
||||
$ttl,
|
||||
static fn(): int => self::NOW,
|
||||
);
|
||||
}
|
||||
|
||||
/** Legt een cachebestand neer met een gegeven leeftijd in seconden. */
|
||||
private function seedCache(string $bytes, int $ageSeconds): void
|
||||
{
|
||||
mkdir($this->dir, 0700, true);
|
||||
file_put_contents($this->file, $bytes);
|
||||
touch($this->file, self::NOW - $ageSeconds);
|
||||
}
|
||||
|
||||
public function testFetchesAndCachesWhenNothingIsStored(): void
|
||||
{
|
||||
$http = (new FakeHttp())->queue(200, self::GIF);
|
||||
|
||||
$result = $this->service($http)->image();
|
||||
|
||||
self::assertSame(['bytes' => self::GIF, 'stale' => false, 'age' => 0], $result);
|
||||
self::assertStringEqualsFile($this->file, self::GIF);
|
||||
self::assertSame([], glob($this->dir . '/*.tmp.*') ?: [], 'geen tijdelijke bestanden achtergelaten');
|
||||
}
|
||||
|
||||
public function testFreshCacheIsServedWithoutFetching(): void
|
||||
{
|
||||
$this->seedCache(self::OLD_GIF, 100);
|
||||
$http = new FakeHttp(); // geen response gepland: een fetch zou de test laten falen
|
||||
|
||||
$result = $this->service($http)->image();
|
||||
|
||||
self::assertSame(self::OLD_GIF, $result['bytes']);
|
||||
self::assertFalse($result['stale']);
|
||||
self::assertSame(100, $result['age']);
|
||||
self::assertSame([], $http->requests);
|
||||
}
|
||||
|
||||
public function testExpiredCacheIsRefetched(): void
|
||||
{
|
||||
$this->seedCache(self::OLD_GIF, 300);
|
||||
$http = (new FakeHttp())->queue(200, self::GIF);
|
||||
|
||||
$result = $this->service($http)->image();
|
||||
|
||||
self::assertSame(self::GIF, $result['bytes']);
|
||||
self::assertFalse($result['stale']);
|
||||
self::assertCount(1, $http->requests);
|
||||
self::assertStringEqualsFile($this->file, self::GIF);
|
||||
}
|
||||
|
||||
public function testUpstreamFailureFallsBackToTheCachedImageMarkedStale(): void
|
||||
{
|
||||
$this->seedCache(self::OLD_GIF, 3600);
|
||||
$http = (new FakeHttp())->queue(500, '');
|
||||
|
||||
$result = $this->service($http)->image();
|
||||
|
||||
self::assertSame(self::OLD_GIF, $result['bytes'], 'ongeacht de leeftijd: liever een oud beeld dan niets');
|
||||
self::assertTrue($result['stale']);
|
||||
self::assertSame(3600, $result['age']);
|
||||
}
|
||||
|
||||
public function testUpstreamFailureWithoutCacheThrows(): void
|
||||
{
|
||||
$http = (new FakeHttp())->queue(500, '');
|
||||
|
||||
$this->expectException(UpstreamException::class);
|
||||
$this->service($http)->image();
|
||||
}
|
||||
|
||||
public function testEmptyCacheFileIsIgnored(): void
|
||||
{
|
||||
$this->seedCache('', 10);
|
||||
$http = (new FakeHttp())->queue(200, self::GIF);
|
||||
|
||||
$result = $this->service($http)->image();
|
||||
|
||||
self::assertSame(self::GIF, $result['bytes']);
|
||||
self::assertCount(1, $http->requests, 'een leeg cachebestand telt niet als geldige cache');
|
||||
}
|
||||
}
|
||||
+41
-1
@@ -9,7 +9,8 @@ function loadServiceWorker({ fetchImpl }) {
|
||||
const store = new Map();
|
||||
const cache = {
|
||||
async addAll(urls) { urls.forEach((u) => store.set(new URL(u, 'http://x/').href, new Response('shell'))); },
|
||||
async put(req, res) { store.set(req.url, res); },
|
||||
// De echte Cache API accepteert zowel een Request als een URL-string als sleutel.
|
||||
async put(req, res) { store.set(typeof req === 'string' ? req : req.url, res); },
|
||||
async match(req) { return store.get(typeof req === 'string' ? req : req.url) || undefined; },
|
||||
async keys() { return [...store.keys()].map((u) => new Request(u)); },
|
||||
};
|
||||
@@ -96,3 +97,42 @@ test('cross-origin and non-GET requests are left alone', () => {
|
||||
listeners.fetch({ request: new Request('http://x/api/data.php', { method: 'POST' }), respondWith: () => { handled = true; } });
|
||||
assert.equal(handled, false);
|
||||
});
|
||||
|
||||
test('the radar image is network-first and cached under a key without querystring', async () => {
|
||||
const { listeners, store } = loadServiceWorker({
|
||||
fetchImpl: async () => new Response('GIF89a', { status: 200, headers: { 'Content-Type': 'image/gif' } }),
|
||||
});
|
||||
|
||||
const res = await dispatchFetch(listeners, 'http://x/api/radar.php?t=123');
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.ok(store.has('http://x/api/radar.php'), 'sleutel zonder ?t=, anders loopt de cache vol met varianten');
|
||||
assert.equal(store.has('http://x/api/radar.php?t=123'), false);
|
||||
});
|
||||
|
||||
test('an offline radar request falls back to the cached image, even with a different querystring', async () => {
|
||||
let online = true;
|
||||
const { listeners } = loadServiceWorker({
|
||||
fetchImpl: async () => {
|
||||
if (!online) throw new TypeError('Failed to fetch');
|
||||
return new Response('GIF89a', { status: 200, headers: { 'Content-Type': 'image/gif' } });
|
||||
},
|
||||
});
|
||||
|
||||
await dispatchFetch(listeners, 'http://x/api/radar.php?t=1');
|
||||
online = false;
|
||||
const res = await dispatchFetch(listeners, 'http://x/api/radar.php?t=2');
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get('X-From-Cache'), '1');
|
||||
assert.equal(await res.text(), 'GIF89a');
|
||||
});
|
||||
|
||||
test('an offline radar request without any cache gives a plain 503, not JSON', async () => {
|
||||
const { listeners } = loadServiceWorker({ fetchImpl: async () => { throw new TypeError('offline'); } });
|
||||
|
||||
const res = await dispatchFetch(listeners, 'http://x/api/radar.php?t=1');
|
||||
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal(await res.text(), 'offline');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user