Files
element-x-ios/UnitTests/Sources/SecurityAndPrivacyScreenViewModelTests.swift
T
Mauro Romito 58fb7c4fcb Wait on durable state in three flaky test suites
These three suites assert against state that is still being loaded or has
already moved on, so they fail whenever a busy runner stretches the window.
All three passed on CI only because `-retry-tests-on-failure` re-ran them.

- MediaUploadPreviewScreenViewModelTests: the processing failure tests treated
  a one second `deferFailure` window as if it also meant the send had finished.
  Preprocessing the valid files outlasts it, so wait for the interaction to be
  re-enabled instead.
- SecurityAndPrivacyScreenViewModelTests: the screen loads its parent spaces and
  its room directory visibility in two independent tasks, and `isSaveDisabled`
  needs both. Every wait now gates on the visibility having landed too.
- RoomNotificationSettingsScreenViewModelTests: the delete tests waited on a
  transient `deletingCustomSetting` flag that the observation coalesces away
  under load. They now wait on the dismiss action and the alert.
2026-07-29 11:53:17 +02:00

479 lines
21 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-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 Combine
@testable import ElementX
import MatrixRustSDK
import Testing
@MainActor
final class SecurityAndPrivacyScreenViewModelTests {
var viewModel: SecurityAndPrivacyScreenViewModelProtocol!
var roomProxy: JoinedRoomProxyMock!
var context: SecurityAndPrivacyScreenViewModelType.Context {
viewModel.context
}
isolated deinit {
viewModel = nil
roomProxy = nil
}
@Test
func setSingleJoinedSpaceMembersAccess() async throws {
let singleRoom = [SpaceServiceRoom].mockSingleRoom
let space = singleRoom[0]
setupViewModel(joinedParentSpaces: singleRoom, joinRule: .public)
let deferred = deferScreenLoaded { $0.selectableJoinedSpaces.count == 1 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType == .anyone)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isSpaceMembersOptionSelectable)
guard case .singleJoined = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .singleJoined")
return
}
context.send(viewAction: .selectedSpaceMembersAccess)
#expect(context.desiredSettings.accessType == .spaceMembers(spaceIDs: [space.id]))
#expect(!context.viewState.shouldShowAccessSectionFooter)
#expect(!context.viewState.isSaveDisabled)
await waitForConfirmation("Join rule has updated") { confirm in
roomProxy.updateJoinRuleClosure = { value in
#expect(value == .restricted(rules: [.roomMembership(roomID: space.id)]))
confirm()
return .success(())
}
context.send(viewAction: .save)
}
}
@Test
func setSingleJoinedAskToJoinWithSpaceMembersAccess() async throws {
let singleRoom = [SpaceServiceRoom].mockSingleRoom
let space = singleRoom[0]
setupViewModel(joinedParentSpaces: singleRoom, joinRule: .public)
let deferred = deferScreenLoaded { $0.selectableJoinedSpaces.count == 1 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType == .anyone)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isAskToJoinWithSpaceMembersOptionSelectable)
guard case .singleJoined = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .singleJoined")
return
}
context.send(viewAction: .selectedAskToJoinWithSpaceMembersAccess)
#expect(context.desiredSettings.accessType == .askToJoinWithSpaceMembers(spaceIDs: [space.id]))
#expect(!context.viewState.shouldShowAccessSectionFooter)
#expect(!context.viewState.isSaveDisabled)
await waitForConfirmation("Join rule has updated") { confirm in
roomProxy.updateJoinRuleClosure = { value in
#expect(value == .knockRestricted(rules: [.roomMembership(roomID: space.id)]))
confirm()
return .success(())
}
context.send(viewAction: .save)
}
}
@Test
func singleUnknownSpaceMembersAccessCanBeReselected() async throws {
let singleRoom = [SpaceServiceRoom].mockSingleRoom
let space = singleRoom[0]
setupViewModel(joinedParentSpaces: [], joinRule: .restricted(rules: [.roomMembership(roomID: space.id)]))
let deferred = deferScreenLoaded { $0.selectableJoinedSpaces.isEmpty }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType == .spaceMembers(spaceIDs: [space.id]))
#expect(context.desiredSettings == context.viewState.currentSettings)
#expect(context.viewState.isSpaceMembersOptionSelectable)
#expect(!context.viewState.shouldShowAccessSectionFooter)
#expect(context.viewState.isSaveDisabled)
guard case .singleUnknown = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .singleUnknown")
return
}
let saveDeferred = deferFulfillment(context.$viewState) { !$0.isSaveDisabled }
context.desiredSettings.accessType = .anyone
try await saveDeferred.fulfill()
#expect(context.viewState.isSpaceMembersOptionSelectable)
context.send(viewAction: .selectedSpaceMembersAccess)
#expect(context.viewState.isSaveDisabled)
#expect(context.desiredSettings.accessType == .spaceMembers(spaceIDs: [space.id]))
guard case .singleUnknown = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .singleUnknown")
return
}
}
@Test
func multipleKnownSpacesMembersSelection() async throws {
let spaces = [SpaceServiceRoom].mockJoinedSpaces2
setupViewModel(joinedParentSpaces: spaces, joinRule: .public)
let deferred = deferScreenLoaded { $0.selectableJoinedSpaces.count == 3 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType == .anyone)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isSpaceMembersOptionSelectable)
guard case .multiple = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .multiple")
return
}
var selectedIDs: PassthroughSubject<Set<String>, Never>!
let deferredAction = deferFulfillment(viewModel.actionsPublisher) { action in
switch action {
case .displayManageAuthorizedSpacesScreen(let authorizedSpacesSelection):
defer { selectedIDs = authorizedSpacesSelection.selectedIDs }
return authorizedSpacesSelection.joinedSpaces.map(\.id) == spaces.map(\.id) &&
authorizedSpacesSelection.unknownSpacesIDs.isEmpty &&
authorizedSpacesSelection.initialSelectedIDs.isEmpty
default:
return false
}
}
context.send(viewAction: .selectedSpaceMembersAccess)
try await deferredAction.fulfill()
selectedIDs.send([spaces[0].id])
#expect(context.desiredSettings.accessType == .spaceMembers(spaceIDs: [spaces[0].id]))
#expect(context.viewState.shouldShowAccessSectionFooter)
#expect(!context.viewState.isSaveDisabled)
await waitForConfirmation("Join rule has updated") { confirm in
roomProxy.updateJoinRuleClosure = { value in
#expect(value == .restricted(rules: [.roomMembership(roomID: spaces[0].id)]))
confirm()
return .success(())
}
context.send(viewAction: .save)
}
}
@Test
func multipleKnownAskToJoinSpacesMembersSelection() async throws {
let spaces = [SpaceServiceRoom].mockJoinedSpaces2
setupViewModel(joinedParentSpaces: spaces, joinRule: .public)
let deferred = deferScreenLoaded { $0.selectableJoinedSpaces.count == 3 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType == .anyone)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isAskToJoinWithSpaceMembersOptionSelectable)
guard case .multiple = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .multiple")
return
}
var selectedIDs: PassthroughSubject<Set<String>, Never>!
let deferredAction = deferFulfillment(viewModel.actionsPublisher) { action in
switch action {
case .displayManageAuthorizedSpacesScreen(let authorizedSpacesSelection):
defer { selectedIDs = authorizedSpacesSelection.selectedIDs }
return authorizedSpacesSelection.joinedSpaces.map(\.id) == spaces.map(\.id) &&
authorizedSpacesSelection.unknownSpacesIDs.isEmpty &&
authorizedSpacesSelection.initialSelectedIDs.isEmpty
default:
return false
}
}
context.send(viewAction: .selectedAskToJoinWithSpaceMembersAccess)
try await deferredAction.fulfill()
selectedIDs.send([spaces[0].id])
#expect(context.desiredSettings.accessType == .askToJoinWithSpaceMembers(spaceIDs: [spaces[0].id]))
#expect(context.viewState.shouldShowAccessSectionFooter)
#expect(!context.viewState.isSaveDisabled)
await waitForConfirmation("Join rule has updated") { confirm in
roomProxy.updateJoinRuleClosure = { value in
#expect(value == .knockRestricted(rules: [.roomMembership(roomID: spaces[0].id)]))
confirm()
return .success(())
}
context.send(viewAction: .save)
}
}
@Test
func multipleSpacesMembersSelection() async throws {
let spaces = [SpaceServiceRoom].mockJoinedSpaces2
setupViewModel(joinedParentSpaces: spaces,
joinRule: .restricted(rules: [.roomMembership(roomID: "unknownSpaceID")]))
let deferred = deferScreenLoaded { $0.selectableSpacesCount == 4 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType.isSpaceMembers)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isSpaceMembersOptionSelectable)
guard case .multiple = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .multiple")
return
}
var selectedIDs: PassthroughSubject<Set<String>, Never>!
let deferredAction = deferFulfillment(viewModel.actionsPublisher) { action in
switch action {
case .displayManageAuthorizedSpacesScreen(let authorizedSpacesSelection):
// We need the
defer { selectedIDs = authorizedSpacesSelection.selectedIDs }
return authorizedSpacesSelection.joinedSpaces.map(\.id) == spaces.map(\.id) &&
authorizedSpacesSelection.unknownSpacesIDs == ["unknownSpaceID"] &&
authorizedSpacesSelection.initialSelectedIDs == ["unknownSpaceID"]
default:
return false
}
}
context.send(viewAction: .manageSpaces)
try await deferredAction.fulfill()
selectedIDs.send([spaces[0].id, "unknownSpaceID"])
#expect(context.desiredSettings.accessType == .spaceMembers(spaceIDs: [spaces[0].id, "unknownSpaceID"]))
#expect(context.viewState.shouldShowAccessSectionFooter)
#expect(!context.viewState.isSaveDisabled)
await waitForConfirmation("Join rule has updated") { confirm in
roomProxy.updateJoinRuleClosure = { value in
#expect(value == .restricted(rules: [.roomMembership(roomID: spaces[0].id), .roomMembership(roomID: "unknownSpaceID")]))
confirm()
return .success(())
}
context.send(viewAction: .save)
}
}
@Test
func multipleSpacesMembersSelectionWithAnExistingNonParentButJoinedSpace() async throws {
let joinedParentSpaces = [SpaceServiceRoom].mockJoinedSpaces2
let singleRoom = [SpaceServiceRoom].mockSingleRoom
let space = singleRoom[0]
let allSpaces = joinedParentSpaces + singleRoom
setupViewModel(joinedParentSpaces: joinedParentSpaces,
topLevelSpaces: allSpaces,
joinRule: .restricted(rules: [.roomMembership(roomID: space.id),
.roomMembership(roomID: "unknownSpaceID")]))
let deferred = deferScreenLoaded { $0.selectableSpacesCount == 5 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType.isSpaceMembers)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isSpaceMembersOptionSelectable)
guard case .multiple = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .multiple")
return
}
var selectedIDs: PassthroughSubject<Set<String>, Never>!
let deferredAction = deferFulfillment(viewModel.actionsPublisher) { action in
switch action {
case .displayManageAuthorizedSpacesScreen(let authorizedSpacesSelection):
// We need the
defer { selectedIDs = authorizedSpacesSelection.selectedIDs }
return authorizedSpacesSelection.joinedSpaces.map(\.id) == allSpaces.map(\.id) &&
authorizedSpacesSelection.unknownSpacesIDs == ["unknownSpaceID"] &&
authorizedSpacesSelection.initialSelectedIDs == [space.id, "unknownSpaceID"]
default:
return false
}
}
context.send(viewAction: .manageSpaces)
try await deferredAction.fulfill()
selectedIDs.send([allSpaces[0].id, "unknownSpaceID"])
#expect(context.desiredSettings.accessType == .spaceMembers(spaceIDs: [allSpaces[0].id, "unknownSpaceID"]))
#expect(context.viewState.shouldShowAccessSectionFooter)
#expect(!context.viewState.isSaveDisabled)
}
@Test
func emptySpaceMembersSelectionEdgeCase() async throws {
// Edge case where there is no available joined parents and the room has a restricted join rule.
// With no space ids in it
setupViewModel(joinedParentSpaces: [],
joinRule: .restricted(rules: []))
let deferred = deferScreenLoaded { $0.selectableSpacesCount == 0 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType.isSpaceMembers)
#expect(context.viewState.isSaveDisabled)
#expect(!context.viewState.isSpaceMembersOptionSelectable)
#expect(!context.viewState.shouldShowAccessSectionFooter)
guard case .empty = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .empty")
return
}
}
@Test
func emptySpaceMembersSelectionWithJoinedParentEdgeCase() async throws {
// Edge case where there is one available joined parent but the room has a restricted join rule.
// With no space ids in it
let singleRoom = [SpaceServiceRoom].mockSingleRoom
setupViewModel(joinedParentSpaces: singleRoom,
joinRule: .restricted(rules: []))
let deferred = deferScreenLoaded { $0.selectableSpacesCount == 1 }
try await deferred.fulfill()
#expect(context.viewState.currentSettings.accessType.isSpaceMembers)
#expect(context.viewState.isSaveDisabled)
#expect(context.viewState.isSpaceMembersOptionSelectable)
#expect(context.viewState.shouldShowAccessSectionFooter)
guard case .multiple = context.viewState.spaceSelection else {
Issue.record("Expected spaceSelection to be .multiple")
return
}
let deferredAction = deferFulfillment(viewModel.actionsPublisher) { action in
switch action {
case .displayManageAuthorizedSpacesScreen(let authorizedSpacesSelection):
return authorizedSpacesSelection.joinedSpaces.map(\.id) == singleRoom.map(\.id) &&
authorizedSpacesSelection.unknownSpacesIDs.isEmpty &&
authorizedSpacesSelection.initialSelectedIDs.isEmpty
default:
return false
}
}
context.send(viewAction: .manageSpaces)
try await deferredAction.fulfill()
}
@Test
func save() async throws {
setupViewModel(joinedParentSpaces: [], joinRule: .public)
// Saving shouldn't dismiss this screen (or trigger any other action).
let deferred = deferFailure(viewModel.actionsPublisher, timeout: .seconds(1)) { _ in true }
context.desiredSettings.accessType = .inviteOnly
context.send(viewAction: .save)
try await deferred.fulfill()
}
@Test
func cancelWithChangesAndDiscard() async throws {
setupViewModel(joinedParentSpaces: [], joinRule: .public)
context.desiredSettings.accessType = .inviteOnly
#expect(!context.viewState.isSaveDisabled)
#expect(context.alertInfo == nil)
context.send(viewAction: .cancel)
#expect(context.alertInfo != nil)
let deferred = deferFulfillment(viewModel.actionsPublisher) {
switch $0 {
case .dismiss:
true
default:
false
}
}
context.alertInfo?.secondaryButton?.action?() // Discard
try await deferred.fulfill()
}
@Test
func cancelWithChangesAndSave() async throws {
setupViewModel(joinedParentSpaces: [], joinRule: .public)
context.desiredSettings.accessType = .inviteOnly
#expect(!context.viewState.isSaveDisabled)
#expect(context.alertInfo == nil)
context.send(viewAction: .cancel)
#expect(context.alertInfo != nil)
let deferred = deferFulfillment(viewModel.actionsPublisher) {
switch $0 {
case .dismiss:
true
default:
false
}
}
context.alertInfo?.primaryButton.action?() // Save
try await deferred.fulfill()
}
@Test
func cancelWithChangesAndSaveWithFailure() async throws {
setupViewModel(joinedParentSpaces: [], joinRule: .public)
roomProxy.updateJoinRuleReturnValue = .failure(.sdkError(RoomProxyMockError.generic))
context.desiredSettings.accessType = .inviteOnly
#expect(!context.viewState.isSaveDisabled)
#expect(context.alertInfo == nil)
context.send(viewAction: .cancel)
#expect(context.alertInfo != nil)
// The screen should not be dismissed if a failure occurred.
let deferred = deferFailure(viewModel.actionsPublisher, timeout: .seconds(1)) { _ in true }
context.alertInfo?.primaryButton.action?() // Save
try await deferred.fulfill()
}
@Test
func encryptionOptionAvailability() {
setupViewModel(joinedParentSpaces: [], joinRule: .public)
#expect(context.viewState.canEnableEncryption)
setupViewModel(joinedParentSpaces: [], joinRule: .public, forceDisableE2EE: true)
#expect(!context.viewState.canEnableEncryption)
}
// MARK: - Helpers
/// Waits for `condition` **and** for the screen to have finished loading.
///
/// The view model fetches its parent spaces and its room directory visibility in two independent tasks.
/// Waiting on the spaces alone leaves `isSaveDisabled` reading `true` whilst the visibility is unknown,
/// so every wait needs to gate on both having landed.
private func deferScreenLoaded(until condition: @escaping (SecurityAndPrivacyScreenViewState) -> Bool) -> DeferredFulfillment<SecurityAndPrivacyScreenViewState> {
deferFulfillment(context.$viewState) { condition($0) && $0.currentSettings.isVisibileInRoomDirectory != nil }
}
private func setupViewModel(joinedParentSpaces: [SpaceServiceRoom],
topLevelSpaces: [SpaceServiceRoom] = [],
joinRule: ElementX.JoinRule,
forceDisableE2EE: Bool = false) {
let appSettings = AppSettings.volatile()
appSettings.knockingEnabled = true
appSettings.forceDisableE2EE.applyRemoteValue(forceDisableE2EE)
roomProxy = JoinedRoomProxyMock(.init(isEncrypted: false,
canonicalAlias: "#room:matrix.org",
members: .allMembersAsCreator,
joinRule: joinRule,
isVisibleInPublicDirectory: true))
roomProxy.updateJoinRuleReturnValue = .success(())
roomProxy.updateRoomDirectoryVisibilityReturnValue = .success(())
viewModel = SecurityAndPrivacyScreenViewModel(roomProxy: roomProxy,
clientProxy: ClientProxyMock(.init(userIDServerName: "matrix.org",
spaceServiceConfiguration: .init(topLevelSpaces: topLevelSpaces,
joinedParentSpaces: joinedParentSpaces))),
userIndicatorController: UserIndicatorControllerMock(),
appSettings: appSettings)
}
}