Files
bitchat/bitchatTests/Services/NotificationServiceTests.swift
T
jackandjack 72c1b6a719 Prep 2.0.0 App Store submission (#1962)
* Integrate Tier 1 2.0.0 security and reliability fixes (#1941, #1935, #1662)

* Add author block controls to Place Feed, Home Feed, and threads

* Prep 2.0.0 App Store submission: update Privacy Policy and bump build to 3

* Remove unrelated board calls from PlaceFeedView

* Address unaddressed Codex review findings (#1931, #1946, #1961, #1924)

* Fix autocorrection callsite in ContentComposerView after #1913/#1870

* Keep channel invite links intact in every language (#1818)

* Fence in-flight notifications on panic wipe and drop DM senderName userInfo (#1783)

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2026-11-28 15:03:12 -10:00

325 lines
12 KiB
Swift

import XCTest
import UserNotifications
import BitFoundation
@testable import bitchat
final class NotificationServiceTests: XCTestCase {
func test_requestAuthorization_skipsWhenRunningTests() {
var requestCallCount = 0
var deps = NotificationService.Dependencies.noop
deps.requestAuthorization = { _, completion in
requestCallCount += 1
completion(true, nil)
}
let service = NotificationService(
isRunningTestsProvider: { true },
dependencies: deps
)
service.requestAuthorization()
XCTAssertEqual(requestCallCount, 0)
}
func test_requestAuthorization_requestsAlertSoundAndBadgePermissions() {
var requestCallCount = 0
var lastOptions: UNAuthorizationOptions?
var deps = NotificationService.Dependencies.noop
deps.requestAuthorization = { options, completion in
requestCallCount += 1
lastOptions = options
completion(true, nil)
}
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps
)
service.requestAuthorization()
XCTAssertEqual(requestCallCount, 1)
XCTAssertEqual(lastOptions, [.alert, .sound, .badge])
}
func test_sendLocalNotification_buildsImmediateRequestWithUserInfo() {
var requests: [UNNotificationRequest] = []
var deps = NotificationService.Dependencies.noop
deps.deliver = { requests.append($0) }
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps
)
service.sendLocalNotification(
title: "Hello",
body: "World",
identifier: "custom-id",
userInfo: ["peerID": "abcd"],
interruptionLevel: .timeSensitive
)
let request = requests.singleValue
XCTAssertEqual(request?.identifier, "custom-id")
XCTAssertEqual(request?.content.title, "Hello")
XCTAssertEqual(request?.content.body, "World")
XCTAssertEqual(request?.content.userInfo["peerID"] as? String, "abcd")
XCTAssertEqual(request?.content.interruptionLevel, .timeSensitive)
XCTAssertNil(request?.trigger)
}
/// Previews shown: the opt-in behavior. Stated explicitly rather than
/// inherited from the shared preference, which now defaults to hidden.
func test_sendPrivateMessageNotification_populatesPeerMetadata() {
var requests: [UNNotificationRequest] = []
var deps = NotificationService.Dependencies.noop
deps.deliver = { requests.append($0) }
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps,
hidePreviewsProvider: { false }
)
let peerID = PeerID(str: "deadbeefdeadbeef")
service.sendPrivateMessageNotification(from: "Alice", message: "hi", peerID: peerID)
let request = requests.singleValue
XCTAssertEqual(request?.content.title, "🔒 DM from Alice")
XCTAssertEqual(request?.content.body, "hi")
XCTAssertEqual(request?.content.userInfo["peerID"] as? String, peerID.id)
XCTAssertEqual(request?.content.userInfo.count, 1)
}
func test_sendPrivateMessageNotification_formatsMediaAndReactions() {
var requests: [UNNotificationRequest] = []
var deps = NotificationService.Dependencies.noop
deps.deliver = { requests.append($0) }
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps,
hidePreviewsProvider: { false }
)
let peerID = PeerID(str: "deadbeefdeadbeef")
service.sendPrivateMessageNotification(
from: "Lulose",
message: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a",
peerID: peerID
)
service.sendPrivateMessageNotification(
from: "Lulose",
message: "[react:7831339C:❤️]",
peerID: peerID
)
XCTAssertEqual(requests.count, 2)
XCTAssertEqual(requests[0].content.body, "Voice message")
XCTAssertEqual(requests[1].content.body, "Reacted ❤️")
}
/// Previews hidden: the default. The routing payload has to survive
/// redaction, or tapping the alert would not open the conversation.
func test_sendPrivateMessageNotification_withPreviewsHidden_keepsRoutingButDropsContent() {
var requests: [UNNotificationRequest] = []
var deps = NotificationService.Dependencies.noop
deps.deliver = { requests.append($0) }
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps,
hidePreviewsProvider: { true }
)
let peerID = PeerID(str: "deadbeefdeadbeef")
service.sendPrivateMessageNotification(from: "Alice", message: "hi", peerID: peerID)
let request = requests.singleValue
XCTAssertFalse(request?.content.title.contains("Alice") ?? true)
XCTAssertFalse(request?.content.body.contains("hi") ?? true)
XCTAssertFalse(request?.content.title.isEmpty ?? true)
XCTAssertEqual(request?.content.userInfo["peerID"] as? String, peerID.id)
XCTAssertEqual(request?.content.userInfo.count, 1)
}
func test_wrapperNotifications_setExpectedIdentifiersAndDeepLinks() {
var requests: [UNNotificationRequest] = []
var deps = NotificationService.Dependencies.noop
deps.deliver = { requests.append($0) }
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps
)
service.sendGeohashActivityNotification(geohash: "87yv", bodyPreview: "Someone is here")
service.sendNetworkAvailableNotification(peerCount: 2)
XCTAssertEqual(requests.count, 2)
XCTAssertEqual(requests[0].content.userInfo["deeplink"] as? String, "bitchat://geohash/87yv")
XCTAssertTrue(requests[0].identifier.hasPrefix("geo-activity-87yv-"))
XCTAssertEqual(requests[1].identifier, "network-available")
XCTAssertEqual(requests[1].content.interruptionLevel, .timeSensitive)
XCTAssertEqual(requests[1].content.body, "2 people around")
}
func test_clearAllNotificationsForPanic_clearsPendingAndDelivered() {
var removePendingCalls = 0
var removeDeliveredCalls = 0
var deps = NotificationService.Dependencies.noop
deps.removeAllPending = { removePendingCalls += 1 }
deps.removeAllDelivered = { removeDeliveredCalls += 1 }
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps
)
service.clearAllNotificationsForPanic()
XCTAssertEqual(removePendingCalls, 1)
XCTAssertEqual(removeDeliveredCalls, 1)
}
func test_clearAllNotificationsForPanic_skipsWhenRunningTests() {
var removePendingCalls = 0
var removeDeliveredCalls = 0
var deps = NotificationService.Dependencies.noop
deps.removeAllPending = { removePendingCalls += 1 }
deps.removeAllDelivered = { removeDeliveredCalls += 1 }
let service = NotificationService(
isRunningTestsProvider: { true },
dependencies: deps
)
service.clearAllNotificationsForPanic()
XCTAssertEqual(removePendingCalls, 0)
XCTAssertEqual(removeDeliveredCalls, 0)
}
func test_clearAllNotificationsForPanic_invalidatesPostsBeforeRemoving() {
let generation = NotificationPostGeneration()
let postedBefore = generation.current
var stillCurrentAtRemoval: Bool?
var deps = NotificationService.Dependencies.noop
deps.removeAllPending = {
stillCurrentAtRemoval = generation.isCurrent(postedBefore)
}
let service = NotificationService(
isRunningTestsProvider: { false },
dependencies: deps,
postGeneration: generation
)
service.clearAllNotificationsForPanic()
XCTAssertEqual(stillCurrentAtRemoval, false)
}
func test_deliver_handsTheCenterARequestNoWipeOvertook() async {
let center = FakeNotificationCenter()
let generation = NotificationPostGeneration()
await NotificationService.deliver(
Self.request("dm-1"),
postedIn: generation.current,
to: center,
generation: generation
)
XCTAssertEqual(center.added, ["dm-1"])
XCTAssertEqual(center.removedDelivered, [])
XCTAssertEqual(center.removedPending, [])
}
func test_deliver_dropsARequestPostedBeforeAWipe() async {
let center = FakeNotificationCenter()
let generation = NotificationPostGeneration()
let postedIn = generation.current
generation.invalidate()
await NotificationService.deliver(
Self.request("dm-1"),
postedIn: postedIn,
to: center,
generation: generation
)
XCTAssertEqual(center.added, [])
}
func test_deliver_takesBackARequestAWipeOvertakesInFlight() async {
let center = FakeNotificationCenter()
let addStarted = expectation(description: "the center started taking the request")
center.holdAdds { addStarted.fulfill() }
let generation = NotificationPostGeneration()
let postedIn = generation.current
let delivery = Task {
await NotificationService.deliver(
Self.request("dm-1"),
postedIn: postedIn,
to: center,
generation: generation
)
}
await fulfillment(of: [addStarted], timeout: TestConstants.settleTimeout)
generation.invalidate()
center.releaseHeldAdd()
await delivery.value
XCTAssertEqual(center.added, ["dm-1"])
XCTAssertEqual(center.removedDelivered, ["dm-1"])
XCTAssertEqual(center.removedPending, ["dm-1"])
}
private static func request(_ identifier: String) -> UNNotificationRequest {
UNNotificationRequest(identifier: identifier, content: UNMutableNotificationContent(), trigger: nil)
}
}
private final class FakeNotificationCenter: NotificationCenterPosting, @unchecked Sendable {
private let lock = NSLock()
private var addedIDs: [String] = []
private var removedDeliveredIDs: [String] = []
private var removedPendingIDs: [String] = []
private var onAddHeld: (() -> Void)?
private var heldAdd: CheckedContinuation<Void, Never>?
var added: [String] { lock.withLock { addedIDs } }
var removedDelivered: [String] { lock.withLock { removedDeliveredIDs } }
var removedPending: [String] { lock.withLock { removedPendingIDs } }
func holdAdds(onHeld: @escaping () -> Void) {
lock.withLock { onAddHeld = onHeld }
}
func releaseHeldAdd() {
let continuation = lock.withLock { () -> CheckedContinuation<Void, Never>? in
defer { heldAdd = nil }
return heldAdd
}
continuation?.resume()
}
func add(_ request: UNNotificationRequest) async throws {
if let onHeld = lock.withLock({ onAddHeld }) {
await withCheckedContinuation { continuation in
lock.withLock { heldAdd = continuation }
onHeld()
}
}
lock.withLock { addedIDs.append(request.identifier) }
}
func removeDeliveredNotifications(withIdentifiers identifiers: [String]) {
lock.withLock { removedDeliveredIDs += identifiers }
}
func removePendingNotificationRequests(withIdentifiers identifiers: [String]) {
lock.withLock { removedPendingIDs += identifiers }
}
}
private extension Array {
var singleValue: Element? {
count == 1 ? self[0] : nil
}
}