Files
Europa/Nuvolari/app/test/data/radar/mock_radar_source_test.dart
T
Alby96andClaude Opus 5 91f9ac0fbf Animate the radar timeline with a double-buffered overlay
Completes milestone 3: frames render over the map, play as a loop, and can be
scrubbed, with the legend drawn from the manifest rather than a constant that
could drift from what the worker actually rendered.

The overlay alternates two MapLibre image sources. Updating one source in place
flickers, because the layer briefly shows a half-written texture; adding every
frame as its own layer avoids that but pins them all in GPU memory, and twenty
512x512 RGBA frames is about 80 MB. Two buffers cost the same whether the
timeline holds six frames or sixty. Platform-channel work is serialised because
`show` is called faster than the round trip completes during playback, and
overlapping updates would swap visibility out of order and strobe.

Prefetching loads a window around the playhead, nearest first and forward
before backward, since playback moves forward and that frame is needed
soonest. `FrameCache` is byte-budgeted rather than entry-counted because frame
size tracks how much precipitation is on screen, and it evicts by distance from
the playhead: plain LRU would keep frames the prefetcher touched a moment ago
even after the playhead moved to the far end of the timeline.

Also adds DpcRadarSource, which reads published frames from our CDN and never
from the DPC API. Without it, the `dpc` adapter would have had to fall back to
mock, putting demo frames on screen under the label of live data — exactly the
confusion the adapter split exists to prevent. It now fails naming the missing
setting instead.

Running it on the emulator caught three things the tests had not:

- The notifier wrote to `state` from inside `build()`, which Riverpod rejects
  as an uninitialised provider. That broke startup, not just tests.
- Eight-month-old demo frames rendered as "Aggiornato 342535 minuti fa". The
  age formatter now steps up to hours and days.
- Demo mode sat permanently behind a stale-data warning and so never showed the
  working state it exists to demonstrate. MockRadarSource now shifts the
  bundled timestamps onto the present, leaving images, order and spacing
  untouched, so the timeline behaves exactly as it would on live data.

Corrects docs/stack-decisions.md, which described a disk cache that was not
built: mock frames already live in the asset bundle, so a disk layer belongs
with the network adapter where it would save a real request.

Verified: analyze clean, 129 tests passing, and on the emulator the loop
advances, wraps, and reports "Aggiornato ora".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 12:57:16 +02:00

233 lines
7.4 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:nuvolari/core/region/region_config.dart';
import 'package:nuvolari/data/radar/arpa_radar_source.dart';
import 'package:nuvolari/data/radar/mock_radar_source.dart';
import 'package:nuvolari/data/radar/radar_manifest.dart';
import 'package:nuvolari/data/radar/radar_source.dart';
/// Serves the repository's real asset files, since `flutter test` does not
/// populate the asset bundle itself.
class _DiskAssetBundle extends CachingAssetBundle {
@override
Future<ByteData> load(String key) async {
final file = File(key);
if (!file.existsSync()) {
throw FlutterError('asset not found: $key');
}
return ByteData.sublistView(Uint8List.fromList(file.readAsBytesSync()));
}
}
class _EmptyAssetBundle extends CachingAssetBundle {
@override
Future<ByteData> load(String key) async =>
throw FlutterError('asset not found: $key');
}
class _FixedAssetBundle extends CachingAssetBundle {
_FixedAssetBundle(this.content);
final String content;
@override
Future<ByteData> load(String key) async =>
ByteData.sublistView(Uint8List.fromList(utf8.encode(content)));
}
void main() {
group('MockRadarSource against the bundled assets', () {
late MockRadarSource source;
setUp(() {
source = MockRadarSource(bundle: _DiskAssetBundle());
});
test('parses the generated manifest', () async {
final manifest = await source.getLatestManifest();
expect(manifest.regionId, 'piemonte');
expect(manifest.product, 'VMI');
expect(manifest.frames, isNotEmpty);
expect(manifest.legend.unit, 'dBZ');
});
test('frames are evenly spaced and ascending', () async {
final frames = await source.getFrames();
expect(frames.length, greaterThanOrEqualTo(12));
for (var i = 1; i < frames.length; i++) {
expect(
frames[i].timestamp.difference(frames[i - 1].timestamp),
const Duration(minutes: 5),
reason: 'gap before frame $i',
);
}
});
test('every frame in the manifest actually exists', () async {
final frames = await source.getFrames();
for (final frame in frames) {
final bytes = await source.loadFrameBytes(frame);
expect(bytes, isNotEmpty, reason: '${frame.path} is empty');
// PNG magic number, so a truncated or misnamed file is caught here
// rather than as a blank overlay on the map.
expect(
bytes.sublist(0, 8),
orderedEquals(<int>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
reason: '${frame.path} is not a PNG',
);
}
});
// The demo frames are drawn for the region's extent. If the two drifted
// apart the overlay would sit off the map with nothing to signal it.
test('the manifest bbox matches the region config', () async {
final manifest = await source.getLatestManifest();
final region = RegionConfig.parse(
File('assets/regions/piemonte.json').readAsStringSync(),
);
expect(manifest.bounds, region.bounds);
});
test('resolves frame paths relative to the manifest', () {
final resolved = source.resolveAssetPath(
RadarFrame(
timestamp: DateTime.utc(2026),
path: 'frames/1768478400000.png',
),
);
expect(resolved, 'assets/mock/frames/1768478400000.png');
});
// The generator writes a fixed epoch so regenerating the assets is
// reproducible. Without rebasing, demo mode would permanently sit behind a
// "data is stale" warning and never show the working state it exists to
// demonstrate.
test('rebases the bundled timestamps onto the present', () async {
final at = DateTime.utc(2026, 3, 4, 10, 7, 33);
final fixed = MockRadarSource(
bundle: _DiskAssetBundle(),
clock: () => at,
);
final manifest = await fixed.getLatestManifest();
final newest = manifest.frames.last.timestamp;
expect(manifest.ageAt(at).inMinutes, lessThan(5));
// Landed on a whole five-minute step, the way a real publish would.
expect(newest.minute % 5, 0);
expect(newest.second, 0);
});
test('rebasing preserves order, spacing and paths', () async {
final original = RadarManifest.parse(
File('assets/mock/manifest.json').readAsStringSync(),
);
final rebased = await MockRadarSource(
bundle: _DiskAssetBundle(),
clock: () => DateTime.utc(2026, 3, 4, 10, 7, 33),
).getLatestManifest();
expect(rebased.frames, hasLength(original.frames.length));
for (var i = 0; i < original.frames.length; i++) {
expect(rebased.frames[i].path, original.frames[i].path);
}
for (var i = 1; i < rebased.frames.length; i++) {
expect(
rebased.frames[i].timestamp.difference(
rebased.frames[i - 1].timestamp,
),
original.frames[i].timestamp.difference(
original.frames[i - 1].timestamp,
),
);
}
});
test('parses the manifest once and reuses it', () async {
final first = await source.getLatestManifest();
final second = await source.getLatestManifest();
expect(identical(first, second), isTrue);
});
});
group('MockRadarSource failure handling', () {
// Demo mode degrades exactly like a live source: the caller sees
// unavailability, not a packaging error it cannot act on.
test('reports a missing manifest as unavailable', () async {
final source = MockRadarSource(bundle: _EmptyAssetBundle());
await expectLater(
source.getLatestManifest(),
throwsA(isA<RadarUnavailableException>()),
);
});
test('reports a malformed manifest as unavailable', () async {
final source = MockRadarSource(bundle: _FixedAssetBundle('{"crs": 1}'));
await expectLater(
source.getLatestManifest(),
throwsA(isA<RadarUnavailableException>()),
);
});
test('reports a missing frame as unavailable', () async {
final source = MockRadarSource(bundle: _EmptyAssetBundle());
await expectLater(
source.loadFrameBytes(
RadarFrame(timestamp: DateTime.utc(2026), path: 'frames/gone.png'),
),
throwsA(isA<RadarUnavailableException>()),
);
});
});
// The adapter is named by configuration but has no authorization behind it.
// Failing loudly is the point: silently serving something else would misreport
// where the data came from.
group('ArpaRadarSource', () {
const source = ArpaRadarSource();
test('every entry point refuses', () async {
await expectLater(
source.getLatestManifest(),
throwsA(isA<RadarUnavailableException>()),
);
await expectLater(
source.getFrames(),
throwsA(isA<RadarUnavailableException>()),
);
await expectLater(
source.loadFrameBytes(
RadarFrame(timestamp: DateTime.utc(2026), path: 'x.png'),
),
throwsA(isA<RadarUnavailableException>()),
);
});
test('says why it is disabled', () async {
await expectLater(
source.getLatestManifest(),
throwsA(
isA<RadarUnavailableException>().having(
(e) => e.message,
'message',
contains('authorization'),
),
),
);
});
});
}