diff --git a/ElementX.xcodeproj/project.pbxproj b/ElementX.xcodeproj/project.pbxproj index 5d4f1c690..2653baa5e 100644 --- a/ElementX.xcodeproj/project.pbxproj +++ b/ElementX.xcodeproj/project.pbxproj @@ -885,6 +885,7 @@ DC1BB5EE5F4D9B6A1F98A77A /* WelcomeScreenScreenViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEC2E8E1B20BB2EA07B0B61E /* WelcomeScreenScreenViewModel.swift */; }; DC68E866D6E664B0D2B06E74 /* MockImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC1DA29A5A041CC0BACA7CB0 /* MockImageCache.swift */; }; DDB47D29C6865669288BF87C /* UIFont+AttributedStringBuilder.m in Sources */ = {isa = PBXBuildFile; fileRef = E8CA187FE656EE5A3F6C7DE5 /* UIFont+AttributedStringBuilder.m */; }; + DDFBDEE1DC32BDD5488F898C /* ClientProxyMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F96CCBEAAA7F2185BFA354 /* ClientProxyMock.swift */; }; DE4F8C4E0F1DB4832F09DE97 /* HomeScreenViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D6764D6976D235926FE5FC /* HomeScreenViewModel.swift */; }; DF004A5B2EABBD0574D06A04 /* SplashScreenCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 854BCEAF2A832176FAACD2CB /* SplashScreenCoordinator.swift */; }; DF05F9C9D3D977EB77E13692 /* DeviceKit in Frameworks */ = {isa = PBXBuildFile; productRef = 385D4C28F9DC5CF53BD9ECDB /* DeviceKit */; }; @@ -952,7 +953,6 @@ ED90A59F068FD0CA27E602ED /* UserProfileListRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = E10DA51DBC8C7E1460DBCCBD /* UserProfileListRow.swift */; }; EDF8919F15DE0FF00EF99E70 /* DocumentPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F5567A7EF6F2AB9473236F6 /* DocumentPicker.swift */; }; EE4E2C1922BBF5169E213555 /* PillAttachmentViewProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B53D6C5C0D14B04D3AB3F6E /* PillAttachmentViewProvider.swift */; }; - EE4F5601356228FF72FC56B6 /* MockClientProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F40F48279322E504153AB0D /* MockClientProxy.swift */; }; EE56238683BC3ECA9BA00684 /* GlobalSearchScreenViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA4D639E27D5882A6A71AECF /* GlobalSearchScreenViewModelTests.swift */; }; EE8491AD81F47DF3C192497B /* DecorationTimelineItemProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 184CF8C196BE143AE226628D /* DecorationTimelineItemProtocol.swift */; }; EE8A37E2A1A77DE5CF941632 /* StateRoomTimelineView.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED983D4DCA5AFA6E1ED96099 /* StateRoomTimelineView.swift */; }; @@ -1332,7 +1332,6 @@ 3E6A9B9DFEE964962C179DE3 /* RoomAttachmentPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomAttachmentPicker.swift; sourceTree = ""; }; 3E93A1BE7D8A2EBCAD51EEB4 /* Array.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Array.swift; sourceTree = ""; }; 3EF1AC723C2609C7705569CA /* MediaLoaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaLoaderTests.swift; sourceTree = ""; }; - 3F40F48279322E504153AB0D /* MockClientProxy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockClientProxy.swift; sourceTree = ""; }; 3F684BDD23ECEADB3053BA5A /* DeveloperOptionsScreenUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeveloperOptionsScreenUITests.swift; sourceTree = ""; }; 3FFDA99C98BE05F43A92343B /* test_pdf.pdf */ = {isa = PBXFileReference; lastKnownFileType = image.pdf; path = test_pdf.pdf; sourceTree = ""; }; 40076C770A5FB83325252973 /* VoiceMessageMediaManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceMessageMediaManager.swift; sourceTree = ""; }; @@ -1947,6 +1946,7 @@ E2B1CC9AA154F4D5435BF60A /* Comparable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Comparable.swift; sourceTree = ""; }; E2DCA495ED42D2463DDAA94D /* TimelineBubbleLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineBubbleLayout.swift; sourceTree = ""; }; E2F27BAB69EB568369F1F6B3 /* OnboardingScreenViewModelProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingScreenViewModelProtocol.swift; sourceTree = ""; }; + E2F96CCBEAAA7F2185BFA354 /* ClientProxyMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClientProxyMock.swift; sourceTree = ""; }; E3059CFA00C67D8787273B20 /* ServerSelectionScreenViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSelectionScreenViewModel.swift; sourceTree = ""; }; E36CB905A2B9EC2C92A2DA7C /* KeychainController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainController.swift; sourceTree = ""; }; E3B97591B2D3D4D67553506D /* AnalyticsClientProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnalyticsClientProtocol.swift; sourceTree = ""; }; @@ -2581,6 +2581,7 @@ children = ( 69CB8242D69B7E4D0B32E18D /* AggregatedReactionMock.swift */, 62011D547772F3DF5D924823 /* ApplicationMock.swift */, + E2F96CCBEAAA7F2185BFA354 /* ClientProxyMock.swift */, 382B50F7E379B3DBBD174364 /* NotificationSettingsProxyMock.swift */, D38391154120264910D19528 /* PollMock.swift */, 36FD673E24FBFCFDF398716A /* RoomMemberProxyMock.swift */, @@ -3660,7 +3661,6 @@ D09A267106B9585D3D0CFC0D /* ClientError.swift */, 18F2958E6D247AE2516BEEE8 /* ClientProxy.swift */, 6033779EB37259F27F938937 /* ClientProxyProtocol.swift */, - 3F40F48279322E504153AB0D /* MockClientProxy.swift */, ); path = Client; sourceTree = ""; @@ -5653,6 +5653,7 @@ 6A0E7551E0D1793245F34CDD /* ClientError.swift in Sources */, 520EEDAFBC778AB0B41F2F53 /* ClientMock.swift in Sources */, 1950A80CD198BED283DFC2CE /* ClientProxy.swift in Sources */, + DDFBDEE1DC32BDD5488F898C /* ClientProxyMock.swift in Sources */, 24BDDD09A90B8BFE3793F3AA /* ClientProxyProtocol.swift in Sources */, 0C797CD650DFD2876BEC5173 /* CollapsibleReactionLayout.swift in Sources */, 9FAF6DA7E8E85C9699757764 /* CollapsibleRoomTimelineView.swift in Sources */, @@ -5847,7 +5848,6 @@ C13128AAA787A4C2CBE4EE82 /* MessageForwardingScreenViewModelProtocol.swift in Sources */, C97325EFDCCEE457432A9E82 /* MessageText.swift in Sources */, 152AE2B8650FB23AFD2E28B9 /* MockAuthenticationServiceProxy.swift in Sources */, - EE4F5601356228FF72FC56B6 /* MockClientProxy.swift in Sources */, B659E3A49889E749E3239EA7 /* MockMediaProvider.swift in Sources */, 2352C541AF857241489756FF /* MockRoomSummaryProvider.swift in Sources */, 09C83DDDB07C28364F325209 /* MockRoomTimelineController.swift in Sources */, diff --git a/ElementX/Sources/Mocks/ClientProxyMock.swift b/ElementX/Sources/Mocks/ClientProxyMock.swift new file mode 100644 index 000000000..fbd97d410 --- /dev/null +++ b/ElementX/Sources/Mocks/ClientProxyMock.swift @@ -0,0 +1,92 @@ +// +// Copyright 2024 New Vector Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Combine +import Foundation + +struct ClientProxyMockConfiguration { + let userID: String + var deviceID: String? + var roomSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider() +} + +extension ClientProxyMock { + convenience init(_ configuration: ClientProxyMockConfiguration) { + self.init() + + userID = configuration.userID + deviceID = configuration.deviceID + + homeserver = "" + + roomSummaryProvider = configuration.roomSummaryProvider + alternateRoomSummaryProvider = MockRoomSummaryProvider() + inviteSummaryProvider = MockRoomSummaryProvider() + + actionsPublisher = PassthroughSubject().eraseToAnyPublisher() + loadingStatePublisher = CurrentValuePublisher(.notLoading) + + userAvatarURLPublisher = CurrentValueSubject(nil).asCurrentValuePublisher() + + userDisplayNamePublisher = CurrentValueSubject("User display name").asCurrentValuePublisher() + + ignoredUsersPublisher = CurrentValueSubject<[String]?, Never>([RoomMemberProxyMock].allMembers.map(\.userID)).asCurrentValuePublisher() + + notificationSettings = NotificationSettingsProxyMock(with: .init()) + + isOnlyDeviceLeftReturnValue = .success(false) + accountURLActionReturnValue = "https://matrix.org/account" + directRoomForUserIDReturnValue = .failure(.failedRetrievingDirectRoom) + createDirectRoomWithExpectedRoomNameReturnValue = .failure(.failedCreatingRoom) + createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReturnValue = .failure(.failedCreatingRoom) + uploadMediaReturnValue = .failure(.failedUploadingMedia(.unknown)) + loadUserDisplayNameReturnValue = .failure(.failedRetrievingUserDisplayName) + setUserDisplayNameReturnValue = .failure(.failedSettingUserDisplayName) + loadUserAvatarURLReturnValue = .failure(.failedRetrievingUserAvatarURL) + setUserAvatarMediaReturnValue = .failure(.failedSettingUserAvatar) + removeUserAvatarReturnValue = .failure(.failedSettingUserAvatar) + logoutReturnValue = nil + searchUsersSearchTermLimitReturnValue = .success(.init(results: [], limited: false)) + profileForReturnValue = .success(.init(userID: "@a:b.com", displayName: "Some user")) + sessionVerificationControllerProxyReturnValue = .failure(.failedRetrievingSessionVerificationController) + ignoreUserReturnValue = .failure(.failedIgnoringUser) + unignoreUserReturnValue = .failure(.failedUnignoringUser) + + loadMediaContentForSourceThrowableError = ClientProxyError.failedLoadingMedia + loadMediaThumbnailForSourceWidthHeightThrowableError = ClientProxyError.failedLoadingMedia + loadMediaFileForSourceBodyThrowableError = ClientProxyError.failedLoadingMedia + + secureBackupController = { + let secureBackupController = SecureBackupControllerMock() + secureBackupController.underlyingRecoveryState = .init(CurrentValueSubject(.enabled)) + secureBackupController.underlyingKeyBackupState = .init(CurrentValueSubject(.enabled)) + return secureBackupController + }() + + roomForIdentifierClosure = { [weak self] identifier in + guard let room = self?.roomSummaryProvider?.roomListPublisher.value.first(where: { $0.id == identifier }) else { + return nil + } + + switch room { + case .empty: + return await RoomProxyMock(with: .init(name: "Empty room")) + case .filled(let details), .invalidated(let details): + return await RoomProxyMock(with: .init(name: details.name)) + } + } + } +} diff --git a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift index c456c0c7c..ef6518a44 100644 --- a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift +++ b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift @@ -716,6 +716,534 @@ class BugReportServiceMock: BugReportServiceProtocol { } } } +class ClientProxyMock: ClientProxyProtocol { + var actionsPublisher: AnyPublisher { + get { return underlyingActionsPublisher } + set(value) { underlyingActionsPublisher = value } + } + var underlyingActionsPublisher: AnyPublisher! + var loadingStatePublisher: CurrentValuePublisher { + get { return underlyingLoadingStatePublisher } + set(value) { underlyingLoadingStatePublisher = value } + } + var underlyingLoadingStatePublisher: CurrentValuePublisher! + var userID: String { + get { return underlyingUserID } + set(value) { underlyingUserID = value } + } + var underlyingUserID: String! + var deviceID: String? + var homeserver: String { + get { return underlyingHomeserver } + set(value) { underlyingHomeserver = value } + } + var underlyingHomeserver: String! + var userDisplayNamePublisher: CurrentValuePublisher { + get { return underlyingUserDisplayNamePublisher } + set(value) { underlyingUserDisplayNamePublisher = value } + } + var underlyingUserDisplayNamePublisher: CurrentValuePublisher! + var userAvatarURLPublisher: CurrentValuePublisher { + get { return underlyingUserAvatarURLPublisher } + set(value) { underlyingUserAvatarURLPublisher = value } + } + var underlyingUserAvatarURLPublisher: CurrentValuePublisher! + var ignoredUsersPublisher: CurrentValuePublisher<[String]?, Never> { + get { return underlyingIgnoredUsersPublisher } + set(value) { underlyingIgnoredUsersPublisher = value } + } + var underlyingIgnoredUsersPublisher: CurrentValuePublisher<[String]?, Never>! + var pusherNotificationClientIdentifier: String? + var roomSummaryProvider: RoomSummaryProviderProtocol? + var alternateRoomSummaryProvider: RoomSummaryProviderProtocol? + var inviteSummaryProvider: RoomSummaryProviderProtocol? + var notificationSettings: NotificationSettingsProxyProtocol { + get { return underlyingNotificationSettings } + set(value) { underlyingNotificationSettings = value } + } + var underlyingNotificationSettings: NotificationSettingsProxyProtocol! + var secureBackupController: SecureBackupControllerProtocol { + get { return underlyingSecureBackupController } + set(value) { underlyingSecureBackupController = value } + } + var underlyingSecureBackupController: SecureBackupControllerProtocol! + + //MARK: - isOnlyDeviceLeft + + var isOnlyDeviceLeftCallsCount = 0 + var isOnlyDeviceLeftCalled: Bool { + return isOnlyDeviceLeftCallsCount > 0 + } + var isOnlyDeviceLeftReturnValue: Result! + var isOnlyDeviceLeftClosure: (() async -> Result)? + + func isOnlyDeviceLeft() async -> Result { + isOnlyDeviceLeftCallsCount += 1 + if let isOnlyDeviceLeftClosure = isOnlyDeviceLeftClosure { + return await isOnlyDeviceLeftClosure() + } else { + return isOnlyDeviceLeftReturnValue + } + } + //MARK: - startSync + + var startSyncCallsCount = 0 + var startSyncCalled: Bool { + return startSyncCallsCount > 0 + } + var startSyncClosure: (() -> Void)? + + func startSync() { + startSyncCallsCount += 1 + startSyncClosure?() + } + //MARK: - stopSync + + var stopSyncCallsCount = 0 + var stopSyncCalled: Bool { + return stopSyncCallsCount > 0 + } + var stopSyncClosure: (() -> Void)? + + func stopSync() { + stopSyncCallsCount += 1 + stopSyncClosure?() + } + //MARK: - accountURL + + var accountURLActionCallsCount = 0 + var accountURLActionCalled: Bool { + return accountURLActionCallsCount > 0 + } + var accountURLActionReceivedAction: AccountManagementAction? + var accountURLActionReceivedInvocations: [AccountManagementAction] = [] + var accountURLActionReturnValue: URL? + var accountURLActionClosure: ((AccountManagementAction) -> URL?)? + + func accountURL(action: AccountManagementAction) -> URL? { + accountURLActionCallsCount += 1 + accountURLActionReceivedAction = action + accountURLActionReceivedInvocations.append(action) + if let accountURLActionClosure = accountURLActionClosure { + return accountURLActionClosure(action) + } else { + return accountURLActionReturnValue + } + } + //MARK: - directRoomForUserID + + var directRoomForUserIDCallsCount = 0 + var directRoomForUserIDCalled: Bool { + return directRoomForUserIDCallsCount > 0 + } + var directRoomForUserIDReceivedUserID: String? + var directRoomForUserIDReceivedInvocations: [String] = [] + var directRoomForUserIDReturnValue: Result! + var directRoomForUserIDClosure: ((String) async -> Result)? + + func directRoomForUserID(_ userID: String) async -> Result { + directRoomForUserIDCallsCount += 1 + directRoomForUserIDReceivedUserID = userID + directRoomForUserIDReceivedInvocations.append(userID) + if let directRoomForUserIDClosure = directRoomForUserIDClosure { + return await directRoomForUserIDClosure(userID) + } else { + return directRoomForUserIDReturnValue + } + } + //MARK: - createDirectRoom + + var createDirectRoomWithExpectedRoomNameCallsCount = 0 + var createDirectRoomWithExpectedRoomNameCalled: Bool { + return createDirectRoomWithExpectedRoomNameCallsCount > 0 + } + var createDirectRoomWithExpectedRoomNameReceivedArguments: (userID: String, expectedRoomName: String?)? + var createDirectRoomWithExpectedRoomNameReceivedInvocations: [(userID: String, expectedRoomName: String?)] = [] + var createDirectRoomWithExpectedRoomNameReturnValue: Result! + var createDirectRoomWithExpectedRoomNameClosure: ((String, String?) async -> Result)? + + func createDirectRoom(with userID: String, expectedRoomName: String?) async -> Result { + createDirectRoomWithExpectedRoomNameCallsCount += 1 + createDirectRoomWithExpectedRoomNameReceivedArguments = (userID: userID, expectedRoomName: expectedRoomName) + createDirectRoomWithExpectedRoomNameReceivedInvocations.append((userID: userID, expectedRoomName: expectedRoomName)) + if let createDirectRoomWithExpectedRoomNameClosure = createDirectRoomWithExpectedRoomNameClosure { + return await createDirectRoomWithExpectedRoomNameClosure(userID, expectedRoomName) + } else { + return createDirectRoomWithExpectedRoomNameReturnValue + } + } + //MARK: - createRoom + + var createRoomNameTopicIsRoomPrivateUserIDsAvatarURLCallsCount = 0 + var createRoomNameTopicIsRoomPrivateUserIDsAvatarURLCalled: Bool { + return createRoomNameTopicIsRoomPrivateUserIDsAvatarURLCallsCount > 0 + } + var createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReceivedArguments: (name: String, topic: String?, isRoomPrivate: Bool, userIDs: [String], avatarURL: URL?)? + var createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReceivedInvocations: [(name: String, topic: String?, isRoomPrivate: Bool, userIDs: [String], avatarURL: URL?)] = [] + var createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReturnValue: Result! + var createRoomNameTopicIsRoomPrivateUserIDsAvatarURLClosure: ((String, String?, Bool, [String], URL?) async -> Result)? + + func createRoom(name: String, topic: String?, isRoomPrivate: Bool, userIDs: [String], avatarURL: URL?) async -> Result { + createRoomNameTopicIsRoomPrivateUserIDsAvatarURLCallsCount += 1 + createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReceivedArguments = (name: name, topic: topic, isRoomPrivate: isRoomPrivate, userIDs: userIDs, avatarURL: avatarURL) + createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReceivedInvocations.append((name: name, topic: topic, isRoomPrivate: isRoomPrivate, userIDs: userIDs, avatarURL: avatarURL)) + if let createRoomNameTopicIsRoomPrivateUserIDsAvatarURLClosure = createRoomNameTopicIsRoomPrivateUserIDsAvatarURLClosure { + return await createRoomNameTopicIsRoomPrivateUserIDsAvatarURLClosure(name, topic, isRoomPrivate, userIDs, avatarURL) + } else { + return createRoomNameTopicIsRoomPrivateUserIDsAvatarURLReturnValue + } + } + //MARK: - uploadMedia + + var uploadMediaCallsCount = 0 + var uploadMediaCalled: Bool { + return uploadMediaCallsCount > 0 + } + var uploadMediaReceivedMedia: MediaInfo? + var uploadMediaReceivedInvocations: [MediaInfo] = [] + var uploadMediaReturnValue: Result! + var uploadMediaClosure: ((MediaInfo) async -> Result)? + + func uploadMedia(_ media: MediaInfo) async -> Result { + uploadMediaCallsCount += 1 + uploadMediaReceivedMedia = media + uploadMediaReceivedInvocations.append(media) + if let uploadMediaClosure = uploadMediaClosure { + return await uploadMediaClosure(media) + } else { + return uploadMediaReturnValue + } + } + //MARK: - roomForIdentifier + + var roomForIdentifierCallsCount = 0 + var roomForIdentifierCalled: Bool { + return roomForIdentifierCallsCount > 0 + } + var roomForIdentifierReceivedIdentifier: String? + var roomForIdentifierReceivedInvocations: [String] = [] + var roomForIdentifierReturnValue: RoomProxyProtocol? + var roomForIdentifierClosure: ((String) async -> RoomProxyProtocol?)? + + func roomForIdentifier(_ identifier: String) async -> RoomProxyProtocol? { + roomForIdentifierCallsCount += 1 + roomForIdentifierReceivedIdentifier = identifier + roomForIdentifierReceivedInvocations.append(identifier) + if let roomForIdentifierClosure = roomForIdentifierClosure { + return await roomForIdentifierClosure(identifier) + } else { + return roomForIdentifierReturnValue + } + } + //MARK: - loadUserDisplayName + + var loadUserDisplayNameCallsCount = 0 + var loadUserDisplayNameCalled: Bool { + return loadUserDisplayNameCallsCount > 0 + } + var loadUserDisplayNameReturnValue: Result! + var loadUserDisplayNameClosure: (() async -> Result)? + + @discardableResult + func loadUserDisplayName() async -> Result { + loadUserDisplayNameCallsCount += 1 + if let loadUserDisplayNameClosure = loadUserDisplayNameClosure { + return await loadUserDisplayNameClosure() + } else { + return loadUserDisplayNameReturnValue + } + } + //MARK: - setUserDisplayName + + var setUserDisplayNameCallsCount = 0 + var setUserDisplayNameCalled: Bool { + return setUserDisplayNameCallsCount > 0 + } + var setUserDisplayNameReceivedName: String? + var setUserDisplayNameReceivedInvocations: [String] = [] + var setUserDisplayNameReturnValue: Result! + var setUserDisplayNameClosure: ((String) async -> Result)? + + func setUserDisplayName(_ name: String) async -> Result { + setUserDisplayNameCallsCount += 1 + setUserDisplayNameReceivedName = name + setUserDisplayNameReceivedInvocations.append(name) + if let setUserDisplayNameClosure = setUserDisplayNameClosure { + return await setUserDisplayNameClosure(name) + } else { + return setUserDisplayNameReturnValue + } + } + //MARK: - loadUserAvatarURL + + var loadUserAvatarURLCallsCount = 0 + var loadUserAvatarURLCalled: Bool { + return loadUserAvatarURLCallsCount > 0 + } + var loadUserAvatarURLReturnValue: Result! + var loadUserAvatarURLClosure: (() async -> Result)? + + @discardableResult + func loadUserAvatarURL() async -> Result { + loadUserAvatarURLCallsCount += 1 + if let loadUserAvatarURLClosure = loadUserAvatarURLClosure { + return await loadUserAvatarURLClosure() + } else { + return loadUserAvatarURLReturnValue + } + } + //MARK: - setUserAvatar + + var setUserAvatarMediaCallsCount = 0 + var setUserAvatarMediaCalled: Bool { + return setUserAvatarMediaCallsCount > 0 + } + var setUserAvatarMediaReceivedMedia: MediaInfo? + var setUserAvatarMediaReceivedInvocations: [MediaInfo] = [] + var setUserAvatarMediaReturnValue: Result! + var setUserAvatarMediaClosure: ((MediaInfo) async -> Result)? + + func setUserAvatar(media: MediaInfo) async -> Result { + setUserAvatarMediaCallsCount += 1 + setUserAvatarMediaReceivedMedia = media + setUserAvatarMediaReceivedInvocations.append(media) + if let setUserAvatarMediaClosure = setUserAvatarMediaClosure { + return await setUserAvatarMediaClosure(media) + } else { + return setUserAvatarMediaReturnValue + } + } + //MARK: - removeUserAvatar + + var removeUserAvatarCallsCount = 0 + var removeUserAvatarCalled: Bool { + return removeUserAvatarCallsCount > 0 + } + var removeUserAvatarReturnValue: Result! + var removeUserAvatarClosure: (() async -> Result)? + + func removeUserAvatar() async -> Result { + removeUserAvatarCallsCount += 1 + if let removeUserAvatarClosure = removeUserAvatarClosure { + return await removeUserAvatarClosure() + } else { + return removeUserAvatarReturnValue + } + } + //MARK: - sessionVerificationControllerProxy + + var sessionVerificationControllerProxyCallsCount = 0 + var sessionVerificationControllerProxyCalled: Bool { + return sessionVerificationControllerProxyCallsCount > 0 + } + var sessionVerificationControllerProxyReturnValue: Result! + var sessionVerificationControllerProxyClosure: (() async -> Result)? + + func sessionVerificationControllerProxy() async -> Result { + sessionVerificationControllerProxyCallsCount += 1 + if let sessionVerificationControllerProxyClosure = sessionVerificationControllerProxyClosure { + return await sessionVerificationControllerProxyClosure() + } else { + return sessionVerificationControllerProxyReturnValue + } + } + //MARK: - logout + + var logoutCallsCount = 0 + var logoutCalled: Bool { + return logoutCallsCount > 0 + } + var logoutReturnValue: URL? + var logoutClosure: (() async -> URL?)? + + func logout() async -> URL? { + logoutCallsCount += 1 + if let logoutClosure = logoutClosure { + return await logoutClosure() + } else { + return logoutReturnValue + } + } + //MARK: - setPusher + + var setPusherWithThrowableError: Error? + var setPusherWithCallsCount = 0 + var setPusherWithCalled: Bool { + return setPusherWithCallsCount > 0 + } + var setPusherWithReceivedConfiguration: PusherConfiguration? + var setPusherWithReceivedInvocations: [PusherConfiguration] = [] + var setPusherWithClosure: ((PusherConfiguration) async throws -> Void)? + + func setPusher(with configuration: PusherConfiguration) async throws { + if let error = setPusherWithThrowableError { + throw error + } + setPusherWithCallsCount += 1 + setPusherWithReceivedConfiguration = configuration + setPusherWithReceivedInvocations.append(configuration) + try await setPusherWithClosure?(configuration) + } + //MARK: - searchUsers + + var searchUsersSearchTermLimitCallsCount = 0 + var searchUsersSearchTermLimitCalled: Bool { + return searchUsersSearchTermLimitCallsCount > 0 + } + var searchUsersSearchTermLimitReceivedArguments: (searchTerm: String, limit: UInt)? + var searchUsersSearchTermLimitReceivedInvocations: [(searchTerm: String, limit: UInt)] = [] + var searchUsersSearchTermLimitReturnValue: Result! + var searchUsersSearchTermLimitClosure: ((String, UInt) async -> Result)? + + func searchUsers(searchTerm: String, limit: UInt) async -> Result { + searchUsersSearchTermLimitCallsCount += 1 + searchUsersSearchTermLimitReceivedArguments = (searchTerm: searchTerm, limit: limit) + searchUsersSearchTermLimitReceivedInvocations.append((searchTerm: searchTerm, limit: limit)) + if let searchUsersSearchTermLimitClosure = searchUsersSearchTermLimitClosure { + return await searchUsersSearchTermLimitClosure(searchTerm, limit) + } else { + return searchUsersSearchTermLimitReturnValue + } + } + //MARK: - profile + + var profileForCallsCount = 0 + var profileForCalled: Bool { + return profileForCallsCount > 0 + } + var profileForReceivedUserID: String? + var profileForReceivedInvocations: [String] = [] + var profileForReturnValue: Result! + var profileForClosure: ((String) async -> Result)? + + func profile(for userID: String) async -> Result { + profileForCallsCount += 1 + profileForReceivedUserID = userID + profileForReceivedInvocations.append(userID) + if let profileForClosure = profileForClosure { + return await profileForClosure(userID) + } else { + return profileForReturnValue + } + } + //MARK: - ignoreUser + + var ignoreUserCallsCount = 0 + var ignoreUserCalled: Bool { + return ignoreUserCallsCount > 0 + } + var ignoreUserReceivedUserID: String? + var ignoreUserReceivedInvocations: [String] = [] + var ignoreUserReturnValue: Result! + var ignoreUserClosure: ((String) async -> Result)? + + func ignoreUser(_ userID: String) async -> Result { + ignoreUserCallsCount += 1 + ignoreUserReceivedUserID = userID + ignoreUserReceivedInvocations.append(userID) + if let ignoreUserClosure = ignoreUserClosure { + return await ignoreUserClosure(userID) + } else { + return ignoreUserReturnValue + } + } + //MARK: - unignoreUser + + var unignoreUserCallsCount = 0 + var unignoreUserCalled: Bool { + return unignoreUserCallsCount > 0 + } + var unignoreUserReceivedUserID: String? + var unignoreUserReceivedInvocations: [String] = [] + var unignoreUserReturnValue: Result! + var unignoreUserClosure: ((String) async -> Result)? + + func unignoreUser(_ userID: String) async -> Result { + unignoreUserCallsCount += 1 + unignoreUserReceivedUserID = userID + unignoreUserReceivedInvocations.append(userID) + if let unignoreUserClosure = unignoreUserClosure { + return await unignoreUserClosure(userID) + } else { + return unignoreUserReturnValue + } + } + //MARK: - loadMediaContentForSource + + var loadMediaContentForSourceThrowableError: Error? + var loadMediaContentForSourceCallsCount = 0 + var loadMediaContentForSourceCalled: Bool { + return loadMediaContentForSourceCallsCount > 0 + } + var loadMediaContentForSourceReceivedSource: MediaSourceProxy? + var loadMediaContentForSourceReceivedInvocations: [MediaSourceProxy] = [] + var loadMediaContentForSourceReturnValue: Data! + var loadMediaContentForSourceClosure: ((MediaSourceProxy) async throws -> Data)? + + func loadMediaContentForSource(_ source: MediaSourceProxy) async throws -> Data { + if let error = loadMediaContentForSourceThrowableError { + throw error + } + loadMediaContentForSourceCallsCount += 1 + loadMediaContentForSourceReceivedSource = source + loadMediaContentForSourceReceivedInvocations.append(source) + if let loadMediaContentForSourceClosure = loadMediaContentForSourceClosure { + return try await loadMediaContentForSourceClosure(source) + } else { + return loadMediaContentForSourceReturnValue + } + } + //MARK: - loadMediaThumbnailForSource + + var loadMediaThumbnailForSourceWidthHeightThrowableError: Error? + var loadMediaThumbnailForSourceWidthHeightCallsCount = 0 + var loadMediaThumbnailForSourceWidthHeightCalled: Bool { + return loadMediaThumbnailForSourceWidthHeightCallsCount > 0 + } + var loadMediaThumbnailForSourceWidthHeightReceivedArguments: (source: MediaSourceProxy, width: UInt, height: UInt)? + var loadMediaThumbnailForSourceWidthHeightReceivedInvocations: [(source: MediaSourceProxy, width: UInt, height: UInt)] = [] + var loadMediaThumbnailForSourceWidthHeightReturnValue: Data! + var loadMediaThumbnailForSourceWidthHeightClosure: ((MediaSourceProxy, UInt, UInt) async throws -> Data)? + + func loadMediaThumbnailForSource(_ source: MediaSourceProxy, width: UInt, height: UInt) async throws -> Data { + if let error = loadMediaThumbnailForSourceWidthHeightThrowableError { + throw error + } + loadMediaThumbnailForSourceWidthHeightCallsCount += 1 + loadMediaThumbnailForSourceWidthHeightReceivedArguments = (source: source, width: width, height: height) + loadMediaThumbnailForSourceWidthHeightReceivedInvocations.append((source: source, width: width, height: height)) + if let loadMediaThumbnailForSourceWidthHeightClosure = loadMediaThumbnailForSourceWidthHeightClosure { + return try await loadMediaThumbnailForSourceWidthHeightClosure(source, width, height) + } else { + return loadMediaThumbnailForSourceWidthHeightReturnValue + } + } + //MARK: - loadMediaFileForSource + + var loadMediaFileForSourceBodyThrowableError: Error? + var loadMediaFileForSourceBodyCallsCount = 0 + var loadMediaFileForSourceBodyCalled: Bool { + return loadMediaFileForSourceBodyCallsCount > 0 + } + var loadMediaFileForSourceBodyReceivedArguments: (source: MediaSourceProxy, body: String?)? + var loadMediaFileForSourceBodyReceivedInvocations: [(source: MediaSourceProxy, body: String?)] = [] + var loadMediaFileForSourceBodyReturnValue: MediaFileHandleProxy! + var loadMediaFileForSourceBodyClosure: ((MediaSourceProxy, String?) async throws -> MediaFileHandleProxy)? + + func loadMediaFileForSource(_ source: MediaSourceProxy, body: String?) async throws -> MediaFileHandleProxy { + if let error = loadMediaFileForSourceBodyThrowableError { + throw error + } + loadMediaFileForSourceBodyCallsCount += 1 + loadMediaFileForSourceBodyReceivedArguments = (source: source, body: body) + loadMediaFileForSourceBodyReceivedInvocations.append((source: source, body: body)) + if let loadMediaFileForSourceBodyClosure = loadMediaFileForSourceBodyClosure { + return try await loadMediaFileForSourceBodyClosure(source, body) + } else { + return loadMediaFileForSourceBodyReturnValue + } + } +} class CompletionSuggestionServiceMock: CompletionSuggestionServiceProtocol { var suggestionsPublisher: AnyPublisher<[SuggestionItem], Never> { get { return underlyingSuggestionsPublisher } diff --git a/ElementX/Sources/Other/SwiftUI/Animation/ShimmerModifier.swift b/ElementX/Sources/Other/SwiftUI/Animation/ShimmerModifier.swift index d282642c7..0a0ccfff0 100644 --- a/ElementX/Sources/Other/SwiftUI/Animation/ShimmerModifier.swift +++ b/ElementX/Sources/Other/SwiftUI/Animation/ShimmerModifier.swift @@ -76,7 +76,7 @@ extension View { } struct ShimmerOverlay_Previews: PreviewProvider, TestablePreview { - static let viewModel = HomeScreenViewModel(userSession: MockUserSession(clientProxy: MockClientProxy(userID: ""), + static let viewModel = HomeScreenViewModel(userSession: MockUserSession(clientProxy: ClientProxyMock(.init(userID: "")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()), analyticsService: ServiceLocator.shared.analytics, diff --git a/ElementX/Sources/Screens/Authentication/WaitlistScreen/View/WaitlistScreen.swift b/ElementX/Sources/Screens/Authentication/WaitlistScreen/View/WaitlistScreen.swift index c92232b8f..8f0440cbd 100644 --- a/ElementX/Sources/Screens/Authentication/WaitlistScreen/View/WaitlistScreen.swift +++ b/ElementX/Sources/Screens/Authentication/WaitlistScreen/View/WaitlistScreen.swift @@ -74,7 +74,7 @@ struct WaitlistScreen_Previews: PreviewProvider, TestablePreview { static let viewModel = WaitlistScreenViewModel(homeserver: .mockMatrixDotOrg) static let successViewModel = { let viewModel = WaitlistScreenViewModel(homeserver: .mockMatrixDotOrg) - viewModel.update(userSession: MockUserSession(clientProxy: MockClientProxy(userID: "@alice:matrix.org"), + viewModel.update(userSession: MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@alice:matrix.org")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock())) return viewModel diff --git a/ElementX/Sources/Screens/BlockedUsersScreen/View/BlockedUsersScreen.swift b/ElementX/Sources/Screens/BlockedUsersScreen/View/BlockedUsersScreen.swift index cdd253e53..f444c0a1a 100644 --- a/ElementX/Sources/Screens/BlockedUsersScreen/View/BlockedUsersScreen.swift +++ b/ElementX/Sources/Screens/BlockedUsersScreen/View/BlockedUsersScreen.swift @@ -62,7 +62,7 @@ struct BlockedUsersScreen: View { // MARK: - Previews struct BlockedUsersScreen_Previews: PreviewProvider, TestablePreview { - static let viewModel = BlockedUsersScreenViewModel(clientProxy: MockClientProxy(userID: RoomMemberProxyMock.mockMe.userID), + static let viewModel = BlockedUsersScreenViewModel(clientProxy: ClientProxyMock(.init(userID: RoomMemberProxyMock.mockMe.userID)), userIndicatorController: UserIndicatorControllerMock()) static var previews: some View { diff --git a/ElementX/Sources/Screens/CreateRoom/View/CreateRoomScreen.swift b/ElementX/Sources/Screens/CreateRoom/View/CreateRoomScreen.swift index 39bc58fe2..123cbc937 100644 --- a/ElementX/Sources/Screens/CreateRoom/View/CreateRoomScreen.swift +++ b/ElementX/Sources/Screens/CreateRoom/View/CreateRoomScreen.swift @@ -175,7 +175,7 @@ struct CreateRoomScreen: View { struct CreateRoom_Previews: PreviewProvider, TestablePreview { static let viewModel = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@userid:example.com")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let parameters = CreateRoomFlowParameters() @@ -189,7 +189,7 @@ struct CreateRoom_Previews: PreviewProvider, TestablePreview { }() static let emtpyViewModel = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@userid:example.com")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let parameters = CreateRoomFlowParameters() diff --git a/ElementX/Sources/Screens/HomeScreen/View/HomeScreen.swift b/ElementX/Sources/Screens/HomeScreen/View/HomeScreen.swift index 329455c9f..36a899507 100644 --- a/ElementX/Sources/Screens/HomeScreen/View/HomeScreen.swift +++ b/ElementX/Sources/Screens/HomeScreen/View/HomeScreen.swift @@ -242,8 +242,8 @@ struct HomeScreen_Previews: PreviewProvider, TestablePreview { .loaded(.mockRooms) } - let clientProxy = MockClientProxy(userID: userID, - roomSummaryProvider: MockRoomSummaryProvider(state: roomSummaryProviderState)) + let clientProxy = ClientProxyMock(.init(userID: userID, + roomSummaryProvider: MockRoomSummaryProvider(state: roomSummaryProviderState))) let userSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), diff --git a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenEmptyStateView.swift b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenEmptyStateView.swift index 655ebd3bb..284b8ad52 100644 --- a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenEmptyStateView.swift +++ b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenEmptyStateView.swift @@ -149,8 +149,8 @@ struct HomeScreenEmptyStateView_Previews: PreviewProvider, TestablePreview { } static let viewModel = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@user:example.com", - roomSummaryProvider: MockRoomSummaryProvider(state: .loaded([]))), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@user:example.com", + roomSummaryProvider: MockRoomSummaryProvider(state: .loaded([])))), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRecoveryKeyConfirmationBanner.swift b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRecoveryKeyConfirmationBanner.swift index 279fdfe8a..f4e09cb14 100644 --- a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRecoveryKeyConfirmationBanner.swift +++ b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRecoveryKeyConfirmationBanner.swift @@ -65,8 +65,8 @@ struct HomeScreenRecoveryKeyConfirmationBanner_Previews: PreviewProvider, Testab } static func buildViewModel() -> HomeScreenViewModel { - let clientProxy = MockClientProxy(userID: "@alice:example.com", - roomSummaryProvider: MockRoomSummaryProvider(state: .loading)) + let clientProxy = ClientProxyMock(.init(userID: "@alice:example.com", + roomSummaryProvider: MockRoomSummaryProvider(state: .loading))) let userSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), diff --git a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRoomCell.swift b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRoomCell.swift index d11454460..5f0c2645b 100644 --- a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRoomCell.swift +++ b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenRoomCell.swift @@ -176,10 +176,10 @@ private extension View { struct HomeScreenRoomCell_Previews: PreviewProvider, TestablePreview { static let summaryProviderGeneric = MockRoomSummaryProvider(state: .loaded(.mockRooms)) static let viewModelGeneric = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "John Doe", roomSummaryProvider: summaryProviderGeneric), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "John Doe", roomSummaryProvider: summaryProviderGeneric)), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) - + return HomeScreenViewModel(userSession: userSession, analyticsService: ServiceLocator.shared.analytics, appSettings: ServiceLocator.shared.settings, @@ -189,7 +189,7 @@ struct HomeScreenRoomCell_Previews: PreviewProvider, TestablePreview { static let summaryProviderForNotificationsState = MockRoomSummaryProvider(state: .loaded(.mockRoomsWithNotificationsState)) static let viewModelForNotificationsState = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "John Doe", roomSummaryProvider: summaryProviderForNotificationsState), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "John Doe", roomSummaryProvider: summaryProviderForNotificationsState)), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenSessionVerificationBanner.swift b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenSessionVerificationBanner.swift index 94b887fa5..de1dfa9ce 100644 --- a/ElementX/Sources/Screens/HomeScreen/View/HomeScreenSessionVerificationBanner.swift +++ b/ElementX/Sources/Screens/HomeScreen/View/HomeScreenSessionVerificationBanner.swift @@ -65,8 +65,8 @@ struct HomeScreenSessionVerificationBanner_Previews: PreviewProvider, TestablePr } static func buildViewModel() -> HomeScreenViewModel { - let clientProxy = MockClientProxy(userID: "@alice:example.com", - roomSummaryProvider: MockRoomSummaryProvider(state: .loading)) + let clientProxy = ClientProxyMock(.init(userID: "@alice:example.com", + roomSummaryProvider: MockRoomSummaryProvider(state: .loading))) let userSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), diff --git a/ElementX/Sources/Screens/InvitesScreen/View/InvitesScreen.swift b/ElementX/Sources/Screens/InvitesScreen/View/InvitesScreen.swift index bb86961bc..410853534 100644 --- a/ElementX/Sources/Screens/InvitesScreen/View/InvitesScreen.swift +++ b/ElementX/Sources/Screens/InvitesScreen/View/InvitesScreen.swift @@ -80,7 +80,7 @@ struct InvitesScreen_Previews: PreviewProvider, TestablePreview { private extension InvitesScreenViewModel { static let noInvites: InvitesScreenViewModel = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@userid:example.com")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let regularViewModel = InvitesScreenViewModel(userSession: userSession, @@ -91,7 +91,7 @@ private extension InvitesScreenViewModel { }() static let someInvite: InvitesScreenViewModel = { - let clientProxy = MockClientProxy(userID: "@userid:example.com") + let clientProxy = ClientProxyMock(.init(userID: "@userid:example.com")) clientProxy.inviteSummaryProvider = MockRoomSummaryProvider(state: .loaded(.mockInvites)) clientProxy.roomSummaryProvider = MockRoomSummaryProvider(state: .loaded(.mockInvites)) let userSession = MockUserSession(clientProxy: clientProxy, diff --git a/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreen.swift b/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreen.swift index 64425d885..8ba7d8d62 100644 --- a/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreen.swift +++ b/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreen.swift @@ -73,8 +73,8 @@ struct NotificationSettingsEditScreen_Previews: PreviewProvider, TestablePreview notificationSettingsProxy.getDefaultRoomNotificationModeIsEncryptedIsOneToOneReturnValue = .allMessages notificationSettingsProxy.getRoomsWithUserDefinedRulesReturnValue = [RoomSummary].mockRooms.compactMap(\.id) - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@alice:example.com", - roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms))), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@alice:example.com", + roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)))), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) var viewModel = NotificationSettingsEditScreenViewModel(chatType: .groupChat, @@ -88,8 +88,8 @@ struct NotificationSettingsEditScreen_Previews: PreviewProvider, TestablePreview let notificationSettingsProxy = NotificationSettingsProxyMock(with: .init()) notificationSettingsProxy.getDefaultRoomNotificationModeIsEncryptedIsOneToOneReturnValue = .mentionsAndKeywordsOnly notificationSettingsProxy.getRoomsWithUserDefinedRulesReturnValue = [] - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@alice:example.com", - roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms))), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@alice:example.com", + roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)))), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) var viewModel = NotificationSettingsEditScreenViewModel(chatType: .oneToOneChat, @@ -103,8 +103,10 @@ struct NotificationSettingsEditScreen_Previews: PreviewProvider, TestablePreview let notificationSettingsProxy = NotificationSettingsProxyMock(with: .init()) notificationSettingsProxy.getDefaultRoomNotificationModeIsEncryptedIsOneToOneReturnValue = .mentionsAndKeywordsOnly notificationSettingsProxy.getRoomsWithUserDefinedRulesReturnValue = [] - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "John Doe"), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) - + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "John Doe")), + mediaProvider: MockMediaProvider(), + voiceMessageMediaManager: VoiceMessageMediaManagerMock()) + var viewModel = NotificationSettingsEditScreenViewModel(chatType: .oneToOneChat, userSession: userSession, notificationSettingsProxy: notificationSettingsProxy) @@ -118,8 +120,8 @@ struct NotificationSettingsEditScreen_Previews: PreviewProvider, TestablePreview notificationSettingsProxy.getDefaultRoomNotificationModeIsEncryptedIsOneToOneReturnValue = .allMessages notificationSettingsProxy.getRoomsWithUserDefinedRulesReturnValue = [RoomSummary].mockRooms.compactMap(\.id) - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@alice:example.com", - roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms))), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@alice:example.com", + roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)))), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) var viewModel = NotificationSettingsEditScreenViewModel(chatType: .groupChat, diff --git a/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreenRoomCell.swift b/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreenRoomCell.swift index ef0b9590a..9ea5c6b19 100644 --- a/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreenRoomCell.swift +++ b/ElementX/Sources/Screens/Settings/NotificationSettingsEditScreen/View/NotificationSettingsEditScreenRoomCell.swift @@ -61,7 +61,7 @@ struct NotificationSettingsEditScreenRoomCell_Previews: PreviewProvider, Testabl static var previews: some View { let summaryProvider = MockRoomSummaryProvider(state: .loaded(.mockRooms)) - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "John Doe", roomSummaryProvider: summaryProvider), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "John Doe", roomSummaryProvider: summaryProvider)), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/ElementX/Sources/Screens/Settings/NotificationSettingsScreen/View/NotificationSettingsScreen.swift b/ElementX/Sources/Screens/Settings/NotificationSettingsScreen/View/NotificationSettingsScreen.swift index 96618914b..dc6f762b8 100644 --- a/ElementX/Sources/Screens/Settings/NotificationSettingsScreen/View/NotificationSettingsScreen.swift +++ b/ElementX/Sources/Screens/Settings/NotificationSettingsScreen/View/NotificationSettingsScreen.swift @@ -222,7 +222,8 @@ struct NotificationSettingsScreen_Previews: PreviewProvider, TestablePreview { notificationSettingsProxy.isRoomMentionEnabledReturnValue = true notificationSettingsProxy.isCallEnabledReturnValue = false - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "John Doe"), mediaProvider: MockMediaProvider(), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "John Doe")), + mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) var viewModel = NotificationSettingsScreenViewModel(appSettings: appSettings, @@ -251,7 +252,9 @@ struct NotificationSettingsScreen_Previews: PreviewProvider, TestablePreview { notificationSettingsProxy.isRoomMentionEnabledReturnValue = true notificationSettingsProxy.isCallEnabledReturnValue = false - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "John Doe"), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "John Doe")), + mediaProvider: MockMediaProvider(), + voiceMessageMediaManager: VoiceMessageMediaManagerMock()) var viewModel = NotificationSettingsScreenViewModel(appSettings: appSettings, userNotificationCenter: notificationCenter, diff --git a/ElementX/Sources/Screens/Settings/SettingsScreen/View/SettingsScreen.swift b/ElementX/Sources/Screens/Settings/SettingsScreen/View/SettingsScreen.swift index a8ac247ad..34c3021e2 100644 --- a/ElementX/Sources/Screens/Settings/SettingsScreen/View/SettingsScreen.swift +++ b/ElementX/Sources/Screens/Settings/SettingsScreen/View/SettingsScreen.swift @@ -244,8 +244,8 @@ struct SettingsScreen_Previews: PreviewProvider, TestablePreview { let verificationController = SessionVerificationControllerProxyMock() verificationController.isVerifiedReturnValue = .success(false) let userSession = MockUserSession(sessionVerificationController: verificationController, - clientProxy: MockClientProxy(userID: "@userid:example.com", - deviceID: "AAAAAAAAAAA"), + clientProxy: ClientProxyMock(.init(userID: "@userid:example.com", + deviceID: "AAAAAAAAAAA")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) return SettingsScreenViewModel(userSession: userSession, diff --git a/ElementX/Sources/Screens/Settings/UserDetailsEditScreen/View/UserDetailsEditScreen.swift b/ElementX/Sources/Screens/Settings/UserDetailsEditScreen/View/UserDetailsEditScreen.swift index 852f5e571..f3d57b6ed 100644 --- a/ElementX/Sources/Screens/Settings/UserDetailsEditScreen/View/UserDetailsEditScreen.swift +++ b/ElementX/Sources/Screens/Settings/UserDetailsEditScreen/View/UserDetailsEditScreen.swift @@ -124,7 +124,7 @@ struct UserDetailsEditScreen: View { // MARK: - Previews struct UserDetailsEditScreen_Previews: PreviewProvider, TestablePreview { - static let viewModel = UserDetailsEditScreenViewModel(clientProxy: MockClientProxy(userID: "@stefan:matrix.org"), + static let viewModel = UserDetailsEditScreenViewModel(clientProxy: ClientProxyMock(.init(userID: "@stefan:matrix.org")), mediaProvider: MockMediaProvider(), userIndicatorController: UserIndicatorControllerMock.default) diff --git a/ElementX/Sources/Screens/StartChatScreen/View/StartChatScreen.swift b/ElementX/Sources/Screens/StartChatScreen/View/StartChatScreen.swift index 812d530b1..d673ad90b 100644 --- a/ElementX/Sources/Screens/StartChatScreen/View/StartChatScreen.swift +++ b/ElementX/Sources/Screens/StartChatScreen/View/StartChatScreen.swift @@ -129,7 +129,7 @@ struct StartChatScreen: View { struct StartChatScreen_Previews: PreviewProvider, TestablePreview { static let viewModel = { - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@userid:example.com")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let userDiscoveryService = UserDiscoveryServiceMock() diff --git a/ElementX/Sources/Services/Authentication/MockAuthenticationServiceProxy.swift b/ElementX/Sources/Services/Authentication/MockAuthenticationServiceProxy.swift index 45ce2d75d..7d7f5a00e 100644 --- a/ElementX/Sources/Services/Authentication/MockAuthenticationServiceProxy.swift +++ b/ElementX/Sources/Services/Authentication/MockAuthenticationServiceProxy.swift @@ -62,7 +62,7 @@ class MockAuthenticationServiceProxy: AuthenticationServiceProxyProtocol { return .failure(.invalidCredentials) } - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: username), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: username)), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) return .success(userSession) diff --git a/ElementX/Sources/Services/Client/ClientProxyProtocol.swift b/ElementX/Sources/Services/Client/ClientProxyProtocol.swift index a438463c1..63f693340 100644 --- a/ElementX/Sources/Services/Client/ClientProxyProtocol.swift +++ b/ElementX/Sources/Services/Client/ClientProxyProtocol.swift @@ -71,6 +71,7 @@ struct PusherConfiguration { let lang: String } +// sourcery: AutoMockable protocol ClientProxyProtocol: AnyObject, MediaLoaderProtocol { var actionsPublisher: AnyPublisher { get } diff --git a/ElementX/Sources/Services/Client/MockClientProxy.swift b/ElementX/Sources/Services/Client/MockClientProxy.swift deleted file mode 100644 index b17051da3..000000000 --- a/ElementX/Sources/Services/Client/MockClientProxy.swift +++ /dev/null @@ -1,185 +0,0 @@ -// -// Copyright 2022 New Vector Ltd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -import Combine -import Foundation -import MatrixRustSDK - -class MockClientProxy: ClientProxyProtocol { - let actionsSubject = PassthroughSubject() - var actionsPublisher: AnyPublisher { - actionsSubject.eraseToAnyPublisher() - } - - let loadingStatePublisher = CurrentValuePublisher(.notLoading) - - let userID: String - let deviceID: String? - let homeserver = "" - let pusherNotificationClientIdentifier: String? = nil - - var roomSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider() - - var alternateRoomSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider() - - var inviteSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider() - - var userAvatarURLPublisher: CurrentValuePublisher { CurrentValueSubject(nil).asCurrentValuePublisher() } - - var userDisplayNamePublisher: CurrentValuePublisher { CurrentValueSubject("User display name").asCurrentValuePublisher() } - - var ignoredUsersPublisher: CurrentValuePublisher<[String]?, Never> { - let ignoredUsers = [RoomMemberProxyMock].allMembers.map(\.userID) - return CurrentValueSubject<[String]?, Never>(ignoredUsers).asCurrentValuePublisher() - } - - var notificationSettings: NotificationSettingsProxyProtocol = NotificationSettingsProxyMock(with: .init()) - - lazy var secureBackupController: SecureBackupControllerProtocol = { - let secureBackupController = SecureBackupControllerMock() - secureBackupController.underlyingRecoveryState = .init(CurrentValueSubject(.enabled)) - secureBackupController.underlyingKeyBackupState = .init(CurrentValueSubject(.enabled)) - return secureBackupController - }() - - init(userID: String, deviceID: String? = nil, roomSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider()) { - self.userID = userID - self.deviceID = deviceID - self.roomSummaryProvider = roomSummaryProvider - } - - func isOnlyDeviceLeft() async -> Result { - .success(false) - } - - func startSync() { } - - func stopSync() { } - - func accountURL(action: AccountManagementAction) -> URL? { - "https://matrix.org/account" - } - - func directRoomForUserID(_ userID: String) async -> Result { - .failure(.failedRetrievingDirectRoom) - } - - func createDirectRoom(with userID: String, expectedRoomName: String?) async -> Result { - .failure(.failedCreatingRoom) - } - - func createRoom(name: String, topic: String?, isRoomPrivate: Bool, userIDs: [String], avatarURL: URL?) async -> Result { - .failure(.failedCreatingRoom) - } - - func uploadMedia(_ media: MediaInfo) async -> Result { - .failure(.failedUploadingMedia(.unknown)) - } - - var roomForIdentifierMocks: [String: RoomProxyMock] = .init() - @MainActor - func roomForIdentifier(_ identifier: String) async -> RoomProxyProtocol? { - guard roomForIdentifierMocks[identifier] == nil else { - return roomForIdentifierMocks[identifier] - } - - guard let room = roomSummaryProvider?.roomListPublisher.value.first(where: { $0.id == identifier }) else { - return nil - } - - switch room { - case .empty: - return RoomProxyMock(with: .init(name: "Empty room")) - case .filled(let details), .invalidated(let details): - return RoomProxyMock(with: .init(name: details.name)) - } - } - - func loadUserDisplayName() async -> Result { - .failure(.failedRetrievingUserDisplayName) - } - - func setUserDisplayName(_ name: String) async -> Result { - .failure(.failedSettingUserDisplayName) - } - - func loadUserAvatarURL() async -> Result { - .failure(.failedRetrievingUserAvatarURL) - } - - func setUserAvatar(media: MediaInfo) async -> Result { - .failure(.failedSettingUserAvatar) - } - - func removeUserAvatar() async -> Result { - .failure(.failedSettingUserAvatar) - } - - func loadMediaContentForSource(_ source: MediaSourceProxy) async throws -> Data { - throw ClientProxyError.failedLoadingMedia - } - - func loadMediaThumbnailForSource(_ source: MediaSourceProxy, width: UInt, height: UInt) async throws -> Data { - throw ClientProxyError.failedLoadingMedia - } - - func loadMediaFileForSource(_ source: MediaSourceProxy, body: String?) async throws -> MediaFileHandleProxy { - throw ClientProxyError.failedLoadingMedia - } - - var sessionVerificationControllerProxyResult: Result? - func sessionVerificationControllerProxy() async -> Result { - if let sessionVerificationControllerProxyResult { - return sessionVerificationControllerProxyResult - } else { - return .failure(.failedRetrievingSessionVerificationController) - } - } - - func logout() async -> URL? { - nil - } - - var setPusherErrorToThrow: Error? - var setPusherArgument: PusherConfiguration? - var setPusherCalled = false - - func setPusher(with configuration: PusherConfiguration) async throws { - if let setPusherErrorToThrow { throw setPusherErrorToThrow } - setPusherCalled = true - setPusherArgument = configuration - } - - var searchUsersResult: Result = .success(.init(results: [], limited: false)) - func searchUsers(searchTerm: String, limit: UInt) async -> Result { - searchUsersResult - } - - var getProfileResult: Result = .success(.init(userID: "@a:b.com", displayName: "Some user")) - private(set) var getProfileCalled = false - func profile(for userID: String) async -> Result { - getProfileCalled = true - return getProfileResult - } - - func ignoreUser(_ userID: String) async -> Result { - .failure(.failedIgnoringUser) - } - - func unignoreUser(_ userID: String) async -> Result { - .failure(.failedUnignoringUser) - } -} diff --git a/ElementX/Sources/UITests/UITestsAppCoordinator.swift b/ElementX/Sources/UITests/UITestsAppCoordinator.swift index fc21e8915..3299705a4 100644 --- a/ElementX/Sources/UITests/UITestsAppCoordinator.swift +++ b/ElementX/Sources/UITests/UITestsAppCoordinator.swift @@ -261,7 +261,7 @@ class MockScreen: Identifiable { ServiceLocator.shared.settings.migratedAccounts[userID] = true let navigationStackCoordinator = NavigationStackCoordinator() - let session = MockUserSession(clientProxy: MockClientProxy(userID: userID), + let session = MockUserSession(clientProxy: ClientProxyMock(.init(userID: userID)), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let coordinator = HomeScreenCoordinator(parameters: .init(userSession: session, @@ -273,7 +273,7 @@ class MockScreen: Identifiable { return navigationStackCoordinator case .settings: let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) let coordinator = SettingsScreenCoordinator(parameters: .init(userSession: MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()), @@ -303,7 +303,7 @@ class MockScreen: Identifiable { case .notificationSettingsScreen: let userNotificationCenter = UserNotificationCenterMock() userNotificationCenter.authorizationStatusReturnValue = .denied - let session = MockUserSession(clientProxy: MockClientProxy(userID: "@mock:matrix.org"), + let session = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@mock:matrix.org")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let parameters = NotificationSettingsScreenCoordinatorParameters(userSession: session, @@ -314,7 +314,7 @@ class MockScreen: Identifiable { case .notificationSettingsScreenMismatchConfiguration: let userNotificationCenter = UserNotificationCenterMock() userNotificationCenter.authorizationStatusReturnValue = .denied - let session = MockUserSession(clientProxy: MockClientProxy(userID: "@mock:matrix.org"), + let session = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@mock:matrix.org")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let notificationSettings = NotificationSettingsProxyMock(with: .init()) @@ -560,7 +560,7 @@ class MockScreen: Identifiable { appSettings.richTextEditorEnabled = id == .userSessionScreenRTE let navigationSplitCoordinator = NavigationSplitCoordinator(placeholderCoordinator: PlaceholderScreenCoordinator()) - let clientProxy = MockClientProxy(userID: "@mock:client.com", roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms))) + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com", roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)))) ServiceLocator.shared.settings.migratedAccounts[clientProxy.userID] = true ServiceLocator.shared.settings.hasShownWelcomeScreen = true @@ -743,7 +743,9 @@ class MockScreen: Identifiable { let userDiscoveryMock = UserDiscoveryServiceMock() userDiscoveryMock.fetchSuggestionsReturnValue = .success([.mockAlice, .mockBob, .mockCharlie]) userDiscoveryMock.searchProfilesWithReturnValue = .success([]) - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@mock:client.com"), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@mock:client.com")), + mediaProvider: MockMediaProvider(), + voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let parameters: StartChatScreenCoordinatorParameters = .init(orientationManager: OrientationManagerMock(), userSession: userSession, userIndicatorController: UserIndicatorControllerMock(), @@ -754,7 +756,7 @@ class MockScreen: Identifiable { return navigationStackCoordinator case .startChatWithSearchResults: let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) let userDiscoveryMock = UserDiscoveryServiceMock() userDiscoveryMock.fetchSuggestionsReturnValue = .success([]) userDiscoveryMock.searchProfilesWithReturnValue = .success([.mockBob, .mockBobby]) @@ -805,9 +807,19 @@ class MockScreen: Identifiable { case .invitesWithBadges: ServiceLocator.shared.settings.seenInvites = Set([RoomSummary].mockInvites.dropFirst(1).compactMap(\.id)) let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") - clientProxy.roomForIdentifierMocks["someAwesomeRoomId1"] = .init(with: .init(name: "First room")) - clientProxy.roomForIdentifierMocks["someAwesomeRoomId2"] = .init(with: .init(name: "Second room")) + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) + + clientProxy.roomForIdentifierClosure = { identifier in + switch identifier { + case "someAwesomeRoomId1": + return RoomProxyMock(with: .init(name: "First room")) + case "someAwesomeRoomId2": + return RoomProxyMock(with: .init(name: "Second room")) + default: + return nil + } + } + let summaryProvider = MockRoomSummaryProvider(state: .loaded(.mockInvites)) clientProxy.inviteSummaryProvider = summaryProvider @@ -817,9 +829,19 @@ class MockScreen: Identifiable { case .invites: ServiceLocator.shared.settings.seenInvites = Set([RoomSummary].mockInvites.compactMap(\.id)) let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") - clientProxy.roomForIdentifierMocks["someAwesomeRoomId1"] = .init(with: .init(name: "First room")) - clientProxy.roomForIdentifierMocks["someAwesomeRoomId2"] = .init(with: .init(name: "Second room")) + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) + + clientProxy.roomForIdentifierClosure = { identifier in + switch identifier { + case "someAwesomeRoomId1": + return RoomProxyMock(with: .init(name: "First room")) + case "someAwesomeRoomId2": + return RoomProxyMock(with: .init(name: "Second room")) + default: + return nil + } + } + let summaryProvider = MockRoomSummaryProvider(state: .loaded(.mockInvites)) clientProxy.inviteSummaryProvider = summaryProvider @@ -828,7 +850,7 @@ class MockScreen: Identifiable { return navigationStackCoordinator case .invitesNoInvites: let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) let coordinator = InvitesScreenCoordinator(parameters: .init(userSession: MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()))) navigationStackCoordinator.setRootCoordinator(coordinator) return navigationStackCoordinator @@ -867,7 +889,7 @@ class MockScreen: Identifiable { return navigationStackCoordinator case .createRoom: let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) let mockUserSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) let createRoomParameters = CreateRoomFlowParameters() let selectedUsers: [UserProfileProxy] = [.mockAlice, .mockBob, .mockCharlie] @@ -880,7 +902,7 @@ class MockScreen: Identifiable { return navigationStackCoordinator case .createRoomNoUsers: let navigationStackCoordinator = NavigationStackCoordinator() - let clientProxy = MockClientProxy(userID: "@mock:client.com") + let clientProxy = ClientProxyMock(.init(userID: "@mock:client.com")) let mockUserSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/UnitTests/Sources/BlockedUsersScreenViewModelTests.swift b/UnitTests/Sources/BlockedUsersScreenViewModelTests.swift index 4c9c7bddb..f9925a8a5 100644 --- a/UnitTests/Sources/BlockedUsersScreenViewModelTests.swift +++ b/UnitTests/Sources/BlockedUsersScreenViewModelTests.swift @@ -22,7 +22,7 @@ import XCTest @MainActor class BlockedUsersScreenViewModelTests: XCTestCase { func testInitialState() { - let clientProxy = MockClientProxy(userID: RoomMemberProxyMock.mockMe.userID) + let clientProxy = ClientProxyMock(.init(userID: RoomMemberProxyMock.mockMe.userID)) let viewModel = BlockedUsersScreenViewModel(clientProxy: clientProxy, userIndicatorController: ServiceLocator.shared.userIndicatorController) diff --git a/UnitTests/Sources/CreateRoomViewModelTests.swift b/UnitTests/Sources/CreateRoomViewModelTests.swift index ffe442ded..c1d318568 100644 --- a/UnitTests/Sources/CreateRoomViewModelTests.swift +++ b/UnitTests/Sources/CreateRoomViewModelTests.swift @@ -22,7 +22,7 @@ import XCTest @MainActor class CreateRoomScreenViewModelTests: XCTestCase { var viewModel: CreateRoomViewModelProtocol! - var clientProxy: MockClientProxy! + var clientProxy: ClientProxyMock! var userSession: MockUserSession! private let usersSubject = CurrentValueSubject<[UserProfileProxy], Never>([]) @@ -34,7 +34,7 @@ class CreateRoomScreenViewModelTests: XCTestCase { override func setUpWithError() throws { cancellables.removeAll() - clientProxy = MockClientProxy(userID: "@a:b.com") + clientProxy = ClientProxyMock(.init(userID: "@a:b.com")) userSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/UnitTests/Sources/HomeScreenViewModelTests.swift b/UnitTests/Sources/HomeScreenViewModelTests.swift index c7b162fa6..510298143 100644 --- a/UnitTests/Sources/HomeScreenViewModelTests.swift +++ b/UnitTests/Sources/HomeScreenViewModelTests.swift @@ -22,7 +22,7 @@ import XCTest @MainActor class HomeScreenViewModelTests: XCTestCase { var viewModel: HomeScreenViewModelProtocol! - var clientProxy: MockClientProxy! + var clientProxy: ClientProxyMock! var context: HomeScreenViewModelType.Context! { viewModel.context } var cancellables = Set() var roomSummaryProvider: MockRoomSummaryProvider! @@ -31,7 +31,7 @@ class HomeScreenViewModelTests: XCTestCase { ServiceLocator.shared.settings.roomListFiltersEnabled = true cancellables.removeAll() roomSummaryProvider = MockRoomSummaryProvider(state: .loaded(.mockRooms)) - clientProxy = MockClientProxy(userID: "@mock:client.com", roomSummaryProvider: roomSummaryProvider) + clientProxy = ClientProxyMock(.init(userID: "@mock:client.com", roomSummaryProvider: roomSummaryProvider)) viewModel = HomeScreenViewModel(userSession: MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()), @@ -89,7 +89,8 @@ class HomeScreenViewModelTests: XCTestCase { func testLeaveRoomAlert() async throws { let mockRoomId = "1" - clientProxy.roomForIdentifierMocks[mockRoomId] = .init(with: .init(id: mockRoomId, name: "Some room")) + + clientProxy.roomForIdentifierClosure = { _ in RoomProxyMock(with: .init(id: mockRoomId, name: "Some room")) } let deferred = deferFulfillment(context.$viewState) { value in value.bindings.leaveRoomAlertItem != nil @@ -106,7 +107,8 @@ class HomeScreenViewModelTests: XCTestCase { let mockRoomId = "1" let room: RoomProxyMock = .init(with: .init(id: mockRoomId, name: "Some room")) room.leaveRoomClosure = { .failure(.failedLeavingRoom) } - clientProxy.roomForIdentifierMocks[mockRoomId] = room + + clientProxy.roomForIdentifierClosure = { _ in room } let deferred = deferFulfillment(context.$viewState) { value in value.bindings.alertInfo != nil @@ -136,7 +138,9 @@ class HomeScreenViewModelTests: XCTestCase { .store(in: &cancellables) let room: RoomProxyMock = .init(with: .init(id: mockRoomId, name: "Some room")) room.leaveRoomClosure = { .success(()) } - clientProxy.roomForIdentifierMocks[mockRoomId] = room + + clientProxy.roomForIdentifierClosure = { _ in room } + context.send(viewAction: .confirmLeaveRoom(roomIdentifier: mockRoomId)) await fulfillment(of: [expectation]) XCTAssertNil(context.alertInfo) diff --git a/UnitTests/Sources/InvitesScreenViewModelTests.swift b/UnitTests/Sources/InvitesScreenViewModelTests.swift index 8a7a71c8b..4b4ddbaff 100644 --- a/UnitTests/Sources/InvitesScreenViewModelTests.swift +++ b/UnitTests/Sources/InvitesScreenViewModelTests.swift @@ -20,7 +20,7 @@ import XCTest @MainActor class InvitesScreenViewModelTests: XCTestCase { var viewModel: InvitesScreenViewModelProtocol! - var clientProxy: MockClientProxy! + var clientProxy: ClientProxyMock! var userSession: MockUserSession! var mockNotificationCenter: NotificationCenterMock! @@ -29,7 +29,7 @@ class InvitesScreenViewModelTests: XCTestCase { } override func setUpWithError() throws { - clientProxy = MockClientProxy(userID: "@a:b.com") + clientProxy = ClientProxyMock(.init(userID: "@a:b.com")) userSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/UnitTests/Sources/MediaUploadingPreprocessorTests.swift b/UnitTests/Sources/MediaUploadingPreprocessorTests.swift index db5b50375..c64a603fb 100644 --- a/UnitTests/Sources/MediaUploadingPreprocessorTests.swift +++ b/UnitTests/Sources/MediaUploadingPreprocessorTests.swift @@ -37,8 +37,8 @@ final class MediaUploadingPreprocessorTests: XCTestCase { XCTAssertEqual(audioURL.lastPathComponent, "test_audio.mp3") XCTAssertEqual(audioInfo.mimetype, "audio/mpeg") - XCTAssertEqual(floor(audioInfo.duration ?? 0), 27252) - XCTAssertEqual(audioInfo.size, 764_176) + XCTAssertEqual(audioInfo.duration ?? 0, 27252, accuracy: 100) + XCTAssertEqual(audioInfo.size ?? 0, 764_176, accuracy: 100) } func testLandscapeMovVideoProcessing() async { @@ -69,14 +69,14 @@ final class MediaUploadingPreprocessorTests: XCTestCase { // Check resulting video info XCTAssertEqual(videoInfo.mimetype, "video/mp4") XCTAssertEqual(videoInfo.blurhash, "K22PJZx^DgadWAbbMuRio$") - XCTAssertEqual(videoInfo.size, 1_431_959) + XCTAssertEqual(videoInfo.size ?? 0, 1_431_959, accuracy: 100) XCTAssertEqual(videoInfo.width, 1280) XCTAssertEqual(videoInfo.height, 720) - XCTAssertEqual(floor(videoInfo.duration ?? 0), 30483) + XCTAssertEqual(videoInfo.duration ?? 0, 30483, accuracy: 100) XCTAssertNotNil(videoInfo.thumbnailInfo) XCTAssertEqual(videoInfo.thumbnailInfo?.mimetype, "image/jpeg") - XCTAssertEqual(videoInfo.thumbnailInfo?.size, 33949) + XCTAssertEqual(videoInfo.thumbnailInfo?.size ?? 0, 33949, accuracy: 100) XCTAssertEqual(videoInfo.thumbnailInfo?.width, 800) XCTAssertEqual(videoInfo.thumbnailInfo?.height, 450) } @@ -109,14 +109,14 @@ final class MediaUploadingPreprocessorTests: XCTestCase { // Check resulting video info XCTAssertEqual(videoInfo.mimetype, "video/mp4") XCTAssertEqual(videoInfo.blurhash, "K7C$_zt70LKQMx^+~B9GIU") - XCTAssertEqual(videoInfo.size, 9_775_822) + XCTAssertEqual(videoInfo.size ?? 0, 9_775_822, accuracy: 100) XCTAssertEqual(videoInfo.width, 1080) XCTAssertEqual(videoInfo.height, 1920) - XCTAssertEqual(floor(videoInfo.duration ?? 0), 21000) + XCTAssertEqual(videoInfo.duration ?? 0, 21000, accuracy: 100) XCTAssertNotNil(videoInfo.thumbnailInfo) XCTAssertEqual(videoInfo.thumbnailInfo?.mimetype, "image/jpeg") - XCTAssertEqual(videoInfo.thumbnailInfo?.size, 82854) + XCTAssertEqual(videoInfo.thumbnailInfo?.size ?? 0, 82854, accuracy: 100) XCTAssertEqual(videoInfo.thumbnailInfo?.width, 337) XCTAssertEqual(videoInfo.thumbnailInfo?.height, 600) } @@ -138,13 +138,13 @@ final class MediaUploadingPreprocessorTests: XCTestCase { // Check resulting image info XCTAssertEqual(imageInfo.mimetype, "image/jpeg") XCTAssertEqual(imageInfo.blurhash, "K%I#.NofkC_4ayayxujsWB") - XCTAssertEqual(imageInfo.size, 3_305_795) + XCTAssertEqual(imageInfo.size ?? 0, 3_305_795, accuracy: 100) XCTAssertEqual(imageInfo.width, 6103) XCTAssertEqual(imageInfo.height, 2621) XCTAssertNotNil(imageInfo.thumbnailInfo) XCTAssertEqual(imageInfo.thumbnailInfo?.mimetype, "image/jpeg") - XCTAssertEqual(imageInfo.thumbnailInfo?.size, 89553) + XCTAssertEqual(imageInfo.thumbnailInfo?.size ?? 0, 89553, accuracy: 100) XCTAssertEqual(imageInfo.thumbnailInfo?.width, 800) XCTAssertEqual(imageInfo.thumbnailInfo?.height, 344) } @@ -166,13 +166,13 @@ final class MediaUploadingPreprocessorTests: XCTestCase { // Check resulting image info XCTAssertEqual(imageInfo.mimetype, "image/jpeg") XCTAssertEqual(imageInfo.blurhash, "KdE:ets+RP^-n*RP%OWAV@") - XCTAssertEqual(imageInfo.size, 4_414_666) + XCTAssertEqual(imageInfo.size ?? 0, 4_414_666, accuracy: 100) XCTAssertEqual(imageInfo.width, 3024) XCTAssertEqual(imageInfo.height, 4032) XCTAssertNotNil(imageInfo.thumbnailInfo) XCTAssertEqual(imageInfo.thumbnailInfo?.mimetype, "image/jpeg") - XCTAssertEqual(imageInfo.thumbnailInfo?.size, 264_500) + XCTAssertEqual(imageInfo.thumbnailInfo?.size ?? 0, 264_500, accuracy: 100) XCTAssertEqual(imageInfo.thumbnailInfo?.width, 600) XCTAssertEqual(imageInfo.thumbnailInfo?.height, 800) } diff --git a/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift b/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift index edd6908be..424feb881 100644 --- a/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift +++ b/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift @@ -23,7 +23,7 @@ import XCTest @MainActor final class NotificationManagerTests: XCTestCase { var notificationManager: NotificationManager! - private let clientProxy = MockClientProxy(userID: "@test:user.net") + private let clientProxy = ClientProxyMock(.init(userID: "@test:user.net")) private lazy var mockUserSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) @@ -53,7 +53,8 @@ final class NotificationManagerTests: XCTestCase { func test_whenRegistered_pusherIsCalled() async { _ = await notificationManager.register(with: Data()) - XCTAssertTrue(clientProxy.setPusherCalled) + + XCTAssertTrue(clientProxy.setPusherWithCalled) } func test_whenRegisteredSuccess_completionSuccessIsCalled() async throws { @@ -65,21 +66,28 @@ final class NotificationManagerTests: XCTestCase { enum TestError: Error { case someError } - clientProxy.setPusherErrorToThrow = TestError.someError + + clientProxy.setPusherWithThrowableError = TestError.someError let success = await notificationManager.register(with: Data()) XCTAssertFalse(success) } - + func test_whenRegistered_pusherIsCalledWithCorrectValues() async throws { let pushkeyData = Data("1234".utf8) _ = await notificationManager.register(with: pushkeyData) - XCTAssertEqual(clientProxy.setPusherArgument?.identifiers.pushkey, pushkeyData.base64EncodedString()) - XCTAssertEqual(clientProxy.setPusherArgument?.identifiers.appId, appSettings.pusherAppId) - XCTAssertEqual(clientProxy.setPusherArgument?.appDisplayName, "\(InfoPlistReader.main.bundleDisplayName) (iOS)") - XCTAssertEqual(clientProxy.setPusherArgument?.deviceDisplayName, UIDevice.current.name) - XCTAssertNotNil(clientProxy.setPusherArgument?.profileTag) - XCTAssertEqual(clientProxy.setPusherArgument?.lang, Bundle.app.preferredLocalizations.first) - guard case let .http(data) = clientProxy.setPusherArgument?.kind else { + + guard let configuration = clientProxy.setPusherWithReceivedInvocations.first else { + XCTFail("Invalid pusher configuration sent") + return + } + + XCTAssertEqual(configuration.identifiers.pushkey, pushkeyData.base64EncodedString()) + XCTAssertEqual(configuration.identifiers.appId, appSettings.pusherAppId) + XCTAssertEqual(configuration.appDisplayName, "\(InfoPlistReader.main.bundleDisplayName) (iOS)") + XCTAssertEqual(configuration.deviceDisplayName, UIDevice.current.name) + XCTAssertNotNil(configuration.profileTag) + XCTAssertEqual(configuration.lang, Bundle.app.preferredLocalizations.first) + guard case let .http(data) = configuration.kind else { XCTFail("Http kind expected") return } diff --git a/UnitTests/Sources/NotificationSettingsEditScreenViewModelTests.swift b/UnitTests/Sources/NotificationSettingsEditScreenViewModelTests.swift index d3a63b693..6110b5d77 100644 --- a/UnitTests/Sources/NotificationSettingsEditScreenViewModelTests.swift +++ b/UnitTests/Sources/NotificationSettingsEditScreenViewModelTests.swift @@ -30,7 +30,7 @@ class NotificationSettingsEditScreenViewModelTests: XCTestCase { } @MainActor override func setUpWithError() throws { - let clientProxy = MockClientProxy(userID: "@a:b.com") + let clientProxy = ClientProxyMock(.init(userID: "@a:b.com")) userSession = MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) diff --git a/UnitTests/Sources/RoomFlowCoordinatorTests.swift b/UnitTests/Sources/RoomFlowCoordinatorTests.swift index 06ae70fcd..f55587062 100644 --- a/UnitTests/Sources/RoomFlowCoordinatorTests.swift +++ b/UnitTests/Sources/RoomFlowCoordinatorTests.swift @@ -27,7 +27,7 @@ class RoomFlowCoordinatorTests: XCTestCase { override func setUp() async throws { cancellables.removeAll() - let clientProxy = MockClientProxy(userID: "hi@bob", roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms))) + let clientProxy = ClientProxyMock(.init(userID: "hi@bob", roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)))) let mediaProvider = MockMediaProvider() let voiceMessageMediaManager = VoiceMessageMediaManagerMock() let userSession = MockUserSession(clientProxy: clientProxy, diff --git a/UnitTests/Sources/SettingsViewModelTests.swift b/UnitTests/Sources/SettingsViewModelTests.swift index cd1f9ff26..e19749dcb 100644 --- a/UnitTests/Sources/SettingsViewModelTests.swift +++ b/UnitTests/Sources/SettingsViewModelTests.swift @@ -27,7 +27,7 @@ class SettingsScreenViewModelTests: XCTestCase { @MainActor override func setUpWithError() throws { cancellables.removeAll() - let userSession = MockUserSession(clientProxy: MockClientProxy(userID: ""), + let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()) viewModel = SettingsScreenViewModel(userSession: userSession, appSettings: ServiceLocator.shared.settings) diff --git a/UnitTests/Sources/StartChatViewModelTests.swift b/UnitTests/Sources/StartChatViewModelTests.swift index 1b8681ea4..3d23909ae 100644 --- a/UnitTests/Sources/StartChatViewModelTests.swift +++ b/UnitTests/Sources/StartChatViewModelTests.swift @@ -21,7 +21,7 @@ import XCTest @MainActor class StartChatScreenViewModelTests: XCTestCase { var viewModel: StartChatScreenViewModelProtocol! - var clientProxy: MockClientProxy! + var clientProxy: ClientProxyMock! var userDiscoveryService: UserDiscoveryServiceMock! var context: StartChatScreenViewModel.Context { @@ -29,7 +29,7 @@ class StartChatScreenViewModelTests: XCTestCase { } override func setUpWithError() throws { - clientProxy = .init(userID: "") + clientProxy = .init(.init(userID: "")) userDiscoveryService = UserDiscoveryServiceMock() userDiscoveryService.fetchSuggestionsReturnValue = .success([]) userDiscoveryService.searchProfilesWithReturnValue = .success([]) diff --git a/UnitTests/Sources/UserDiscoveryService/UserDiscoveryServiceTest.swift b/UnitTests/Sources/UserDiscoveryService/UserDiscoveryServiceTest.swift index f8b3a88cb..8fde1b14c 100644 --- a/UnitTests/Sources/UserDiscoveryService/UserDiscoveryServiceTest.swift +++ b/UnitTests/Sources/UserDiscoveryService/UserDiscoveryServiceTest.swift @@ -21,68 +21,68 @@ import XCTest @MainActor class UserDiscoveryServiceTest: XCTestCase { var service: UserDiscoveryService! - var clientProxy: MockClientProxy! + var clientProxy: ClientProxyMock! override func setUpWithError() throws { - clientProxy = .init(userID: "@foo:matrix.org") + clientProxy = .init(.init(userID: "@foo:matrix.org")) service = UserDiscoveryService(clientProxy: clientProxy) } func testQueryShowingResults() async throws { - clientProxy.searchUsersResult = .success(.init(results: [UserProfileProxy.mockAlice], limited: true)) + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: [UserProfileProxy.mockAlice], limited: true)) let results = await (try? search(query: "AAA").get()) ?? [] assertSearchResults(results, toBe: 1) } - + func testOwnerIsFiltered() async throws { - clientProxy.searchUsersResult = .success(.init(results: [UserProfileProxy(userID: "@foo:matrix.org")], limited: true)) - + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: [UserProfileProxy(userID: "@foo:matrix.org")], limited: true)) + let results = await (try? search(query: "AAA").get()) ?? [] assertSearchResults(results, toBe: 0) } func testGetProfileIsNotCalled() async { - clientProxy.searchUsersResult = .success(.init(results: searchResults, limited: true)) - clientProxy.getProfileResult = .success(.init(userID: "@alice:matrix.org")) + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: searchResults, limited: true)) + clientProxy.profileForReturnValue = .success(.init(userID: "@alice:matrix.org")) let results = await (try? search(query: "AAA").get()) ?? [] assertSearchResults(results, toBe: 3) - XCTAssertFalse(clientProxy.getProfileCalled) + XCTAssertFalse(clientProxy.profileForCalled) } func testGetProfileIsNotCalledForAccountOwnerID() async { - clientProxy.searchUsersResult = .success(.init(results: searchResults, limited: true)) - clientProxy.getProfileResult = .success(.init(userID: "@alice:matrix.org")) - + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: searchResults, limited: true)) + clientProxy.profileForReturnValue = .success(.init(userID: "@alice:matrix.org")) + let results = await (try? search(query: "foo:matrix.org").get()) ?? [] assertSearchResults(results, toBe: 3) - XCTAssertFalse(clientProxy.getProfileCalled) + XCTAssertFalse(clientProxy.profileForCalled) } func testLocalResultShows() async { - clientProxy.searchUsersResult = .success(.init(results: searchResults, limited: true)) - clientProxy.getProfileResult = .success(.init(userID: "@some:matrix.org")) + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: searchResults, limited: true)) + clientProxy.profileForReturnValue = .success(.init(userID: "@some:matrix.org")) let results = await (try? search(query: "@a:b.com").get()) ?? [] assertSearchResults(results, toBe: 4) - XCTAssertTrue(clientProxy.getProfileCalled) + XCTAssertTrue(clientProxy.profileForCalled) } func testLocalResultShowsOnSearchError() async { - clientProxy.searchUsersResult = .failure(.failedSearchingUsers) - clientProxy.getProfileResult = .success(.init(userID: "@some:matrix.org")) + clientProxy.searchUsersSearchTermLimitReturnValue = .failure(.failedSearchingUsers) + clientProxy.profileForReturnValue = .success(.init(userID: "@some:matrix.org")) let results = await (try? search(query: "@a:b.com").get()) ?? [] assertSearchResults(results, toBe: 1) - XCTAssertTrue(clientProxy.getProfileCalled) + XCTAssertTrue(clientProxy.profileForCalled) } func testSearchErrorTriggers() async { - clientProxy.searchUsersResult = .failure(.failedSearchingUsers) - clientProxy.getProfileResult = .success(.init(userID: "@some:matrix.org")) + clientProxy.searchUsersSearchTermLimitReturnValue = .failure(.failedSearchingUsers) + clientProxy.profileForReturnValue = .success(.init(userID: "@some:matrix.org")) switch await search(query: "some query") { case .success: @@ -91,30 +91,30 @@ class UserDiscoveryServiceTest: XCTestCase { XCTAssertEqual(error, UserDiscoveryErrorType.failedSearchingUsers) } - XCTAssertFalse(clientProxy.getProfileCalled) + XCTAssertFalse(clientProxy.profileForCalled) } func testLocalResultWithDuplicates() async { - clientProxy.searchUsersResult = .success(.init(results: searchResults, limited: true)) - clientProxy.getProfileResult = .success(.init(userID: "@bob:matrix.org")) + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: searchResults, limited: true)) + clientProxy.profileForReturnValue = .success(.init(userID: "@bob:matrix.org")) let results = await (try? search(query: "@a:b.com").get()) ?? [] assertSearchResults(results, toBe: 3) let firstUserID = results.first?.userID XCTAssertEqual(firstUserID, "@bob:matrix.org") - XCTAssertTrue(clientProxy.getProfileCalled) + XCTAssertTrue(clientProxy.profileForCalled) } func testSearchResultsShowWhenGetProfileFails() async { - clientProxy.searchUsersResult = .success(.init(results: searchResults, limited: true)) - clientProxy.getProfileResult = .failure(.failedGettingUserProfile) + clientProxy.searchUsersSearchTermLimitReturnValue = .success(.init(results: searchResults, limited: true)) + clientProxy.profileForReturnValue = .failure(.failedGettingUserProfile) let results = await (try? search(query: "@a:b.com").get()) ?? [] let firstUserID = results.first?.userID XCTAssertEqual(firstUserID, "@a:b.com") - XCTAssertTrue(clientProxy.getProfileCalled) + XCTAssertTrue(clientProxy.profileForCalled) } // MARK: - Private diff --git a/UnitTests/Sources/UserSession/UserSessionTests.swift b/UnitTests/Sources/UserSession/UserSessionTests.swift index a806b6db9..8c6ec7eba 100644 --- a/UnitTests/Sources/UserSession/UserSessionTests.swift +++ b/UnitTests/Sources/UserSession/UserSessionTests.swift @@ -19,11 +19,15 @@ import XCTest final class UserSessionTests: XCTestCase { var userSession: UserSession! - let clientProxy = MockClientProxy(userID: "@test:user.net") + var clientProxy: ClientProxyMock! + let actionsPublisher = PassthroughSubject() private var cancellables = Set() override func setUpWithError() throws { + clientProxy = ClientProxyMock(.init(userID: "@test:user.net")) + clientProxy.actionsPublisher = actionsPublisher.eraseToAnyPublisher() + cancellables.removeAll() userSession = UserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), @@ -42,8 +46,11 @@ final class UserSessionTests: XCTestCase { let controller = SessionVerificationControllerProxyMock.configureMock(callbacks: PassthroughSubject(), isVerified: false, requestDelay: .zero) - clientProxy.sessionVerificationControllerProxyResult = .success(controller) - clientProxy.actionsSubject.send(.receivedSyncUpdate) + + clientProxy.sessionVerificationControllerProxyReturnValue = .success(controller) + + actionsPublisher.send(.receivedSyncUpdate) + waitForExpectations(timeout: 1.0) } @@ -52,7 +59,7 @@ final class UserSessionTests: XCTestCase { let controller = SessionVerificationControllerProxyMock.configureMock(callbacks: PassthroughSubject(), isVerified: false, requestDelay: .zero) - clientProxy.sessionVerificationControllerProxyResult = .success(controller) + clientProxy.sessionVerificationControllerProxyReturnValue = .success(controller) controller.callbacks.sink { value in switch value { @@ -64,7 +71,7 @@ final class UserSessionTests: XCTestCase { } .store(in: &cancellables) - clientProxy.actionsSubject.send(.receivedSyncUpdate) + actionsPublisher.send(.receivedSyncUpdate) controller.callbacks.send(.finished) waitForExpectations(timeout: 1.0) } diff --git a/UnitTests/Sources/WaitlistScreenViewModelTests.swift b/UnitTests/Sources/WaitlistScreenViewModelTests.swift index 2f348c8b0..bb1e30ed9 100644 --- a/UnitTests/Sources/WaitlistScreenViewModelTests.swift +++ b/UnitTests/Sources/WaitlistScreenViewModelTests.swift @@ -31,7 +31,7 @@ class WaitlistScreenViewModelTests: XCTestCase { XCTAssertNil(context.viewState.userSession, "No user session should be set on a new view model.") XCTAssertTrue(context.viewState.isWaiting, "The view should start off in the waiting state.") - viewModel.update(userSession: MockUserSession(clientProxy: MockClientProxy(userID: "@alice:matrix.org"), + viewModel.update(userSession: MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@alice:matrix.org")), mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()))