Files
element-x-ios/UnitTests/Sources/NotificationManager/NotificationServiceTests.swift
Mauro 268d6c8ead Notify every signed-in account and turn notifications on and off per account (#6337)
* Store the notifications switch per account

Adds AccountSettings.enableNotifications and moves the app-wide value into the signed in accounts before they're restored: the first account takes it out of the app settings and the others get the same switch, so someone who turned notifications off keeps them off.

* Add a notification service to every user session

Each account's NotificationService sets its pusher when its notifications are on and deletes it when they're off (appending with multiple accounts), keeps the account's unread count and decides which of its delivered notifications to clear. It asks the NotificationManager, the only owner of the notification center, through actions: remove the notifications matching a rule, request authorization and the unread count. The UserSessionManager connects every live session's service to the manager, and flows and screens use the session's service instead of the manager, which leaves the flow parameters.

* Route notifications by account

Taps only open rooms of the active account for now, a tap made while restoring only opens once its account is the active one, replies are sent from the account they were made for, and signing out only clears that account's notifications unless it was the last one. The notification extension hides pushes for an account that signed out while other accounts are still signed in.

* Turn notifications on and off for each account

The notification settings switch is now saved per account, and each account's NotificationService sets or deletes its pusher when it changes, asking for permission when it's turned on.

* Apply review suggestions to multi-account notifications

Migration
- Move the notifications switch with a single per-account migration, like 26.10.1 and 26.10.2, and drop its dedicated test.

Notification manager and service
- Follow each account's badge count publisher directly, removing the badge count action and the stored counts.
- Only reset the badge and unregister from APNs when the last account signs out, as each account already clears its own notifications.
- Set up the service's subscriptions in a single setupSubscriptions().
- Rename switchChanged(to:) to enableNotificationsChanged(to:) and pusherConfiguration(identifiers:) to pusherConfiguration(for:).
- Build the service without hopping to the main actor, it already runs there.

Notification service extension
- Check the account's switch in NotificationHandler using the session's settings, and log an error when a push arrives for an account that's turned off.
- Always show pushes that match no signed-in account and log an error, so a broken setup stays visible.

Other
- Store a pending inline reply in a PendingInlineReplyDetails struct.
- Assign the chats tab badge with weakAssign.
- Make PusherConfiguration Equatable so the pusher test checks it in one expectation.
- Clarify the comment about notifications without a receiver.

* Print instead of logging before the app hooks run in the NSE

A push that matches no signed-in account goes back to printing, as MXLog shouldn't be used before the app hooks have run. The push is still shown so a broken setup stays visible.
2026-10-15 13:10:26 +02:00

255 lines
10 KiB
Swift

//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
@testable import ElementX
import MatrixRustSDK
import MatrixRustSDKMocks
import SwiftUI
import Testing
import UserNotifications
@MainActor
final class NotificationServiceTests {
private let clientProxy = ClientProxyMock(.init(userID: "@alice:example.com"))
private let appSettings = AppSettings.volatile()
private let userSettings: UserSettings
private var actions: [NotificationServiceAction] = []
private var cancellables = Set<AnyCancellable>()
init() {
userSettings = appSettings.userSettings(for: "@alice:example.com")
}
// MARK: - Pushers
@Test
func registeringSetsThePusher() async throws {
let service = makeService()
let deviceToken = Data("1234".utf8)
await service.register(deviceToken: deviceToken)
let defaultPayload = APNSPayload(aps: APSInfo(mutableContent: 1,
alert: APSAlert(locKey: "Notification", locArgs: [])),
pusherNotificationClientIdentifier: nil)
let expectedConfiguration = try PusherConfiguration(identifiers: .init(pushkey: deviceToken.base64EncodedString(), appId: appSettings.pusherAppID),
kind: .http(data: .init(url: appSettings.pushGatewayNotifyEndpoint.absoluteString,
format: .eventIdOnly,
defaultPayload: defaultPayload.toJsonString())),
appDisplayName: "\(InfoPlistReader.main.bundleDisplayName) (iOS)",
deviceDisplayName: UIDevice.current.name,
profileTag: appSettings.pusherProfileTag,
lang: Bundle.app.preferredLocalizations.first ?? "en",
append: false)
#expect(clientProxy.setPusherWithReceivedInvocations == [expectedConfiguration])
}
@Test
func pushersAppendWithMultipleAccounts() async throws {
appSettings.multiAccountEnabled = true
let service = makeService()
await service.register(deviceToken: Data())
let configuration = try #require(clientProxy.setPusherWithReceivedInvocations.first)
#expect(configuration.append)
}
@Test
func registeringGeneratesAndSavesTheProfileTag() async {
appSettings.pusherProfileTag = nil
await makeService().register(deviceToken: Data())
#expect(appSettings.pusherProfileTag != nil)
}
@Test
func registeringKeepsTheSavedProfileTag() async {
appSettings.pusherProfileTag = "12345"
await makeService().register(deviceToken: Data())
#expect(appSettings.pusherProfileTag == "12345")
}
@Test
func registeringWhileTurnedOffDeletesThePusher() async throws {
let service = makeService(isEnabled: false)
let deviceToken = Data("1234".utf8)
await service.register(deviceToken: deviceToken)
#expect(!clientProxy.setPusherWithCalled)
let identifiers = try #require(clientProxy.deletePusherWithReceivedIdentifiers)
#expect(identifiers.pushkey == deviceToken.base64EncodedString())
#expect(identifiers.appId == appSettings.pusherAppID)
}
// MARK: - Switch
@Test
func turningOffDeletesThePusher() async {
let service = makeService()
await service.register(deviceToken: Data("1234".utf8))
await waitForConfirmation("The pusher should be deleted", timeout: .seconds(10)) { confirm in
clientProxy.deletePusherWithClosure = { _ in confirm() }
userSettings.account.enableNotifications = false
}
#expect(!service.isEnabled)
}
@Test
func turningOnSetsThePusherAndAsksForPermission() async {
let service = makeService(isEnabled: false)
await service.register(deviceToken: Data("1234".utf8))
await waitForConfirmation("The pusher should be set", timeout: .seconds(10)) { confirm in
clientProxy.setPusherWithClosure = { _ in confirm() }
userSettings.account.enableNotifications = true
}
#expect(service.isEnabled)
#expect(isRequestAuthorization(actions.last))
}
@Test
func turningOnBeforeRegisteringOnlyAsksForPermission() {
let service = makeService(isEnabled: false)
userSettings.account.enableNotifications = true
#expect(service.isEnabled)
#expect(!clientProxy.setPusherWithCalled)
#expect(isRequestAuthorization(actions.last))
}
@Test
func requestingAuthorizationAsksTheManager() {
let service = makeService()
service.requestAuthorization()
#expect(isRequestAuthorization(actions.last))
}
// MARK: - Badge
@Test
func badgeCountStartsFromTheUnreadCount() {
clientProxy.totalUnreadNotifications = 3
let service = makeService()
#expect(service.badgeCountPublisher.value == 3)
}
@Test
func roomListChangesUpdateTheBadgeCount() async throws {
let roomListSubject = CurrentValueSubject<[RoomSummary], Never>([])
let roomSummaryProvider = RoomSummaryProviderMock(.init())
roomSummaryProvider.roomListPublisher = roomListSubject.asCurrentValuePublisher()
clientProxy.staticRoomSummaryProvider = roomSummaryProvider
let service = makeService()
let deferred = deferFulfillment(service.badgeCountPublisher) { $0 == 7 }
clientProxy.totalUnreadNotifications = 7
roomListSubject.send([])
try await deferred.fulfill()
}
// MARK: - Delivered notifications
@Test
func clearingARoomOnlyMatchesThatRoom() throws {
let service = makeService()
service.removeDeliveredMessageNotifications(for: "!room:example.com")
let rule = try #require(removalRules.last)
#expect(try rule(notification(roomID: "!room:example.com")))
#expect(try !rule(notification(roomID: "!other:example.com")))
}
@Test
func clearingFullyReadRoomsOnlyMatchesReadNotifications() throws {
let room = RoomSummary(room: RoomSDKMock(), id: "!room:matrix.org", settingsMode: .allMessages,
hasUnreadMessages: false, hasUnreadMentions: false, hasUnreadNotifications: false)
let lastMessageDate = try #require(room.lastMessageDate)
let service = makeService()
service.removeDeliveredNotificationsForFullyReadRooms([room])
let rule = try #require(removalRules.last)
// Delivered after the last message was sent, which is always the case for the last message's notification.
let readNotification = try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: room.id,
NotificationConstants.UserInfoKey.eventDate: lastMessageDate.addingTimeInterval(0.5)],
date: lastMessageDate.addingTimeInterval(5))
let newerNotification = try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: room.id,
NotificationConstants.UserInfoKey.eventDate: lastMessageDate.addingTimeInterval(1)],
date: lastMessageDate.addingTimeInterval(5))
#expect(rule(readNotification))
#expect(!rule(newerNotification))
#expect(try !rule(notification(roomID: "!other:example.com")))
}
@Test
func clearingWithoutFullyReadRoomsAsksNothing() {
let room = RoomSummary(room: RoomSDKMock(), id: "!room:matrix.org", settingsMode: .allMessages,
hasUnreadMessages: true, hasUnreadMentions: false, hasUnreadNotifications: true)
let service = makeService()
service.removeDeliveredNotificationsForFullyReadRooms([room])
#expect(removalRules.isEmpty)
}
@Test
func tearingDownDeletesThePusherAndRemovesEveryNotification() async throws {
let service = makeService()
await service.register(deviceToken: Data())
await service.tearDown()
#expect(clientProxy.deletePusherWithCalled)
let rule = try #require(removalRules.last)
#expect(try rule(notification(roomID: "!any:example.com")))
}
// MARK: - Helpers
private func makeService(isEnabled: Bool = true) -> NotificationService {
userSettings.account.enableNotifications = isEnabled
let service = NotificationService(clientProxy: clientProxy, userSettings: userSettings)
service.actionsPublisher
.sink { [weak self] action in
self?.actions.append(action)
}
.store(in: &cancellables)
return service
}
private func notification(roomID: String) throws -> UNNotification {
try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: roomID])
}
private var removalRules: [(UNNotification) -> Bool] {
actions.compactMap { action in
guard case let .removeDeliveredNotifications(rule) = action else { return nil }
return rule
}
}
private func isRequestAuthorization(_ action: NotificationServiceAction?) -> Bool {
guard case .requestAuthorization = action else { return false }
return true
}
}