Files
element-x-ios/UnitTests/Sources/ElementCallServiceTests.swift
T
Mauro a520d94760 Swift 6 Migration (#5733)
* Enable Swift 6.2 with default main actor isolation for the app target

Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default).

# Conflicts:
#	ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

* Update the code generation templates for Swift 6

Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings.

# Conflicts:
#	ElementX/Sources/Mocks/Generated/GeneratedMocks.swift

* Make the data layer and services nonisolated and Sendable

Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation.

* Adopt the new isolation across call sites, mocks and signatures

Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms.

^ Conflicts:
^	ElementX/Sources/Services/SecureBackup/SecureBackupController.swift

* Remove redundant @MainActor annotations

With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required.

* Fix concurrency hotspots surfaced by the migration

Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs.

* Fix the unit tests for Swift 6 concurrency

Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures.

* offload diffs on concurrent threads instead of main actor

* make room info protocols sendable

* use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview.

* use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor.

* small pr comments issues being addressed

* update enterprise

* Update StaticCode to 1.1.0 and specify the required Swift isolation.

* fix ElementCallServiceTests

* update enterprise

* re-generate mocks

* update enterprise

* enterprise new code conformed to swift 6

---------

Co-authored-by: Doug <douglase@element.io>
2026-06-18 17:55:31 +02:00

283 lines
12 KiB
Swift

//
// Copyright 2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import CallKit
import Clocks
@testable import ElementX
import PushKit
import Testing
@MainActor
final class ElementCallServiceTests {
private var callProvider: CXProviderMock!
private var currentDate: Date!
private var testClock: TestClock<Duration>!
private var pushRegistry: PKPushRegistry!
private var service: ElementCallService!
init() {
pushRegistry = PKPushRegistry(queue: nil)
callProvider = CXProviderMock(.init())
currentDate = Date()
testClock = TestClock()
let dateProvider: () -> Date = {
self.currentDate
}
service = ElementCallService(callProvider: callProvider, timeProvider: TimeProvider(clock: testClock, now: dateProvider))
}
deinit {
callProvider = nil
currentDate = nil
testClock = nil
pushRegistry = nil
}
@Test
func incomingCall() async {
#expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled)
await waitForConfirmation { confirmation in
let pkPushPayloadMock = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30)
service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: pkPushPayloadMock, for: .voIP) {
confirmation()
}
}
#expect(callProvider.reportNewIncomingCallWithUpdateCompletionCalled)
// Verify the provider was called with a CXCallUpdate that has video enabled
if let args = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments {
#expect(args.update.hasVideo == true)
} else {
Issue.record("Expected reportNewIncomingCallWithUpdateCompletionReceivedArguments to be captured")
}
}
@Test
func incomingVoiceCall() async {
#expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled)
await waitForConfirmation { confirmation in
let pkPushPayloadMock = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30)
.updateIsVoice(true)
service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: pkPushPayloadMock, for: .voIP) {
confirmation()
}
}
#expect(callProvider.reportNewIncomingCallWithUpdateCompletionCalled)
// Verify the provider was called with a CXCallUpdate that has video enabled
if let args = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments {
// Due to a limitation on Callkit and Webviews, we currently have to report voice calls as having video,
// even if they are voice calls :/ If not the webview is not started and the call is not shown to the user.
#expect(args.update.hasVideo == true)
} else {
Issue.record("Expected reportNewIncomingCallWithUpdateCompletionReceivedArguments to be captured")
}
}
@Test(.disabled())
func callIsTimingOut() async {
#expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled)
await confirmation { confirmation in
let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 20)
service.pushRegistry(pushRegistry,
didReceiveIncomingPushWith: pushPayload,
for: .voIP) {
confirmation()
}
}
await confirmation { confirmation in
callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in
if reason == .unanswered {
confirmation()
} else {
Issue.record("Call should have ended as unanswered")
}
}
// advance past the timeout
await testClock.advance(by: .seconds(30))
}
}
@Test
func lifetimeIsCapped() async {
await confirmation { confirmation in
callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in
if reason == .unanswered {
confirmation()
} else {
Issue.record("Call should have ended as unanswered")
}
}
#expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled)
let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 300)
service.pushRegistry(pushRegistry,
didReceiveIncomingPushWith: pushPayload,
for: .voIP) { }
// Advance past the max timeout but below the 300
await testClock.advance(by: .seconds(100))
}
}
@Test
func callIntentRawValues() {
// Test to ensure that the implicit rawValue of the string enum matches the MSC values
#expect(CallIntent.audio.rawValue == "audio")
#expect(CallIntent.video.rawValue == "video")
}
@Test
func timeoutClearsIncomingCallStateBeforeNextPush() async {
// Drive push #1 to its 60s unanswered timeout
await confirmation { confirmation in
callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in
if reason == .unanswered {
confirmation()
}
}
let firstPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60)
service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: firstPayload, for: .voIP) { }
await testClock.advance(by: .seconds(70))
}
callProvider.reportCallWithEndedAtReasonClosure = nil
let firstCallUUID = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid
// Send push #2 for the same room; the previous incoming state must be cleared,
// so the second push gets a fresh CallID.
await waitForConfirmation { confirmation in
let secondPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60)
service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: secondPayload, for: .voIP) {
confirmation()
}
}
let secondCallUUID = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid
#expect(firstCallUUID != nil)
#expect(secondCallUUID != nil)
#expect(firstCallUUID != secondCallUUID)
let unansweredCount = callProvider.reportCallWithEndedAtReasonReceivedInvocations.filter { $0.reason == .unanswered }.count
#expect(unansweredCount == 1)
}
@Test
func setupCallSessionCancelsPendingUnansweredTimeout() async {
// Schedule the 60s unanswered timer via an incoming push
await waitForConfirmation { confirmation in
let payload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60)
service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) {
confirmation()
}
}
// Simulate the answer flow handing off to setupCallSession, which must cancel
// the pending endUnansweredCallTask as part of clearing the incoming state.
await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome")
var unansweredFired = false
callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in
if reason == .unanswered {
unansweredFired = true
}
}
// Advance past what would have been the 60s unanswered timeout
await testClock.advance(by: .seconds(120))
for _ in 0..<3 {
await Task.yield()
}
#expect(!unansweredFired, "endUnansweredCallTask should have been cancelled by setupCallSession")
}
@Test
func expiredPushReportsMissedCall() async {
// An expired push is a real call we missed, so it should show up in Recents as one.
let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 20)
currentDate = currentDate.addingTimeInterval(60)
await expectImmediatelyEndedCallReported(forPayload: pushPayload, expectedReason: .unanswered)
let update = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update
#expect(update?.localizedCallerName == "welcome")
#expect(update?.remoteHandle?.value == "!room:example.com")
}
@Test
func duplicateRoomPushReportsCallAsHandled() async {
// A duplicate push for an ongoing call is reported as handled, leaving the ongoing call alone.
await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome")
let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30)
await expectImmediatelyEndedCallReported(forPayload: pushPayload, expectedReason: .answeredElsewhere)
// The call should be named so neither the brief system UI nor the Recents entry shows "Unknown".
let update = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update
#expect(update?.localizedCallerName == "welcome")
#expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com")
}
private func expectImmediatelyEndedCallReported(forPayload payload: PKPushPayloadMock,
expectedReason: CXCallEndedReason) async {
let baselineNewIncomingCount = callProvider.reportNewIncomingCallWithUpdateCompletionCallsCount
let baselineEndedCount = callProvider.reportCallWithEndedAtReasonCallsCount
await waitForConfirmation { confirmation in
service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) {
confirmation()
}
}
#expect(callProvider.reportNewIncomingCallWithUpdateCompletionCallsCount == baselineNewIncomingCount + 1)
#expect(callProvider.reportCallWithEndedAtReasonCallsCount == baselineEndedCount + 1)
let reportedCall = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments
let endedCall = callProvider.reportCallWithEndedAtReasonReceivedArguments
#expect(reportedCall?.uuid == endedCall?.uuid)
#expect(endedCall?.reason == expectedReason)
}
}
private class PKPushPayloadMock: PKPushPayload {
var dict: [AnyHashable: Any] = [:]
override init() {
dict[ElementCallServiceNotificationKey.roomID.rawValue] = "!room:example.com"
dict[ElementCallServiceNotificationKey.roomDisplayName.rawValue] = "welcome"
dict[ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue] = "$000"
dict[ElementCallServiceNotificationKey.expirationDate.rawValue] = Date(timeIntervalSince1970: 10)
}
override var dictionaryPayload: [AnyHashable: Any] {
dict
}
func updatingExpiration(_ from: Date, lifetime: TimeInterval) -> Self {
dict[ElementCallServiceNotificationKey.expirationDate.rawValue] = from.addingTimeInterval(lifetime)
return self
}
func updateIsVoice(_ isVoice: Bool) -> Self {
dict[ElementCallServiceNotificationKey.isVoiceCall.rawValue] = isVoice
return self
}
}