feat(app): add native omni-search screen over the search gateway

Pure request/parse/row logic in lib/features/search/domain, a
gateway-backed repository, and Material plus Cupertino bodies.
The header and rows share one scroll view, and the server's
truncation, scan and cap facts stay visible even when a bounded
scan returns no matches.

Tests cover the exact search envelope, token parsing, stale replies,
retry, truncation bounds and platform layouts. A Web-only fixture
and CDP probe support rendered verification; the screen is not yet
registered in the shell.
This commit is contained in:
2026-10-21 16:41:30 +01:00
parent 7ecd3903c0
commit 51140cd3b7
21 changed files with 3020 additions and 0 deletions
@@ -0,0 +1,90 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
import 'package:pipelines_app/features/search/domain/search_query.dart';
import 'search_test_support.dart';
void main() {
test('a server error is shown, and retry issues a fresh request', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.fail(0, StateError('server is down'));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.error);
expect(controller.error, contains('server is down'));
final retry = controller.retry();
await pumpEventQueue();
expect(gateway.calls, hasLength(2));
expect(gateway.lastSearch, {'query': 'plan', 'kind': '', 'limit': 0});
gateway.succeed(
1,
envelope([
{
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {'id': 7},
},
]),
);
await retry;
expect(controller.error, isNull);
expect(controller.results, hasLength(1));
expect(controller.bodyKind, SearchBodyKind.results);
});
test('a stale failure never replaces the newest query state', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('first');
await pumpEventQueue();
controller.updateQuery('second');
await pumpEventQueue();
gateway.fail(0, StateError('stale failure'));
await pumpEventQueue();
expect(controller.error, isNull);
expect(controller.loading, isTrue);
expect(controller.bodyKind, SearchBodyKind.searching);
gateway.succeed(
1,
envelope([
{
'kind': 'pipeline',
'target': 'pipeline:9',
'pipeline': {'id': 9},
},
]),
);
await pumpEventQueue();
expect(controller.error, isNull);
expect(controller.results.single['target'], 'pipeline:9');
expect(controller.bodyKind, SearchBodyKind.results);
});
test(
'a missing search_results payload reports the unsupported copy',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.succeed(0, {'type': 'pong'});
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.error);
expect(controller.error, unsupportedSearchCopy);
},
);
}
@@ -0,0 +1,240 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
import 'search_test_support.dart';
void main() {
test('empty query with no kind is idle and sends no request', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery(' ');
await pumpEventQueue();
expect(gateway.calls, isEmpty);
expect(controller.bodyKind, SearchBodyKind.idle);
expect(controller.results, isEmpty);
expect(controller.loaded, isFalse);
expect(controller.loading, isFalse);
});
test('the request carries the parsed query, kind and limit 0', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('t:run Plan TYPE:artifact');
await pumpEventQueue();
expect(gateway.calls, hasLength(1));
expect(gateway.lastSearch, {
'query': 'Plan',
'kind': 'artifact',
'limit': 0,
});
});
test(
'a kind selector change removes type tokens and sends at once',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan t:run');
await pumpEventQueue();
expect(gateway.lastSearch['kind'], 'run');
controller.selectKind(SearchKind.pipeline);
await pumpEventQueue();
expect(controller.query.trim(), 'plan');
expect(controller.query, isNot(contains('t:run')));
expect(controller.selectedKind, SearchKind.pipeline);
expect(gateway.calls, hasLength(2));
expect(gateway.lastSearch, {
'query': 'plan',
'kind': 'pipeline',
'limit': 0,
});
},
);
test(
'kind-only browsing sends a blank query and reports the empty copy',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.selectKind(SearchKind.pipeline);
await pumpEventQueue();
expect(gateway.lastSearch, {'query': '', 'kind': 'pipeline', 'limit': 0});
expect(controller.bodyKind, SearchBodyKind.searching);
gateway.succeed(0, envelope(const []));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.empty);
expect(controller.emptyMessage, 'No pipelines yet.');
},
);
test('the latest query wins and a stale reply is dropped', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('first');
await pumpEventQueue();
controller.updateQuery('second');
await pumpEventQueue();
expect(gateway.calls, hasLength(2));
gateway.succeed(
0,
envelope([
{
'kind': 'run',
'target': 'run:1',
'run': {'id': 1},
},
]),
);
await pumpEventQueue();
expect(controller.results, isEmpty);
expect(controller.loading, isTrue);
expect(controller.bodyKind, SearchBodyKind.searching);
gateway.succeed(
1,
envelope([
{
'kind': 'run',
'target': 'run:2',
'run': {'id': 2},
},
]),
);
await pumpEventQueue();
expect(controller.results.single['target'], 'run:2');
expect(controller.loading, isFalse);
expect(controller.bodyKind, SearchBodyKind.results);
});
test('truncation and scan bounds come from the server envelope', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.succeed(
0,
envelope(
[
{
'kind': 'field',
'target': 'run:11:4:output',
'field': {'run_id': 11},
},
],
truncated: true,
scannedSteps: 2000,
scannedBytes: 1048576,
cap: 50,
),
);
await pumpEventQueue();
expect(controller.truncated, isTrue);
expect(controller.scannedSteps, 2000);
expect(controller.scannedBytes, 1048576);
expect(controller.cap, 50);
expect(controller.boundsText, contains('truncated'));
expect(controller.boundsText, contains('cap 50'));
expect(controller.boundsText, contains('2000 steps'));
});
test(
'a truncated empty reply reports the scan bound instead of a complete empty',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('needle');
await pumpEventQueue();
gateway.succeed(
0,
envelope(
const [],
truncated: true,
scannedSteps: 2000,
scannedBytes: 1048576,
cap: 50,
),
);
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.empty);
expect(
controller.emptyMessage,
'No matches for "needle" within the server\'s scan limit.',
);
expect(controller.boundsText, contains('Results truncated'));
expect(controller.boundsText, contains('0 results'));
expect(controller.boundsText, contains('2000 steps'));
expect(controller.boundsText, contains('scan limit 1.0 MiB'));
},
);
test(
'a complete empty reply stays a plain empty with no bounds line',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('needle');
await pumpEventQueue();
gateway.succeed(0, envelope(const []));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.empty);
expect(controller.emptyMessage, 'No matches for "needle".');
expect(controller.boundsText, isNull);
},
);
test('in-hand kind narrowing keeps the list honest while loading', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.succeed(
0,
envelope([
{
'kind': 'run',
'target': 'run:1',
'run': {'id': 1},
},
{
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {'id': 7},
},
]),
);
await pumpEventQueue();
expect(controller.shownResults, hasLength(2));
controller.selectKind(SearchKind.run);
await pumpEventQueue();
expect(controller.shownResults, hasLength(1));
expect(controller.shownResults.single['target'], 'run:1');
});
}
@@ -0,0 +1,118 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
import 'package:pipelines_app/features/search/domain/search_query.dart';
const unsupported =
'This server does not support search. Update the Pipelines server, then try again.';
void main() {
test('kind vocabulary is exactly the server vocabulary, All kinds first', () {
expect(SearchKind.values.map((kind) => kind.wire), [
'',
'pipeline',
'run',
'step',
'field',
'artifact',
'version',
]);
expect(SearchKind.values.map((kind) => kind.label), [
'All kinds',
'Pipelines',
'Runs',
'Steps',
'Fields',
'Artifacts',
'Versions',
]);
expect(SearchKind.fromWire('run'), SearchKind.run);
expect(SearchKind.fromWire(''), SearchKind.all);
expect(SearchKind.fromWire('prompts'), SearchKind.all);
expect(SearchKind.fromWire(null), SearchKind.all);
});
test('both type aliases and kinds are case insensitive', () {
for (final kind in SearchKind.values.where(
(kind) => kind != SearchKind.all,
)) {
for (final prefix in ['t', 'type', 'T', 'TyPe']) {
final parsed = parseSearchQuery(
'$prefix:${kind.wire.toUpperCase()} plan',
);
expect(parsed.query, ' plan');
expect(parsed.kind, kind);
expect(parsed.hasType, isTrue);
}
}
});
test('normal, quoted and unsupported text is preserved byte for byte', () {
const preserved = [
' ordinary text\twith\nspacing ',
'"t:pipeline" "hello world"',
"'type:artifact'",
'"escaped \\" t:run"',
'"unclosed t:run',
't:prompt type:unknown t: t:PIPELINES',
'not:t:run t:run,',
'prefix"t:run"',
'\\t:run',
];
for (final query in preserved) {
final parsed = parseSearchQuery(query, SearchKind.field);
expect(parsed.query, query);
expect(parsed.kind, SearchKind.field);
expect(parsed.hasType, isFalse);
}
expect(
parseSearchQuery('t:artifact "t:pipeline" report').query,
' "t:pipeline" report',
);
});
test('last supported token wins over the selector; unknown tokens stay', () {
final parsed = parseSearchQuery(
't:run plan TYPE:artifact t:unknown',
SearchKind.pipeline,
);
expect(parsed.query, ' plan t:unknown');
expect(parsed.kind, SearchKind.artifact);
expect(parsed.hasType, isTrue);
expect(parseSearchQuery('plan', SearchKind.step).kind, SearchKind.step);
});
test('type-only query is distinguishable from literal and blank input', () {
final typed = parseSearchQuery('t:pipeline');
expect(typed.query, '');
expect(typed.kind, SearchKind.pipeline);
expect(typed.hasType, isTrue);
final blank = parseSearchQuery('');
expect(blank.query, '');
expect(blank.kind, SearchKind.all);
expect(blank.hasType, isFalse);
});
test('blank text is sendable only with a supported nonempty kind', () {
for (final kind in SearchKind.values) {
expect(searchQuerySendable(' \n\t ', kind), kind != SearchKind.all);
}
expect(searchQuerySendable('', SearchKind.all), isFalse);
expect(searchQuerySendable('plan', SearchKind.all), isTrue);
expect(searchQuerySendable(' plan ', SearchKind.all), isTrue);
});
test(
'failure copy distinguishes an unsupported server from a plain error',
() {
expect(searchFailureText(null), unsupported);
expect(searchFailureText(' '), unsupported);
expect(searchFailureText('unknown command: search'), unsupported);
expect(searchFailureText('unsupported command'), unsupported);
expect(searchFailureText('boom'), 'boom');
expect(
searchFailureText('request timed out after 30000ms'),
'request timed out after 30000ms',
);
},
);
}
@@ -0,0 +1,106 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/data/search_repository.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
class RecordingGateway implements ApiGateway {
String? type;
JsonMap fields = {};
JsonMap reply = {};
Object? failure;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
this.type = type;
this.fields = Map.of(fields);
if (failure case final error?) throw error;
return reply;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
void main() {
test(
'search sends exactly search/query/kind/limit and parses bounds',
() async {
final gateway = RecordingGateway()
..reply = {
'search_results': {
'query': 'plan',
'kind': 'run',
'results': [
{
'kind': 'run',
'target': 'run:11',
'run': {'id': 11},
},
],
'truncated': true,
'scanned_steps': 27,
'scanned_bytes': 4096,
'cap': 50,
'scan_bound_bytes': 1048576,
},
};
final repository = SearchRepository(gateway);
final response = await repository.search(
query: 'plan',
kind: SearchKind.run,
);
expect(gateway.type, 'search');
expect(gateway.fields, {
'search': {'query': 'plan', 'kind': 'run', 'limit': 0},
});
expect(response, isNotNull);
expect(response!.query, 'plan');
expect(response.kind, SearchKind.run);
expect(response.results.single['target'], 'run:11');
expect(response.truncated, isTrue);
expect(response.scannedSteps, 27);
expect(response.scannedBytes, 4096);
expect(response.cap, 50);
expect(response.scanBoundBytes, 1048576);
},
);
test('all-kinds search still sends the empty kind field', () async {
final gateway = RecordingGateway()
..reply = {
'search_results': {'results': <JsonMap>[]},
};
await SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all);
expect(gateway.fields, {
'search': {'query': 'plan', 'kind': '', 'limit': 0},
});
});
test(
'a reply without search_results is null, not an empty success',
() async {
final gateway = RecordingGateway()..reply = {'type': 'pong'};
final response = await SearchRepository(
gateway,
).search(query: 'plan', kind: SearchKind.all);
expect(response, isNull);
},
);
test('server refusals propagate to the caller unchanged', () async {
final gateway = RecordingGateway()
..failure = StateError('permission denied');
await expectLater(
SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all),
throwsA(
isA<StateError>().having(
(error) => error.message,
'message',
'permission denied',
),
),
);
});
}
@@ -0,0 +1,161 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/domain/search_row.dart';
JsonMap pipelineHit([JsonMap overrides = const {}]) => {
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {
'id': 7,
'name': 'release',
'version': 3,
'stages': 4,
...overrides,
},
};
JsonMap versionHit() => {
'kind': 'version',
'target': 'pipeline:9:v2',
'recency': '2026-01-01T00:00:00Z',
'version': {
'pipeline_id': 9,
'version': 2,
'content_hash': 'abc',
'created_at': '2026-01-01T00:00:00Z',
},
};
JsonMap runHit([JsonMap overrides = const {}]) => {
'kind': 'run',
'target': 'run:11',
'run': {
'id': 11,
'pipeline_name': 'release',
'status': 'succeeded',
'created_at': '2026-01-01T00:00:00Z',
...overrides,
},
};
JsonMap stepHit([JsonMap overrides = const {}]) => {
'kind': 'step',
'target': 'run:11:4',
'step': {
'run_id': 11,
'sequence': 4,
'stage': 'builder',
'visit': 2,
'outcome': 'success',
...overrides,
},
};
JsonMap fieldHit([JsonMap overrides = const {}]) => {
'kind': 'field',
'target': 'run:11:4:output',
'matched_field': 'output',
'field': {
'run_id': 11,
'sequence': 4,
'field': 'output',
'snippet': 'the release is ready',
...overrides,
},
};
JsonMap artifactHit([JsonMap overrides = const {}]) => {
'kind': 'artifact',
'target': '/artifacts/11/4/notes.md',
'artifact': {
'run_id': 11,
'sequence': 4,
'name': 'notes.md',
'content_type': 'text/markdown',
'size_bytes': 2048,
...overrides,
},
};
void main() {
test('per-kind rows mirror the browser titles and secondary lines', () {
final pipeline = searchRowView(pipelineHit(), 'release');
expect(pipeline.title, 'release');
expect(pipeline.secondary, 'pipeline 7 · v3 · 4 stages');
expect(pipeline.kindLabel, 'Pipeline');
expect(pipeline.target, 'pipeline:7');
final blankName = searchRowView(pipelineHit({'name': ' '}), 'x');
expect(blankName.title, 'pipeline 7');
final version = searchRowView(versionHit(), 'release');
expect(version.title, 'pipeline 9 · v2');
expect(version.secondary, startsWith('content abc · '));
expect(version.recency, isNotNull);
final run = searchRowView(runHit(), 'release');
expect(run.title, 'run #11 · release');
expect(run.secondary, startsWith('succeeded · '));
expect(run.secondary.split(' · '), hasLength(2));
final unnamed = searchRowView(runHit({'pipeline_name': ''}), '');
expect(unnamed.title, 'run #11');
final step = searchRowView(stepHit({'target': '#success'}), '');
expect(step.title, 'run #11 · builder visit 2');
expect(step.secondary, 'success · → #success');
final artifact = searchRowView(artifactHit(), 'notes');
expect(artifact.title, 'notes.md');
expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB');
});
test('a field snippet marks the first case-insensitive query occurrence', () {
final row = searchRowView(fieldHit(), 'RELEASE');
expect(row.snippet, 'the release is ready');
expect(row.snippetSpans.map((span) => (span.text, span.matched)), [
('the ', false),
('release', true),
(' is ready', false),
]);
expect(row.snippetSpans.where((span) => span.matched), hasLength(1));
final absent = searchRowView(fieldHit({'snippet': 'no match'}), 'absent');
expect(absent.snippetSpans.single.matched, isFalse);
expect(absent.snippetSpans.single.text, 'no match');
final blank = searchRowView(fieldHit({'snippet': ''}), 'release');
expect(blank.snippetSpans, isEmpty);
});
test('unknown or targetless hits are read-only and never open a guess', () {
final unknown = searchRowView({
'kind': 'future_kind',
'target': 'widget:7',
}, 'x');
expect(unknown.title, 'widget:7');
expect(unknown.secondary, 'kind "future_kind" · read-only');
expect(unknown.openable, isFalse);
expect(unknown.target, isNull);
expect(unknown.kindLabel, 'Unrecognised result');
final targetless = searchRowView({
'kind': 'run',
'run': {'id': 11},
}, 'x');
expect(targetless.openable, isFalse);
expect(targetless.target, isNull);
expect(searchRowView(pipelineHit(), '').openable, isTrue);
expect(searchRowView(versionHit(), '').openable, isTrue);
expect(searchRowView(artifactHit(), '').openable, isTrue);
});
test('byte sizes use the shared binary rendering', () {
expect(humanBytes(0), '0 B');
expect(humanBytes(1023), '1023 B');
expect(humanBytes(1024), '1.0 KiB');
expect(humanBytes(2048), '2.0 KiB');
expect(humanBytes(1048576), '1.0 MiB');
});
}
@@ -0,0 +1,146 @@
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/search/search_screen.dart';
class RecordingGateway implements ApiGateway {
RecordingGateway(this.reply);
final JsonMap Function(String query, String kind) reply;
final calls = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(Map.of(fields));
final search = Map<String, dynamic>.from(fields['search'] as Map);
return reply(search['query'] as String, search['kind'] as String);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap response(
List<JsonMap> results, {
bool truncated = false,
int scannedSteps = 2,
int scannedBytes = 128,
}) => {
'search_results': {
'results': results,
'truncated': truncated,
'scanned_steps': scannedSteps,
'scanned_bytes': scannedBytes,
'cap': 50,
'scan_bound_bytes': 1 << 20,
},
};
final pipeline = {
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4},
};
Widget material(Widget child) => MaterialApp(home: child);
void main() {
testWidgets(
'a fresh screen sends no request and idle is not an empty result',
(tester) async {
final gateway = RecordingGateway((_, _) => response([pipeline]));
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
expect(gateway.calls, isEmpty);
expect(
find.text('Search pipelines, runs and artifacts.'),
findsOneWidget,
);
expect(find.textContaining('No matches'), findsNothing);
},
);
testWidgets('an empty server result shows the query-specific empty copy', (
tester,
) async {
final gateway = RecordingGateway((_, _) => response(const []));
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
await tester.enterText(find.byKey(const ValueKey('search.field')), 'zzz');
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect(gateway.calls, hasLength(1));
expect(find.text('No matches for "zzz".'), findsOneWidget);
expect(find.text('Searching…'), findsNothing);
});
testWidgets(
'a truncated empty reply keeps the server scan warning on screen',
(tester) async {
final gateway = RecordingGateway(
(_, _) => response(
const [],
truncated: true,
scannedSteps: 2000,
scannedBytes: 1048576,
),
);
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
await tester.enterText(
find.byKey(const ValueKey('search.field')),
'needle',
);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect(
find.text('No matches for "needle" within the server\'s scan limit.'),
findsOneWidget,
);
expect(find.textContaining('Results truncated'), findsOneWidget);
expect(find.textContaining('scanned 2000 steps'), findsOneWidget);
expect(find.textContaining('scan limit 1.0 MiB'), findsOneWidget);
},
);
testWidgets('changing Kind clears a typed token and requests the new kind', (
tester,
) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final gateway = RecordingGateway((_, _) => response([pipeline]));
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
await tester.enterText(
find.byKey(const ValueKey('search.field')),
'plan t:run',
);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect((gateway.calls.single['search'] as Map)['kind'], 'run');
await tester.tap(find.byKey(const ValueKey('search.kind')));
await tester.pumpAndSettle();
await tester.tap(find.text('Pipelines').last);
await tester.pumpAndSettle();
final field = tester.widget<SearchBar>(
find.byKey(const ValueKey('search.field')),
);
expect(field.controller!.text.trim(), 'plan');
expect(field.controller!.text, isNot(contains('t:run')));
expect((gateway.calls.last['search'] as Map)['kind'], 'pipeline');
});
}
@@ -0,0 +1,223 @@
import 'package:flutter/cupertino.dart';
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/search/domain/search_models.dart';
import 'package:pipelines_app/features/search/search_screen.dart';
class ImmediateGateway implements ApiGateway {
ImmediateGateway(this.reply);
final JsonMap Function(String query, String kind) reply;
final calls = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(Map.of(fields));
final search = Map<String, dynamic>.from(fields['search'] as Map);
return reply(search['query'] as String, search['kind'] as String);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
class FailingThenSucceedingGateway implements ApiGateway {
FailingThenSucceedingGateway(this.success);
final JsonMap success;
var calls = 0;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls++;
if (calls == 1) throw StateError('unknown command: search');
return success;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap hit({
required String kind,
required String target,
required Map<String, dynamic> payload,
}) => {'kind': kind, 'target': target, ...payload};
JsonMap response(List<JsonMap> results) => {
'search_results': {
'results': results,
'truncated': false,
'scanned_steps': 4,
'scanned_bytes': 512,
'cap': 50,
'scan_bound_bytes': 1 << 20,
},
};
final pipeline = hit(
kind: 'pipeline',
target: 'pipeline:7',
payload: {
'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4},
},
);
final field = hit(
kind: 'field',
target: 'run:11:4:output',
payload: {
'matched_field': 'output',
'field': {
'run_id': 11,
'sequence': 4,
'field': 'output',
'snippet': 'the release is ready',
},
},
);
void useNarrowSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
Widget largeText(Widget child) => MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2)),
child: child,
);
Future<void> search(WidgetTester tester, String query) async {
await tester.enterText(find.byKey(const ValueKey('search.field')), query);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
}
void main() {
for (final width in [390.0, 1000.0]) {
testWidgets(
'Material search is native and usable at width $width and 2x text',
(tester) async {
useNarrowSurface(tester);
tester.view.physicalSize = Size(width, 844);
final gateway = ImmediateGateway((_, _) => response([pipeline, field]));
JsonMap? opened;
await tester.pumpWidget(
MaterialApp(
home: largeText(
SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: false,
),
),
),
);
expect(find.byType(SearchBar), findsOneWidget);
expect(find.byType(DropdownButton<SearchKind>), findsOneWidget);
expect(find.text('All kinds'), findsOneWidget);
expect(gateway.calls, isEmpty);
await search(tester, 'release');
expect(gateway.calls.single, {
'search': {'query': 'release', 'kind': '', 'limit': 0},
});
expect(find.text('Release planner'), findsOneWidget);
expect(find.textContaining('the release is ready'), findsOneWidget);
expect(find.textContaining('4 results'), findsNothing);
expect(tester.takeException(), isNull);
await tester.tap(
find.byKey(const ValueKey('search.result.pipeline:7')),
);
expect(opened?['target'], 'pipeline:7');
expect(opened?['kind'], 'pipeline');
},
);
}
testWidgets(
'Cupertino search uses native controls and opens the real target',
(tester) async {
useNarrowSurface(tester);
final gateway = ImmediateGateway((_, _) => response([pipeline]));
JsonMap? opened;
await tester.pumpWidget(
CupertinoApp(
home: largeText(
SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: true,
),
),
),
);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
await search(tester, 'release');
expect(find.text('Release planner'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.tap(find.byKey(const ValueKey('search.result.pipeline:7')));
expect(opened?['target'], 'pipeline:7');
},
);
testWidgets('a read-only hit cannot be opened', (tester) async {
useNarrowSurface(tester);
final unknown = hit(
kind: 'future_kind',
target: 'widget:7',
payload: const {},
);
final gateway = ImmediateGateway((_, _) => response([unknown]));
JsonMap? opened;
await tester.pumpWidget(
MaterialApp(
home: SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: false,
),
),
);
await search(tester, 'widget');
expect(find.textContaining('read-only'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('search.result.widget:7')));
expect(opened, isNull);
});
testWidgets('an unsupported server shows its sentence and retry recovers', (
tester,
) async {
useNarrowSurface(tester);
final gateway = FailingThenSucceedingGateway(response([pipeline]));
await tester.pumpWidget(
MaterialApp(
home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false),
),
);
await search(tester, 'release');
expect(
find.text(
'This server does not support search. Update the Pipelines server, then try again.',
),
findsOneWidget,
);
expect(find.byKey(const ValueKey('search.retry')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('search.retry')));
await tester.pumpAndSettle();
expect(gateway.calls, 2);
expect(find.text('Release planner'), findsOneWidget);
expect(find.byKey(const ValueKey('search.retry')), findsNothing);
});
}
@@ -0,0 +1,50 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/data/search_repository.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
class QueuedGateway implements ApiGateway {
final calls = <JsonMap>[];
final pending = <Completer<JsonMap>>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add(Map.of(fields));
final completer = Completer<JsonMap>();
pending.add(completer);
return completer.future;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
void succeed(int index, JsonMap reply) => pending[index].complete(reply);
void fail(int index, Object error) => pending[index].completeError(error);
JsonMap get lastSearch =>
Map<String, dynamic>.from((calls.last['search'] as Map));
}
JsonMap envelope(
List<JsonMap> results, {
bool truncated = false,
int scannedSteps = 0,
int scannedBytes = 0,
int cap = 50,
int scanBoundBytes = 1 << 20,
}) => {
'search_results': {
'results': results,
'truncated': truncated,
'scanned_steps': scannedSteps,
'scanned_bytes': scannedBytes,
'cap': cap,
'scan_bound_bytes': scanBoundBytes,
},
};
OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController(
repository: SearchRepository(gateway),
debounce: Duration.zero,
);