From 0e3d7984ab2534170f755ee3a79d8265bfd11864 Mon Sep 17 00:00:00 2001 From: Doug Date: Fri, 6 Jan 2023 10:20:01 +0000 Subject: [PATCH] Refactor - Merge SessionVerificationControllerProxyMock into MockSessionVerificationControllerProxy. - Merge ClientProxyMock into MockClientProxy. - Simplify naming. --- ElementX.xcodeproj/project.pbxproj | 14 +- .../Services/Client/MockClientProxy.swift | 36 +++++- ...ckSessionVerificationControllerProxy.swift | 9 +- .../NotificationManager/ClientProxyMock.swift | 122 ------------------ .../NotificationManagerTests.swift | 86 ++++++------ ...ssionVerificationControllerProxyMock.swift | 45 ------- .../UserSession/UserSessionTests.swift | 46 ++++--- changelog.d/pr-390.change | 1 + 8 files changed, 111 insertions(+), 248 deletions(-) delete mode 100644 UnitTests/Sources/NotificationManager/ClientProxyMock.swift delete mode 100644 UnitTests/Sources/UserSession/SessionVerificationControllerProxyMock.swift create mode 100644 changelog.d/pr-390.change diff --git a/ElementX.xcodeproj/project.pbxproj b/ElementX.xcodeproj/project.pbxproj index 9a941c65f0..8066f03665 100644 --- a/ElementX.xcodeproj/project.pbxproj +++ b/ElementX.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -206,7 +206,6 @@ 69BCBB4FB2DC3D61A28D3FD8 /* TimelineStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DC2C9E0E15C79BBDA80F0A2 /* TimelineStyle.swift */; }; 6A0E7551E0D1793245F34CDD /* ClientError.swift in Sources */ = {isa = PBXBuildFile; fileRef = D09A267106B9585D3D0CFC0D /* ClientError.swift */; }; 6AC1DC1EAD9F7568360DA1BA /* ServerSelectionModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = A30A1758E2B73EF38E7C42F8 /* ServerSelectionModels.swift */; }; - 6AE7082703DB19F74A83F677 /* SessionVerificationControllerProxyMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDC0DCEE729FCBE315C7445C /* SessionVerificationControllerProxyMock.swift */; }; 6B15FF984906AAFCF9DC4F58 /* OnboardingUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C88046D6A070D9827181C4D /* OnboardingUITests.swift */; }; 6C67774E8387D44426718BD9 /* FilePreviewCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADB3A7BCE745626EC61EF3C3 /* FilePreviewCoordinator.swift */; }; 6C9F6C7F2B35288C4230EF3F /* FilePreviewModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55EA4B03F92F31EAA83B3F7B /* FilePreviewModels.swift */; }; @@ -374,7 +373,6 @@ BD782053BE4C3D2F0BDE5699 /* ServiceLocator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F95CADD0A5DBD76B990FCB /* ServiceLocator.swift */; }; BEEEB659A0BA510D7BE6345C /* RoomMemberProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D1790942BE4FE0D8273191B /* RoomMemberProxy.swift */; }; BFB534E338A3D949944FB2F5 /* NotificationServiceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B490675B8E31423AF116BDA /* NotificationServiceProxy.swift */; }; - C07B25B7F552657C158DA85B /* ClientProxyMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5461F0B817787C9694D9620A /* ClientProxyMock.swift */; }; C1910A16BDF131FECA77BE22 /* EmojiPickerScreenCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEA38B9851CFCC4D67F5587D /* EmojiPickerScreenCoordinator.swift */; }; C3522917C0C367C403429EEC /* CoordinatorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = B251F5B4511D1CA0BA8361FE /* CoordinatorProtocol.swift */; }; C35CF4DAB1467FE1BBDC204B /* MessageTimelineItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEAF1C75771D9DC75877F4B4 /* MessageTimelineItem.swift */; }; @@ -712,7 +710,6 @@ 541542F5AC323709D8563458 /* AnalyticsPrompt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnalyticsPrompt.swift; sourceTree = ""; }; 542D4F49FABA056DEEEB3400 /* RustTracing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RustTracing.swift; sourceTree = ""; }; 5445FCE0CE15E634FDC1A2E2 /* AnalyticsService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnalyticsService.swift; sourceTree = ""; }; - 5461F0B817787C9694D9620A /* ClientProxyMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClientProxyMock.swift; sourceTree = ""; }; 55BC11560C8A2598964FFA4C /* bs */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = bs; path = bs.lproj/Localizable.strings; sourceTree = ""; }; 55D7187F6B0C0A651AC3DFFA /* in */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = in; path = in.lproj/Localizable.strings; sourceTree = ""; }; 55EA4B03F92F31EAA83B3F7B /* FilePreviewModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilePreviewModels.swift; sourceTree = ""; }; @@ -799,7 +796,7 @@ 8D6094DEAAEB388E1AE118C6 /* MockRoomTimelineProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockRoomTimelineProvider.swift; sourceTree = ""; }; 8D8169443E5AC5FF71BFB3DB /* cs */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = cs; path = cs.lproj/Localizable.strings; sourceTree = ""; }; 8DC2C9E0E15C79BBDA80F0A2 /* TimelineStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineStyle.swift; sourceTree = ""; }; - 8E088F2A1B9EC529D3221931 /* UITests.xctestplan */ = {isa = PBXFileReference; path = UITests.xctestplan; sourceTree = ""; }; + 8E088F2A1B9EC529D3221931 /* UITests.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = UITests.xctestplan; sourceTree = ""; }; 8ED2D2F6A137A95EA50413BE /* UserNotificationControllerProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserNotificationControllerProtocol.swift; sourceTree = ""; }; 8F7D42E66E939B709C1EC390 /* MockRoomSummaryProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockRoomSummaryProvider.swift; sourceTree = ""; }; 8FC26871038FB0E4AAE22605 /* apple_emojis_data.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = apple_emojis_data.json; sourceTree = ""; }; @@ -1011,10 +1008,9 @@ EBE5502760CF6CA2D7201883 /* ja */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = ja; path = ja.lproj/Localizable.stringsdict; sourceTree = ""; }; ED044D00F2176681CC02CD54 /* HomeScreenRoomCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeScreenRoomCell.swift; sourceTree = ""; }; ED1D792EB82506A19A72C8DE /* RoomTimelineItemProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomTimelineItemProtocol.swift; sourceTree = ""; }; - ED482057AE39D5C6D9C5F3D8 /* message.caf */ = {isa = PBXFileReference; path = message.caf; sourceTree = ""; }; + ED482057AE39D5C6D9C5F3D8 /* message.caf */ = {isa = PBXFileReference; lastKnownFileType = file; path = message.caf; sourceTree = ""; }; EDAA4472821985BF868CC21C /* ServerSelectionViewModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSelectionViewModelTests.swift; sourceTree = ""; }; EDB6E40BAD4504D899FAAC9A /* TemplateViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateViewModel.swift; sourceTree = ""; }; - EDC0DCEE729FCBE315C7445C /* SessionVerificationControllerProxyMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionVerificationControllerProxyMock.swift; sourceTree = ""; }; EE8BCD14EFED23459A43FDFF /* ja */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ja; path = ja.lproj/Localizable.strings; sourceTree = ""; }; EEAF1C75771D9DC75877F4B4 /* MessageTimelineItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageTimelineItem.swift; sourceTree = ""; }; EEE384418EB1FEDFA62C9CD0 /* RoomTimelineViewFactoryProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomTimelineViewFactoryProtocol.swift; sourceTree = ""; }; @@ -1521,7 +1517,6 @@ 53280D2292E6C9C7821773FD /* UserSession */ = { isa = PBXGroup; children = ( - EDC0DCEE729FCBE315C7445C /* SessionVerificationControllerProxyMock.swift */, F36C0A6D59717193F49EA986 /* UserSessionTests.swift */, ); path = UserSession; @@ -1839,7 +1834,6 @@ 7DBC911559934065993A5FF4 /* NotificationManager */ = { isa = PBXGroup; children = ( - 5461F0B817787C9694D9620A /* ClientProxyMock.swift */, 0376C429FAB1687C3D905F3E /* MockCoder.swift */, 30ED584467DB380E3CEFB1DB /* NotificationManagerTests.swift */, DC0AEA686E425F86F6BA0404 /* UNNotification+Creator.swift */, @@ -2869,7 +2863,6 @@ 0F9E38A75337D0146652ACAB /* BackgroundTaskTests.swift in Sources */, 7F61F9ACD5EC9E845EF3EFBF /* BugReportServiceTests.swift in Sources */, C7CFDB4929DDD9A3B5BA085D /* BugReportViewModelTests.swift in Sources */, - C07B25B7F552657C158DA85B /* ClientProxyMock.swift in Sources */, 9C45CE85325CD591DADBC4CA /* ElementXTests.swift in Sources */, 501304F26B52DF7024011B6C /* EmojiMartJSONLoaderTests.swift in Sources */, 25618589E0DE0F1E95FC7B5C /* EmojiProviderTests.swift in Sources */, @@ -2894,7 +2887,6 @@ 46562110EE202E580A5FFD9C /* RoomScreenViewModelTests.swift in Sources */, EA31DD9043B91ECB8E45A9A6 /* ScreenshotDetectorTests.swift in Sources */, 93875ADD456142D20823ED24 /* ServerSelectionViewModelTests.swift in Sources */, - 6AE7082703DB19F74A83F677 /* SessionVerificationControllerProxyMock.swift in Sources */, 86675910612A12409262DFBD /* SessionVerificationStateMachineTests.swift in Sources */, 755727E0B756430DFFEC4732 /* SessionVerificationViewModelTests.swift in Sources */, 206F0DBAB6AF042CA1FF2C0D /* SettingsViewModelTests.swift in Sources */, diff --git a/ElementX/Sources/Services/Client/MockClientProxy.swift b/ElementX/Sources/Services/Client/MockClientProxy.swift index 17ecdafee5..f8559b5494 100644 --- a/ElementX/Sources/Services/Client/MockClientProxy.swift +++ b/ElementX/Sources/Services/Client/MockClientProxy.swift @@ -79,14 +79,31 @@ class MockClientProxy: ClientProxyProtocol { throw ClientProxyError.failedLoadingMedia } + var sessionVerificationControllerProxyResult: Result? func sessionVerificationControllerProxy() async -> Result { - .failure(.failedRetrievingSessionVerificationController) + if let sessionVerificationControllerProxyResult { + return sessionVerificationControllerProxyResult + } else { + return .failure(.failedRetrievingSessionVerificationController) + } } - + func logout() async { // no-op } - + + var setPusherCalled = false + var setPusherErrorToThrow: Error? + var setPusherPushkey: String? + var setPusherKind: PusherKind? + var setPusherAppId: String? + var setPusherAppDisplayName: String? + var setPusherDeviceDisplayName: String? + var setPusherProfileTag: String? + var setPusherLang: String? + var setPusherUrl: String? + var setPusherFormat: PushFormat? + var setPusherDefaultPayload: [AnyHashable: Any]? // swiftlint:disable:next function_parameter_count func setPusher(pushkey: String, kind: PusherKind?, @@ -98,6 +115,17 @@ class MockClientProxy: ClientProxyProtocol { url: String?, format: PushFormat?, defaultPayload: [AnyHashable: Any]?) async throws { - // no-op + if let setPusherErrorToThrow { throw setPusherErrorToThrow } + setPusherCalled = true + setPusherPushkey = pushkey + setPusherKind = kind + setPusherAppId = appId + setPusherAppDisplayName = appDisplayName + setPusherDeviceDisplayName = deviceDisplayName + setPusherProfileTag = profileTag + setPusherLang = lang + setPusherUrl = url + setPusherFormat = format + setPusherDefaultPayload = defaultPayload } } diff --git a/ElementX/Sources/Services/SessionVerification/MockSessionVerificationControllerProxy.swift b/ElementX/Sources/Services/SessionVerification/MockSessionVerificationControllerProxy.swift index d8d1a2af05..607ec00268 100644 --- a/ElementX/Sources/Services/SessionVerification/MockSessionVerificationControllerProxy.swift +++ b/ElementX/Sources/Services/SessionVerification/MockSessionVerificationControllerProxy.swift @@ -22,10 +22,11 @@ struct MockSessionVerificationControllerProxy: SessionVerificationControllerProx var callbacks = PassthroughSubject() var isVerified = false + var requestDelay: Duration = .seconds(2) func requestVerification() async -> Result { Task.detached { - try await Task.sleep(nanoseconds: 2_000_000_000) + try await Task.sleep(for: requestDelay) callbacks.send(.receivedVerificationData(Self.emojis)) } @@ -34,7 +35,7 @@ struct MockSessionVerificationControllerProxy: SessionVerificationControllerProx func approveVerification() async -> Result { Task.detached { - try await Task.sleep(nanoseconds: 2_000_000_000) + try await Task.sleep(for: requestDelay) callbacks.send(.finished) } @@ -43,7 +44,7 @@ struct MockSessionVerificationControllerProxy: SessionVerificationControllerProx func declineVerification() async -> Result { Task.detached { - try await Task.sleep(nanoseconds: 2_000_000_000) + try await Task.sleep(for: requestDelay) callbacks.send(.cancelled) } @@ -52,7 +53,7 @@ struct MockSessionVerificationControllerProxy: SessionVerificationControllerProx func cancelVerification() async -> Result { Task.detached { - try await Task.sleep(nanoseconds: 2_000_000_000) + try await Task.sleep(for: requestDelay) callbacks.send(.cancelled) } diff --git a/UnitTests/Sources/NotificationManager/ClientProxyMock.swift b/UnitTests/Sources/NotificationManager/ClientProxyMock.swift deleted file mode 100644 index 592cbc9597..0000000000 --- a/UnitTests/Sources/NotificationManager/ClientProxyMock.swift +++ /dev/null @@ -1,122 +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 -@testable import ElementX -import Foundation - -class ClientProxyMock: ClientProxyProtocol { - var sessionVerificationControllerProxyResult: Result? - - var visibleRoomsSummaryProvider: ElementX.RoomSummaryProviderProtocol? - - var allRoomsSummaryProvider: ElementX.RoomSummaryProviderProtocol? - - let callbacks = PassthroughSubject() - - var userIdentifier = "" - - var isSoftLogout = false - - var deviceId: String? = "" - - var homeserver = "" - - var restorationToken: ElementX.RestorationToken? - - var roomSummaryProvider: ElementX.RoomSummaryProviderProtocol? - - internal init() { } - - func startSync() { } - - func stopSync() { } - - func restartSync() { } - - func roomForIdentifier(_ identifier: String) async -> ElementX.RoomProxyProtocol? { - nil - } - - func loadUserDisplayName() async -> Result { - .failure(.failedLoadingMedia) - } - - func loadUserAvatarURLString() async -> Result { - .failure(.failedLoadingMedia) - } - - func accountDataEvent(type: String) async -> Result where Content: Decodable { - .failure(.failedLoadingMedia) - } - - func setAccountData(content: Content, type: String) async -> Result where Content: Encodable { - .failure(.failedLoadingMedia) - } - - func sessionVerificationControllerProxy() async -> Result { - if let sessionVerificationControllerProxyResult { - return sessionVerificationControllerProxyResult - } else { - return .failure(.failedLoadingMedia) - } - } - - func logout() async { } - - var setPusherCalled = false - var setPusherErrorToThrow: Error? - var setPusherPushkey: String? - var setPusherKind: PusherKind? - var setPusherAppId: String? - var setPusherAppDisplayName: String? - var setPusherDeviceDisplayName: String? - var setPusherProfileTag: String? - var setPusherLang: String? - var setPusherUrl: String? - var setPusherFormat: PushFormat? - var setPusherDefaultPayload: [AnyHashable: Any]? - - // swiftlint:disable:next function_parameter_count - func setPusher(pushkey: String, kind: PusherKind?, appId: String, appDisplayName: String, deviceDisplayName: String, profileTag: String?, lang: String, url: String?, format: PushFormat?, defaultPayload: [AnyHashable: Any]?) async throws { - if let setPusherErrorToThrow { - throw setPusherErrorToThrow - } - setPusherCalled = true - setPusherPushkey = pushkey - setPusherKind = kind - setPusherAppId = appId - setPusherAppDisplayName = appDisplayName - setPusherDeviceDisplayName = deviceDisplayName - setPusherProfileTag = profileTag - setPusherLang = lang - setPusherUrl = url - setPusherFormat = format - setPusherDefaultPayload = defaultPayload - } - - func mediaSourceForURLString(_ urlString: String) -> ElementX.MediaSourceProxy { - MediaSourceProxy(urlString: "") - } - - func loadMediaContentForSource(_ source: ElementX.MediaSourceProxy) async throws -> Data { - Data() - } - - func loadMediaThumbnailForSource(_ source: ElementX.MediaSourceProxy, width: UInt, height: UInt) async throws -> Data { - Data() - } -} diff --git a/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift b/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift index be0ff48b5e..ebd1dbfb2b 100644 --- a/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift +++ b/UnitTests/Sources/NotificationManager/NotificationManagerTests.swift @@ -20,8 +20,8 @@ import Combine @testable import ElementX final class NotificationManagerTests: XCTestCase { - var sut: NotificationManager! - private let clientProxyMock = ClientProxyMock() + var notificationManager: NotificationManager! + private let clientProxy = MockClientProxy(userIdentifier: "@test:user.net") private let notificationCenter = UserNotificationCenterSpy() private var authorizationStatusWasGranted = false private var shouldDisplayInAppNotificationReturnValue = false @@ -30,16 +30,16 @@ final class NotificationManagerTests: XCTestCase { private let settings = ServiceLocator.shared.settings override func setUp() { - sut = NotificationManager(clientProxy: clientProxyMock, notificationCenter: notificationCenter) + notificationManager = NotificationManager(clientProxy: clientProxy, notificationCenter: notificationCenter) } func test_whenRegistered_pusherIsCalled() async { - _ = await sut.register(with: Data()) - XCTAssertTrue(clientProxyMock.setPusherCalled) + _ = await notificationManager.register(with: Data()) + XCTAssertTrue(clientProxy.setPusherCalled) } func test_whenRegisteredSuccess_completionSuccessIsCalled() async throws { - let success = await sut.register(with: Data()) + let success = await notificationManager.register(with: Data()) XCTAssertTrue(success) } @@ -47,25 +47,25 @@ final class NotificationManagerTests: XCTestCase { enum TestError: Error { case someError } - clientProxyMock.setPusherErrorToThrow = TestError.someError - let success = await sut.register(with: Data()) + clientProxy.setPusherErrorToThrow = TestError.someError + let success = await notificationManager.register(with: Data()) XCTAssertFalse(success) } @MainActor func test_whenRegistered_pusherIsCalledWithCorrectValues() async throws { let pushkeyData = Data("1234".utf8) - _ = await sut.register(with: pushkeyData) - XCTAssertEqual(clientProxyMock.setPusherPushkey, pushkeyData.base64EncodedString()) - XCTAssertEqual(clientProxyMock.setPusherAppId, settings?.pusherAppId) - XCTAssertEqual(clientProxyMock.setPusherKind, .http) - XCTAssertEqual(clientProxyMock.setPusherAppId, settings?.pusherAppId) - XCTAssertEqual(clientProxyMock.setPusherAppDisplayName, "\(InfoPlistReader.target.bundleDisplayName) (iOS)") - XCTAssertEqual(clientProxyMock.setPusherDeviceDisplayName, UIDevice.current.name) - XCTAssertNotNil(clientProxyMock.setPusherProfileTag) - XCTAssertEqual(clientProxyMock.setPusherLang, Bundle.preferredLanguages.first) - XCTAssertEqual(clientProxyMock.setPusherUrl, settings?.pushGatewayBaseURL.absoluteString) - XCTAssertEqual(clientProxyMock.setPusherFormat, .eventIdOnly) + _ = await notificationManager.register(with: pushkeyData) + XCTAssertEqual(clientProxy.setPusherPushkey, pushkeyData.base64EncodedString()) + XCTAssertEqual(clientProxy.setPusherAppId, settings?.pusherAppId) + XCTAssertEqual(clientProxy.setPusherKind, .http) + XCTAssertEqual(clientProxy.setPusherAppId, settings?.pusherAppId) + XCTAssertEqual(clientProxy.setPusherAppDisplayName, "\(InfoPlistReader.target.bundleDisplayName) (iOS)") + XCTAssertEqual(clientProxy.setPusherDeviceDisplayName, UIDevice.current.name) + XCTAssertNotNil(clientProxy.setPusherProfileTag) + XCTAssertEqual(clientProxy.setPusherLang, Bundle.preferredLanguages.first) + XCTAssertEqual(clientProxy.setPusherUrl, settings?.pushGatewayBaseURL.absoluteString) + XCTAssertEqual(clientProxy.setPusherFormat, .eventIdOnly) let defaultPayload: [AnyHashable: Any] = [ "aps": [ "mutable-content": 1, @@ -75,31 +75,31 @@ final class NotificationManagerTests: XCTestCase { ] ] ] - let actualPayload = NSDictionary(dictionary: clientProxyMock.setPusherDefaultPayload ?? [:]) + let actualPayload = NSDictionary(dictionary: clientProxy.setPusherDefaultPayload ?? [:]) XCTAssertTrue(actualPayload.isEqual(to: defaultPayload)) } func test_whenRegisteredAndPusherTagNotSetInSettings_tagGeneratedAndSavedInSettings() async throws { settings?.pusherProfileTag = nil - _ = await sut.register(with: Data()) + _ = await notificationManager.register(with: Data()) XCTAssertNotNil(settings?.pusherProfileTag) } func test_whenRegisteredAndPusherTagIsSetInSettings_tagNotGenerated() async throws { settings?.pusherProfileTag = "12345" - _ = await sut.register(with: Data()) + _ = await notificationManager.register(with: Data()) XCTAssertEqual(settings?.pusherProfileTag, "12345") } func test_whenShowLocalNotification_notificationRequestGetsAdded() async throws { - await sut.showLocalNotification(with: "Title", subtitle: "Subtitle") + await notificationManager.showLocalNotification(with: "Title", subtitle: "Subtitle") let request = try XCTUnwrap(notificationCenter.addRequest) XCTAssertEqual(request.content.title, "Title") XCTAssertEqual(request.content.subtitle, "Subtitle") } func test_whenStart_notificationCategoriesAreSet() throws { - sut.start() + notificationManager.start() let replyAction = UNTextInputNotificationAction(identifier: NotificationConstants.Action.inlineReply, title: ElementL10n.actionQuickReply, options: []) @@ -111,13 +111,13 @@ final class NotificationManagerTests: XCTestCase { } func test_whenStart_delegateIsSet() throws { - sut.start() + notificationManager.start() let delegate = try XCTUnwrap(notificationCenter.delegate) - XCTAssertTrue(delegate.isEqual(sut)) + XCTAssertTrue(delegate.isEqual(notificationManager)) } func test_whenStart_requestAuthorizationCalledWithCorrectParams() async throws { - sut.start() + notificationManager.start() await Task.yield() XCTAssertEqual(notificationCenter.requestAuthorizationOptions, [.alert, .sound, .badge]) } @@ -125,53 +125,53 @@ final class NotificationManagerTests: XCTestCase { func test_whenStartAndAuthorizationGranted_delegateCalled() async throws { authorizationStatusWasGranted = false notificationCenter.requestAuthorizationGrantedReturnValue = true - sut.delegate = self - sut.start() + notificationManager.delegate = self + notificationManager.start() try await Task.sleep(for: .milliseconds(100)) XCTAssertTrue(authorizationStatusWasGranted) } func test_whenWillPresentNotificationsDelegateNotSet_CorrectPresentationOptionsReturned() async throws { - sut.start() + notificationManager.start() let archiver = MockCoder(requiringSecureCoding: false) let notification = try XCTUnwrap(UNNotification(coder: archiver)) - let options = await sut.userNotificationCenter(UNUserNotificationCenter.current(), willPresent: notification) + let options = await notificationManager.userNotificationCenter(UNUserNotificationCenter.current(), willPresent: notification) XCTAssertEqual(options, [.badge, .sound, .list, .banner]) } func test_whenWillPresentNotificationsDelegateSetAndNotificationsShoudNotBeDisplayed_CorrectPresentationOptionsReturned() async throws { shouldDisplayInAppNotificationReturnValue = false - sut.delegate = self - sut.start() + notificationManager.delegate = self + notificationManager.start() let notification = try UNNotification.with(userInfo: [AnyHashable: Any]()) - let options = await sut.userNotificationCenter(UNUserNotificationCenter.current(), willPresent: notification) + let options = await notificationManager.userNotificationCenter(UNUserNotificationCenter.current(), willPresent: notification) XCTAssertEqual(options, []) } func test_whenWillPresentNotificationsDelegateSetAndNotificationsShoudBeDisplayed_CorrectPresentationOptionsReturned() async throws { shouldDisplayInAppNotificationReturnValue = true - sut.delegate = self - sut.start() + notificationManager.delegate = self + notificationManager.start() let notification = try UNNotification.with(userInfo: [AnyHashable: Any]()) - let options = await sut.userNotificationCenter(UNUserNotificationCenter.current(), willPresent: notification) + let options = await notificationManager.userNotificationCenter(UNUserNotificationCenter.current(), willPresent: notification) XCTAssertEqual(options, [.badge, .sound, .list, .banner]) } func test_whenNotificationCenterReceivedResponseInLineReply_delegateIsCalled() async throws { handleInlineReplyDelegateCalled = false - sut.delegate = self - sut.start() + notificationManager.delegate = self + notificationManager.start() let response = try UNTextInputNotificationResponse.with(userInfo: [AnyHashable: Any](), actionIdentifier: NotificationConstants.Action.inlineReply) - await sut.userNotificationCenter(UNUserNotificationCenter.current(), didReceive: response) + await notificationManager.userNotificationCenter(UNUserNotificationCenter.current(), didReceive: response) XCTAssertTrue(handleInlineReplyDelegateCalled) } func test_whenNotificationCenterReceivedResponseWithActionIdentifier_delegateIsCalled() async throws { notificationTappedDelegateCalled = false - sut.delegate = self - sut.start() + notificationManager.delegate = self + notificationManager.start() let response = try UNTextInputNotificationResponse.with(userInfo: [AnyHashable: Any](), actionIdentifier: UNNotificationDefaultActionIdentifier) - await sut.userNotificationCenter(UNUserNotificationCenter.current(), didReceive: response) + await notificationManager.userNotificationCenter(UNUserNotificationCenter.current(), didReceive: response) XCTAssertTrue(notificationTappedDelegateCalled) } } diff --git a/UnitTests/Sources/UserSession/SessionVerificationControllerProxyMock.swift b/UnitTests/Sources/UserSession/SessionVerificationControllerProxyMock.swift deleted file mode 100644 index 43607ac52b..0000000000 --- a/UnitTests/Sources/UserSession/SessionVerificationControllerProxyMock.swift +++ /dev/null @@ -1,45 +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 -@testable import ElementX -import Foundation - -class SessionVerificationControllerProxyMock: SessionVerificationControllerProxyProtocol { - var callbacks: PassthroughSubject - - var isVerified: Bool - - init(callbacks: PassthroughSubject, isVerified: Bool) { - self.callbacks = callbacks - self.isVerified = isVerified - } - - func requestVerification() async -> Result { - .failure(.failedApprovingVerification) - } - - func approveVerification() async -> Result { - .failure(.failedApprovingVerification) - } - - func declineVerification() async -> Result { - .failure(.failedApprovingVerification) - } - - func cancelVerification() async -> Result { - .failure(.failedApprovingVerification) - } -} diff --git a/UnitTests/Sources/UserSession/UserSessionTests.swift b/UnitTests/Sources/UserSession/UserSessionTests.swift index 1cea4eff03..49732c34fa 100644 --- a/UnitTests/Sources/UserSession/UserSessionTests.swift +++ b/UnitTests/Sources/UserSession/UserSessionTests.swift @@ -18,37 +18,42 @@ import Combine import XCTest final class UserSessionTests: XCTestCase { - var sut: UserSession! - let clientProxyMock = ClientProxyMock() - private var cancellables: Set! + var userSession: UserSession! + let clientProxy = MockClientProxy(userIdentifier: "@test:user.net") + + private var cancellables: Set = [] + override func setUpWithError() throws { cancellables = [] - sut = UserSession(clientProxy: clientProxyMock, mediaProvider: MockMediaProvider()) + userSession = UserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider()) } - func test_whenUserSessionReceivesSyncUpdateAndSessionControllerRetrievedAndSessionNotVierified_sessionVerificationNeededEventReceived() throws { + func test_whenUserSessionReceivesSyncUpdateAndSessionControllerRetrievedAndSessionNotVerified_sessionVerificationNeededEventReceived() throws { let expectation = expectation(description: "SessionVerificationNeeded expectation") - sut.callbacks.sink { callback in + userSession.callbacks.sink { callback in switch callback { case .sessionVerificationNeeded: expectation.fulfill() default: break } - }.store(in: &cancellables) + } + .store(in: &cancellables) - let controller = SessionVerificationControllerProxyMock(callbacks: PassthroughSubject(), - isVerified: false) - clientProxyMock.sessionVerificationControllerProxyResult = .success(controller) - clientProxyMock.callbacks.send(.receivedSyncUpdate) + let controller = MockSessionVerificationControllerProxy(callbacks: PassthroughSubject(), + isVerified: false, + requestDelay: .zero) + clientProxy.sessionVerificationControllerProxyResult = .success(controller) + clientProxy.callbacks.send(.receivedSyncUpdate) waitForExpectations(timeout: 1.0) } func test_whenUserSessionReceivesSyncUpdateAndSessionIsVerified_didVerifySessionEventReceived() throws { let expectation = expectation(description: "DidVerifySessionEvent expectation") - let controller = SessionVerificationControllerProxyMock(callbacks: PassthroughSubject(), - isVerified: false) - clientProxyMock.sessionVerificationControllerProxyResult = .success(controller) + let controller = MockSessionVerificationControllerProxy(callbacks: PassthroughSubject(), + isVerified: false, + requestDelay: .zero) + clientProxy.sessionVerificationControllerProxyResult = .success(controller) controller.callbacks.sink { value in switch value { @@ -57,24 +62,27 @@ final class UserSessionTests: XCTestCase { default: break } - }.store(in: &cancellables) + } + .store(in: &cancellables) - clientProxyMock.callbacks.send(.receivedSyncUpdate) + clientProxy.callbacks.send(.receivedSyncUpdate) controller.callbacks.send(.finished) waitForExpectations(timeout: 1.0) } func test_whenUserSessionReceivesUpdatedRestoreToken_updateRestoreTokenNeededEventReceived() throws { let expectation = expectation(description: "UpdatedRestoreToken expectation") - sut.callbacks.sink { callback in + userSession.callbacks.sink { callback in switch callback { case .updateRestoreTokenNeeded: expectation.fulfill() default: break } - }.store(in: &cancellables) - clientProxyMock.callbacks.send(.updatedRestoreToken) + } + .store(in: &cancellables) + + clientProxy.callbacks.send(.updatedRestoreToken) waitForExpectations(timeout: 1.0) } } diff --git a/changelog.d/pr-390.change b/changelog.d/pr-390.change new file mode 100644 index 0000000000..3959da527f --- /dev/null +++ b/changelog.d/pr-390.change @@ -0,0 +1 @@ +UserSession: Add unit tests. \ No newline at end of file