1
0
forked from firka/firka

test: add e2e tests for widget screenshot comparison and notification diffing

This commit is contained in:
2026-09-08 07:20:39 +02:00
parent 394b7bfd70
commit 0f0b7c0c8b
7 changed files with 614 additions and 2 deletions

View File

@@ -28,6 +28,7 @@ steps:
commands:
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
- cd firka
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
- flutter pub get
- name: codegen
@@ -77,6 +78,36 @@ steps:
- dart pub get
- MOCK_KRETA_SERVER_URL=http://127.0.0.1:8090 dart test
- name: firka-e2e-tests
image: git.firka.app/firka/firka-builder:latest
commands:
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
- sleep 1
- cd firka
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
- cp $(find "$PUB_CACHE" -name libisar.so | grep linux | head -n 1) libisar.so 2>/dev/null || true
- flutter test test/data/widget_test.dart test/e2e/screenshot_widget_test.dart test/e2e/notification_diff_test.dart
- name: firka-integration-tests
image: git.firka.app/firka/firka-builder:latest
privileged: true
volumes:
- /dev/kvm:/dev/kvm
commands:
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
- 'grep -q "::1" /etc/hosts || echo "::1 localhost ip6-localhost ip6-loopback" >> /etc/hosts 2>/dev/null || true'
- sysctl -w net.ipv6.conf.all.disable_ipv6=0 2>/dev/null || true
- sed -i 's/TIMEOUT=60/TIMEOUT=300/' /opt/bin/start-emulator.sh
- sed -i 's/-snapshot default_boot/-no-snapshot-load/' /opt/bin/start-emulator.sh
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
- sleep 1
- /opt/bin/start-emulator.sh
- adb reverse tcp:8090 tcp:8090
- cd firka
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
- flutter test integration_test/widget_e2e_test.dart
- name: build-release
image: git.firka.app/firka/firka-builder:latest
when:

3
firka/.gitignore vendored
View File

@@ -52,4 +52,5 @@ app.*.map.json
coverage
# Generated files
*.g.dart
*.g.dart
libisar.so

View File

@@ -7,6 +7,10 @@
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
analyzer:
exclude:
- build/**
- android/**
include: package:flutter_lints/flutter.yaml
linter:

View File

@@ -15,6 +15,8 @@ class LocalNotificationService {
FlutterLocalNotificationsPlugin();
static bool _initialized = false;
static final List<({int id, String title, String body})> postedNotifications = [];
static Future<void> init() async {
if (_initialized) return;
@@ -38,6 +40,12 @@ class LocalNotificationService {
_initialized = true;
}
/// Returns active notifications currently shown in the system status bar (Android 6.0+).
static Future<List<ActiveNotification>> getActiveNotifications() async {
await init();
return await _plugin.getActiveNotifications();
}
/// Shows a single notification. [id] should be stable per logical
/// notification (e.g. derived from account key + category) so a repeat
/// wakeup that finds the same new items updates rather than duplicates it.
@@ -46,6 +54,8 @@ class LocalNotificationService {
required String title,
required String body,
}) async {
postedNotifications.add((id: id, title: title, body: body));
await init();
await _plugin.show(
id,

View File

@@ -9,7 +9,7 @@ const _lockFileName = 'codegen-lock.yaml';
void main() async {
final root = _projectRoot();
print(root);
stdout.writeln(root);
var ran = false;
if (_iconsOutOfDate(root)) {

View File

@@ -0,0 +1,318 @@
// ignore_for_file: depend_on_referenced_packages
import 'dart:convert';
import 'dart:io';
import 'package:firka/app/app_state.dart';
import 'package:firka/app/initialization.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/local_notification_service.dart';
import 'package:firka/services/notification_diff_service.dart';
import 'package:firka_common/data/database.dart';
import 'package:firka_common/data/models/token_model.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:kreta_api/kreta_api.dart';
import 'package:logging/logging.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
const _mockServerUrl = 'http://127.0.0.1:8090';
class _RealHttpOverrides extends HttpOverrides {}
Future<TokenGrantResponse> _authenticateMockServer(HttpClient httpClient) async {
final loginReq = await httpClient.getUrl(Uri.parse('$_mockServerUrl/Account/Login'));
final loginResp = await loginReq.close();
final loginBody = await loginResp.transform(utf8.decoder).join();
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
if (match == null) {
throw Exception('Failed to extract code from mock server login: $loginBody');
}
final code = match.group(1)!;
final tokenReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/connect/token'));
tokenReq.headers.contentType = ContentType('application', 'x-www-form-urlencoded');
tokenReq.write('grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}');
final tokenResp = await tokenReq.close();
final tokenBody = await tokenResp.transform(utf8.decoder).join();
if (tokenResp.statusCode != 200) {
throw Exception('Token request failed (${tokenResp.statusCode}): $tokenBody');
}
return TokenGrantResponse.fromJson(jsonDecode(tokenBody) as Map<String, dynamic>);
}
Future<void> _postItem(HttpClient httpClient, String endpoint, Map<String, dynamic> item) async {
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl$endpoint'));
req.headers.contentType = ContentType.json;
req.write(jsonEncode(item));
final resp = await req.close();
if (resp.statusCode != 200 && resp.statusCode != 204) {
final body = await resp.transform(utf8.decoder).join();
throw Exception('POST $endpoint failed (${resp.statusCode}): $body');
}
}
Future<void> _seedMockLessonsToday(HttpClient httpClient) async {
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/today'));
final resp = await req.close();
if (resp.statusCode != 200) {
final body = await resp.transform(utf8.decoder).join();
throw Exception('Failed to shift lessons to today (${resp.statusCode}): $body');
}
}
class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform
with MockPlatformInterfaceMixin {
Future<bool?> initialize(
InitializationSettings initializationSettings, {
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
void Function(NotificationResponse)? onDidReceiveBackgroundNotificationResponse,
}) async => true;
@override
Future<void> show(
int id,
String? title,
String? body, {
NotificationDetails? notificationDetails,
String? payload,
}) async {}
@override
Future<List<ActiveNotification>> getActiveNotifications() async => [];
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
HttpOverrides.global = _RealHttpOverrides();
FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform();
logger = Logger("NotificationDiffTest");
group('Notification System End-to-End Test with Mock Kreta Server', () {
late HttpClient httpClient;
setUp(() {
HttpOverrides.global = _RealHttpOverrides();
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(MethodCall methodCall) async => Directory.systemTemp.path,
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('dev.fluttercommunity.plus/package_info'),
(MethodCall methodCall) async => {
'appName': 'firka',
'packageName': 'app.firka.naplo',
'version': '1.0.0',
'buildNumber': '1',
},
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('firka.app/main'),
(MethodCall methodCall) async => 'SM-A705FN;11;30',
);
});
tearDown(() {
httpClient.close(force: true);
});
testWidgets('Synthetic FCM wakeup diffs changes correctly and posts notifications', (tester) async {
HttpOverrides.global = _RealHttpOverrides();
await tester.runAsync(() async {
await _seedMockLessonsToday(httpClient);
final isar = await initDB();
await isar.writeTxn(() async {
await isar.clear();
});
Settings = SettingsRepository(isar);
await Settings.loadAll();
await Settings.mockBackendEnabled.set(true);
await Settings.mockBackendUrl.set(_mockServerUrl);
await Settings.notifyAll.set(true);
await Settings.notifyGrades.set(true);
await Settings.notifyHomeworkTests.set(true);
await Settings.notifyLessons.set(true);
await Settings.notifyAbsences.set(true);
await Settings.notifyMessages.set(true);
await Settings.notifyMutedSubjects.set('[]');
final tokenResp = await _authenticateMockServer(httpClient);
final tokenModel = TokenModel.fromResp(tokenResp);
await isar.writeTxn(() async {
await isar.tokenModels.clear();
await isar.tokenModels.put(tokenModel);
});
await initializeApp();
expect(initDone, isTrue);
if (initData.client != null) {
await initData.client!.init();
await initData.client!.renewCache(reInit: false);
}
LocalNotificationService.postedNotifications.clear();
await NotificationDiffService.checkAll();
expect(LocalNotificationService.postedNotifications, isEmpty);
LocalNotificationService.postedNotifications.clear();
final newGradeUid = 'test-grade-${DateTime.now().millisecondsSinceEpoch}';
final newGradeTime = DateTime.now().toUtc().toIso8601String();
await _postItem(httpClient, '/admin/api/grades', {
'Uid': newGradeUid,
'RogzitesDatuma': newGradeTime,
'KeszitesDatuma': newGradeTime,
'Tantargy': {
'Uid': '10,INF',
'Nev': 'Informatika',
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
'SortIndex': 10,
},
'Tema': 'Algoritmusok',
'Tipus': {'Uid': '1', 'Nev': 'Gyakorlati feladat'},
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
'ErtekeloTanarNeve': 'Turing Alan',
'Jelleg': 'Ertekeles',
'SzamErtek': 5,
'SzovegesErtek': 'Jeles',
'SulySzazalekErteke': 100,
'OsztalyCsoport': {'Uid': '10,11.A'},
});
await NotificationDiffService.checkAll();
expect(LocalNotificationService.postedNotifications, isNotEmpty);
final gradeNotif = LocalNotificationService.postedNotifications.firstWhere(
(n) => n.title.contains('jegy'),
);
expect(gradeNotif.title, contains('jegy'));
expect(gradeNotif.body, contains('Informatika'));
LocalNotificationService.postedNotifications.clear();
final newHwUid = 'test-hw-${DateTime.now().millisecondsSinceEpoch}';
final newHwTime = DateTime.now().toUtc().toIso8601String();
await _postItem(httpClient, '/admin/api/homework', {
'Uid': newHwUid,
'Tantargy': {
'Uid': '11,BIO',
'Nev': 'Biológia',
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
'SortIndex': 11,
},
'TantargyNeve': 'Biológia',
'RogzitoTanarNeve': 'Darwin Károly',
'Szoveg': 'Olvassátok el a sejtbiológia fejezetet.',
'FeladasDatuma': newHwTime,
'HataridoDatuma': DateTime.now().add(const Duration(days: 3)).toUtc().toIso8601String(),
'RogzitesIdopontja': newHwTime,
'IsTanarRogzitette': true,
'IsMegoldva': false,
'IsBeadhato': false,
'OsztalyCsoport': {'Uid': '10,11.A'},
});
await NotificationDiffService.checkAll();
expect(LocalNotificationService.postedNotifications, isNotEmpty);
final hwNotif = LocalNotificationService.postedNotifications.firstWhere(
(n) => n.title.contains('házi feladat'),
);
expect(hwNotif.title, contains('házi feladat'));
expect(hwNotif.body, contains('Biológia'));
LocalNotificationService.postedNotifications.clear();
await _postItem(httpClient, '/admin/api/timetable/mutate', {
'Uid': '5000',
'Nev': 'Matematika',
'HelyettesTanarNeve': 'Prof. Helyettes',
'Allapot': {
'Uid': '1',
'Nev': 'Megtartott',
'Leiras': 'Megtartott óra',
},
'Tipus': {
'Uid': '1',
'Nev': 'Tanóra',
'Leiras': 'Tanóra',
},
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
});
await NotificationDiffService.checkAll();
expect(LocalNotificationService.postedNotifications, isNotEmpty);
final subNotif = LocalNotificationService.postedNotifications.firstWhere(
(n) => n.title.contains('Helyettesítés'),
);
expect(subNotif.title, equals('Helyettesítés'));
expect(subNotif.body, contains('Prof. Helyettes'));
LocalNotificationService.postedNotifications.clear();
await _postItem(httpClient, '/admin/api/timetable/mutate', {
'Uid': '5000',
'Nev': 'Matematika',
'Allapot': {
'Uid': '3',
'Nev': 'Elmaradt',
'Leiras': 'Elmaradt óra',
},
'Tipus': {
'Uid': 'UresOra',
'Nev': 'UresOra',
'Leiras': 'Lyukasóra',
},
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
});
await NotificationDiffService.checkAll();
expect(LocalNotificationService.postedNotifications, isNotEmpty);
final cancelNotif = LocalNotificationService.postedNotifications.firstWhere(
(n) => n.title.contains('Elmaradt óra'),
);
expect(cancelNotif.title, equals('Elmaradt óra'));
LocalNotificationService.postedNotifications.clear();
await Settings.notifyMutedSubjects.set(jsonEncode(['Fizika']));
final mutedGradeUid = 'test-grade-muted-${DateTime.now().millisecondsSinceEpoch}';
final mutedGradeTime = DateTime.now().toUtc().toIso8601String();
await _postItem(httpClient, '/admin/api/grades', {
'Uid': mutedGradeUid,
'RogzitesDatuma': mutedGradeTime,
'KeszitesDatuma': mutedGradeTime,
'Tantargy': {
'Uid': '12,FIZ',
'Nev': 'Fizika',
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
'SortIndex': 12,
},
'Tema': 'Mechanika',
'Tipus': {'Uid': '1', 'Nev': 'Írásbeli'},
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
'ErtekeloTanarNeve': 'Newton Izsák',
'Jelleg': 'Ertekeles',
'SzamErtek': 5,
'SzovegesErtek': 'Jeles',
'SulySzazalekErteke': 100,
'OsztalyCsoport': {'Uid': '10,11.A'},
});
await NotificationDiffService.checkAll();
final fizikaNotifs = LocalNotificationService.postedNotifications
.where((n) => n.body.contains('Fizika') || n.body.contains('Newton'))
.toList();
expect(fizikaNotifs, isEmpty);
});
});
});
}

View File

@@ -0,0 +1,248 @@
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
const _mockServerUrl = 'http://127.0.0.1:8090';
class _RealHttpOverrides extends HttpOverrides {}
Future<List<Map<String, dynamic>>> _getMockLessons(HttpClient httpClient) async {
final req = await httpClient.getUrl(Uri.parse('$_mockServerUrl/admin/api/timetable'));
final resp = await req.close();
final body = await resp.transform(utf8.decoder).join();
final list = jsonDecode(body) as List;
return list.cast<Map<String, dynamic>>();
}
Future<void> _putMockLessons(HttpClient httpClient, List<Map<String, dynamic>> lessons) async {
final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl/admin/api/timetable'));
req.headers.contentType = ContentType.json;
req.write(jsonEncode(lessons));
final resp = await req.close();
if (resp.statusCode != 204 && resp.statusCode != 200) {
final body = await resp.transform(utf8.decoder).join();
throw Exception('Failed to update mock lessons (${resp.statusCode}): $body');
}
}
Future<void> _seedMockLessonsToday(HttpClient httpClient) async {
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/today'));
final resp = await req.close();
if (resp.statusCode != 200) {
final body = await resp.transform(utf8.decoder).join();
throw Exception('Failed to shift lessons to today (${resp.statusCode}): $body');
}
}
class TimetableWidgetView extends StatelessWidget {
final GlobalKey boundaryKey;
final List<Map<String, dynamic>> lessons;
const TimetableWidgetView({
required this.boundaryKey,
required this.lessons,
super.key,
});
@override
Widget build(BuildContext context) {
const bgColor = Color(0xFFFAFFF0);
const cardColor = Color(0xFFEFF4E3);
const textPrimary = Color(0xFF1B1C18);
const textSecondary = Color(0xFF45483D);
const warningColor = Color(0xFFE65100);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: bgColor,
body: Center(
child: RepaintBoundary(
key: boundaryKey,
child: Container(
width: 320,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(16),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Mai órarend',
style: TextStyle(
color: textSecondary,
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 12),
for (final lesson in lessons.take(4))
Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: lesson['HelyettesTanarNeve'] != null &&
(lesson['HelyettesTanarNeve'] as String).isNotEmpty
? warningColor.withValues(alpha: 0.15)
: cardColor,
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Text(
'${lesson['Oraszam'] ?? 1}.',
style: const TextStyle(
color: textSecondary,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
lesson['Nev'] as String? ?? '',
style: const TextStyle(
color: textPrimary,
fontWeight: FontWeight.w600,
),
),
if (lesson['HelyettesTanarNeve'] != null &&
(lesson['HelyettesTanarNeve'] as String).isNotEmpty)
Text(
'Helyettes: ${lesson['HelyettesTanarNeve']}',
style: const TextStyle(
color: warningColor,
fontSize: 12,
),
),
],
),
),
if (lesson['TeremNeve'] != null)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: textSecondary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(6),
),
child: Text(
lesson['TeremNeve'] as String,
style: const TextStyle(
color: textSecondary,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
],
),
),
),
),
),
);
}
}
Future<List<int>> _capturePng(WidgetTester tester, GlobalKey key) async {
return await tester.runAsync(() async {
final boundary = key.currentContext!.findRenderObject() as RenderRepaintBoundary;
final image = await boundary.toImage(pixelRatio: 2.0);
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return byteData!.buffer.asUint8List().toList();
}) ?? [];
}
int _countDifferentBytes(List<int> a, List<int> b) {
int diff = 0;
final minLen = a.length < b.length ? a.length : b.length;
for (int i = 0; i < minLen; i++) {
if (a[i] != b[i]) diff++;
}
diff += (a.length - b.length).abs();
return diff;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
HttpOverrides.global = _RealHttpOverrides();
group('Widget End-to-End Screenshot Comparison Test', () {
late HttpClient httpClient;
late List<Map<String, dynamic>> originalLessons;
setUp(() async {
HttpOverrides.global = _RealHttpOverrides();
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
originalLessons = await _getMockLessons(httpClient);
});
tearDown(() async {
try {
await _putMockLessons(httpClient, originalLessons);
} catch (_) {}
httpClient.close(force: true);
});
testWidgets('Widget screenshots differ programmatically after mock server timetable mutation', (tester) async {
HttpOverrides.global = _RealHttpOverrides();
late List<Map<String, dynamic>> lessonsBefore;
await tester.runAsync(() async {
await _seedMockLessonsToday(httpClient);
lessonsBefore = await _getMockLessons(httpClient);
});
expect(lessonsBefore.isNotEmpty, isTrue);
final boundaryKey1 = GlobalKey();
await tester.pumpWidget(TimetableWidgetView(boundaryKey: boundaryKey1, lessons: lessonsBefore));
await tester.pump();
final screenshotBefore = await _capturePng(tester, boundaryKey1);
expect(screenshotBefore, isNotEmpty);
late List<Map<String, dynamic>> lessonsAfter;
final targetName = lessonsBefore.first['Nev'];
await tester.runAsync(() async {
final mutateReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/mutate'));
mutateReq.headers.contentType = ContentType.json;
mutateReq.write(jsonEncode({
'Uid': lessonsBefore.first['Uid'],
'Nev': targetName,
'TeremNeve': 'LAB-999',
'HelyettesTanarNeve': 'Prof. E2E Teszt',
}));
final mutateResp = await mutateReq.close();
expect(mutateResp.statusCode, equals(200));
lessonsAfter = await _getMockLessons(httpClient);
});
final targetLesson = lessonsAfter.firstWhere((l) => l['Nev'] == targetName);
expect(targetLesson['TeremNeve'], equals('LAB-999'));
expect(targetLesson['HelyettesTanarNeve'], equals('Prof. E2E Teszt'));
final boundaryKey2 = GlobalKey();
await tester.pumpWidget(TimetableWidgetView(boundaryKey: boundaryKey2, lessons: lessonsAfter));
await tester.pump();
final screenshotAfter = await _capturePng(tester, boundaryKey2);
expect(screenshotAfter, isNotEmpty);
expect(screenshotBefore, isNot(equals(screenshotAfter)));
expect(_countDifferentBytes(screenshotBefore, screenshotAfter), greaterThan(0));
});
});
}