mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-02 21:06:00 +00:00
Combine the Server Selection screen into the Server Confirmation screen and add autocompletion when entering an account provider. (#5949)
* Adjust login flow to exclusively use the ServerSelectionScreen * Move async code to server selection vm * ServerSelection supports pro picker options * Use homeserver address for both confirmation and picker modes * rename ServerSelectionScreenMode * remove ServerConfirmationScreen It's been superseded by the ServerSelectionScreen * rename userInput * Update strings with latest design strings * Add server input autocompletion * Store previous servers in AppSettings and autofill on server signin * Audit changes for logging * Enforce lowercase server history storage * Update tests * Update Xcode project * PR review fixups * Add HomeserverHistoryManager * Review fixups 2 * Review fixups 3
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
//
|
||||
// Copyright 2026 Element Creations Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
@testable import ElementX
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct HomeserverHistoryManagerTests {
|
||||
@Test
|
||||
func matchExistingServer() {
|
||||
// given a configured manager
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"example.com"
|
||||
])
|
||||
|
||||
// when querying a value that matches something in the list
|
||||
// then it returns that value without case sensitiveity
|
||||
#expect(manager.server(matchingPrefix: "ma") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "Ma") == "matrix.org")
|
||||
}
|
||||
|
||||
@Test
|
||||
func matchExistingServerinLRUOrder() {
|
||||
// given a configured manager with multiple values with similar prefixes
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"mandibles.chomp"
|
||||
])
|
||||
|
||||
// when querying the common portions of the prefix
|
||||
// then the result is the most recent addition to the list
|
||||
#expect(manager.server(matchingPrefix: "m") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "ma") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "man") == "mandibles.chomp")
|
||||
}
|
||||
|
||||
@Test
|
||||
func serversAreAddedInLRUOrder() {
|
||||
// given a configured manager
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"mandibles.chomp"
|
||||
])
|
||||
|
||||
// when adding a new server
|
||||
manager.addServerToList("merch.com")
|
||||
|
||||
// then querying gives priority to the latest addition
|
||||
#expect(manager.server(matchingPrefix: "m") == "merch.com")
|
||||
#expect(manager.server(matchingPrefix: "ma") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "man") == "mandibles.chomp")
|
||||
}
|
||||
|
||||
@Test
|
||||
func serversAreUpdatedInLRUOrder() {
|
||||
// given a configured manager
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"mandibles.chomp",
|
||||
"merch.com"
|
||||
])
|
||||
|
||||
// then querying has its given priority
|
||||
#expect(manager.server(matchingPrefix: "m") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "me") == "merch.com")
|
||||
#expect(manager.server(matchingPrefix: "ma") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "man") == "mandibles.chomp")
|
||||
|
||||
// when adding an existing server (case insensitive)
|
||||
manager.addServerToList("MERCH.com")
|
||||
|
||||
// then querying is updated to give the latest prioity
|
||||
#expect(manager.server(matchingPrefix: "m") == "merch.com")
|
||||
#expect(manager.server(matchingPrefix: "me") == "merch.com")
|
||||
#expect(manager.server(matchingPrefix: "ma") == "matrix.org")
|
||||
#expect(manager.server(matchingPrefix: "man") == "mandibles.chomp")
|
||||
}
|
||||
|
||||
@Test func matchNothingOnMiss() {
|
||||
// given a configured manager
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"example.com"
|
||||
])
|
||||
|
||||
// when making a query that matches nothing in its list, then there are no matches
|
||||
#expect(manager.server(matchingPrefix: "mi") == nil)
|
||||
#expect(manager.server(matchingPrefix: "g") == nil)
|
||||
}
|
||||
|
||||
@Test func additionalServerIncludedInResults() {
|
||||
// given a configured manager
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"example.com"
|
||||
])
|
||||
#expect(manager.server(matchingPrefix: "f") == nil)
|
||||
|
||||
// when adding a new server
|
||||
manager.addServerToList("FOO.bar")
|
||||
|
||||
// then it will become available with subsequent matching queries
|
||||
#expect(manager.server(matchingPrefix: "f") == "foo.bar")
|
||||
#expect(manager.server(matchingPrefix: "F") == "foo.bar")
|
||||
}
|
||||
|
||||
@Test func removingServerIsGone() {
|
||||
// given a configured manager
|
||||
let manager = createManager(withServerHistory: [
|
||||
"matrix.org",
|
||||
"example.com"
|
||||
])
|
||||
|
||||
// when removing a server
|
||||
manager.removeServerFromList("example.com")
|
||||
|
||||
// then it is no longer available in query results
|
||||
#expect(manager.server(matchingPrefix: "e") == nil)
|
||||
// and doesn't affect the other server entries
|
||||
#expect(manager.server(matchingPrefix: "m") == "matrix.org")
|
||||
}
|
||||
|
||||
private func createManager(withServerHistory history: [String]) -> HomeserverHistoryManager {
|
||||
let appSettings = AppSettings.volatile()
|
||||
appSettings.previousServers = history
|
||||
|
||||
return HomeserverHistoryManager(appSettings: appSettings)
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// Copyright 2025 Element Creations Ltd.
|
||||
// Copyright 2023-2025 New Vector Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
@testable import ElementX
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ServerConfirmationScreenViewStateTests {
|
||||
@Test
|
||||
func loginMessageString() {
|
||||
let matrixDotOrgLogin = ServerConfirmationScreenViewState(mode: .confirmation(LoginHomeserver.mockMatrixDotOrg.address),
|
||||
authenticationFlow: .login)
|
||||
#expect(matrixDotOrgLogin.message == L10n.screenServerConfirmationMessageLoginMatrixDotOrg, "matrix.org should have a custom message.")
|
||||
|
||||
let elementDotIoLogin = ServerConfirmationScreenViewState(mode: .confirmation("element.io"),
|
||||
authenticationFlow: .login)
|
||||
#expect(elementDotIoLogin.message == L10n.screenServerConfirmationMessageLoginElementDotIo, "element.io should have a custom message.")
|
||||
|
||||
let otherLogin = ServerConfirmationScreenViewState(mode: .confirmation(LoginHomeserver.mockOAuth.address),
|
||||
authenticationFlow: .login)
|
||||
#expect(otherLogin.message == "", "Other servers should not show a message.")
|
||||
|
||||
let pickerLogin = ServerConfirmationScreenViewState(mode: .picker(["element.io", "matrix.org"]),
|
||||
authenticationFlow: .login)
|
||||
#expect(pickerLogin.message == nil, "The picker mode should not show a message.")
|
||||
}
|
||||
|
||||
@Test
|
||||
func registerMessageString() {
|
||||
let matrixDotOrgRegister = ServerConfirmationScreenViewState(mode: .confirmation(LoginHomeserver.mockMatrixDotOrg.address),
|
||||
authenticationFlow: .register)
|
||||
#expect(matrixDotOrgRegister.message == L10n.screenServerConfirmationMessageRegister, "The registration message should always be the same.")
|
||||
|
||||
let oAuthRegister = ServerConfirmationScreenViewState(mode: .confirmation(LoginHomeserver.mockOAuth.address),
|
||||
authenticationFlow: .register)
|
||||
#expect(oAuthRegister.message == L10n.screenServerConfirmationMessageRegister, "The registration message should always be the same.")
|
||||
}
|
||||
}
|
||||
@@ -1,398 +0,0 @@
|
||||
//
|
||||
// Copyright 2025 Element Creations Ltd.
|
||||
// Copyright 2022-2025 New Vector Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
@testable import ElementX
|
||||
import MatrixRustSDKMocks
|
||||
import SwiftUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
final class ServerConfirmationScreenViewModelTests {
|
||||
var clientFactory: AuthenticationClientFactoryMock!
|
||||
var client: ClientSDKMock!
|
||||
var service: AuthenticationServiceProtocol!
|
||||
|
||||
var viewModel: ServerConfirmationScreenViewModel!
|
||||
var context: ServerConfirmationScreenViewModel.Context {
|
||||
viewModel.context
|
||||
}
|
||||
|
||||
private let appSettings: AppSettings
|
||||
|
||||
init() {
|
||||
appSettings = AppSettings.volatile()
|
||||
}
|
||||
|
||||
// MARK: - Confirmation mode
|
||||
|
||||
@Test
|
||||
func confirmLoginWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured.
|
||||
setupViewModel(authenticationFlow: .login)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(context.viewState.mode == .confirmation(service.homeserver.value.address))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then a call to configure service should be made.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesReceivedArguments?.prompt == .consent)
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
}
|
||||
|
||||
@Test
|
||||
func confirmLoginAfterConfiguration() async throws {
|
||||
// Given a view model for login using a service that has already been configured (via the server selection screen).
|
||||
setupViewModel(authenticationFlow: .login)
|
||||
guard case .success = await service.configure(for: viewModel.state.homeserverAddress, flow: .login) else {
|
||||
Issue.record("The configuration should succeed.")
|
||||
return
|
||||
}
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
#expect(context.viewState.mode == .confirmation(service.homeserver.value.address))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configured homeserver should be used and no additional client should be built.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesReceivedArguments?.prompt == .consent)
|
||||
}
|
||||
|
||||
@Test
|
||||
func confirmRegisterWithoutConfiguration() async throws {
|
||||
// Given a view model for registration using a service that hasn't been configured.
|
||||
setupViewModel(authenticationFlow: .register)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(context.viewState.mode == .confirmation(service.homeserver.value.address))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then a call to configure service should be made.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
// The create prompt is broken: https://github.com/element-hq/matrix-authentication-service/issues/3429
|
||||
// #expect(client.urlForOauthOauthConfigurationPromptReceivedArguments?.prompt == .create)
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
}
|
||||
|
||||
@Test
|
||||
func confirmRegisterAfterConfiguration() async throws {
|
||||
// Given a view model for registration using a service that has already been configured (via the server selection screen).
|
||||
setupViewModel(authenticationFlow: .register)
|
||||
guard case .success = await service.configure(for: viewModel.state.homeserverAddress, flow: .register) else {
|
||||
Issue.record("The configuration should succeed.")
|
||||
return
|
||||
}
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
#expect(context.viewState.mode == .confirmation(service.homeserver.value.address))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configured homeserver should be used and no additional client should be built.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
// The create prompt is broken: https://github.com/element-hq/matrix-authentication-service/issues/3429
|
||||
// #expect(client.urlForOauthOauthConfigurationPromptReceivedArguments?.prompt == .create)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func confirmPasswordLoginWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured (against a server that doesn't support OAuth).
|
||||
setupViewModel(authenticationFlow: .login, supportsOAuth: false)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(context.viewState.mode == .confirmation(service.homeserver.value.address))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then a call to configure service should be made, but not for the OAuth URL.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
}
|
||||
|
||||
@Test
|
||||
func confirmPasswordLoginAfterConfiguration() async throws {
|
||||
// Given a view model for login using a service that has already been configured (via the server selection screen).
|
||||
setupViewModel(authenticationFlow: .login, supportsOAuth: false)
|
||||
guard case .success = await service.configure(for: viewModel.state.homeserverAddress, flow: .login) else {
|
||||
Issue.record("The configuration should succeed.")
|
||||
return
|
||||
}
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
#expect(context.viewState.mode == .confirmation(service.homeserver.value.address))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configured homeserver should be used and no additional client should be built, nor a call to get the OAuth URL.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func registrationNotSupportedAlert() async throws {
|
||||
// Given a view model for registration using a service that hasn't been configured and the default server doesn't support registration.
|
||||
// Note: We don't currently take the create prompt into account when determining registration support.
|
||||
setupViewModel(authenticationFlow: .register, supportsOAuth: false, supportsOAuthCreatePrompt: false)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(context.alertInfo == nil)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(context.observe(\.alertInfo)) { $0 != nil }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configuration should fail with an alert about not supporting registration.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(context.alertInfo?.id == .registration)
|
||||
}
|
||||
|
||||
@Test
|
||||
func loginNotSupportedAlert() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured and the default server doesn't support login.
|
||||
setupViewModel(authenticationFlow: .login, supportsOAuth: false, supportsOAuthCreatePrompt: false, supportsPasswordLogin: false)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(context.alertInfo == nil)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(context.observe(\.alertInfo)) { $0 != nil }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configuration should fail with an alert about not supporting login.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(context.alertInfo?.id == .login)
|
||||
}
|
||||
|
||||
@Test
|
||||
func elementProRequired() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured and the default server requires Element Pro.
|
||||
setupViewModel(authenticationFlow: .login, supportsOAuth: false, supportsOAuthCreatePrompt: false, supportsPasswordLogin: false, requiresElementPro: true)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(context.alertInfo == nil)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(context.observe(\.alertInfo)) { $0 != nil }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configuration should fail with an alert telling the user to download Element Pro.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(context.alertInfo?.id == .elementProRequired(serverName: "matrix.org"))
|
||||
}
|
||||
|
||||
// MARK: - Picker mode
|
||||
|
||||
@Test
|
||||
func pickerWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured.
|
||||
setupViewModel(authenticationFlow: .login, restrictedFlow: true)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(context.viewState.mode == .picker(appSettings.accountProviders))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then a call to configure service should be made.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesReceivedArguments?.prompt == .consent)
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
}
|
||||
|
||||
@Test
|
||||
func pickerAfterConfiguration() async throws {
|
||||
// Given a view model for login using a service that has already been configured (via the server selection screen).
|
||||
setupViewModel(authenticationFlow: .login, restrictedFlow: true)
|
||||
guard case .success = await service.configure(for: appSettings.accountProviders[0], flow: .login) else {
|
||||
Issue.record("The configuration should succeed.")
|
||||
return
|
||||
}
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
#expect(context.viewState.mode == .picker(appSettings.accountProviders))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configured homeserver should be used and no additional client should be built.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesReceivedArguments?.prompt == .consent)
|
||||
}
|
||||
|
||||
@Test
|
||||
func pickerForPasswordLoginWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured (against a server that doesn't support OAuth).
|
||||
setupViewModel(authenticationFlow: .login, supportsOAuth: false, restrictedFlow: true)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(context.viewState.mode == .picker(appSettings.accountProviders))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then a call to configure service should be made, but not for the OAuth URL.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
}
|
||||
|
||||
@Test
|
||||
func pickerForPasswordLoginAfterConfiguration() async throws {
|
||||
// Given a view model for login using a service that has already been configured (via the server selection screen).
|
||||
setupViewModel(authenticationFlow: .login, supportsOAuth: false, restrictedFlow: true)
|
||||
guard case .success = await service.configure(for: appSettings.accountProviders[0], flow: .login) else {
|
||||
Issue.record("The configuration should succeed.")
|
||||
return
|
||||
}
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
#expect(context.viewState.mode == .picker(appSettings.accountProviders))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When continuing from the confirmation screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the configured homeserver should be used and no additional client should be built, nor a call to get the OAuth URL.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func setupViewModel(authenticationFlow: AuthenticationFlow,
|
||||
supportsOAuth: Bool = true,
|
||||
supportsOAuthCreatePrompt: Bool = true,
|
||||
supportsPasswordLogin: Bool = true,
|
||||
restrictedFlow: Bool = false,
|
||||
requiresElementPro: Bool = false) {
|
||||
var mode = ServerConfirmationScreenMode.confirmation("matrix.org")
|
||||
if restrictedFlow {
|
||||
appSettings.override(accountProviders: ["matrix.org", "beta.matrix.org"],
|
||||
allowOtherAccountProviders: false,
|
||||
hideBrandChrome: false,
|
||||
pushGatewayBaseURL: appSettings.pushGatewayBaseURL,
|
||||
oAuthRedirectURL: appSettings.oAuthRedirectURL,
|
||||
oAuthClientURIPath: appSettings.oAuthClientURIPath,
|
||||
websiteURL: appSettings.websiteURL,
|
||||
logoURL: appSettings.logoURL,
|
||||
copyrightURL: appSettings.copyrightURL,
|
||||
acceptableUseURL: appSettings.acceptableUseURL,
|
||||
privacyURL: appSettings.privacyURL,
|
||||
encryptionURL: appSettings.encryptionURL,
|
||||
deviceVerificationURL: appSettings.deviceVerificationURL,
|
||||
chatBackupDetailsURL: appSettings.chatBackupDetailsURL,
|
||||
identityPinningViolationDetailsURL: appSettings.identityPinningViolationDetailsURL,
|
||||
historySharingDetailsURL: appSettings.historySharingDetailsURL,
|
||||
elementWebHosts: appSettings.elementWebHosts,
|
||||
accountProvisioningHost: appSettings.accountProvisioningHost,
|
||||
bugReportApplicationID: appSettings.bugReportApplicationID,
|
||||
analyticsTermsURL: appSettings.analyticsTermsURL,
|
||||
mapTilerConfiguration: AppSettings.bundledMapTilerConfiguration)
|
||||
mode = .picker(appSettings.accountProviders)
|
||||
}
|
||||
|
||||
// Manually create a configuration as the default homeserver address setting is immutable.
|
||||
client = ClientSDKMock(.init(oAuthLoginURL: supportsOAuth ? "https://account.matrix.org/authorize" : nil,
|
||||
supportsOAuthCreatePrompt: supportsOAuthCreatePrompt,
|
||||
supportsPasswordLogin: supportsPasswordLogin,
|
||||
elementWellKnown: requiresElementPro ? "{\"version\":1,\"enforce_element_pro\":true}" : nil))
|
||||
let configuration = AuthenticationClientFactoryMock.Configuration(homeserverClients: ["matrix.org": client])
|
||||
|
||||
clientFactory = AuthenticationClientFactoryMock(configuration)
|
||||
service = AuthenticationService(userSessionStore: UserSessionStoreMock(.init()),
|
||||
encryptionKeyProvider: EncryptionKeyProvider(),
|
||||
classicAppManager: nil,
|
||||
clientFactory: clientFactory,
|
||||
appSettings: appSettings,
|
||||
appHooks: AppHooks())
|
||||
|
||||
viewModel = ServerConfirmationScreenViewModel(authenticationService: service,
|
||||
mode: mode,
|
||||
authenticationFlow: authenticationFlow,
|
||||
appSettings: appSettings,
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
|
||||
// Add a fake window in order for the OAuth flow to continue
|
||||
viewModel.context.send(viewAction: .updateWindow(UIWindow()))
|
||||
}
|
||||
}
|
||||
|
||||
private extension ServerConfirmationScreenViewState {
|
||||
var homeserverAddress: String {
|
||||
switch mode {
|
||||
case .confirmation(let accountProvider):
|
||||
accountProvider
|
||||
case .picker:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ServerConfirmationScreenViewModelAction {
|
||||
var isContinueWithOAuth: Bool {
|
||||
switch self {
|
||||
case .continueWithOAuth: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
var isContinueWithPassword: Bool {
|
||||
switch self {
|
||||
case .continueWithPassword: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,17 @@
|
||||
//
|
||||
|
||||
@testable import ElementX
|
||||
import MatrixRustSDKMocks
|
||||
import SwiftUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ServerSelectionScreenViewModelTests {
|
||||
private static let passwordOnlyServer = "example.com" // password only, no OAuth
|
||||
private static let pickerProviders = ["matrix.org", "beta.matrix.org", passwordOnlyServer]
|
||||
|
||||
var appSettings: AppSettings!
|
||||
var client: ClientSDKMock!
|
||||
var clientFactory: AuthenticationClientFactoryMock!
|
||||
var service: AuthenticationServiceProtocol!
|
||||
var viewModel: ServerSelectionScreenViewModelProtocol!
|
||||
@@ -22,13 +29,13 @@ struct ServerSelectionScreenViewModelTests {
|
||||
@Test
|
||||
mutating func selectForLogin() async throws {
|
||||
// Given a view model for login.
|
||||
setup(authenticationFlow: .login)
|
||||
try setup(authenticationFlow: .login)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
|
||||
// When selecting matrix.org.
|
||||
context.homeserverAddress = "matrix.org"
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0 == .updated }
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
@@ -40,7 +47,7 @@ struct ServerSelectionScreenViewModelTests {
|
||||
@Test
|
||||
mutating func loginNotSupportedAlert() async throws {
|
||||
// Given a view model for login.
|
||||
setup(authenticationFlow: .login)
|
||||
try setup(authenticationFlow: .login)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(context.alertInfo == nil)
|
||||
@@ -59,13 +66,13 @@ struct ServerSelectionScreenViewModelTests {
|
||||
@Test
|
||||
mutating func selectForRegistration() async throws {
|
||||
// Given a view model for registration.
|
||||
setup(authenticationFlow: .register)
|
||||
try setup(authenticationFlow: .register)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
|
||||
// When selecting matrix.org.
|
||||
context.homeserverAddress = "matrix.org"
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0 == .updated }
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
@@ -77,7 +84,7 @@ struct ServerSelectionScreenViewModelTests {
|
||||
@Test
|
||||
mutating func registrationNotSupportedAlert() async throws {
|
||||
// Given a view model for registration.
|
||||
setup(authenticationFlow: .register)
|
||||
try setup(authenticationFlow: .register)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(context.alertInfo == nil)
|
||||
@@ -96,7 +103,7 @@ struct ServerSelectionScreenViewModelTests {
|
||||
@Test
|
||||
mutating func elementProRequiredAlert() async throws {
|
||||
// Given a view model for login.
|
||||
setup(authenticationFlow: .login)
|
||||
try setup(authenticationFlow: .login)
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(context.alertInfo == nil)
|
||||
@@ -115,10 +122,10 @@ struct ServerSelectionScreenViewModelTests {
|
||||
@Test
|
||||
mutating func invalidServer() async throws {
|
||||
// Given a new instance of the view model.
|
||||
setup(authenticationFlow: .login)
|
||||
try setup(authenticationFlow: .login)
|
||||
#expect(!context.viewState.isShowingFooterError, "There should not be an error message for a new view model.")
|
||||
#expect(context.viewState.footerErrorMessage == nil, "There should not be an error message for a new view model.")
|
||||
#expect(String(context.viewState.footerMessage) == L10n.screenChangeServerFormNotice,
|
||||
#expect(String(context.viewState.footerMessage) == L10n.screenChangeServerTextfieldFooterLogin,
|
||||
"The standard footer message should be shown.")
|
||||
|
||||
// When attempting to discover an invalid server
|
||||
@@ -130,7 +137,7 @@ struct ServerSelectionScreenViewModelTests {
|
||||
// Then the footer should now be showing an error.
|
||||
#expect(context.viewState.isShowingFooterError, "The error message should be stored.")
|
||||
#expect(context.viewState.footerErrorMessage != nil, "The error message should be stored.")
|
||||
#expect(String(context.viewState.footerMessage) != L10n.screenChangeServerFormNotice,
|
||||
#expect(String(context.viewState.footerMessage) != L10n.screenChangeServerTextfieldFooterLogin,
|
||||
"The error message should be shown.")
|
||||
|
||||
// And when clearing the error.
|
||||
@@ -141,16 +148,204 @@ struct ServerSelectionScreenViewModelTests {
|
||||
|
||||
// Then the error message should now be removed.
|
||||
#expect(context.viewState.footerErrorMessage == nil, "The error message should have been cleared.")
|
||||
#expect(String(context.viewState.footerMessage) == L10n.screenChangeServerFormNotice,
|
||||
#expect(String(context.viewState.footerMessage) == L10n.screenChangeServerTextfieldFooterLogin,
|
||||
"The standard footer message should be shown again.")
|
||||
}
|
||||
|
||||
// MARK: - userInput mode
|
||||
|
||||
@Test
|
||||
mutating func userInputPasswordLoginWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured against a server that doesn't support OAuth.
|
||||
try setup(authenticationFlow: .login)
|
||||
context.homeserverAddress = Self.passwordOnlyServer
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
|
||||
// When confirming from the server selection screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the service should be configured but no OAuth URL fetched.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
}
|
||||
|
||||
@Test
|
||||
mutating func userInputPasswordLoginAfterConfiguration() async throws {
|
||||
// Given a view model for login using a service that has already been configured against a server that doesn't support OAuth.
|
||||
try setup(authenticationFlow: .login)
|
||||
context.homeserverAddress = Self.passwordOnlyServer
|
||||
guard case .success = await service.configure(for: context.homeserverAddress, flow: .login) else {
|
||||
Issue.record("The configuration should succeed.")
|
||||
return
|
||||
}
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
|
||||
// When confirming from the server selection screen.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the service should be re-configured but no OAuth URL fetched.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 2)
|
||||
}
|
||||
|
||||
// MARK: - Picker mode
|
||||
|
||||
@Test
|
||||
mutating func pickerWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured.
|
||||
try setup(authenticationFlow: .login, mode: .picker(Self.pickerProviders))
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(context.viewState.mode == .picker(Self.pickerProviders))
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 0)
|
||||
|
||||
// When confirming from the picker.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithOAuth }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the service should be configured and the OAuth URL fetched.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesCallsCount == 1)
|
||||
#expect(client.urlForOauthOauthConfigurationPromptLoginHintDeviceIdAdditionalScopesReceivedArguments?.prompt == .consent)
|
||||
#expect(service.homeserver.value.loginMode == .oAuth(supportsCreatePrompt: true))
|
||||
}
|
||||
|
||||
@Test
|
||||
mutating func pickerForPasswordLoginWithoutConfiguration() async throws {
|
||||
// Given a view model for login using a service that hasn't been configured against a server that doesn't support OAuth.
|
||||
try setup(authenticationFlow: .login, mode: .picker(Self.pickerProviders))
|
||||
context.homeserverAddress = Self.passwordOnlyServer
|
||||
#expect(service.homeserver.value.loginMode == .unknown)
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 0)
|
||||
|
||||
// When confirming from the picker.
|
||||
let deferred = deferFulfillment(viewModel.actions) { $0.isContinueWithPassword }
|
||||
context.send(viewAction: .confirm)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the service should be configured but no OAuth URL fetched.
|
||||
#expect(clientFactory.makeClientHomeserverAddressSessionDirectoriesPassphraseClientSessionDelegateAppSettingsAppHooksCallsCount == 1)
|
||||
#expect(service.homeserver.value.loginMode == .password)
|
||||
}
|
||||
|
||||
// MARK: - Autocomplete
|
||||
|
||||
@Test
|
||||
mutating func autocompleteMatchesPreviousServers() async throws {
|
||||
// Given a view model with a previous server in history.
|
||||
try setup(authenticationFlow: .login)
|
||||
appSettings.previousServers = ["myserver.com"]
|
||||
context.homeserverAddress = ""
|
||||
let textField = UITextField()
|
||||
context.send(viewAction: .updateTextField(textField))
|
||||
|
||||
// When the user types a prefix that matches the previous server.
|
||||
let typedSoFar = "my"
|
||||
let nextCharacter = "s"
|
||||
let typed = typedSoFar + nextCharacter
|
||||
let expectedAddress = "myserver.com"
|
||||
textField.text = typedSoFar
|
||||
let deferred = deferFulfillment(context.observe(\.homeserverAddress)) { $0 == expectedAddress }
|
||||
_ = textField.delegate?.textField?(textField, shouldChangeCharactersIn: NSRange(location: typedSoFar.count, length: 0), replacementString: nextCharacter)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the address should be completed and the appended portion selected.
|
||||
let selectionStart = expectedAddress.index(expectedAddress.startIndex, offsetBy: typed.count)
|
||||
#expect(context.homeserverAddress == expectedAddress)
|
||||
#expect(context.homeserverSelection == TextSelection(range: selectionStart..<expectedAddress.endIndex))
|
||||
}
|
||||
|
||||
@Test
|
||||
mutating func autocompleteFromAccountProviders() async throws {
|
||||
// Given a view model with no previous server history, falling back to the default account providers.
|
||||
try setup(authenticationFlow: .login)
|
||||
#expect(appSettings.previousServers.isEmpty)
|
||||
context.homeserverAddress = ""
|
||||
let textField = UITextField()
|
||||
context.send(viewAction: .updateTextField(textField))
|
||||
|
||||
// When the user types a prefix that matches an account provider.
|
||||
let typedSoFar = "ma"
|
||||
let nextCharacter = "t"
|
||||
let typed = typedSoFar + nextCharacter
|
||||
let expectedAddress = "matrix.org"
|
||||
textField.text = typedSoFar
|
||||
let deferred = deferFulfillment(context.observe(\.homeserverAddress)) { $0 == expectedAddress }
|
||||
_ = textField.delegate?.textField?(textField, shouldChangeCharactersIn: NSRange(location: typedSoFar.count, length: 0), replacementString: nextCharacter)
|
||||
try await deferred.fulfill()
|
||||
|
||||
// Then the address should be completed and the appended portion selected.
|
||||
let selectionStart = expectedAddress.index(expectedAddress.startIndex, offsetBy: typed.count)
|
||||
#expect(context.homeserverAddress == expectedAddress)
|
||||
#expect(context.homeserverSelection == TextSelection(range: selectionStart..<expectedAddress.endIndex))
|
||||
}
|
||||
|
||||
@Test
|
||||
mutating func autocompleteNoMatch() async throws {
|
||||
// Given a view model with a known set of servers.
|
||||
try setup(authenticationFlow: .login)
|
||||
appSettings.previousServers = ["myserver.com"]
|
||||
context.homeserverAddress = ""
|
||||
let textField = UITextField()
|
||||
context.send(viewAction: .updateTextField(textField))
|
||||
|
||||
// When the user types a string that doesn't match any known server prefix.
|
||||
textField.text = "xy"
|
||||
_ = textField.delegate?.textField?(textField, shouldChangeCharactersIn: NSRange(location: 2, length: 0), replacementString: "z")
|
||||
try await Task.sleep(for: .milliseconds(50))
|
||||
|
||||
// Then the address should remain unchanged.
|
||||
#expect(context.homeserverAddress == "")
|
||||
}
|
||||
|
||||
@Test
|
||||
mutating func autocompleteLRUOrder() async throws {
|
||||
// Given a view model with an ordered server history.
|
||||
try setup(authenticationFlow: .login)
|
||||
appSettings.previousServers = ["abc.foo", "matrix.org", "mantis.asdf"]
|
||||
context.homeserverAddress = ""
|
||||
let textField = UITextField()
|
||||
context.send(viewAction: .updateTextField(textField))
|
||||
|
||||
// Step 1: type "m" — first "m" match in history is "matrix.org".
|
||||
textField.text = ""
|
||||
var deferred = deferFulfillment(context.observe(\.homeserverAddress)) { $0 == "matrix.org" }
|
||||
_ = textField.delegate?.textField?(textField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "m")
|
||||
try await deferred.fulfill()
|
||||
#expect(context.homeserverAddress == "matrix.org")
|
||||
|
||||
// Step 2: type "a" replacing the highlighted suffix — still matches "matrix.org".
|
||||
// textField.text = "matrix.org", "atrix.org" highlighted (loc: 1, len: 9).
|
||||
deferred = deferFulfillment(context.observe(\.homeserverAddress)) { $0 == "matrix.org" }
|
||||
_ = textField.delegate?.textField?(textField, shouldChangeCharactersIn: NSRange(location: 1, length: 9), replacementString: "a")
|
||||
try await deferred.fulfill()
|
||||
#expect(context.homeserverAddress == "matrix.org")
|
||||
|
||||
// Step 3: type "n" replacing the highlighted suffix — "man" now matches "mantis.asdf".
|
||||
// textField.text = "matrix.org", "trix.org" highlighted (loc: 2, len: 8).
|
||||
deferred = deferFulfillment(context.observe(\.homeserverAddress)) { $0 == "mantis.asdf" }
|
||||
_ = textField.delegate?.textField?(textField, shouldChangeCharactersIn: NSRange(location: 2, length: 8), replacementString: "n")
|
||||
try await deferred.fulfill()
|
||||
#expect(context.homeserverAddress == "mantis.asdf")
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private mutating func setup(authenticationFlow: AuthenticationFlow) {
|
||||
let appSettings = AppSettings.volatile()
|
||||
private mutating func setup(authenticationFlow: AuthenticationFlow,
|
||||
mode: ServerSelectionScreenMode = .userInput) throws {
|
||||
appSettings = AppSettings.volatile()
|
||||
|
||||
let factoryConfiguration = AuthenticationClientFactoryMock.Configuration()
|
||||
// matrix.org: OAuth. example.com: password only. server.net: no login. secure.gov: OAuth + Element Pro required.
|
||||
client = factoryConfiguration.homeserverClients["matrix.org"]
|
||||
clientFactory = AuthenticationClientFactoryMock(factoryConfiguration)
|
||||
|
||||
clientFactory = AuthenticationClientFactoryMock(.init())
|
||||
service = AuthenticationService(userSessionStore: UserSessionStoreMock(.init()),
|
||||
encryptionKeyProvider: EncryptionKeyProvider(),
|
||||
classicAppManager: nil,
|
||||
@@ -159,8 +354,29 @@ struct ServerSelectionScreenViewModelTests {
|
||||
appHooks: AppHooks())
|
||||
|
||||
viewModel = ServerSelectionScreenViewModel(authenticationService: service,
|
||||
mode: mode,
|
||||
authenticationFlow: authenticationFlow,
|
||||
appSettings: appSettings,
|
||||
homeserverHistoryManager: HomeserverHistoryManager(appSettings: appSettings),
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
|
||||
let scene = try #require(UIApplication.shared.connectedScenes.first as? UIWindowScene)
|
||||
viewModel.context.send(viewAction: .updateWindow(UIWindow(windowScene: scene)))
|
||||
}
|
||||
}
|
||||
|
||||
private extension ServerSelectionScreenViewModelAction {
|
||||
var isContinueWithOAuth: Bool {
|
||||
switch self {
|
||||
case .continueWithOAuth: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
var isContinueWithPassword: Bool {
|
||||
switch self {
|
||||
case .continueWithPassword: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user