User sessions tests (#390)

* User sessions tests

* Refactor

- Merge SessionVerificationControllerProxyMock into MockSessionVerificationControllerProxy.
- Merge ClientProxyMock into MockClientProxy.
- Simplify naming.

Co-authored-by: Doug <douglase@element.io>
This commit is contained in:
Aleksandrs Proskurins
2023-01-06 12:53:19 +02:00
committed by GitHub
parent 34eb835a0b
commit bf9b82334d
7 changed files with 185 additions and 175 deletions
@@ -1,116 +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 ClientProxySpy: ClientProxyProtocol {
var visibleRoomsSummaryProvider: ElementX.RoomSummaryProviderProtocol?
var allRoomsSummaryProvider: ElementX.RoomSummaryProviderProtocol?
let callbacks = PassthroughSubject<ClientProxyCallback, Never>()
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<String, ElementX.ClientProxyError> {
.failure(.failedLoadingMedia)
}
func loadUserAvatarURLString() async -> Result<String, ElementX.ClientProxyError> {
.failure(.failedLoadingMedia)
}
func accountDataEvent<Content>(type: String) async -> Result<Content?, ClientProxyError> where Content: Decodable {
.failure(.failedLoadingMedia)
}
func setAccountData<Content>(content: Content, type: String) async -> Result<Void, ClientProxyError> where Content: Encodable {
.failure(.failedLoadingMedia)
}
func sessionVerificationControllerProxy() async -> Result<ElementX.SessionVerificationControllerProxyProtocol, ClientProxyError> {
.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()
}
}
@@ -20,8 +20,8 @@ import Combine
@testable import ElementX
final class NotificationManagerTests: XCTestCase {
var sut: NotificationManager!
private let clientProxySpy = ClientProxySpy()
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: clientProxySpy, notificationCenter: notificationCenter)
notificationManager = NotificationManager(clientProxy: clientProxy, notificationCenter: notificationCenter)
}
func test_whenRegistered_pusherIsCalled() async {
_ = await sut.register(with: Data())
XCTAssertTrue(clientProxySpy.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
}
clientProxySpy.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(clientProxySpy.setPusherPushkey, pushkeyData.base64EncodedString())
XCTAssertEqual(clientProxySpy.setPusherAppId, settings?.pusherAppId)
XCTAssertEqual(clientProxySpy.setPusherKind, .http)
XCTAssertEqual(clientProxySpy.setPusherAppId, settings?.pusherAppId)
XCTAssertEqual(clientProxySpy.setPusherAppDisplayName, "\(InfoPlistReader.target.bundleDisplayName) (iOS)")
XCTAssertEqual(clientProxySpy.setPusherDeviceDisplayName, UIDevice.current.name)
XCTAssertNotNil(clientProxySpy.setPusherProfileTag)
XCTAssertEqual(clientProxySpy.setPusherLang, Bundle.preferredLanguages.first)
XCTAssertEqual(clientProxySpy.setPusherUrl, settings?.pushGatewayBaseURL.absoluteString)
XCTAssertEqual(clientProxySpy.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: clientProxySpy.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)
}
}