Merge main

This commit is contained in:
2026-11-02 00:36:49 +00:00
33 changed files with 2239 additions and 378 deletions
@@ -0,0 +1,18 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_thumbnail_image.dart';
void main() {
test('decodes a large picture just big enough to cover its box', () {
// Landscape into a square: the height binds, the width overflows.
final wide = coverTargetSize(4000, 2000, width: 200, height: 200);
expect((wide.width, wide.height), (400, 200));
// Portrait into a 4:3 tile: the width binds.
final tall = coverTargetSize(1000, 3000, width: 400, height: 300);
expect((tall.width, tall.height), (400, 1200));
});
test('never upscales a picture smaller than its box', () {
final small = coverTargetSize(100, 80, width: 200, height: 200);
expect((small.width, small.height), (null, null));
});
}
@@ -0,0 +1,70 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_row_widgets.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_cache.dart';
void main() {
test('chatJsonEquals compares decoded JSON structurally', () {
expect(
chatJsonEquals(
{
'a': [
1,
'x',
{'b': true},
],
},
{
'a': [
1,
'x',
{'b': true},
],
},
),
isTrue,
);
expect(chatJsonEquals({'a': 1}, {'a': 2}), isFalse);
expect(chatJsonEquals({'a': 1}, {'b': 1}), isFalse);
expect(chatJsonEquals([1, 2], [1, 2, 3]), isFalse);
expect(chatJsonEquals({'a': null}, <String, dynamic>{}), isFalse);
});
test('ChatRowWidgets reuses a widget until its row or inputs change', () {
final rows = ChatRowWidgets();
var builds = 0;
Widget build() {
builds++;
return SizedBox(width: builds.toDouble());
}
final first = rows.widgetFor('k', {'text': 'a'}, [1], build);
expect(rows.widgetFor('k', {'text': 'a'}, [1], build), same(first));
expect(builds, 1);
expect(rows.widgetFor('k', {'text': 'b'}, [1], build), isNot(same(first)));
final second = rows.widgetFor('k', {'text': 'b'}, [2], build);
expect(builds, 3);
rows.prune();
// A row the last build did not ask for is forgotten.
rows.prune();
expect(rows.widgetFor('k', {'text': 'b'}, [2], build), isNot(same(second)));
expect(builds, 4);
});
test('ChatMarkdownCache parses a text once and stays bounded', () {
final cache = ChatMarkdownCache(maxEntries: 2, maxChars: 100);
final blocks = cache.blocksFor('# One');
expect(cache.blocksFor('# One'), same(blocks));
expect(cache.parses, 1);
cache.blocksFor('two');
cache.blocksFor('three');
// The least recently used text was evicted and parses again.
expect(cache.blocksFor('# One'), isNot(same(blocks)));
expect(cache.parses, 4);
// A text larger than the character budget is parsed but never held.
final long = 'x' * 200;
cache.blocksFor(long);
cache.blocksFor(long);
expect(cache.parses, 6);
});
}
@@ -0,0 +1,159 @@
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart' as widgets;
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_cache.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart';
import '../conversation/chat_thread_fixtures.dart';
/// Measurement harness: streams 200 text deltas into a 300-message transcript
/// and counts message builds, markdown builds/parses and per-delta frame time;
/// then scrolls the long transcript up and back down.
const _messages = 300;
const _deltas = 200;
String _answer(int index) =>
'## Answer $index\n\nSome **bold** text with `code` and a '
'[link](https://example.com/$index).\n\n'
'```dart\n'
'${List.generate(30, (line) => 'final v$line = $index * $line;').join('\n')}'
'\n```\n\n'
'- one\n- two\n- three\n';
List<JsonMap> _transcript() => [
for (var index = 0; index < _messages; index++)
// The newest message is the operator's, so the reply opens a new turn.
index.isOdd
? chatMessage(
'u$index',
'user',
parts: [
{'type': 'text', 'text': 'Question $index'},
],
)
: chatMessage(
'a$index',
'assistant',
parts: [
{'type': 'text', 'id': 't$index', 'text': _answer(index)},
],
),
];
Future<FakeChatGateway> _open(WidgetTester tester) async {
tester.view.physicalSize = const Size(1000, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(_transcript());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
),
);
final watch = Stopwatch()..start();
await tester.pumpAndSettle();
watch.stop();
// ignore: avoid_print
print(
'PERF open: parses=${chatMarkdownCache.parses} '
'settleMs=${watch.elapsedMilliseconds}',
);
return gateway;
}
String _stats(List<int> samples) {
final sorted = [...samples]..sort();
final mean = sorted.reduce((a, b) => a + b) / sorted.length;
return 'meanUs=${mean.round()} p50Us=${sorted[sorted.length ~/ 2]} '
'p90Us=${sorted[sorted.length * 9 ~/ 10]} maxUs=${sorted.last}';
}
void main() {
setUp(chatMarkdownCache.clear);
testWidgets('streaming deltas rebuild only the live turn', (tester) async {
final gateway = await _open(tester);
var messageBuilds = 0;
var markdownBuilds = 0;
var totalBuilds = 0;
widgets.debugOnRebuildDirtyWidget = (element, _) {
final widget = element.widget;
if (widget is ChatMessageView) messageBuilds++;
if (widget is ChatMarkdownView) markdownBuilds++;
totalBuilds++;
};
addTearDown(() => widgets.debugOnRebuildDirtyWidget = null);
final parsesBefore = chatMarkdownCache.parses;
final perDelta = <int>[];
final watch = Stopwatch();
for (var index = 0; index < _deltas; index++) {
gateway.emitEvent(
chatTextFrame(
index == 0 ? 'Live reply ' : 'word$index ',
messageId: 'live',
),
);
await tester.idle();
watch
..reset()
..start();
await tester.pump();
watch.stop();
perDelta.add(watch.elapsedMicroseconds);
}
widgets.debugOnRebuildDirtyWidget = null;
final parses = chatMarkdownCache.parses - parsesBefore;
// ignore: avoid_print
print(
'PERF stream: deltas=$_deltas messages=$_messages '
'messageBuilds=$messageBuilds markdownBuilds=$markdownBuilds '
'markdownParses=$parses totalBuilds=$totalBuilds frame ${_stats(perDelta)}',
);
expect(
find.textContaining('word${_deltas - 1}', findRichText: true),
findsOneWidget,
);
// Only the live turn rebuilds per delta (plus slack for the turn that
// starts the stream); every finished message is left alone.
expect(messageBuilds, lessThanOrEqualTo(_deltas + 10));
expect(parses, lessThanOrEqualTo(_deltas + 10));
});
testWidgets('scrolling a long transcript reuses parsed markdown', (
tester,
) async {
await _open(tester);
final list = find.byKey(const ValueKey<String>('chat-thread-s'));
final parsesBefore = chatMarkdownCache.parses;
var parsesUp = 0;
final frames = <int>[];
final watch = Stopwatch();
// Up 40 drags and back down 40: the way back revisits parsed rows.
for (final dy in [...List.filled(40, 600.0), ...List.filled(40, -600.0)]) {
await tester.drag(list, Offset(0, dy));
watch
..reset()
..start();
await tester.pump(const Duration(milliseconds: 16));
watch.stop();
frames.add(watch.elapsedMicroseconds);
if (frames.length == 40) {
parsesUp = chatMarkdownCache.parses - parsesBefore;
}
}
await tester.pumpAndSettle();
final parses = chatMarkdownCache.parses - parsesBefore;
// ignore: avoid_print
print(
'PERF scroll: drags=${frames.length} markdownParses=$parses '
'(up=$parsesUp down=${parses - parsesUp}) '
'frame ${_stats(frames)}',
);
});
}
@@ -0,0 +1,253 @@
// Measures wasted background work outside the chat transcript: timers kept
// alive by list rows, rebuilds per minute tick, offstage tabs' work and the
// rebuilds a burst of run events causes. Each scenario prints its numbers
// (`BENCH ...`) and asserts the budgets the shared clock and the narrowed
// notifications keep.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
import 'package:pipelines_app/features/runs/ui/runs_list.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart';
import 'package:pipelines_app/ui/text/relative_time_label.dart';
class _Gateway implements ApiGateway {
final controller = StreamController<JsonMap>.broadcast(sync: true);
List<JsonMap> runs = [];
@override
Stream<JsonMap> get frames => controller.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async => {
'runs': [for (final run in runs) Map<String, dynamic>.of(run)],
};
}
/// Counts element rebuilds by widget type while installed.
class _Rebuilds {
final Map<Type, int> counts = {};
void install() => debugOnRebuildDirtyWidget = (element, _) => counts.update(
element.widget.runtimeType,
(n) => n + 1,
ifAbsent: () => 1,
);
void uninstall() => debugOnRebuildDirtyWidget = null;
int of(Type type) => counts[type] ?? 0;
int get total => counts.values.fold(0, (a, b) => a + b);
void reset() => counts.clear();
}
/// Tracks every Timer created in its zone (one-shot and periodic).
class _Timers {
final List<Timer> created = [];
int get active => created.where((t) => t.isActive).length;
late final ZoneSpecification spec = ZoneSpecification(
createTimer: (self, parent, zone, duration, f) {
final timer = parent.createTimer(zone, duration, f);
created.add(timer);
return timer;
},
createPeriodicTimer: (self, parent, zone, period, f) {
final timer = parent.createPeriodicTimer(zone, period, f);
created.add(timer);
return timer;
},
);
}
List<JsonMap> _runs(int count, DateTime now) => [
for (var i = 0; i < count; i++)
{
'id': i + 1,
'name': 'Pipeline ${i % 7}',
'title': 'Run ${i + 1}',
'status': i < 20 ? 'running' : 'succeeded',
'executing': i < 20,
'completed_steps': 1,
// The lifecycle fields a server list row carries.
'notify_mode': 'auto',
'resource_wait': null,
'cancel_requested': false,
'cleanup_unconfirmed': false,
// Every 20 seconds back: the newest rows change label each minute.
'created_at': now.subtract(Duration(seconds: 20 * i)).toIso8601String(),
},
];
// The app passes a stable tear-off (`_select`), never a fresh closure.
void _open(num _) {}
void main() {
late _Gateway gateway;
late RunsController controller;
final rebuilds = _Rebuilds();
setUp(() async {
gateway = _Gateway()..runs = _runs(300, DateTime.now());
controller = RunsController(RunsRepository(gateway));
controller.listen(gateway.frames);
await controller.load();
});
tearDown(() async {
rebuilds.uninstall();
controller.dispose();
await gateway.controller.close();
});
Widget shell(AppDestination destination) => MaterialApp(
home: AdaptiveShell(
destination: destination,
destinationBodies: {
AppDestination.runs: (_) => AnimatedBuilder(
animation: controller,
builder: (_, _) =>
RunsList(controller: controller, onSelected: _open),
),
AppDestination.pipelines: (_) => const Center(child: Text('pipelines')),
},
),
);
/// Sends frame [i] of a busy stream: most frames repeat a running row's
/// current state; every fifth advances its step count.
void frame(int i) {
final id = 1 + i % 20;
final row = gateway.runs[id - 1];
if (i % 5 == 0) row['completed_steps'] = 2 + i;
gateway.controller.add({
'type': 'run_event',
'run_id': id,
'status': 'running',
'completed_steps': row['completed_steps'],
});
}
Future<void> sizeView(WidgetTester tester) async {
tester.view.physicalSize = const Size(400, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
}
testWidgets('300-run list: timers and rebuilds per minute tick', (
tester,
) async {
await sizeView(tester);
final timers = _Timers();
await runZoned(zoneSpecification: timers.spec, () async {
await tester.pumpWidget(shell(AppDestination.runs));
await tester.pump();
final labels = find.byType(RelativeTimeLabel).evaluate().length;
final active = timers.active;
// Measure one whole minute after the first tick, wherever it falls.
await tester.pump(const Duration(minutes: 1));
await tester.pump();
final created = timers.created.length;
rebuilds
..reset()
..install();
await tester.pump(const Duration(minutes: 1));
await tester.pump();
final perMinute = timers.created.length - created;
rebuilds.uninstall();
// ignore: avoid_print
print(
'BENCH list300 mountedLabels=$labels activeTimers=$active '
'labelRebuildsPerMinute=${rebuilds.of(RelativeTimeLabel)} '
'totalRebuildsPerMinute=${rebuilds.total} '
'timersScheduledPerMinute=$perMinute',
);
expect(active, lessThanOrEqualTo(1));
await tester.pumpWidget(const SizedBox());
expect(timers.active, 0);
});
});
testWidgets('offstage Runs tab: minute ticks and run events', (tester) async {
await sizeView(tester);
final timers = _Timers();
await runZoned(zoneSpecification: timers.spec, () async {
await tester.pumpWidget(shell(AppDestination.runs));
await tester.pump();
await tester.pumpWidget(shell(AppDestination.pipelines));
await tester.pump(const Duration(seconds: 1)); // fade-through done
final active = timers.active;
rebuilds
..reset()
..install();
await tester.pump(const Duration(minutes: 2));
await tester.pump();
final tick = rebuilds.of(RelativeTimeLabel);
rebuilds.reset();
for (var i = 0; i < 50; i++) {
frame(i);
await tester.pump();
}
await tester.pump();
rebuilds.uninstall();
// ignore: avoid_print
print(
'BENCH offstage activeTimers=$active labelRebuildsIn2Minutes=$tick '
'burst50: runsListRebuilds=${rebuilds.of(RunsList)} '
'shellBarRebuilds=${rebuilds.of(FloatingDestinationBar)} '
'totalRebuilds=${rebuilds.total}',
);
expect(tick, 0);
expect(rebuilds.of(FloatingDestinationBar), 0);
await tester.pumpWidget(const SizedBox());
expect(timers.active, 0);
});
});
testWidgets('visible Runs tab: a 50-frame run_event burst', (tester) async {
await sizeView(tester);
var notifications = 0;
controller.addListener(() => notifications++);
await tester.pumpWidget(shell(AppDestination.runs));
await tester.pump();
final rows = find.byType(RunListRow).evaluate().length;
rebuilds
..reset()
..install();
final wall = Stopwatch()..start();
// Frames arrive between frames on a real socket: pump after each.
for (var i = 0; i < 50; i++) {
frame(i);
await tester.pump();
}
await tester.pump();
rebuilds.uninstall();
final seconds = wall.elapsed.inSeconds;
// ignore: avoid_print
print(
'BENCH visibleBurst50 controllerNotifications=$notifications '
'runsListRebuilds=${rebuilds.of(RunsList)} '
'runRowRebuilds=${rebuilds.of(RunListRow)} '
'shellBarRebuilds=${rebuilds.of(FloatingDestinationBar)} '
'totalRebuilds=${rebuilds.total}',
);
final top = rebuilds.counts.entries.toList()
..sort((a, b) => b.value - a.value);
// ignore: avoid_print
print(
'BENCH top ${top.take(15).map((e) => '${e.key}=${e.value}').join(' ')}',
);
// Only the ten frames that advance a step change anything visible.
expect(notifications, lessThanOrEqualTo(10));
// Each notification rebuilds the one row whose run changed, not every
// built row (16 rows rebuilt per notification before memoized rows). An
// executing row also rebuilds when its wall-clock duration text moves to
// the next second, at most once per second the burst took.
expect(
rebuilds.of(RunListRow),
lessThanOrEqualTo(notifications + rows * (seconds + 1)),
);
await tester.pumpWidget(const SizedBox());
});
}
@@ -0,0 +1,170 @@
// Measures the work a list does for data that did not change: the chat
// sessions list on a running-state change, and the artifact gallery opening a
// visit with hundreds of artifacts. Each scenario prints `BENCH ...` numbers
// and asserts the budget the memoized rows and lazy gallery keep.
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_tile.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_body.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart';
class _Rebuilds {
final Map<Type, int> counts = {};
void install() => debugOnRebuildDirtyWidget = (element, _) => counts.update(
element.widget.runtimeType,
(n) => n + 1,
ifAbsent: () => 1,
);
void uninstall() => debugOnRebuildDirtyWidget = null;
int of(Type type) => counts[type] ?? 0;
int get total => counts.values.fold(0, (a, b) => a + b);
}
int _elements(WidgetTester tester) {
var count = 0;
void visit(Element element) {
count++;
element.visitChildren(visit);
}
tester.binding.rootElement!.visitChildren(visit);
return count;
}
// Stable callbacks, as the screen passes its own methods.
void _session(JsonMap _) {}
void _clear() {}
bool _unseen(JsonMap _) => false;
String? _noError(String _) => null;
Future<ArtifactFetchResult> _fetch(Uri _) async =>
ArtifactFetchResult(status: 404, bytes: Uint8List(0));
void main() {
Future<void> sizeView(WidgetTester tester) async {
tester.view.physicalSize = const Size(400, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
}
testWidgets('chat sessions list: 50 running-state changes', (tester) async {
await sizeView(tester);
final sessions = ValueNotifier<List<JsonMap>>([
for (var i = 0; i < 200; i++)
{
'id': 's$i',
'title': 'Chat $i',
'directory': '/repo/${i % 3}',
'harness': 'claude',
'running': false,
'updated_at': DateTime.now()
.subtract(Duration(minutes: i))
.toIso8601String(),
},
]);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ValueListenableBuilder(
valueListenable: sessions,
builder: (_, list, _) => ChatSessionsBody(
sessions: list,
query: '',
loading: false,
error: null,
onOpen: _session,
onRename: _session,
onClose: _session,
onReopen: _session,
onStar: _session,
onHide: _session,
onClearSearch: _clear,
isUnseen: _unseen,
errorFor: _noError,
),
),
),
),
);
await tester.pump();
final built = find.byType(ChatSessionRow).evaluate().length;
final rebuilds = _Rebuilds()..install();
for (var i = 0; i < 50; i++) {
// The controller replaces only the changed row's map.
final id = i % 5;
sessions.value = [
for (final s in sessions.value)
s['id'] == 's$id' ? {...s, 'running': s['running'] != true} : s,
];
await tester.pump();
}
rebuilds.uninstall();
// ignore: avoid_print
print(
'BENCH chatSessions200 builtRows=$built '
'rowRebuilds=${rebuilds.of(ChatSessionRow)} '
'totalRebuilds=${rebuilds.total}',
);
// One row per change, not all 200 (10,000 row rebuilds before).
expect(rebuilds.of(ChatSessionRow), 50);
});
testWidgets('gallery: open a visit with 500 artifacts', (tester) async {
await sizeView(tester);
final group = ArtifactGroup(
stageKey: 'render',
visit: 1,
artifacts: [
for (var i = 0; i < 500; i++)
ArtifactRecord.fromJson({
'name': 'frame-$i.png',
'url': '/artifacts/1/frame-$i.png',
'content_type': 'image/png',
'size_bytes': 1000 + i,
}),
],
);
for (final mode in ArtifactGalleryMode.values) {
ArtifactVisitList.lastMode = mode;
final watch = Stopwatch()..start();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ArtifactVisitList(
key: ValueKey(mode),
groups: [group],
initiallyCollapsed: false,
fetch: _fetch,
),
),
),
);
await tester.pumpAndSettle();
final settle = watch.elapsedMilliseconds;
final tiles =
find.byType(ArtifactTile).evaluate().length +
find.byType(ArtifactThumbnail).evaluate().length;
final elements = _elements(tester);
// A scroll frame through the open section.
watch.reset();
await tester.drag(find.byType(CustomScrollView), const Offset(0, -2000));
await tester.pump();
final scroll = watch.elapsedMicroseconds;
// ignore: avoid_print
print(
'BENCH gallery500 mode=${mode.name} builtItems=$tiles '
'elements=$elements openMs=$settle scrollFrameUs=$scroll',
);
// Only the visible tiles are built (all 500 were before).
expect(tiles, lessThan(100));
await tester.pumpWidget(const SizedBox());
}
ArtifactVisitList.lastMode = ArtifactGalleryMode.grid;
});
}
+51
View File
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/layout/memo_subtree.dart';
void main() {
testWidgets('rebuilds only when the memo changes', (tester) async {
var builds = 0;
Widget host(Object memo) => Directionality(
textDirection: TextDirection.ltr,
child: MemoSubtree(
memo: memo,
builder: (_) {
builds++;
return Text('$memo');
},
),
);
await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'x'}), true)));
// An equal map (a new instance) and equal props keep the built child.
await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'x'}), true)));
expect(builds, 1);
await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'y'}), true)));
expect(builds, 2);
await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'y'}), false)));
expect(builds, 3);
});
testWidgets('the built subtree still follows its inherited widgets', (
tester,
) async {
Widget host(Color color) => MaterialApp(
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: color)),
home: MemoSubtree(
memo: 1,
builder: (_) => Builder(
builder: (context) => ColoredBox(
key: const Key('box'),
color: Theme.of(context).colorScheme.primary,
),
),
),
);
Color shown() =>
tester.widget<ColoredBox>(find.byKey(const Key('box'))).color;
await tester.pumpWidget(host(Colors.red));
final before = shown();
await tester.pumpWidget(host(Colors.blue));
await tester.pumpAndSettle();
expect(shown(), isNot(before));
});
}
+107
View File
@@ -0,0 +1,107 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/layout/sliver_reveal.dart';
void main() {
Widget host({
required bool open,
Duration duration = kThemeAnimationDuration,
}) => MaterialApp(
home: CustomScrollView(
slivers: [
SliverReveal(
open: open,
duration: duration,
curve: Curves.easeInOut,
sliver: SliverList.builder(
itemCount: 1000,
itemBuilder: (_, index) =>
SizedBox(height: 50, child: Text('item $index')),
),
),
const SliverToBoxAdapter(child: Text('after')),
],
),
);
double afterTop(WidgetTester tester) =>
tester.getTopLeft(find.text('after')).dy;
testWidgets('closed builds nothing; open builds only the visible items', (
tester,
) async {
await tester.pumpWidget(host(open: false));
expect(find.textContaining('item'), findsNothing);
expect(afterTop(tester), 0);
await tester.pumpWidget(host(open: true));
await tester.pump(kThemeAnimationDuration ~/ 2);
// Part-way open: the items reveal from the top, clipped at the extent.
expect(find.text('item 0'), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('item 0'), findsOneWidget);
expect(find.text('item 999', skipOffstage: false), findsNothing);
expect(tester.widgetList(find.textContaining('item')).length, lessThan(40));
});
testWidgets('closing shrinks the extent, then drops the items', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: CustomScrollView(
slivers: [
SliverReveal(
open: true,
duration: kThemeAnimationDuration,
curve: Curves.linear,
sliver: SliverList.list(
children: [
for (var i = 0; i < 4; i++)
SizedBox(height: 50, child: Text('item $i')),
],
),
),
const SliverToBoxAdapter(child: Text('after')),
],
),
),
);
expect(afterTop(tester), 200);
await tester.pumpWidget(
MaterialApp(
home: CustomScrollView(
slivers: [
SliverReveal(
open: false,
duration: kThemeAnimationDuration,
curve: Curves.linear,
sliver: SliverList.list(
children: [
for (var i = 0; i < 4; i++)
SizedBox(height: 50, child: Text('item $i')),
],
),
),
const SliverToBoxAdapter(child: Text('after')),
],
),
),
);
await tester.pump(kThemeAnimationDuration ~/ 2);
expect(afterTop(tester), closeTo(100, 1));
await tester.pumpAndSettle();
expect(afterTop(tester), 0);
expect(find.textContaining('item'), findsNothing);
});
testWidgets('no motion opens and closes at once', (tester) async {
await tester.pumpWidget(host(open: false, duration: Duration.zero));
await tester.pumpWidget(host(open: true, duration: Duration.zero));
await tester.pump();
expect(find.text('item 0'), findsOneWidget);
await tester.pumpWidget(host(open: false, duration: Duration.zero));
await tester.pump();
expect(find.textContaining('item'), findsNothing);
});
}
+65 -13
View File
@@ -1,45 +1,96 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/text/relative_time.dart';
import 'package:pipelines_app/ui/text/relative_time_clock.dart';
import 'package:pipelines_app/ui/text/relative_time_label.dart';
/// The start of the current wall-clock minute, where the shared clock ticks.
DateTime _minute() {
final now = DateTime.now();
return DateTime(now.year, now.month, now.day, now.hour, now.minute);
}
void main() {
testWidgets('updates at the next relative-time boundary', (tester) async {
final instant = DateTime.now().subtract(const Duration(minutes: 4));
final clock = RelativeTimeClock.shared;
testWidgets('updates on the next minute tick', (tester) async {
final instant = _minute().subtract(const Duration(minutes: 4));
await tester.pumpWidget(
MaterialApp(home: RelativeTimeLabel(instant: instant)),
);
expect(find.text('4m'), findsOneWidget);
await tester.pump(const Duration(minutes: 1, seconds: 1));
await tester.pump(const Duration(minutes: 1));
expect(find.text('5m'), findsOneWidget);
});
testWidgets('future labels schedule their next boundary', (tester) async {
final instant = DateTime.now().add(const Duration(minutes: 4));
testWidgets('future labels count down on the ticks', (tester) async {
final instant = _minute().add(
const Duration(minutes: 4, milliseconds: 500),
);
await tester.pumpWidget(
MaterialApp(home: RelativeTimeLabel(instant: instant)),
);
expect(find.text('in 3m'), findsOneWidget);
expect(find.text(formatRelativeTime(instant)!), findsOneWidget);
await tester.pump(const Duration(minutes: 1, seconds: 1));
await tester.pump(const Duration(minutes: 2));
expect(find.text('in 2m'), findsOneWidget);
});
testWidgets('cancels its timer when disposed', (tester) async {
testWidgets('many labels share one timer, released when disposed', (
tester,
) async {
final instant = DateTime.now().subtract(const Duration(minutes: 4));
await tester.pumpWidget(
MaterialApp(
home: RelativeTimeLabel(
instant: DateTime.now().subtract(const Duration(minutes: 4)),
home: Wrap(
children: [
for (var i = 0; i < 50; i++) RelativeTimeLabel(instant: instant),
],
),
),
);
expect(clock.ticking, isTrue);
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
expect(clock.ticking, isFalse);
await tester.pump(const Duration(hours: 1));
});
testWidgets('a muted label skips ticks and catches up when shown', (
tester,
) async {
final instant = _minute().subtract(const Duration(minutes: 4));
var builds = 0;
Widget app(bool enabled) => MaterialApp(
home: TickerMode(
enabled: enabled,
child: Builder(
builder: (_) {
builds++;
return RelativeTimeLabel(instant: instant);
},
),
),
);
await tester.pumpWidget(app(false));
final label = find.byType(RelativeTimeLabel);
var labelBuilds = 0;
debugOnRebuildDirtyWidget = (element, _) {
if (element.widget is RelativeTimeLabel) labelBuilds++;
};
addTearDown(() => debugOnRebuildDirtyWidget = null);
await tester.pump(const Duration(minutes: 1));
expect(labelBuilds, 0);
expect(find.descendant(of: label, matching: find.text('4m')), findsOneWidget);
await tester.pumpWidget(app(true));
expect(find.text('5m'), findsOneWidget);
expect(builds, 2);
});
testWidgets('keeps ticking while inactive, pauses while hidden and '
'refreshes on resume', (tester) async {
final instant = DateTime.now().subtract(const Duration(minutes: 4));
final instant = _minute().subtract(const Duration(minutes: 4));
await tester.pumpWidget(
MaterialApp(home: RelativeTimeLabel(instant: instant)),
);
@@ -49,12 +100,13 @@ void main() {
WidgetsBinding.instance.handleAppLifecycleStateChanged(
AppLifecycleState.inactive,
);
await tester.pump(const Duration(minutes: 1, seconds: 1));
await tester.pump(const Duration(minutes: 1));
expect(find.text('5m'), findsOneWidget);
WidgetsBinding.instance.handleAppLifecycleStateChanged(
AppLifecycleState.hidden,
);
expect(clock.ticking, isFalse);
await tester.pump(const Duration(minutes: 1, seconds: 1));
expect(find.text('5m'), findsOneWidget);
@@ -64,8 +116,8 @@ void main() {
WidgetsBinding.instance.handleAppLifecycleStateChanged(
AppLifecycleState.resumed,
);
expect(clock.ticking, isTrue);
await tester.pump();
await tester.pump(const Duration(minutes: 1, seconds: 1));
expect(find.text('5m'), findsOneWidget);
});
}