feat: compose Android app and verify native calendar and reminders

This commit is contained in:
Codex
2026-10-13 09:14:47 +08:00
parent 2c4256b880
commit 5ceab20b67
37 changed files with 695 additions and 229 deletions
@@ -8,7 +8,7 @@
<application
android:label="河畔Everyday"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@drawable/ic_hepan_launcher">
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" android:exported="false" />
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver" android:exported="false">
<intent-filter>
@@ -111,9 +111,9 @@ class CalendarBridge(private val activity: Activity, messenger: BinaryMessenger)
}
val id = args["eventId"] as? String
if (id != null && ownership(id, key, calendarId)) {
val count = resolver.update(ContentUris.withAppendedId(Events.CONTENT_URI,id.toLong()), values,
"${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=? AND ${Events.CALENDAR_ID}=?",
arrayOf(owner, marker(key), calendarId))
val count = resolver.update(Events.CONTENT_URI, values,
"${Events._ID}=? AND ${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=? AND ${Events.CALENDAR_ID}=? AND ${Events.DELETED}=0",
arrayOf(id, owner, marker(key), calendarId))
check(count==1) { "日程已被修改" }
return id
}
@@ -121,7 +121,7 @@ class CalendarBridge(private val activity: Activity, messenger: BinaryMessenger)
}
private fun delete(id: String, key: String) {
if (!ownership(id,key)) return
resolver.delete(ContentUris.withAppendedId(Events.CONTENT_URI,id.toLong()),
"${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=?", arrayOf(owner,marker(key)))
resolver.delete(Events.CONTENT_URI,
"${Events._ID}=? AND ${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=?", arrayOf(id,owner,marker(key)))
}
}
@@ -0,0 +1,7 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#348F91" android:pathData="M0,0h108v108h-108z" />
<path android:fillColor="#FFFFFF" android:pathData="M28,29h52v43h-52z" />
<path android:fillColor="#348F91" android:pathData="M32,41h44v27h-44z" />
<path android:strokeColor="#FFFFFF" android:strokeWidth="4" android:strokeLineCap="round" android:pathData="M40,25v12M68,25v12M36,79c12,-9 24,9 36,0" />
<path android:fillColor="#FFFFFF" android:pathData="M40,49h8v8h-8zM60,49h8v8h-8z" />
</vector>
+128
View File
@@ -0,0 +1,128 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/main.dart';
import 'package:hepan_everyday/data/file_snapshot_store.dart';
import 'package:hepan_everyday/data/json_schedule_import.dart';
import 'package:hepan_everyday/domain/app_settings.dart';
import 'package:hepan_everyday/domain/course.dart';
import 'package:hepan_everyday/features/profile/import_preview.dart';
import '../test/support/fakes.dart';
import '../test/domain/schedule_engine_test.dart' show course;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(tzdata.initializeTimeZones);
testWidgets(
'offline import, preview cancellation, color settings and reopening preserve saved courses',
(tester) async {
final directory = await Directory.systemTemp.createTemp(
'hepan-device-test-',
);
final store = FileSnapshotStore(directory);
final controller = AppController(
store,
FakeNotifications(),
FakeCalendar(),
() => DateTime.utc(2026, 9, 9),
);
await controller.initialize();
await tester.pumpWidget(buildApplication(controller));
await tester.pumpAndSettle();
expect(find.bySemanticsLabel('课表'), findsOneWidget);
await tester.tap(find.bySemanticsLabel('我的'));
await tester.pumpAndSettle();
await tester.tap(find.text('课表设置'));
await tester.pumpAndSettle();
await tester.tap(find.text('单色'));
await tester.pumpAndSettle();
expect(controller.snapshot.settings.colorMode, ColorMode.single);
// Native file chooser itself is verified manually; preview uses the same UI as file import.
await tester.scrollUntilVisible(find.byKey(const Key('semester-weeks')),300,
scrollable:find.byType(Scrollable).last);
await tester.ensureVisible(find.text('学期开始日'));
await tester.pumpAndSettle();
await tester.tap(find.text('学期开始日'));await tester.pumpAndSettle();
await tester.tap(find.text('确定'));await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('semester-weeks')),'5');
await tester.ensureVisible(find.text('保存学期设置'));
await tester.tap(find.text('保存学期设置'));await tester.pumpAndSettle();
expect(controller.snapshot.settings.semester!.totalWeeks,5);
expect(controller.snapshot.settings.semester!.startDate,DateTime.utc(2026,9,9));
final draft = ImportDraft(
courses: [course(last: 2)],
explicitlyEmpty: false,
source: CourseSource.file,
parserVersion: 'device-json-v1',
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (_) =>
ImportPreview(draft: draft, controller: controller),
),
child: const Text('预览文件'),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('预览文件'));
await tester.pumpAndSettle();
await tester.tap(find.text('取消'));
await tester.pumpAndSettle();
expect(controller.snapshot.courses, isEmpty);
await tester.tap(find.text('预览文件'));
await tester.pumpAndSettle();
await tester.tap(find.text('确认导入'));
await tester.pumpAndSettle();
expect(controller.snapshot.courses.single.id, 'math');
await tester.pumpWidget(buildApplication(controller));
await tester.pumpAndSettle();
expect(find.text('矩阵论'), findsOneWidget);
final before = await File('${directory.path}/hepan_snapshot.json')
.readAsString();
await controller.showDemo();
await tester.pumpAndSettle();
expect(find.text('示例课表'), findsOneWidget);
expect(
await File('${directory.path}/hepan_snapshot.json').readAsString(),
before,
);
await controller.applyImport(
const ImportDraft(
courses: [],
explicitlyEmpty: false,
source: CourseSource.file,
parserVersion: 'bad',
),
confirmedEmpty: false,
);
expect(controller.snapshot.courses.single.id, 'math');
final reopened = AppController(
store,
FakeNotifications(),
FakeCalendar(),
controller.clock,
);
await reopened.initialize();
expect(reopened.snapshot.courses.single.id, 'math');
expect(reopened.snapshot.settings.colorMode, ColorMode.single);
await tester.pumpWidget(const SizedBox());
controller.dispose();
reopened.dispose();
await directory.delete(recursive: true);
},
);
}
@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/services/android_calendar_service.dart';
import 'package:hepan_everyday/domain/schedule_engine.dart';
import '../test/domain/schedule_engine_test.dart' show course;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets(
'native dedicated calendar creates updates deduplicates and deletes owned events',
(tester) async {
tzdata.initializeTimeZones();
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
final gateway = MethodCalendarGateway();
final service = AndroidCalendarService(gateway);
expect(await service.requestAccess(),isTrue);
final calendars = await service.listWritableCalendars();
final selected = calendars.where(
(c) => c.name == 'Hepan_Integration_Test',
);
if (selected.isEmpty) {
fail('请先在专用模拟器建立 Hepan Integration Test 日历');
}
final id = selected.single.id;
final events = ScheduleEngine.occurrences([
course(last: 2),
], Semester(startDate: DateTime(2026, 9, 9), totalWeeks: 1));
var mapping = await service.sync(events, id, {});
expect(mapping, hasLength(1));
final original = mapping.values.single;
mapping = await service.sync(events, id, {}); // lost mapping recovery
expect(mapping.values.single, original);
expect(await gateway.ownedEvents(id), hasLength(1));
await gateway.delete(original, 'wrong-occurrence');
expect(await gateway.ownedEvents(id), hasLength(1));
await service.deleteOwned(mapping);
expect(await gateway.ownedEvents(id), isEmpty);
},
);
}
+41 -34
View File
@@ -170,40 +170,43 @@ class AppController extends ChangeNotifier {
}
calendarSyncError = null;
});
Future<void> enableCalendarFromUserAction(String calendarId) =>
_run(() async {
if (isDemo) throw StateError('示例课表不会导入日历');
if (snapshot.settings.semester == null) throw StateError('请先设置学期');
if (!await calendar.requestAccess()) {
calendarSyncError = '日历权限未获允许';
return;
}
if (snapshot.calendarCleanupPending) {
await _cleanupCalendar();
}
final calendars = await calendar.listWritableCalendars();
if (!calendars.any((c) => c.id == calendarId)) {
calendarSyncError = '请选择可写入的日历';
return;
}
final settings = snapshot.settings.copyWith(
calendarEnabled: true,
calendarId: calendarId,
);
try {
final ids = await calendar.sync(
ScheduleEngine.occurrences(snapshot.courses, settings.semester!),
calendarId,
snapshot.calendarEventIds,
);
await _save(
snapshot.copyWith(settings: settings, calendarEventIds: ids),
);
calendarSyncError = null;
} catch (_) {
calendarSyncError = '日历同步失败,可重试';
}
});
Future<void> enableCalendarFromUserAction(
String calendarId,
) => _run(() async {
if (isDemo) throw StateError('示例课表不会导入日历');
if (snapshot.settings.semester == null) throw StateError('请先设置学期');
if (!await calendar.requestAccess()) {
calendarSyncError = '日历权限未获允许';
return;
}
if (snapshot.calendarCleanupPending) {
await _cleanupCalendar();
}
final calendars = await calendar.listWritableCalendars();
if (!calendars.any((c) => c.id == calendarId)) {
calendarSyncError = '请选择可写入的日历';
return;
}
final settings = snapshot.settings.copyWith(
calendarEnabled: true,
calendarId: calendarId,
);
// Keep the chosen calendar for recovery if the first native sync fails midway.
await _save(
snapshot.copyWith(settings: settings.copyWith(calendarEnabled: false)),
);
try {
final ids = await calendar.sync(
ScheduleEngine.occurrences(snapshot.courses, settings.semester!),
calendarId,
snapshot.calendarEventIds,
);
await _save(snapshot.copyWith(settings: settings, calendarEventIds: ids));
calendarSyncError = null;
} catch (_) {
calendarSyncError = '日历同步失败,可重试';
}
});
Future<void> enableRemindersFromUserAction() => _run(() async {
if (isDemo) throw StateError('示例课表不会生成提醒');
await notifications.requestPermissions();
@@ -225,6 +228,10 @@ class AppController extends ChangeNotifier {
Future<void> _cleanupCalendar() async {
try {
await calendar.deleteOwned(snapshot.calendarEventIds);
final calendarId = snapshot.settings.calendarId;
if (calendarId != null) {
await calendar.deleteOwned(await calendar.ownedEventIds(calendarId));
}
await _save(
snapshot.copyWith(calendarEventIds: {}, calendarCleanupPending: false),
);
+48 -1
View File
@@ -1,4 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import '../domain/schedule_engine.dart';
import '../features/timetable/course_details.dart';
import 'app_controller.dart';
import 'app_theme.dart';
@@ -13,28 +17,40 @@ class HepanApp extends StatelessWidget {
required this.controller,
this.schoolBuilder,
this.school,
this.notificationSelection,
});
final AppController controller;
final Widget Function()? schoolBuilder;
final SchoolSession? school;
final ValueNotifier<String?>? notificationSelection;
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: '河畔Everyday',
theme: hepanTheme(),
locale: const Locale('zh', 'CN'),
supportedLocales: const [Locale('zh', 'CN')],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: _Shell(
controller: controller,
schoolBuilder: schoolBuilder,
school: school,
notificationSelection: notificationSelection,
),
);
}
class _Shell extends StatefulWidget {
const _Shell({required this.controller, this.schoolBuilder, this.school});
const _Shell({
required this.controller,
this.schoolBuilder,
this.school,
this.notificationSelection,
});
final AppController controller;
final Widget Function()? schoolBuilder;
final SchoolSession? school;
final ValueNotifier<String?>? notificationSelection;
@override
State<_Shell> createState() => _ShellState();
}
@@ -45,14 +61,45 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
widget.notificationSelection?.addListener(_selectNotification);
WidgetsBinding.instance.addPostFrameCallback((_) => _selectNotification());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
widget.notificationSelection?.removeListener(_selectNotification);
super.dispose();
}
Future<void> _selectNotification() async {
final key = widget.notificationSelection?.value;
if (key == null || !mounted) {
return;
}
widget.notificationSelection!.value = null;
await widget.controller.leaveDemo();
if (!mounted) {
return;
}
Navigator.of(context).popUntil((route) => route.isFirst);
setState(() => _tab = 0);
final semester = widget.controller.snapshot.settings.semester;
if (semester == null) {
return;
}
final events = ScheduleEngine.occurrences(
widget.controller.snapshot.courses,
semester,
).where((e) => e.key == key);
if (events.isNotEmpty) {
showCourseDetails(context, events.first);
} else {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('这门课程已更新,请查看当前课表')));
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
@@ -34,6 +34,16 @@ class _SettingsPageState extends State<SettingsPage> {
}
Future<void> _calendar(bool enabled) async {
try {
await _calendarAction(enabled);
} catch (_) {
if (mounted) {
_notice('日历暂时不可用,请检查权限后重试');
}
}
}
Future<void> _calendarAction(bool enabled) async {
final c = widget.controller;
if (enabled) {
if (!await c.calendar.requestAccess()) {
+41 -119
View File
@@ -1,122 +1,44 @@
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:timezone/data/latest.dart' as tzdata;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: .center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
import 'app/app_controller.dart';
import 'app/hepan_app.dart';
import 'data/file_snapshot_store.dart';
import 'services/local_notification_service.dart';
import 'services/android_calendar_service.dart';
import 'features/school/school_session.dart';
import 'features/school/school_auth_page.dart';
Widget buildApplication(
AppController controller, {
ValueNotifier<String?>? notificationSelection,
SchoolSession? school,
}) => HepanApp(
controller: controller,
notificationSelection: notificationSelection,
school: school,
schoolBuilder: school == null
? null
: () => SchoolAuthPage(session: school, controller: controller),
);
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
tzdata.initializeTimeZones();
final selection = ValueNotifier<String?>(null);
final gateway = PluginReminderGateway(onTap: (key) => selection.value = key);
final controller = AppController(
FileSnapshotStore(await getApplicationSupportDirectory()),
LocalNotificationService(gateway),
AndroidCalendarService(MethodCalendarGateway()),
DateTime.now,
);
await controller.initialize();
runApp(
buildApplication(
controller,
notificationSelection: selection,
school: SchoolSession(),
),
);
}
@@ -51,6 +51,11 @@ class AndroidCalendarService extends CalendarService {
AndroidCalendarService(this.gateway);
final CalendarGateway gateway;
@override
Future<Map<String, String>> ownedEventIds(String calendarId) async => {
for (final event in await gateway.ownedEvents(calendarId))
if (event.owned && event.calendarId == calendarId) event.key: event.id,
};
@override
Future<bool> requestAccess() => gateway.requestAccess();
@override
Future<List<DeviceCalendar>> listWritableCalendars() => gateway.calendars();
@@ -14,4 +14,6 @@ abstract class CalendarService {
Map<String, String> knownEventIds,
);
Future<void> deleteOwned(Map<String, String> eventIds);
Future<Map<String, String>> ownedEventIds(String calendarId) async =>
const {};
}
@@ -147,18 +147,27 @@ class PluginReminderGateway extends ReminderGateway {
final void Function(String key)? onTap;
final _plugin = FlutterLocalNotificationsPlugin();
Future<void>? _initializing;
Future<void> initialize() => _initializing ??= () async {
await _plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('ic_stat_calendar'),
),
onDidReceiveNotificationResponse: (response) => _select(response.payload),
);
final launch = await _plugin.getNotificationAppLaunchDetails();
if (launch?.didNotificationLaunchApp == true) {
_select(launch?.notificationResponse?.payload);
Future<void> initialize() => _initializing ??= Future<void>(() async {
try {
final ready = await _plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('ic_stat_calendar'),
),
onDidReceiveNotificationResponse: (response) =>
_select(response.payload),
);
if (ready != true) {
throw StateError('通知服务初始化失败');
}
final launch = await _plugin.getNotificationAppLaunchDetails();
if (launch?.didNotificationLaunchApp == true) {
_select(launch?.notificationResponse?.payload);
}
} catch (_) {
_initializing = null;
rethrow;
}
}();
});
void _select(String? payload) {
if (payload?.startsWith('hepan:') == true) {
onTap?.call(payload!.substring(6));
+13
View File
@@ -219,6 +219,11 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
flutter_localizations:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_test:
dependency: "direct dev"
description: flutter
@@ -263,6 +268,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
intl:
dependency: transitive
description:
name: intl
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.dev"
source: hosted
version: "0.20.3"
jni:
dependency: transitive
description:
+2
View File
@@ -7,6 +7,8 @@ environment:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
webview_flutter: 4.14.1
flutter_local_notifications: 22.3.2
timezone: 0.11.1
+26
View File
@@ -9,6 +9,9 @@ import 'package:hepan_everyday/data/json_schedule_import.dart';
import '../support/fakes.dart';
import '../domain/schedule_engine_test.dart' show course;
import '../services/calendar_service_test.dart' show CalendarProvider;
import 'package:hepan_everyday/services/android_calendar_service.dart';
void main() {
setUpAll(tzdata.initializeTimeZones);
@@ -35,6 +38,29 @@ void main() {
);
});
tearDown(() => controller.dispose());
test('turning off after interrupted first sync cleans events even without saved IDs', () async {
store.value = store.value!.copyWith(
courses: [
course(id: 'a'),
course(id: 'b'),
],
);
final provider = CalendarProvider()..failAfterFirst = true;
final interrupted = AppController(
store,
notifications,
AndroidCalendarService(provider),
controller.clock,
);
await interrupted.initialize();
await interrupted.enableCalendarFromUserAction('local');
expect(interrupted.calendarSyncError, isNotNull);
expect(provider.records, hasLength(1));
provider.failAfterFirst = false;
await interrupted.disableCalendar(deleteEvents: true);
expect(provider.records, isEmpty);
interrupted.dispose();
});
test(
'failed calendar cleanup is retried after reopening while sync is off',
() async {
@@ -0,0 +1,38 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hepan_everyday/services/local_notification_service.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('transient native initialization failure can be retried', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
AndroidFlutterLocalNotificationsPlugin.registerWith();
const channel = MethodChannel('dexterous.com/flutter/local_notifications');
var attempts = 0;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'initialize') {
attempts++;
if (attempts == 1) {
throw PlatformException(code: 'temporarily-unavailable');
}
return true;
}
if (call.method == 'getNotificationAppLaunchDetails') {
return {'notificationLaunchedApp': false};
}
return null;
});
addTearDown(() {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
final gateway = PluginReminderGateway();
await expectLater(gateway.initialize(), throwsA(isA<PlatformException>()));
await gateway.initialize();
expect(attempts, 2);
});
}
-30
View File
@@ -1,30 +0,0 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hepan_everyday/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
+39
View File
@@ -2,11 +2,44 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/app/hepan_app.dart';
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/features/profile/settings_page.dart';
import 'package:hepan_everyday/services/calendar_service.dart';
import '../support/fakes.dart';
import 'navigation_test.dart' show uiController;
void main() {
setUpAll(tzdata.initializeTimeZones);
testWidgets('calendar provider failure is explained and keeps switch off', (
tester,
) async {
final controller = AppController(
MemoryStore(),
FakeNotifications(),
UnavailableCalendar(),
DateTime.now,
);
await controller.initialize();
await tester.pumpWidget(
MaterialApp(home: SettingsPage(controller: controller)),
);
await tester.pumpAndSettle();
await tester.scrollUntilVisible(
find.text('导入手机日历'),
250,
scrollable: find.byType(Scrollable).first,
);
await tester.ensureVisible(find.text('导入手机日历'));
await tester.pumpAndSettle();
await tester.tap(find.text('导入手机日历'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('日历暂时不可用,请检查权限后重试'), findsOneWidget);
expect(controller.snapshot.settings.calendarEnabled, isFalse);
controller.dispose();
});
testWidgets(
'invalid semester weeks are rejected without changing saved data',
(tester) async {
@@ -57,3 +90,9 @@ void main() {
controller.dispose();
});
}
class UnavailableCalendar extends FakeCalendar {
@override
Future<List<DeviceCalendar>> listWritableCalendars() async =>
throw StateError('unavailable');
}
+56
View File
@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/main.dart';
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/app/hepan_app.dart';
import 'package:hepan_everyday/domain/app_snapshot.dart';
import 'package:hepan_everyday/domain/app_settings.dart';
import 'package:hepan_everyday/domain/semester.dart';
import '../support/fakes.dart';
import '../domain/schedule_engine_test.dart' show course;
void main() {
setUpAll(tzdata.initializeTimeZones);
testWidgets(
'actual startup connects both tabs and reminder tap opens saved course',
(tester) async {
final selection = ValueNotifier<String?>(null);
final controller = AppController(
MemoryStore(
AppSnapshot(
courses: [course(last: 2)],
settings: AppSettings(
semester: Semester(
startDate: DateTime(2026, 9, 9),
totalWeeks: 5,
),
),
),
),
FakeNotifications(),
FakeCalendar(),
() => DateTime.utc(2026, 9, 8),
);
await controller.initialize();
await tester.pumpWidget(
buildApplication(controller, notificationSelection: selection),
);
await tester.pumpAndSettle();
expect(find.bySemanticsLabel('课表'), findsOneWidget);
expect(find.bySemanticsLabel('我的'), findsOneWidget);
await tester.tap(find.bySemanticsLabel('我的'));
await tester.pumpAndSettle();
selection.value = 'math/2026-09-09';
await tester.pumpAndSettle();
expect(find.text('知道了'), findsOneWidget);
expect(find.textContaining('08:30–10:05'), findsOneWidget);
await tester.tap(find.text('知道了'));
await tester.pumpAndSettle();
expect(find.byType(HepanApp), findsOneWidget);
controller.dispose();
selection.dispose();
},
);
}
+62
View File
@@ -0,0 +1,62 @@
// Device-only fixture entry point. Never used by the distributable APK.
import 'package:flutter/material.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:timezone/timezone.dart' as tz;
import 'package:hepan_everyday/main.dart' show buildApplication;
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/domain/app_snapshot.dart';
import 'package:hepan_everyday/domain/app_settings.dart';
import 'package:hepan_everyday/domain/schedule_engine.dart';
import 'package:hepan_everyday/services/local_notification_service.dart';
import '../test/support/fakes.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
tzdata.initializeTimeZones();
final now = tz.TZDateTime.now(tz.getLocation('Asia/Shanghai'));
final date = DateTime.utc(now.year, now.month, now.day);
final course = Course(
id: 'native-probe',
name: '系统提醒验证(测试)',
teacher: '测试教师',
room: '测试教室',
weekday: now.weekday,
startPeriod: 1,
endPeriod: 2,
weeks: {1},
source: CourseSource.file,
);
final settings = AppSettings(
semester: Semester(startDate: date, totalWeeks: 1),
);
final selection = ValueNotifier<String?>(null);
final gateway = PluginReminderGateway(onTap: (key) => selection.value = key);
final service = LocalNotificationService(gateway);
const fireDelay = int.fromEnvironment(
'PROBE_DELAY_SECONDS',
defaultValue: 30,
);
final start = now.add(Duration(minutes: 15, seconds: fireDelay));
await service.reconcile(
[
CourseOccurrence(
key: 'native-probe/${date.toIso8601String().substring(0, 10)}',
course: course,
week: 1,
start: start,
end: start.add(const Duration(minutes: 95)),
),
],
settings,
now,
);
final controller = AppController(
MemoryStore(AppSnapshot(courses: [course], settings: settings)),
FakeNotifications(),
FakeCalendar(),
DateTime.now,
);
await controller.initialize();
runApp(buildApplication(controller, notificationSelection: selection));
}