From b7eca00b6f143630ada8474d24a46d5351f548cc Mon Sep 17 00:00:00 2001 From: Fadi George Date: Mon, 9 Nov 2026 11:31:14 -0800 Subject: [PATCH 1/2] feat: add FlutterFramework SwiftPM dependency FlutterFramework requires Flutter 3.41+, so raise the minimum Flutter and Dart SDK constraints accordingly. Co-Authored-By: Claude Opus 5.5 --- ios/onesignal_flutter/Package.swift | 2 ++ pubspec.yaml | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ios/onesignal_flutter/Package.swift b/ios/onesignal_flutter/Package.swift index 6377bdc8..bb9ec2bf 100644 --- a/ios/onesignal_flutter/Package.swift +++ b/ios/onesignal_flutter/Package.swift @@ -12,6 +12,7 @@ func oneSignalEnvFlag(_ name: String) -> Bool { let oneSignalDisableLocation = oneSignalEnvFlag("ONESIGNAL_DISABLE_LOCATION") var oneSignalDependencies: [Target.Dependency] = [ + .product(name: "FlutterFramework", package: "FlutterFramework"), .product(name: "OneSignalFramework", package: "OneSignal-XCFramework"), .product(name: "OneSignalInAppMessages", package: "OneSignal-XCFramework"), .product(name: "OneSignalExtension", package: "OneSignal-XCFramework"), @@ -30,6 +31,7 @@ let package = Package( .library(name: "onesignal-flutter", targets: ["onesignal_flutter"]) ], dependencies: [ + .package(name: "FlutterFramework", path: "../FlutterFramework"), .package(url: "https://github.com/OneSignal/OneSignal-XCFramework", exact: "5.8.1"), ], targets: [ diff --git a/pubspec.yaml b/pubspec.yaml index 8f959393..ada3d259 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -31,5 +31,5 @@ dev_dependencies: rps: ^0.9.1 environment: - sdk: ">=2.12.0 <4.0.0" - flutter: ">=2.0.0" + sdk: ^3.11.0 + flutter: ">=3.41.0" From 43d5268cdc1f6fcad2dd50c76bc1057f2ed22d74 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Mon, 9 Nov 2026 11:31:14 -0800 Subject: [PATCH 2/2] chore: apply Dart 3.x tall format style Raising the SDK minimum switches dart format to the tall style. Formatting only, no code changes. Co-Authored-By: Claude Opus 5.5 --- lib/onesignal_flutter.dart | 24 ++- lib/src/debug.dart | 10 +- lib/src/defines.dart | 2 +- lib/src/inappmessage.dart | 13 +- lib/src/inappmessages.dart | 39 ++-- lib/src/liveactivities.dart | 40 ++-- lib/src/notification.dart | 36 ++-- lib/src/notifications.dart | 75 ++++--- lib/src/pushsubscription.dart | 11 +- lib/src/session.dart | 6 +- lib/src/subscription.dart | 19 +- lib/src/user.dart | 12 +- test/debug_test.dart | 24 ++- test/inappmessage_test.dart | 20 +- test/inappmessages_test.dart | 64 +++--- test/liveactivities_test.dart | 69 ++++--- test/mock_channel.dart | 111 ++++++----- test/notification_test.dart | 216 ++++++++++---------- test/notifications_test.dart | 344 ++++++++++++++++++-------------- test/pushsubscription_test.dart | 4 +- test/session_test.dart | 33 +-- test/subscription_test.dart | 22 +- test/user_test.dart | 63 ++---- test/utils_test.dart | 10 +- 24 files changed, 686 insertions(+), 581 deletions(-) diff --git a/lib/onesignal_flutter.dart b/lib/onesignal_flutter.dart index 974140db..e33c3152 100644 --- a/lib/onesignal_flutter.dart +++ b/lib/onesignal_flutter.dart @@ -65,8 +65,9 @@ class OneSignal { /// user context to that specific user. static Future login(String externalId) async { if (isMissing(externalId, 'login: externalId')) return; - return await _channel - .invokeMethod('OneSignal#login', {'externalId': externalId}); + return await _channel.invokeMethod('OneSignal#login', { + 'externalId': externalId, + }); } /// Login to OneSignal under the user identified by the [externalId] provided. @@ -74,11 +75,14 @@ class OneSignal { /// The act of logging a user into the OneSignal SDK will switch the /// user context to that specific user. @Deprecated( - 'Do not use, this method is not implemented. See https://documentation.onesignal.com/docs/identity-verification for updates.') + 'Do not use, this method is not implemented. See https://documentation.onesignal.com/docs/identity-verification for updates.', + ) static Future loginWithJWT(String externalId, String jwt) async { if (defaultTargetPlatform == TargetPlatform.android) { - return await _channel.invokeMethod( - 'OneSignal#loginWithJWT', {'externalId': externalId, 'jwt': jwt}); + return await _channel.invokeMethod('OneSignal#loginWithJWT', { + 'externalId': externalId, + 'jwt': jwt, + }); } } @@ -96,15 +100,17 @@ class OneSignal { /// This field is only relevant when the application has /// opted into data privacy protections. See [consentRequired]. static Future consentGiven(bool granted) async { - return await _channel - .invokeMethod("OneSignal#consentGiven", {'granted': granted}); + return await _channel.invokeMethod("OneSignal#consentGiven", { + 'granted': granted, + }); } /// Allows you to completely disable the SDK until your app calls the /// OneSignal.consentGiven(true) function. This is useful if you want /// to show a Terms and Conditions or privacy popup for GDPR. static Future consentRequired(bool require) async { - return await _channel - .invokeMethod("OneSignal#consentRequired", {'required': require}); + return await _channel.invokeMethod("OneSignal#consentRequired", { + 'required': require, + }); } } diff --git a/lib/src/debug.dart b/lib/src/debug.dart index 8169a10a..706b3c38 100644 --- a/lib/src/debug.dart +++ b/lib/src/debug.dart @@ -11,8 +11,9 @@ class OneSignalDebug { /// The parameter [logLevel] controls /// how verbose logs in the console/logcat are Future setLogLevel(OSLogLevel logLevel) async { - return await _channel - .invokeMethod("OneSignal#setLogLevel", {'logLevel': logLevel.index}); + return await _channel.invokeMethod("OneSignal#setLogLevel", { + 'logLevel': logLevel.index, + }); } /// Sets the log level for the SDK. @@ -20,7 +21,8 @@ class OneSignalDebug { /// The parameter [visualLevel] controls /// if the SDK will show alerts for each logged message Future setAlertLevel(OSLogLevel visualLevel) async { - return await _channel.invokeMethod( - "OneSignal#setAlertLevel", {'visualLevel': visualLevel.index}); + return await _channel.invokeMethod("OneSignal#setAlertLevel", { + 'visualLevel': visualLevel.index, + }); } } diff --git a/lib/src/defines.dart b/lib/src/defines.dart index 77b04665..ae9f2638 100644 --- a/lib/src/defines.dart +++ b/lib/src/defines.dart @@ -24,7 +24,7 @@ enum OSiOSSettings { inAppAlerts, inAppLaunchUrl, promptBeforeOpeningPushUrl, - inFocusDisplayOption + inFocusDisplayOption, } enum OSSession { DIRECT, INDIRECT, UNATTRIBUTED, DISABLED } diff --git a/lib/src/inappmessage.dart b/lib/src/inappmessage.dart index c8f4960a..1d9449a7 100644 --- a/lib/src/inappmessage.dart +++ b/lib/src/inappmessage.dart @@ -10,8 +10,9 @@ class OSInAppMessageClickEvent extends JSONStringRepresentable { OSInAppMessageClickEvent(Map json) { this.message = OSInAppMessage(json["message"].cast()); - this.result = - OSInAppMessageClickResult(json["result"].cast()); + this.result = OSInAppMessageClickResult( + json["result"].cast(), + ); } String jsonRepresentation() { @@ -42,10 +43,10 @@ class OSInAppMessageClickResult extends JSONStringRepresentable { } Map mapRepresentation() => { - 'action_id': this.actionId, - 'url': this.url, - 'closing_message': this.closingMessage, - }; + 'action_id': this.actionId, + 'url': this.url, + 'closing_message': this.closingMessage, + }; String jsonRepresentation() => convertToJsonString(mapRepresentation()); } diff --git a/lib/src/inappmessages.dart b/lib/src/inappmessages.dart index 638cce43..66b873f4 100644 --- a/lib/src/inappmessages.dart +++ b/lib/src/inappmessages.dart @@ -8,13 +8,17 @@ import 'package:onesignal_flutter/src/utils.dart'; typedef void OnClickInAppMessageListener(OSInAppMessageClickEvent event); typedef void OnWillDisplayInAppMessageListener( - OSInAppMessageWillDisplayEvent event); + OSInAppMessageWillDisplayEvent event, +); typedef void OnDidDisplayInAppMessageListener( - OSInAppMessageDidDisplayEvent event); + OSInAppMessageDidDisplayEvent event, +); typedef void OnWillDismissInAppMessageListener( - OSInAppMessageWillDismissEvent event); + OSInAppMessageWillDismissEvent event, +); typedef void OnDidDismissInAppMessageListener( - OSInAppMessageDidDismissEvent event); + OSInAppMessageDidDismissEvent event, +); class OneSignalInAppMessages { // private channels used to bridge to ObjC/Java @@ -86,27 +90,36 @@ class OneSignalInAppMessages { if (call.method == 'OneSignal#onClickInAppMessage') { for (var listener in _clickListeners) { listener( - OSInAppMessageClickEvent(call.arguments.cast())); + OSInAppMessageClickEvent(call.arguments.cast()), + ); } } else if (call.method == 'OneSignal#onWillDisplayInAppMessage') { for (var listener in _willDisplayListeners) { - listener(OSInAppMessageWillDisplayEvent( - call.arguments.cast())); + listener( + OSInAppMessageWillDisplayEvent( + call.arguments.cast(), + ), + ); } } else if (call.method == 'OneSignal#onDidDisplayInAppMessage') { for (var listener in _didDisplayListeners) { - listener(OSInAppMessageDidDisplayEvent( - call.arguments.cast())); + listener( + OSInAppMessageDidDisplayEvent(call.arguments.cast()), + ); } } else if (call.method == 'OneSignal#onWillDismissInAppMessage') { for (var listener in _willDismissListeners) { - listener(OSInAppMessageWillDismissEvent( - call.arguments.cast())); + listener( + OSInAppMessageWillDismissEvent( + call.arguments.cast(), + ), + ); } } else if (call.method == 'OneSignal#onDidDismissInAppMessage') { for (var listener in _didDismissListeners) { - listener(OSInAppMessageDidDismissEvent( - call.arguments.cast())); + listener( + OSInAppMessageDidDismissEvent(call.arguments.cast()), + ); } } return null; diff --git a/lib/src/liveactivities.dart b/lib/src/liveactivities.dart index 7791df22..60cc98cd 100644 --- a/lib/src/liveactivities.dart +++ b/lib/src/liveactivities.dart @@ -16,8 +16,10 @@ class OneSignalLiveActivities { return; } if (defaultTargetPlatform == TargetPlatform.iOS) { - return await _channel.invokeMethod("OneSignal#enterLiveActivity", - {'activityId': activityId, 'token': token}); + return await _channel.invokeMethod("OneSignal#enterLiveActivity", { + 'activityId': activityId, + 'token': token, + }); } } @@ -28,8 +30,9 @@ class OneSignalLiveActivities { Future exitLiveActivity(String activityId) async { if (isMissing(activityId, 'exitLiveActivity: activityId')) return; if (defaultTargetPlatform == TargetPlatform.iOS) { - return await _channel.invokeMethod( - "OneSignal#exitLiveActivity", {'activityId': activityId}); + return await _channel.invokeMethod("OneSignal#exitLiveActivity", { + 'activityId': activityId, + }); } } @@ -55,8 +58,9 @@ class OneSignalLiveActivities { }; } - return await _channel - .invokeMethod("OneSignal#setupDefault", {'options': optionsMap}); + return await _channel.invokeMethod("OneSignal#setupDefault", { + 'options': optionsMap, + }); } } @@ -67,7 +71,10 @@ class OneSignalLiveActivities { /// /// Only applies to iOS. Future startDefault( - String activityId, dynamic attributes, dynamic content) async { + String activityId, + dynamic attributes, + dynamic content, + ) async { if (isMissing(activityId, 'startDefault: activityId') || !_isMap(attributes, 'startDefault: attributes') || !_isMap(content, 'startDefault: content')) { @@ -77,7 +84,7 @@ class OneSignalLiveActivities { return await _channel.invokeMethod("OneSignal#startDefault", { 'activityId': activityId, 'attributes': attributes, - 'content': content + 'content': content, }); } } @@ -94,8 +101,10 @@ class OneSignalLiveActivities { return; } if (defaultTargetPlatform == TargetPlatform.iOS) { - return await _channel.invokeMethod("OneSignal#setPushToStartToken", - {'activityType': activityType, 'token': token}); + return await _channel.invokeMethod("OneSignal#setPushToStartToken", { + 'activityType': activityType, + 'token': token, + }); } } @@ -109,8 +118,9 @@ class OneSignalLiveActivities { return; } if (defaultTargetPlatform == TargetPlatform.iOS) { - return await _channel.invokeMethod( - "OneSignal#removePushToStartToken", {'activityType': activityType}); + return await _channel.invokeMethod("OneSignal#removePushToStartToken", { + 'activityType': activityType, + }); } } @@ -129,6 +139,8 @@ class LiveActivitySetupOptions { /// When true, OneSignal will listen for pushToUpdate tokens for each started live activity. final bool enablePushToUpdate; - LiveActivitySetupOptions( - {this.enablePushToStart = true, this.enablePushToUpdate = true}); + LiveActivitySetupOptions({ + this.enablePushToStart = true, + this.enablePushToUpdate = true, + }); } diff --git a/lib/src/notification.dart b/lib/src/notification.dart index e187b900..f5a6a708 100644 --- a/lib/src/notification.dart +++ b/lib/src/notification.dart @@ -221,7 +221,8 @@ class OSNotification extends JSONStringRepresentable { this.androidNotificationId = json['androidNotificationId'] as int?; if (json.containsKey('backgroundImageLayout')) { this.backgroundImageLayout = OSAndroidBackgroundImageLayout( - json['backgroundImageLayout'].cast()); + json['backgroundImageLayout'].cast(), + ); } if (json.containsKey('groupedNotifications')) { final dynamic jsonGroupedNotifications = json['groupedNotifications']; @@ -229,8 +230,10 @@ class OSNotification extends JSONStringRepresentable { ? jsonDecode(jsonGroupedNotifications) as List : jsonGroupedNotifications as List; this.groupedNotifications = jsonList - .map((dynamic item) => - OSNotification((item as Map).cast())) + .map( + (dynamic item) => + OSNotification((item as Map).cast()), + ) .toList(); } @@ -277,8 +280,9 @@ class OSNotification extends JSONStringRepresentable { if (this.launchUrl != null) 'launchUrl': this.launchUrl, if (this.additionalData != null) 'additionalData': this.additionalData, if (this.buttons != null) - 'buttons': - this.buttons!.map((button) => button.mapRepresentation()).toList(), + 'buttons': this.buttons! + .map((button) => button.mapRepresentation()) + .toList(), if (this.rawPayload != null) 'rawPayload': this.rawPayload, if (this.attachments != null) 'attachments': this.attachments, if (this.contentAvailable != null) @@ -292,8 +296,7 @@ class OSNotification extends JSONStringRepresentable { if (this.interruptionLevel != null) 'interruptionLevel': this.interruptionLevel, if (this.groupedNotifications != null) - 'groupedNotifications': this - .groupedNotifications! + 'groupedNotifications': this.groupedNotifications! .map((notification) => notification.mapRepresentation()) .toList(), if (this.androidNotificationId != null) @@ -313,8 +316,8 @@ class OSNotification extends JSONStringRepresentable { if (this.collapseId != null) 'collapseId': this.collapseId, if (this.priority != null) 'priority': this.priority, if (this.backgroundImageLayout != null) - 'backgroundImageLayout': - this.backgroundImageLayout!.mapRepresentation(), + 'backgroundImageLayout': this.backgroundImageLayout! + .mapRepresentation(), }; } @@ -334,8 +337,10 @@ class OSNotificationClickResult extends JSONStringRepresentable { this.url = json['url']; } - Map mapRepresentation() => - {'action_id': this.actionId, 'url': this.url}; + Map mapRepresentation() => { + 'action_id': this.actionId, + 'url': this.url, + }; String jsonRepresentation() => convertToJsonString(mapRepresentation()); } @@ -423,7 +428,7 @@ class OSAndroidBackgroundImageLayout extends JSONStringRepresentable { return { 'image': this.image, 'titleTextColor': this.titleTextColor, - 'bodyTextColor': this.bodyTextColor + 'bodyTextColor': this.bodyTextColor, }; } @@ -448,8 +453,9 @@ class OSNotificationWillDisplayEvent extends JSONStringRepresentable { } String jsonRepresentation() { - return convertToJsonString( - {'notification': this.notification.mapRepresentation()}); + return convertToJsonString({ + 'notification': this.notification.mapRepresentation(), + }); } } @@ -469,7 +475,7 @@ class OSNotificationClickEvent extends JSONStringRepresentable { String jsonRepresentation() { return convertToJsonString({ 'notification': this.notification.mapRepresentation(), - 'result': this.result.mapRepresentation() + 'result': this.result.mapRepresentation(), }); } } diff --git a/lib/src/notifications.dart b/lib/src/notifications.dart index 3952a643..1d76b46e 100644 --- a/lib/src/notifications.dart +++ b/lib/src/notifications.dart @@ -9,7 +9,8 @@ import 'package:onesignal_flutter/src/utils.dart'; typedef void OnNotificationPermissionChangeObserver(bool permission); typedef void OnNotificationWillDisplayListener( - OSNotificationWillDisplayEvent event); + OSNotificationWillDisplayEvent event, +); typedef void OnNotificationClickListener(OSNotificationClickEvent event); @@ -60,8 +61,9 @@ class OneSignalNotifications { /// ephemeral, // only available in iOS 14 Future permissionNative() async { if (defaultTargetPlatform == TargetPlatform.iOS) { - return OSNotificationPermission - .values[await _channel.invokeMethod("OneSignal#permissionNative")]; + return OSNotificationPermission.values[await _channel.invokeMethod( + "OneSignal#permissionNative", + )]; } else { return _permission ? OSNotificationPermission.authorized @@ -78,20 +80,25 @@ class OneSignalNotifications { /// Removes a single notification. Future removeNotification(int notificationId) async { if (defaultTargetPlatform == TargetPlatform.android) { - return await _channel.invokeMethod( - "OneSignal#removeNotification", {'notificationId': notificationId}); + return await _channel.invokeMethod("OneSignal#removeNotification", { + 'notificationId': notificationId, + }); } } /// Removes a grouped notification. Future removeGroupedNotifications(String notificationGroup) async { if (isMissing( - notificationGroup, 'removeGroupedNotifications: notificationGroup')) { + notificationGroup, + 'removeGroupedNotifications: notificationGroup', + )) { return; } if (defaultTargetPlatform == TargetPlatform.android) { - return await _channel.invokeMethod("OneSignal#removeGroupedNotifications", - {'notificationGroup': notificationGroup}); + return await _channel.invokeMethod( + "OneSignal#removeGroupedNotifications", + {'notificationGroup': notificationGroup}, + ); } } @@ -103,17 +110,20 @@ class OneSignalNotifications { /// Prompt the user for permission to receive push notifications. This will display the native /// system prompt to request push notification permission. Future requestPermission(bool fallbackToSettings) async { - return await _channel.invokeMethod("OneSignal#requestPermission", - {'fallbackToSettings': fallbackToSettings}); + return await _channel.invokeMethod("OneSignal#requestPermission", { + 'fallbackToSettings': fallbackToSettings, + }); } /// Instead of having to prompt the user for permission to send them push notifications, /// your app can request provisional authorization. Future registerForProvisionalAuthorization( - bool fallbackToSettings) async { + bool fallbackToSettings, + ) async { if (defaultTargetPlatform == TargetPlatform.iOS) { - return await _channel - .invokeMethod("OneSignal#registerForProvisionalAuthorization"); + return await _channel.invokeMethod( + "OneSignal#registerForProvisionalAuthorization", + ); } else { return false; } @@ -128,7 +138,8 @@ class OneSignalNotifications { // Remove a push subscription observer that has been previously added. void removePermissionObserver( - OnNotificationPermissionChangeObserver observer) { + OnNotificationPermissionChangeObserver observer, + ) { _observers.remove(observer); } @@ -142,8 +153,9 @@ class OneSignalNotifications { Future _handleMethod(MethodCall call) async { if (call.method == 'OneSignal#onClickNotification') { - var event = - OSNotificationClickEvent(call.arguments.cast()); + var event = OSNotificationClickEvent( + call.arguments.cast(), + ); if (_clickListeners.isNotEmpty) { for (var listener in _clickListeners) { listener(event); @@ -159,13 +171,18 @@ class OneSignalNotifications { } } else if (call.method == 'OneSignal#onWillDisplayNotification') { for (var listener in _willDisplayListeners) { - listener(OSNotificationWillDisplayEvent( - call.arguments.cast())); + listener( + OSNotificationWillDisplayEvent( + call.arguments.cast(), + ), + ); } var event = OSNotificationWillDisplayEvent( - call.arguments.cast()); - _channel.invokeMethod("OneSignal#proceedWithWillDisplay", - {'notificationId': event.notification.notificationId}); + call.arguments.cast(), + ); + _channel.invokeMethod("OneSignal#proceedWithWillDisplay", { + 'notificationId': event.notification.notificationId, + }); } else if (call.method == 'OneSignal#onNotificationPermissionDidChange') { this.onNotificationPermissionDidChange(call.arguments["permission"]); } @@ -179,25 +196,29 @@ class OneSignalNotifications { } void addForegroundWillDisplayListener( - OnNotificationWillDisplayListener listener) { + OnNotificationWillDisplayListener listener, + ) { _willDisplayListeners.add(listener); } void removeForegroundWillDisplayListener( - OnNotificationWillDisplayListener listener) { + OnNotificationWillDisplayListener listener, + ) { _willDisplayListeners.remove(listener); } /// The notification willDisplay listener is called whenever a notification arrives /// and the application is in foreground void preventDefault(String notificationId) { - _channel.invokeMethod( - "OneSignal#preventDefault", {'notificationId': notificationId}); + _channel.invokeMethod("OneSignal#preventDefault", { + 'notificationId': notificationId, + }); } void displayNotification(String notificationId) { - _channel.invokeMethod( - "OneSignal#displayNotification", {'notificationId': notificationId}); + _channel.invokeMethod("OneSignal#displayNotification", { + 'notificationId': notificationId, + }); } /// The notification click listener is called whenever the user opens a diff --git a/lib/src/pushsubscription.dart b/lib/src/pushsubscription.dart index 88ee4552..7ef74439 100644 --- a/lib/src/pushsubscription.dart +++ b/lib/src/pushsubscription.dart @@ -3,7 +3,8 @@ import 'package:flutter/services.dart'; import 'package:onesignal_flutter/src/subscription.dart'; typedef void OnPushSubscriptionChangeObserver( - OSPushSubscriptionChangedState stateChanges); + OSPushSubscriptionChangedState stateChanges, +); class OneSignalPushSubscription { MethodChannel _channel = const MethodChannel('OneSignal#pushsubscription'); @@ -72,14 +73,16 @@ class OneSignalPushSubscription { // Private function that gets called by ObjC/Java Future _handleMethod(MethodCall call) async { if (call.method == 'OneSignal#onPushSubscriptionChange') { - this._onPushSubscriptionChange(OSPushSubscriptionChangedState( - call.arguments.cast())); + this._onPushSubscriptionChange( + OSPushSubscriptionChangedState(call.arguments.cast()), + ); } return null; } void _onPushSubscriptionChange( - OSPushSubscriptionChangedState stateChanges) async { + OSPushSubscriptionChangedState stateChanges, + ) async { this._id = stateChanges.current.id; this._token = stateChanges.current.token; this._optedIn = stateChanges.current.optedIn; diff --git a/lib/src/session.dart b/lib/src/session.dart index 511edc45..8c34d312 100644 --- a/lib/src/session.dart +++ b/lib/src/session.dart @@ -28,7 +28,9 @@ class OneSignalSession { logError('addOutcomeWithValue: value must be a finite number'); return; } - return await _channel.invokeMethod("OneSignal#addOutcomeWithValue", - {"outcome_name": name, "outcome_value": value}); + return await _channel.invokeMethod("OneSignal#addOutcomeWithValue", { + "outcome_name": name, + "outcome_value": value, + }); } } diff --git a/lib/src/subscription.dart b/lib/src/subscription.dart index 36af1f74..c0adeae6 100644 --- a/lib/src/subscription.dart +++ b/lib/src/subscription.dart @@ -15,8 +15,11 @@ class OSPushSubscriptionState extends JSONStringRepresentable { this.optedIn = json['optedIn'] as bool; } - Map mapRepresentation() => - {'id': this.id, 'token': this.token, 'optedIn': this.optedIn}; + Map mapRepresentation() => { + 'id': this.id, + 'token': this.token, + 'optedIn': this.optedIn, + }; String jsonRepresentation() => convertToJsonString(mapRepresentation()); } @@ -30,17 +33,19 @@ class OSPushSubscriptionChangedState extends JSONStringRepresentable { OSPushSubscriptionChangedState(Map json) { if (json.containsKey('current')) - this.current = - OSPushSubscriptionState(json['current'].cast()); + this.current = OSPushSubscriptionState( + json['current'].cast(), + ); if (json.containsKey('previous')) - this.previous = - OSPushSubscriptionState(json['previous'].cast()); + this.previous = OSPushSubscriptionState( + json['previous'].cast(), + ); } String jsonRepresentation() { return convertToJsonString({ 'current': current.mapRepresentation(), - 'previous': previous.mapRepresentation() + 'previous': previous.mapRepresentation(), }); } } diff --git a/lib/src/user.dart b/lib/src/user.dart index 3fef9665..cf04c6b8 100644 --- a/lib/src/user.dart +++ b/lib/src/user.dart @@ -19,9 +19,9 @@ class OSUserState extends JSONStringRepresentable { } Map mapRepresentation() => { - 'onesignalId': this.onesignalId, - 'externalId': this.externalId, - }; + 'onesignalId': this.onesignalId, + 'externalId': this.externalId, + }; String jsonRepresentation() => convertToJsonString(mapRepresentation()); } @@ -207,8 +207,10 @@ class OneSignalUser { /// /// [name] is the event name to track. /// [properties] is an optional map of custom properties associated with the event. - Future trackEvent(String name, - [Map? properties]) async { + Future trackEvent( + String name, [ + Map? properties, + ]) async { if (isMissing(name, 'trackEvent: name')) return; return await _channel.invokeMethod("OneSignal#trackEvent", { 'name': name, diff --git a/test/debug_test.dart b/test/debug_test.dart index b56d07d8..734b8d8c 100644 --- a/test/debug_test.dart +++ b/test/debug_test.dart @@ -16,21 +16,25 @@ void main() { group('OneSignalDebug', () { group('setLogLevel', () { for (final logLevel in OSLogLevel.values) { - test('sets log level to ${logLevel.toString().split('.').last}', - () async { - await OneSignal.Debug.setLogLevel(logLevel); - expect(channelController.state.logLevel, logLevel); - }); + test( + 'sets log level to ${logLevel.toString().split('.').last}', + () async { + await OneSignal.Debug.setLogLevel(logLevel); + expect(channelController.state.logLevel, logLevel); + }, + ); } }); group('setAlertLevel', () { for (final logLevel in OSLogLevel.values) { - test('sets alert level to ${logLevel.toString().split('.').last}', - () async { - await OneSignal.Debug.setAlertLevel(logLevel); - expect(channelController.state.visualLevel, logLevel); - }); + test( + 'sets alert level to ${logLevel.toString().split('.').last}', + () async { + await OneSignal.Debug.setAlertLevel(logLevel); + expect(channelController.state.visualLevel, logLevel); + }, + ); } }); }); diff --git a/test/inappmessage_test.dart b/test/inappmessage_test.dart index be5bb927..a4f9684f 100644 --- a/test/inappmessage_test.dart +++ b/test/inappmessage_test.dart @@ -2,9 +2,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:onesignal_flutter/src/inappmessage.dart'; import 'package:onesignal_flutter/src/utils.dart'; -const validMessageJson = { - 'message_id': 'test-message-id-123', -}; +const validMessageJson = {'message_id': 'test-message-id-123'}; const validClickResultJson = { 'action_id': 'action-123', @@ -78,9 +76,7 @@ void main() { }); test('creates from minimal JSON', () { - final json = { - 'closing_message': false, - }; + final json = {'closing_message': false}; final result = OSInAppMessageClickResult(json); expect(result.actionId, isNull); @@ -98,9 +94,7 @@ void main() { }); test('jsonRepresentation handles null optional fields', () { - final json = { - 'closing_message': false, - }; + final json = {'closing_message': false}; final result = OSInAppMessageClickResult(json); final jsonString = result.jsonRepresentation(); @@ -128,9 +122,7 @@ void main() { test('creates from JSON with minimal fields', () { final json = { 'message': validMessageJson, - 'result': { - 'closing_message': false, - }, + 'result': {'closing_message': false}, }; final event = OSInAppMessageClickEvent(json); @@ -142,9 +134,7 @@ void main() { test('jsonRepresentation returns correct JSON string', () { final json = { - 'message': { - 'message_id': 'test-message-id-123', - }, + 'message': {'message_id': 'test-message-id-123'}, 'result': { 'action_id': 'action-123', 'url': 'https://example.com', diff --git a/test/inappmessages_test.dart b/test/inappmessages_test.dart index ae7a61f2..86175dba 100644 --- a/test/inappmessages_test.dart +++ b/test/inappmessages_test.dart @@ -4,9 +4,7 @@ import 'package:onesignal_flutter/src/inappmessages.dart'; import 'mock_channel.dart'; -const validMessageJson = { - 'message_id': 'test-message-id-123', -}; +const validMessageJson = {'message_id': 'test-message-id-123'}; const validClickResultJson = { 'action_id': 'action-123', @@ -47,17 +45,16 @@ void main() { }); group('addTriggers', () { - test('invokes OneSignal#addTriggers method with map of triggers', - () async { - final triggers = { - 'purchase_made': 'true', - 'user_level': '5', - }; + test( + 'invokes OneSignal#addTriggers method with map of triggers', + () async { + final triggers = {'purchase_made': 'true', 'user_level': '5'}; - await inAppMessages.addTriggers(triggers); + await inAppMessages.addTriggers(triggers); - expect(channelController.state.triggers, triggers); - }); + expect(channelController.state.triggers, triggers); + }, + ); test('handles empty triggers map', () async { await inAppMessages.addTriggers({}); @@ -75,14 +72,16 @@ void main() { }); group('removeTriggers', () { - test('invokes OneSignal#removeTriggers method with list of keys', - () async { - final keys = ['trigger1', 'trigger2']; + test( + 'invokes OneSignal#removeTriggers method with list of keys', + () async { + final keys = ['trigger1', 'trigger2']; - await inAppMessages.removeTriggers(keys); + await inAppMessages.removeTriggers(keys); - expect(channelController.state.removedTriggers, keys); - }); + expect(channelController.state.removedTriggers, keys); + }, + ); test('handles empty keys list', () async { await inAppMessages.removeTriggers([]); @@ -112,13 +111,15 @@ void main() { }); group('arePaused', () { - test('invokes OneSignal#arePaused method and returns correct value', - () async { - await inAppMessages.paused(true); - final result = await inAppMessages.arePaused(); + test( + 'invokes OneSignal#arePaused method and returns correct value', + () async { + await inAppMessages.paused(true); + final result = await inAppMessages.arePaused(); - expect(result, true); - }); + expect(result, true); + }, + ); test('returns false when not paused', () async { final result = await inAppMessages.arePaused(); @@ -147,10 +148,7 @@ void main() { channelController.simulateInAppMessageEvent( 'OneSignal#onClickInAppMessage', - { - 'message': validMessageJson, - 'result': validClickResultJson, - }, + {'message': validMessageJson, 'result': validClickResultJson}, ); expect(listenerCalled, true); @@ -168,10 +166,7 @@ void main() { channelController.simulateInAppMessageEvent( 'OneSignal#onClickInAppMessage', - { - 'message': validMessageJson, - 'result': validClickResultJson, - }, + {'message': validMessageJson, 'result': validClickResultJson}, ); expect(listenerCalled, false); @@ -369,10 +364,7 @@ void main() { channelController.simulateInAppMessageEvent( 'OneSignal#onClickInAppMessage', - { - 'message': validMessageJson, - 'result': validClickResultJson, - }, + {'message': validMessageJson, 'result': validClickResultJson}, ); expect(listenerCount, 2); diff --git a/test/liveactivities_test.dart b/test/liveactivities_test.dart index e15cc2b7..8b65e5ba 100644 --- a/test/liveactivities_test.dart +++ b/test/liveactivities_test.dart @@ -27,14 +27,16 @@ void main() { }); group('enterLiveActivity', () { - test('invokes OneSignal#enterLiveActivity with activityId and token', - () async { - await liveActivities.enterLiveActivity(activityId, token); - - expect(channelController.state.liveActivityEntered, true); - expect(channelController.state.liveActivityId, activityId); - expect(channelController.state.liveActivityToken, token); - }); + test( + 'invokes OneSignal#enterLiveActivity with activityId and token', + () async { + await liveActivities.enterLiveActivity(activityId, token); + + expect(channelController.state.liveActivityEntered, true); + expect(channelController.state.liveActivityId, activityId); + expect(channelController.state.liveActivityToken, token); + }, + ); test('rejects empty activityId or token', () async { await liveActivities.enterLiveActivity('', token); @@ -120,12 +122,19 @@ void main() { }; await liveActivities.startDefault( - activityId, complexAttributes, complexContent); + activityId, + complexAttributes, + complexContent, + ); - expect(channelController.state.liveActivityAttributes['nested']['key'], - 'value'); - expect(channelController.state.liveActivityContent['data']['status'], - 'running'); + expect( + channelController.state.liveActivityAttributes['nested']['key'], + 'value', + ); + expect( + channelController.state.liveActivityContent['data']['status'], + 'running', + ); }); test('rejects empty activityId', () async { @@ -143,14 +152,16 @@ void main() { }); group('setPushToStartToken', () { - test('invokes OneSignal#setPushToStartToken with activityType and token', - () async { - await liveActivities.setPushToStartToken(activityType, token); - - expect(channelController.state.liveActivityPushToStartSet, true); - expect(channelController.state.liveActivityType, activityType); - expect(channelController.state.liveActivityPushToken, token); - }); + test( + 'invokes OneSignal#setPushToStartToken with activityType and token', + () async { + await liveActivities.setPushToStartToken(activityType, token); + + expect(channelController.state.liveActivityPushToStartSet, true); + expect(channelController.state.liveActivityType, activityType); + expect(channelController.state.liveActivityPushToken, token); + }, + ); test('rejects empty activityType or token', () async { await liveActivities.setPushToStartToken('', token); @@ -161,13 +172,15 @@ void main() { }); group('removePushToStartToken', () { - test('invokes OneSignal#removePushToStartToken with activityType', - () async { - await liveActivities.removePushToStartToken(activityType); - - expect(channelController.state.liveActivityPushToStartRemoved, true); - expect(channelController.state.liveActivityType, activityType); - }); + test( + 'invokes OneSignal#removePushToStartToken with activityType', + () async { + await liveActivities.removePushToStartToken(activityType); + + expect(channelController.state.liveActivityPushToStartRemoved, true); + expect(channelController.state.liveActivityType, activityType); + }, + ); test('rejects empty activityType', () async { await liveActivities.removePushToStartToken(''); diff --git a/test/mock_channel.dart b/test/mock_channel.dart index 20d3a8b2..b0efbd2b 100644 --- a/test/mock_channel.dart +++ b/test/mock_channel.dart @@ -12,18 +12,24 @@ class OneSignalMockChannelController { final MethodChannel _channel = const MethodChannel('OneSignal'); final MethodChannel _debugChannel = const MethodChannel('OneSignal#debug'); final MethodChannel _tagsChannel = const MethodChannel('OneSignal#tags'); - final MethodChannel _locationChannel = - const MethodChannel('OneSignal#location'); - final MethodChannel _inAppMessagesChannel = - const MethodChannel('OneSignal#inappmessages'); - final MethodChannel _liveActivitiesChannel = - const MethodChannel('OneSignal#liveactivities'); - final MethodChannel _notificationsChannel = - const MethodChannel('OneSignal#notifications'); - final MethodChannel _pushSubscriptionChannel = - const MethodChannel('OneSignal#pushsubscription'); - final MethodChannel _sessionChannel = - const MethodChannel('OneSignal#session'); + final MethodChannel _locationChannel = const MethodChannel( + 'OneSignal#location', + ); + final MethodChannel _inAppMessagesChannel = const MethodChannel( + 'OneSignal#inappmessages', + ); + final MethodChannel _liveActivitiesChannel = const MethodChannel( + 'OneSignal#liveactivities', + ); + final MethodChannel _notificationsChannel = const MethodChannel( + 'OneSignal#notifications', + ); + final MethodChannel _pushSubscriptionChannel = const MethodChannel( + 'OneSignal#pushsubscription', + ); + final MethodChannel _sessionChannel = const MethodChannel( + 'OneSignal#session', + ); final MethodChannel _userChannel = const MethodChannel('OneSignal#user'); late OneSignalState state; @@ -59,29 +65,32 @@ class OneSignalMockChannelController { void simulatePushSubscriptionChange(Map changeData) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage( - _pushSubscriptionChannel.name, - _pushSubscriptionChannel.codec.encodeMethodCall( - MethodCall('OneSignal#onPushSubscriptionChange', changeData), - ), - (ByteData? data) {}, - ); + _pushSubscriptionChannel.name, + _pushSubscriptionChannel.codec.encodeMethodCall( + MethodCall('OneSignal#onPushSubscriptionChange', changeData), + ), + (ByteData? data) {}, + ); } // Helper method to simulate user state changes from native void simulateUserStateChange(Map changeData) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage( - _userChannel.name, - _userChannel.codec.encodeMethodCall( - MethodCall('OneSignal#onUserStateChange', changeData), - ), - (ByteData? data) {}, - ); + _userChannel.name, + _userChannel.codec.encodeMethodCall( + MethodCall('OneSignal#onUserStateChange', changeData), + ), + (ByteData? data) {}, + ); } // Generic helper method to simulate method calls from native on any channel void simulateMethodCall( - String channelName, String methodName, dynamic arguments) { + String channelName, + String methodName, + dynamic arguments, + ) { final MethodChannel channel; switch (channelName) { @@ -121,12 +130,10 @@ class OneSignalMockChannelController { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage( - channel.name, - channel.codec.encodeMethodCall( - MethodCall(methodName, arguments), - ), - (ByteData? data) {}, - ); + channel.name, + channel.codec.encodeMethodCall(MethodCall(methodName, arguments)), + (ByteData? data) {}, + ); } // Convenience wrapper for in-app message events @@ -197,8 +204,9 @@ class OneSignalMockChannelController { state.deleteTags = call.arguments; return {"success": true}; case "OneSignal#setExternalUserId": - state.externalId = (call.arguments - as Map)['externalUserId'] as String?; + state.externalId = + (call.arguments as Map)['externalUserId'] + as String?; return {"success": true}; case "OneSignal#removeExternalUserId": state.externalId = null; @@ -212,8 +220,9 @@ class OneSignalMockChannelController { // Notifications requestPermission (with fallbackToSettings argument) // Falls through to the notifications handler below state.requestPermissionCalled = true; - state.requestPermissionFallbackToSettings = (call.arguments - as Map)['fallbackToSettings'] as bool?; + state.requestPermissionFallbackToSettings = + (call.arguments as Map)['fallbackToSettings'] + as bool?; return true; case "OneSignal#setShared": state.locationShared = call.arguments as bool?; @@ -234,8 +243,9 @@ class OneSignalMockChannelController { break; case "OneSignal#setupDefault": state.liveActivitySetupCalled = true; - state.liveActivitySetupOptions = (call.arguments - as Map)['options'] as Map?; + state.liveActivitySetupOptions = + (call.arguments as Map)['options'] + as Map?; break; case "OneSignal#startDefault": state.liveActivityStarted = true; @@ -248,15 +258,17 @@ class OneSignalMockChannelController { break; case "OneSignal#setPushToStartToken": state.liveActivityPushToStartSet = true; - state.liveActivityType = (call.arguments - as Map)['activityType'] as String?; + state.liveActivityType = + (call.arguments as Map)['activityType'] + as String?; state.liveActivityPushToken = (call.arguments as Map)['token'] as String?; break; case "OneSignal#removePushToStartToken": state.liveActivityPushToStartRemoved = true; - state.liveActivityType = (call.arguments - as Map)['activityType'] as String?; + state.liveActivityType = + (call.arguments as Map)['activityType'] + as String?; break; case "OneSignal#addTrigger": state.addTrigger(call.arguments as Map); @@ -280,21 +292,24 @@ class OneSignalMockChannelController { return state.inAppMessagesPaused ?? false; case "OneSignal#displayNotification": // This is called on OneSignal#notifications channel - state.displayedNotificationId = (call.arguments - as Map)['notificationId'] as String?; + state.displayedNotificationId = + (call.arguments as Map)['notificationId'] + as String?; break; case "OneSignal#preventDefault": // This is called on OneSignal#notifications channel - state.preventedNotificationId = (call.arguments - as Map)['notificationId'] as String?; + state.preventedNotificationId = + (call.arguments as Map)['notificationId'] + as String?; break; case "OneSignal#removeNotification": state.removedNotificationId = (call.arguments as Map)['notificationId'] as int?; break; case "OneSignal#removeGroupedNotifications": - state.removedNotificationGroup = (call.arguments - as Map)['notificationGroup'] as String?; + state.removedNotificationGroup = + (call.arguments as Map)['notificationGroup'] + as String?; break; case "OneSignal#clearAll": state.clearedAllNotifications = true; @@ -454,7 +469,7 @@ class OneSignalState { bool? clearedAllNotifications; bool? notificationPermission; int? - notificationPermissionNative; // 0 = notDetermined, 1 = denied, 2 = authorized, etc. + notificationPermissionNative; // 0 = notDetermined, 1 = denied, 2 = authorized, etc. bool? canRequestPermission; bool? requestPermissionCalled; bool? requestPermissionFallbackToSettings; diff --git a/test/notification_test.dart b/test/notification_test.dart index 688c34c1..8cf1011b 100644 --- a/test/notification_test.dart +++ b/test/notification_test.dart @@ -143,8 +143,10 @@ void main() { final notification = OSNotification(androidOnlyJson); expect(notification.backgroundImageLayout, isNotNull); - expect(notification.backgroundImageLayout!.image, - 'https://example.com/bg.png'); + expect( + notification.backgroundImageLayout!.image, + 'https://example.com/bg.png', + ); expect(notification.backgroundImageLayout!.titleTextColor, '#FF000000'); expect(notification.backgroundImageLayout!.bodyTextColor, '#FF666666'); }); @@ -178,14 +180,8 @@ void main() { final json = { 'notificationId': 'parent-notification', 'groupedNotifications': [ - { - 'notificationId': 'grouped-1', - 'title': 'Title 1', - }, - { - 'notificationId': 'grouped-2', - 'title': 'Title 2', - }, + {'notificationId': 'grouped-1', 'title': 'Title 1'}, + {'notificationId': 'grouped-2', 'title': 'Title 2'}, ], }; @@ -313,11 +309,7 @@ void main() { }); test('creates from JSON', () { - final json = { - 'id': 'action1', - 'text': 'Open', - 'icon': 'open.png', - }; + final json = {'id': 'action1', 'text': 'Open', 'icon': 'open.png'}; final button = OSActionButton.fromJson(json); expect(button.id, 'action1'); @@ -326,10 +318,7 @@ void main() { }); test('creates from JSON without icon', () { - final json = { - 'id': 'action2', - 'text': 'Dismiss', - }; + final json = {'id': 'action2', 'text': 'Dismiss'}; final button = OSActionButton.fromJson(json); expect(button.id, 'action2'); @@ -374,18 +363,11 @@ void main() { test('mapRepresentation omits absent icons', () { final button = OSActionButton(id: 'action5', text: 'Dismiss'); - expect(button.mapRepresentation(), { - 'id': 'action5', - 'text': 'Dismiss', - }); + expect(button.mapRepresentation(), {'id': 'action5', 'text': 'Dismiss'}); }); test('mapRepresentation returns correct map', () { - final button = OSActionButton( - id: 'btn', - text: 'Text', - icon: 'icon.png', - ); + final button = OSActionButton(id: 'btn', text: 'Text', icon: 'icon.png'); final map = button.mapRepresentation(); expect(map['id'], 'btn'); @@ -445,9 +427,7 @@ void main() { group('OSNotificationWillDisplayEvent', () { test('creates from valid JSON', () { - final json = { - 'notification': validNotificationJson, - }; + final json = {'notification': validNotificationJson}; final event = OSNotificationWillDisplayEvent(json); expect(event.notification, isNotNull); @@ -456,9 +436,7 @@ void main() { }); test('creates with iOS notification data', () { - final json = { - 'notification': iosOnlyJson, - }; + final json = {'notification': iosOnlyJson}; final event = OSNotificationWillDisplayEvent(json); expect(event.notification.contentAvailable, true); @@ -466,9 +444,7 @@ void main() { }); test('jsonRepresentation returns correct JSON string', () { - final json = { - 'notification': validNotificationJson, - }; + final json = {'notification': validNotificationJson}; final event = OSNotificationWillDisplayEvent(json); final jsonRep = event.jsonRepresentation(); final decoded = jsonDecode(jsonRep) as Map; @@ -542,15 +518,19 @@ void main() { channelController.resetState(); }); - test('display() calls displayNotification with correct notification ID', - () { - final notification = OSNotification(validNotificationJson); + test( + 'display() calls displayNotification with correct notification ID', + () { + final notification = OSNotification(validNotificationJson); - notification.display(); + notification.display(); - expect( - channelController.state.displayedNotificationId, 'notification-123'); - }); + expect( + channelController.state.displayedNotificationId, + 'notification-123', + ); + }, + ); test('display() works with different notification IDs', () { final json = {'notificationId': 'custom-notification-id'}; @@ -558,8 +538,10 @@ void main() { notification.display(); - expect(channelController.state.displayedNotificationId, - 'custom-notification-id'); + expect( + channelController.state.displayedNotificationId, + 'custom-notification-id', + ); }); test('multiple display() calls update the displayed notification ID', () { @@ -583,18 +565,20 @@ void main() { channelController.resetState(); }); - test('preventDefault() calls preventDefault with correct notification ID', - () { - final json = { - 'notification': validNotificationJson, - }; - final event = OSNotificationWillDisplayEvent(json); + test( + 'preventDefault() calls preventDefault with correct notification ID', + () { + final json = {'notification': validNotificationJson}; + final event = OSNotificationWillDisplayEvent(json); - event.preventDefault(); + event.preventDefault(); - expect( - channelController.state.preventedNotificationId, 'notification-123'); - }); + expect( + channelController.state.preventedNotificationId, + 'notification-123', + ); + }, + ); test('preventDefault() works with different notification IDs', () { final json = { @@ -604,27 +588,31 @@ void main() { event.preventDefault(); - expect(channelController.state.preventedNotificationId, - 'custom-will-display-id'); + expect( + channelController.state.preventedNotificationId, + 'custom-will-display-id', + ); }); - test('multiple preventDefault() calls update the prevented notification ID', - () { - final json1 = { - 'notification': {'notificationId': 'prevent-1'}, - }; - final json2 = { - 'notification': {'notificationId': 'prevent-2'}, - }; - final event1 = OSNotificationWillDisplayEvent(json1); - final event2 = OSNotificationWillDisplayEvent(json2); - - event1.preventDefault(); - expect(channelController.state.preventedNotificationId, 'prevent-1'); - - event2.preventDefault(); - expect(channelController.state.preventedNotificationId, 'prevent-2'); - }); + test( + 'multiple preventDefault() calls update the prevented notification ID', + () { + final json1 = { + 'notification': {'notificationId': 'prevent-1'}, + }; + final json2 = { + 'notification': {'notificationId': 'prevent-2'}, + }; + final event1 = OSNotificationWillDisplayEvent(json1); + final event2 = OSNotificationWillDisplayEvent(json2); + + event1.preventDefault(); + expect(channelController.state.preventedNotificationId, 'prevent-1'); + + event2.preventDefault(); + expect(channelController.state.preventedNotificationId, 'prevent-2'); + }, + ); }); group('OSNotificationClickEvent preventDefault', () { @@ -636,19 +624,23 @@ void main() { channelController.resetState(); }); - test('preventDefault() calls preventDefault with correct notification ID', - () { - final json = { - 'notification': validNotificationJson, - 'result': clickResultJson, - }; - final event = OSNotificationClickEvent(json); + test( + 'preventDefault() calls preventDefault with correct notification ID', + () { + final json = { + 'notification': validNotificationJson, + 'result': clickResultJson, + }; + final event = OSNotificationClickEvent(json); - event.preventDefault(); + event.preventDefault(); - expect( - channelController.state.preventedNotificationId, 'notification-123'); - }); + expect( + channelController.state.preventedNotificationId, + 'notification-123', + ); + }, + ); test('preventDefault() works with different notification IDs', () { final json = { @@ -660,29 +652,37 @@ void main() { event.preventDefault(); expect( - channelController.state.preventedNotificationId, 'custom-click-id'); + channelController.state.preventedNotificationId, + 'custom-click-id', + ); }); - test('multiple preventDefault() calls update the prevented notification ID', - () { - final json1 = { - 'notification': {'notificationId': 'click-prevent-1'}, - 'result': {}, - }; - final json2 = { - 'notification': {'notificationId': 'click-prevent-2'}, - 'result': {}, - }; - final event1 = OSNotificationClickEvent(json1); - final event2 = OSNotificationClickEvent(json2); - - event1.preventDefault(); - expect( - channelController.state.preventedNotificationId, 'click-prevent-1'); - - event2.preventDefault(); - expect( - channelController.state.preventedNotificationId, 'click-prevent-2'); - }); + test( + 'multiple preventDefault() calls update the prevented notification ID', + () { + final json1 = { + 'notification': {'notificationId': 'click-prevent-1'}, + 'result': {}, + }; + final json2 = { + 'notification': {'notificationId': 'click-prevent-2'}, + 'result': {}, + }; + final event1 = OSNotificationClickEvent(json1); + final event2 = OSNotificationClickEvent(json2); + + event1.preventDefault(); + expect( + channelController.state.preventedNotificationId, + 'click-prevent-1', + ); + + event2.preventDefault(); + expect( + channelController.state.preventedNotificationId, + 'click-prevent-2', + ); + }, + ); }); } diff --git a/test/notifications_test.dart b/test/notifications_test.dart index b6d088e0..1d73c05b 100644 --- a/test/notifications_test.dart +++ b/test/notifications_test.dart @@ -30,19 +30,21 @@ void main() { expect(notifications.permission, false); }); - test('permission gets updated via observer during lifecycleInit', - () async { - channelController.state.notificationPermission = false; - await notifications.lifecycleInit(); - expect(notifications.permission, false); - - // Test that the observer added in lifecycleInit updates _permission - notifications.onNotificationPermissionDidChange(true); - expect(notifications.permission, true); - - notifications.onNotificationPermissionDidChange(false); - expect(notifications.permission, false); - }); + test( + 'permission gets updated via observer during lifecycleInit', + () async { + channelController.state.notificationPermission = false; + await notifications.lifecycleInit(); + expect(notifications.permission, false); + + // Test that the observer added in lifecycleInit updates _permission + notifications.onNotificationPermissionDidChange(true); + expect(notifications.permission, true); + + notifications.onNotificationPermissionDidChange(false); + expect(notifications.permission, false); + }, + ); }); group('permissionNative', () { @@ -60,15 +62,17 @@ void main() { expect(permission, OSNotificationPermission.denied); }); - test('returns authorized on iOS when native method returns authorized', - () async { - debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - channelController.state.notificationPermissionNative = - OSNotificationPermission.authorized.index; - - final permission = await notifications.permissionNative(); - expect(permission, OSNotificationPermission.authorized); - }); + test( + 'returns authorized on iOS when native method returns authorized', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + channelController.state.notificationPermissionNative = + OSNotificationPermission.authorized.index; + + final permission = await notifications.permissionNative(); + expect(permission, OSNotificationPermission.authorized); + }, + ); test('returns denied on iOS when native method returns denied', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; @@ -108,8 +112,10 @@ void main() { debugDefaultTargetPlatformOverride = TargetPlatform.android; const notificationGroup = 'test_group'; await notifications.removeGroupedNotifications(notificationGroup); - expect(channelController.state.removedNotificationGroup, - notificationGroup); + expect( + channelController.state.removedNotificationGroup, + notificationGroup, + ); }); test('rejects empty notificationGroup', () async { @@ -127,38 +133,49 @@ void main() { }); group('requestPermission', () { - test('invokes OneSignal#requestPermission with fallbackToSettings true', - () async { - await notifications.requestPermission(true); - expect(channelController.state.requestPermissionCalled, true); - expect( - channelController.state.requestPermissionFallbackToSettings, true); - }); + test( + 'invokes OneSignal#requestPermission with fallbackToSettings true', + () async { + await notifications.requestPermission(true); + expect(channelController.state.requestPermissionCalled, true); + expect( + channelController.state.requestPermissionFallbackToSettings, + true, + ); + }, + ); - test('invokes OneSignal#requestPermission with fallbackToSettings false', - () async { - await notifications.requestPermission(false); - expect(channelController.state.requestPermissionCalled, true); - expect( - channelController.state.requestPermissionFallbackToSettings, false); - }); + test( + 'invokes OneSignal#requestPermission with fallbackToSettings false', + () async { + await notifications.requestPermission(false); + expect(channelController.state.requestPermissionCalled, true); + expect( + channelController.state.requestPermissionFallbackToSettings, + false, + ); + }, + ); }); group('registerForProvisionalAuthorization', () { test('invokes method on iOS only', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final result = - await notifications.registerForProvisionalAuthorization(true); + final result = await notifications.registerForProvisionalAuthorization( + true, + ); expect(result, true); expect( - channelController.state.registerForProvisionalAuthorizationCalled, - true); + channelController.state.registerForProvisionalAuthorizationCalled, + true, + ); }); test('returns false on Android', () async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final result = - await notifications.registerForProvisionalAuthorization(true); + final result = await notifications.registerForProvisionalAuthorization( + true, + ); expect(result, false); }); }); @@ -285,102 +302,123 @@ void main() { 'notification': { 'notificationId': 'buffered-click-id', 'title': 'Test', - 'body': 'Test body' + 'body': 'Test body', }, - 'result': {'action_id': null, 'url': null} + 'result': {'action_id': null, 'url': null}, }; - test('click arriving before any listener is buffered and delivered', - () async { - channelController.simulateNotificationEvent( - 'OneSignal#onClickNotification', clickData); + test( + 'click arriving before any listener is buffered and delivered', + () async { + channelController.simulateNotificationEvent( + 'OneSignal#onClickNotification', + clickData, + ); - final received = []; - notifications.addClickListener(received.add); + final received = []; + notifications.addClickListener(received.add); - // The drain is deferred to a microtask. - await Future.delayed(Duration.zero); + // The drain is deferred to a microtask. + await Future.delayed(Duration.zero); - expect(received.length, 1); - expect(received.first.notification.notificationId, 'buffered-click-id'); - }); + expect(received.length, 1); + expect( + received.first.notification.notificationId, + 'buffered-click-id', + ); + }, + ); test( - 'buffered click fans out to all listeners registered before the drain', - () async { - channelController.simulateNotificationEvent( - 'OneSignal#onClickNotification', clickData); + 'buffered click fans out to all listeners registered before the drain', + () async { + channelController.simulateNotificationEvent( + 'OneSignal#onClickNotification', + clickData, + ); + + // Both listeners register synchronously (e.g. analytics then nav) before + // the deferred drain runs, so both receive the cold-start click. + var firstReceived = 0; + var secondReceived = 0; + notifications.addClickListener((event) => firstReceived++); + notifications.addClickListener((event) => secondReceived++); - // Both listeners register synchronously (e.g. analytics then nav) before - // the deferred drain runs, so both receive the cold-start click. - var firstReceived = 0; - var secondReceived = 0; - notifications.addClickListener((event) => firstReceived++); - notifications.addClickListener((event) => secondReceived++); - - await Future.delayed(Duration.zero); - - expect(firstReceived, 1); - expect(secondReceived, 1); - }); - - test('drain survives a listener that removes itself during its callback', - () async { - channelController.simulateNotificationEvent( - 'OneSignal#onClickNotification', clickData); + await Future.delayed(Duration.zero); - var received = 0; - late OnNotificationClickListener oneShot; - oneShot = (event) { - received++; - notifications.removeClickListener(oneShot); - }; - notifications.addClickListener(oneShot); + expect(firstReceived, 1); + expect(secondReceived, 1); + }, + ); - // Mutating _clickListeners mid-drain must not throw - // ConcurrentModificationError or drop the event. - await Future.delayed(Duration.zero); + test( + 'drain survives a listener that removes itself during its callback', + () async { + channelController.simulateNotificationEvent( + 'OneSignal#onClickNotification', + clickData, + ); + + var received = 0; + late OnNotificationClickListener oneShot; + oneShot = (event) { + received++; + notifications.removeClickListener(oneShot); + }; + notifications.addClickListener(oneShot); + + // Mutating _clickListeners mid-drain must not throw + // ConcurrentModificationError or drop the event. + await Future.delayed(Duration.zero); - expect(received, 1); - }); + expect(received, 1); + }, + ); test('drain continues after a listener throws for one event', () async { final firstClickData = { 'notification': { 'notificationId': 'first-click-id', 'title': 'First', - 'body': 'Test body' + 'body': 'Test body', }, - 'result': {'action_id': null, 'url': null} + 'result': {'action_id': null, 'url': null}, }; final secondClickData = { 'notification': { 'notificationId': 'second-click-id', 'title': 'Second', - 'body': 'Test body' + 'body': 'Test body', }, - 'result': {'action_id': null, 'url': null} + 'result': {'action_id': null, 'url': null}, }; channelController.simulateNotificationEvent( - 'OneSignal#onClickNotification', firstClickData); + 'OneSignal#onClickNotification', + firstClickData, + ); channelController.simulateNotificationEvent( - 'OneSignal#onClickNotification', secondClickData); + 'OneSignal#onClickNotification', + secondClickData, + ); final received = []; final errors = []; - final guarded = runZonedGuarded>(() async { - notifications.addClickListener((event) { - final notificationId = event.notification.notificationId; - received.add(notificationId); - if (notificationId == 'first-click-id') { - throw StateError('boom'); - } - }); - - await Future.delayed(Duration.zero); - }, (error, stackTrace) { - errors.add(error); - }); + final guarded = runZonedGuarded>( + () async { + notifications.addClickListener((event) { + final notificationId = event.notification.notificationId; + received.add(notificationId); + if (notificationId == 'first-click-id') { + throw StateError('boom'); + } + }); + + await Future.delayed(Duration.zero); + }, + (error, stackTrace) { + errors.add(error); + }, + ); await guarded; @@ -389,23 +427,27 @@ void main() { expect(errors.single, isA()); }); - test('clicks are not buffered after the first listener has registered', - () async { - var firstReceived = 0; - notifications.addClickListener((event) => firstReceived++); - - // A click after registration is delivered live, not buffered. - channelController.simulateNotificationEvent( - 'OneSignal#onClickNotification', clickData); - expect(firstReceived, 1); - - // A later listener does not receive the earlier (already delivered) - // click; nothing is buffered once a listener has registered. - var secondReceived = 0; - notifications.addClickListener((event) => secondReceived++); - await Future.delayed(Duration.zero); - expect(secondReceived, 0); - }); + test( + 'clicks are not buffered after the first listener has registered', + () async { + var firstReceived = 0; + notifications.addClickListener((event) => firstReceived++); + + // A click after registration is delivered live, not buffered. + channelController.simulateNotificationEvent( + 'OneSignal#onClickNotification', + clickData, + ); + expect(firstReceived, 1); + + // A later listener does not receive the earlier (already delivered) + // click; nothing is buffered once a listener has registered. + var secondReceived = 0; + notifications.addClickListener((event) => secondReceived++); + await Future.delayed(Duration.zero); + expect(secondReceived, 0); + }, + ); }); group('Will Display Listeners', () { @@ -413,8 +455,8 @@ void main() { 'notification': { 'notificationId': 'test-id', 'title': 'Test', - 'body': 'Test body' - } + 'body': 'Test body', + }, }; test('addForegroundWillDisplayListener adds listener', () async { @@ -425,7 +467,9 @@ void main() { notifications.addForegroundWillDisplayListener(listener); channelController.simulateNotificationEvent( - 'OneSignal#onWillDisplayNotification', notificationData); + 'OneSignal#onWillDisplayNotification', + notificationData, + ); expect(listenerCalled, true); }); @@ -439,7 +483,9 @@ void main() { notifications.addForegroundWillDisplayListener(listener); notifications.removeForegroundWillDisplayListener(listener); channelController.simulateNotificationEvent( - 'OneSignal#onWillDisplayNotification', notificationData); + 'OneSignal#onWillDisplayNotification', + notificationData, + ); expect(listenerCalled, false); }); @@ -459,7 +505,9 @@ void main() { notifications.addForegroundWillDisplayListener(listener2); channelController.simulateNotificationEvent( - 'OneSignal#onWillDisplayNotification', notificationData); + 'OneSignal#onWillDisplayNotification', + notificationData, + ); expect(listener1Called, true); expect(listener2Called, true); @@ -481,7 +529,9 @@ void main() { notifications.removeForegroundWillDisplayListener(listener1); channelController.simulateNotificationEvent( - 'OneSignal#onWillDisplayNotification', notificationData); + 'OneSignal#onWillDisplayNotification', + notificationData, + ); expect(listener1Called, false); expect(listener2Called, true); @@ -507,23 +557,25 @@ void main() { }); group('onNotificationPermissionDidChange', () { - test('calls all registered permission observers with permission value', - () { - var observer1PermissionValue; - var observer2PermissionValue; + test( + 'calls all registered permission observers with permission value', + () { + var observer1PermissionValue; + var observer2PermissionValue; - notifications.addPermissionObserver((permission) { - observer1PermissionValue = permission; - }); - notifications.addPermissionObserver((permission) { - observer2PermissionValue = permission; - }); + notifications.addPermissionObserver((permission) { + observer1PermissionValue = permission; + }); + notifications.addPermissionObserver((permission) { + observer2PermissionValue = permission; + }); - notifications.onNotificationPermissionDidChange(true); + notifications.onNotificationPermissionDidChange(true); - expect(observer1PermissionValue, true); - expect(observer2PermissionValue, true); - }); + expect(observer1PermissionValue, true); + expect(observer2PermissionValue, true); + }, + ); test('observers can be called multiple times with different values', () { final receivedValues = []; diff --git a/test/pushsubscription_test.dart b/test/pushsubscription_test.dart index b6ce2989..79c0ca8d 100644 --- a/test/pushsubscription_test.dart +++ b/test/pushsubscription_test.dart @@ -209,12 +209,12 @@ void main() { 'current': { 'id': 'updated-id', 'token': 'updated-token', - 'optedIn': true + 'optedIn': true, }, 'previous': { 'id': 'initial-id', 'token': 'initial-token', - 'optedIn': false + 'optedIn': false, }, }; diff --git a/test/session_test.dart b/test/session_test.dart index 40889c78..563fdfa5 100644 --- a/test/session_test.dart +++ b/test/session_test.dart @@ -66,17 +66,24 @@ void main() { }); group('addOutcomeWithValue', () { - test('invokes OneSignal#addOutcomeWithValue with name and value', - () async { - const outcomeName = 'valued_outcome'; - const outcomeValue = 42.5; - - await session.addOutcomeWithValue(outcomeName, outcomeValue); - - expect(channelController.state.addedOutcomeWithValueName, outcomeName); - expect( - channelController.state.addedOutcomeWithValueValue, outcomeValue); - }); + test( + 'invokes OneSignal#addOutcomeWithValue with name and value', + () async { + const outcomeName = 'valued_outcome'; + const outcomeValue = 42.5; + + await session.addOutcomeWithValue(outcomeName, outcomeValue); + + expect( + channelController.state.addedOutcomeWithValueName, + outcomeName, + ); + expect( + channelController.state.addedOutcomeWithValueValue, + outcomeValue, + ); + }, + ); test('handles negative value', () async { const outcomeName = 'negative_outcome'; @@ -86,7 +93,9 @@ void main() { expect(channelController.state.addedOutcomeWithValueName, outcomeName); expect( - channelController.state.addedOutcomeWithValueValue, outcomeValue); + channelController.state.addedOutcomeWithValueValue, + outcomeValue, + ); }); test('can be called multiple times with different values', () async { diff --git a/test/subscription_test.dart b/test/subscription_test.dart index ca90dee4..dec75e35 100644 --- a/test/subscription_test.dart +++ b/test/subscription_test.dart @@ -8,11 +8,7 @@ final pushSubState = { }; final pushChangeState = { - 'current': { - 'id': 'current-id', - 'token': 'current-token', - 'optedIn': true, - }, + 'current': {'id': 'current-id', 'token': 'current-token', 'optedIn': true}, 'previous': { 'id': 'previous-id', 'token': 'previous-token', @@ -22,11 +18,7 @@ final pushChangeState = { final pushNullChangeState = { 'current': {'id': null, 'token': null, 'optedIn': false}, - 'previous': { - 'id': 'previous-id', - 'token': 'previous-token', - 'optedIn': true, - }, + 'previous': {'id': 'previous-id', 'token': 'previous-token', 'optedIn': true}, }; void main() { @@ -183,8 +175,9 @@ void main() { }); test('handles null values in current state', () { - final changedState = - OSPushSubscriptionChangedState(pushNullChangeState); + final changedState = OSPushSubscriptionChangedState( + pushNullChangeState, + ); expect(changedState.current.id, isNull); expect(changedState.current.token, isNull); @@ -231,8 +224,9 @@ void main() { }); test('handles null values in json representation', () { - final changedState = - OSPushSubscriptionChangedState(pushNullChangeState); + final changedState = OSPushSubscriptionChangedState( + pushNullChangeState, + ); final jsonString = changedState.jsonRepresentation(); expect(jsonString, contains('"current"')); diff --git a/test/user_test.dart b/test/user_test.dart index 0bbf085e..01be08c5 100644 --- a/test/user_test.dart +++ b/test/user_test.dart @@ -34,10 +34,7 @@ void main() { test('handles null/missing onesignalId', () { // with null onesignalId - final stateWithNull = OSUserState({ - ...userState, - 'onesignalId': null, - }); + final stateWithNull = OSUserState({...userState, 'onesignalId': null}); expect(stateWithNull.onesignalId, isNull); expect(stateWithNull.externalId, 'test-external-id'); @@ -51,10 +48,7 @@ void main() { test('handles null/missing externalId', () { // with null externalId - final stateWithNull = OSUserState({ - ...userState, - 'externalId': null, - }); + final stateWithNull = OSUserState({...userState, 'externalId': null}); expect(stateWithNull.onesignalId, 'test-onesignal-id'); expect(stateWithNull.externalId, isNull); @@ -67,10 +61,7 @@ void main() { }); test('handles all null values', () { - final state = OSUserState({ - 'onesignalId': null, - 'externalId': null, - }); + final state = OSUserState({'onesignalId': null, 'externalId': null}); expect(state.onesignalId, isNull); expect(state.externalId, isNull); @@ -87,10 +78,7 @@ void main() { }); test('returns json string with null fields', () { - final state = OSUserState({ - 'onesignalId': null, - 'externalId': null, - }); + final state = OSUserState({'onesignalId': null, 'externalId': null}); final jsonString = state.jsonRepresentation(); expect(jsonString, contains('"onesignalId": null')); @@ -130,9 +118,7 @@ void main() { group('OSUserChangedState', () { test('initializes with current state', () { - final changedState = OSUserChangedState({ - 'current': userState, - }); + final changedState = OSUserChangedState({'current': userState}); expect(changedState.current.onesignalId, 'test-onesignal-id'); expect(changedState.current.externalId, 'test-external-id'); @@ -140,10 +126,7 @@ void main() { test('handles null values in current state', () { final changedState = OSUserChangedState({ - 'current': { - 'onesignalId': null, - 'externalId': null, - }, + 'current': {'onesignalId': null, 'externalId': null}, }); expect(changedState.current.onesignalId, isNull); @@ -151,9 +134,7 @@ void main() { }); test('jsonRepresentation returns correct format', () { - final changedState = OSUserChangedState({ - 'current': userState, - }); + final changedState = OSUserChangedState({'current': userState}); final jsonString = changedState.jsonRepresentation(); expect(jsonString, contains('"current":')); @@ -176,15 +157,9 @@ void main() { }); test('addAliases invokes native method with multiple aliases', () async { - await user.addAliases({ - 'customId': '12345', - 'userId': 'abc', - }); + await user.addAliases({'customId': '12345', 'userId': 'abc'}); - expect(controller.state.aliases, { - 'customId': '12345', - 'userId': 'abc', - }); + expect(controller.state.aliases, {'customId': '12345', 'userId': 'abc'}); }); test('removeAlias invokes native method with alias label', () async { @@ -206,11 +181,7 @@ void main() { }); test('addTags invokes native method with multiple tags', () async { - await user.addTags({ - 'level': 10, - 'score': 500, - 'name': 'Player1', - }); + await user.addTags({'level': 10, 'score': 500, 'name': 'Player1'}); expect(controller.state.tags, { 'level': '10', @@ -232,17 +203,11 @@ void main() { }); test('getTags returns tags from native', () async { - controller.state.tags = { - 'level': '10', - 'score': '500', - }; + controller.state.tags = {'level': '10', 'score': '500'}; final tags = await user.getTags(); - expect(tags, { - 'level': '10', - 'score': '500', - }); + expect(tags, {'level': '10', 'score': '500'}); }); test('addEmail invokes native method with email', () async { @@ -398,9 +363,7 @@ void main() { await user.lifecycleInit(); - controller.simulateUserStateChange({ - 'current': userState, - }); + controller.simulateUserStateChange({'current': userState}); expect(callCount, 3); }); diff --git a/test/utils_test.dart b/test/utils_test.dart index 046cedbf..e64b933f 100644 --- a/test/utils_test.dart +++ b/test/utils_test.dart @@ -21,8 +21,8 @@ void main() { final map = { 'outer': { 'inner': 'value', - 'nested': {'deep': 'data'} - } + 'nested': {'deep': 'data'}, + }, }; final result = testObj.convertToJsonString(map); @@ -37,7 +37,7 @@ void main() { final testObj = TestJSONStringRepresentable(); final map = { 'items': [1, 2, 3], - 'strings': ['a', 'b', 'c'] + 'strings': ['a', 'b', 'c'], }; final result = testObj.convertToJsonString(map); @@ -88,7 +88,7 @@ void main() { test('convertToJsonString formats with proper indentation', () { final testObj = TestJSONStringRepresentable(); final map = { - 'level1': {'level2': 'value'} + 'level1': {'level2': 'value'}, }; final result = testObj.convertToJsonString(map); @@ -127,7 +127,7 @@ void main() { 'bool': true, 'null': null, 'list': [1, 2], - 'map': {'nested': 'value'} + 'map': {'nested': 'value'}, }; final result = testObj.convertToJsonString(map);