Files
Docwell/Phone-App/test/widget_test.dart
T
tajniak81andClaude Opus 5.5 f20e5f96f9 Add search filters, space pins, find and replace and page layout
- Search can be narrowed by space, author and last change; the index
  records a mapping version and rebuilds when it changes.
- Editors can pin up to 12 pages to a space's home.
- Find and replace in the editor (Ctrl+F), with match case.
- Pages can be set to full width and a serif or mono font.
- Tailwind now scans the editor package, so its classes are generated.
- Fix golangci-lint findings, including push device names that were
  saved before being trimmed and capped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:35:18 +01:00

338 lines
11 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:convert';
import 'dart:io';
import 'package:docwell_mobile/api/docwell_api.dart';
import 'package:docwell_mobile/app.dart';
import 'package:docwell_mobile/screens/comments_screen.dart';
import 'package:docwell_mobile/screens/share_screen.dart';
import 'package:docwell_mobile/screens/space_screen.dart';
import 'package:docwell_mobile/session.dart';
import 'package:docwell_mobile/share.dart';
import 'package:flutter/material.dart' hide Page;
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
const ann = {
'id': 'u1',
'email': 'ann@docwell.test',
'name': 'Ann',
'avatar': '',
'locale': 'en',
'theme': 'system',
'status': 'active',
'verified': true,
'created': '2026-10-01 09:00:00.000Z',
'role': 'admin',
'organization': 'o1',
'organizationName': 'Acme',
'totp': false,
};
const workspace = {
'id': 'w1',
'name': 'Acme Docs',
'slug': 'acme',
'organization': 'o1',
'organizationName': 'Acme',
'role': 'owner',
'created': '2026-10-01 09:00:00.000Z',
};
const space = {
'id': 's1',
'workspace': 'w1',
'name': 'Guides',
'slug': 'guides',
'icon': '',
'description': 'How we work',
'visibility': 'open',
'defaultRole': 'editor',
'role': 'editor',
'limited': false,
'created': '2026-10-01 09:00:00.000Z',
};
Map<String, dynamic> node(String id, String parent, String title) => {
'id': id,
'parent': parent,
'title': title,
'icon': '',
'position': 'a',
'restricted': false,
'updated': '2026-10-01 09:00:00.000Z',
};
http.Response json(int status, Object body) => http.Response(
jsonEncode(body),
status,
headers: {'content-type': 'application/json'},
);
/// A fake docwell-server. [down] makes every request fail like a dropped
/// connection.
class FakeServer {
bool down = false;
final comments = <Map<String, dynamic>>[];
MockClient get client => MockClient((req) async {
if (down) throw const SocketException('offline');
final authed = req.headers['Authorization'] == 'Bearer tok';
switch ((req.method, req.url.path)) {
case ('POST', '/api/v1/auth/login'):
final body = jsonDecode(req.body) as Map<String, dynamic>;
if (body['password'] == 'password123') {
return json(200, {'token': 'tok', 'user': ann});
}
if (body['password'] == 'two-step') {
return json(401, {'error': 'totp_required', 'challenge': 'ch1'});
}
return json(401, {'error': 'invalid_credentials'});
case ('POST', '/api/v1/auth/totp/verify'):
final body = jsonDecode(req.body) as Map<String, dynamic>;
return body['challenge'] == 'ch1' && body['code'] == '123456'
? json(200, {'token': 'tok', 'user': ann})
: json(400, {'error': 'invalid_code'});
case ('POST', '/api/v1/auth/refresh'):
return authed
? json(200, {'token': 'tok', 'user': ann})
: json(401, {'error': 'unauthorized'});
}
if (!authed) return json(401, {'error': 'unauthorized'});
switch ((req.method, req.url.path)) {
case ('GET', '/api/v1/workspaces'):
return json(200, [workspace]);
case ('GET', '/api/v1/workspaces/w1/spaces'):
return json(200, [space]);
case ('GET', '/api/v1/workspaces/w1/recent'):
return json(200, []);
case ('GET', '/api/v1/notifications'):
return json(200, {'items': [], 'unread': 2});
case ('GET', '/api/v1/spaces/s1/pages'):
return json(200, [
node('p1', '', 'Setup'),
node('p2', 'p1', 'Details'),
]);
case ('GET', '/api/v1/pages/p1/comments'):
return json(200, comments);
case ('POST', '/api/v1/pages/p1/comments'):
final body = jsonDecode(req.body) as Map<String, dynamic>;
final c = {
'id': 'c${comments.length + 1}',
'parent': body['parent'] ?? '',
'page': 'p1',
'author': {'id': 'u1', 'email': 'ann@docwell.test', 'name': 'Ann'},
'body': body['body'],
'quote': '',
'anchor': null,
'created': '2026-10-01 09:00:00.000Z',
'editedAt': '',
'resolvedAt': '',
'resolvedBy': null,
'reactions': [],
'canEdit': true,
'canDelete': true,
'canResolve': true,
};
comments.add(c);
return json(201, c);
}
return json(404, {'error': 'not_found'});
});
DocwellApi api(String server, ResponseCache cache) =>
DocwellApi(server, client: client, cache: cache);
}
Future<void> signIn(WidgetTester tester, String password) async {
await tester.enterText(find.byKey(const Key('server')), 'server.test');
await tester.enterText(find.byKey(const Key('email')), 'ann@docwell.test');
await tester.enterText(find.byKey(const Key('password')), password);
await tester.tap(find.widgetWithText(FilledButton, 'Sign in'));
await tester.pumpAndSettle();
}
void main() {
late FakeServer server;
late MemorySessionStore sessions;
late MemoryCache cache;
setUp(() {
server = FakeServer();
sessions = MemorySessionStore();
cache = MemoryCache();
});
Widget app() =>
DocwellApp(sessions: sessions, apiFor: (url) => server.api(url, cache));
testWidgets('signs in, lists the workspace, and signs out', (tester) async {
await tester.pumpWidget(app());
await tester.pumpAndSettle();
await signIn(tester, 'wrong');
expect(find.text('Wrong email or password.'), findsOneWidget);
await signIn(tester, 'password123');
expect(find.text('Acme Docs'), findsOneWidget);
expect(find.text('Guides'), findsOneWidget);
expect(sessions.server, 'https://server.test');
expect(sessions.token, 'tok');
await tester.tap(find.byTooltip('Account'));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('sign-out')));
await tester.pumpAndSettle();
expect(find.text('Sign in to Docwell'), findsOneWidget);
expect(sessions.token, isNull);
});
testWidgets('asks for the authenticator code', (tester) async {
await tester.pumpWidget(app());
await tester.pumpAndSettle();
await signIn(tester, 'two-step');
expect(find.text('Two-step sign-in'), findsOneWidget);
await tester.enterText(find.byKey(const Key('code')), '123456');
await tester.tap(find.widgetWithText(FilledButton, 'Verify'));
await tester.pumpAndSettle();
expect(find.text('Guides'), findsOneWidget);
});
testWidgets('starts offline from the saved session and cache', (
tester,
) async {
// A first, online start fills the cache.
sessions
..server = 'https://server.test'
..token = 'tok';
await tester.pumpWidget(app());
await tester.pumpAndSettle();
expect(find.text('Guides'), findsOneWidget);
// Then the connection drops and the app starts again.
server.down = true;
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(app());
await tester.pumpAndSettle();
expect(find.byKey(const Key('offline')), findsOneWidget);
expect(find.text('Guides'), findsOneWidget);
// A dropped connection does not sign out.
expect(sessions.token, 'tok');
});
testWidgets('a rejected token signs out', (tester) async {
sessions
..server = 'https://server.test'
..token = 'expired';
await tester.pumpWidget(app());
await tester.pumpAndSettle();
expect(find.text('Sign in to Docwell'), findsOneWidget);
expect(sessions.token, isNull);
});
testWidgets('shows the page tree, folded', (tester) async {
final api = server.api('https://server.test', cache)..token = 'tok';
final session = AppSession(api: api, user: User.fromJson(ann));
await tester.pumpWidget(
MaterialApp(
home: SpaceScreen(session: session, space: Space.fromJson(space)),
),
);
await tester.pumpAndSettle();
expect(find.text('Setup'), findsOneWidget);
expect(find.text('Details'), findsNothing);
await tester.tap(find.byTooltip('Unfold'));
await tester.pumpAndSettle();
expect(find.text('Details'), findsOneWidget);
expect(find.byTooltip('New page'), findsOneWidget);
});
testWidgets('adds a comment and a reply', (tester) async {
final api = server.api('https://server.test', cache)..token = 'tok';
final session = AppSession(api: api, user: User.fromJson(ann));
final page = Page.fromJson({
'id': 'p1',
'workspace': 'w1',
'space': 's1',
'parent': '',
'title': 'Setup',
'icon': '',
'created': '',
'updated': '',
'deletedAt': '',
'inTrash': false,
'archivedAt': '',
'archived': false,
'ancestors': [],
'role': 'editor',
'restricted': false,
'isTemplate': false,
'favorite': false,
'pinnedAt': '',
'fullWidth': false,
'font': '',
});
await tester.pumpWidget(
MaterialApp(
home: CommentsScreen(session: session, page: page),
),
);
await tester.pumpAndSettle();
expect(find.text('No comments yet.'), findsOneWidget);
await tester.enterText(find.byKey(const Key('comment-text')), 'Looks good');
await tester.tap(find.byKey(const Key('comment-send')));
await tester.pumpAndSettle();
expect(find.text('Looks good'), findsOneWidget);
await tester.tap(find.text('Reply'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('comment-text')), 'Thanks');
await tester.tap(find.byKey(const Key('comment-send')));
await tester.pumpAndSettle();
expect(find.text('Thanks'), findsOneWidget);
expect(server.comments.last['parent'], 'c1');
});
test('tree rows get their depth', () {
final rows = treeRows([
PageNode.fromJson(node('a', '', 'A')),
PageNode.fromJson(node('b', 'a', 'B')),
PageNode.fromJson(node('c', 'b', 'C')),
PageNode.fromJson(node('d', '', 'D')),
]);
expect(rows.map((r) => r.depth), [0, 1, 2, 0]);
});
test('shared text becomes paragraphs with links', () {
final doc = sharedDoc('Read this\nhttps://example.com/a later');
final paras = doc['content'] as List;
expect(paras, hasLength(2));
final second = (paras[1] as Map)['content'] as List;
expect((second[0] as Map)['marks'], isNotNull);
expect((second[1] as Map)['text'], ' later');
expect(sharedTitle(const SharedText('first line\nsecond')), 'first line');
expect(sharedTitle(const SharedText('x', 'Article')), 'Article');
});
test(
'reads fall back to the cache only when the server is unreachable',
() async {
final api = server.api('https://server.test', cache)..token = 'tok';
expect((await api.workspaces()).single.name, 'Acme Docs');
expect(api.offline, isFalse);
server.down = true;
expect((await api.workspaces()).single.name, 'Acme Docs');
expect(api.offline, isTrue);
// Nothing cached: the error comes through.
await expectLater(api.pages('s1'), throwsA(isA<SocketException>()));
server.down = false;
// A refusal is never hidden behind the cache.
api.token = 'other';
await expectLater(api.workspaces(), throwsA(isA<DocwellApiException>()));
},
);
}