Beam/UnitTests/Sources/HomeScreenViewModelTests.swift

372 lines
14 KiB
Swift
Raw Normal View History

//
// Copyright 2022-2024 New Vector Ltd.
2022-02-14 18:05:21 +02:00
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
2022-02-14 18:05:21 +02:00
//
import Combine
2022-02-14 18:05:21 +02:00
import XCTest
@testable import ElementX
@MainActor
2022-02-14 18:05:21 +02:00
class HomeScreenViewModelTests: XCTestCase {
2022-06-06 12:38:07 +03:00
var viewModel: HomeScreenViewModelProtocol!
var context: HomeScreenViewModelType.Context! { viewModel.context }
var clientProxy: ClientProxyMock!
var roomSummaryProvider: RoomSummaryProviderMock!
var appSettings: AppSettings!
var cancellables = Set<AnyCancellable>()
Sliding Sync + New Timeline API (#189) * Begin adopting new Timeline API. * Add edited indicator and reactions. * vector-im/element-x-ios/issues/65 - Sliding sync support * Fix missing room display name, wrong placeholder avatar text color and various other warnings that would fail the build on the CI * Various tweaks: * using release version of the demo branch of the sdk * enabled home screen last room messages * switched debug mode rust logging to warn * enabled redactions * enabled new logout flows and soft logout * enabled replies * Fix room member display name and avatar crashes / race condition, fix unit tests * Make the ClientProxy and the UserSession MainActors * Remove unused MatrixRustSDK imports, we should strive to keep these only in top level services and proxies * Don't start either of the syncs while in soft logout * #181: Style the session verification banner to match Figma. * #181: Update verification modal. * #181: Update snapshot tests. * Make session verification state machine less pedantic * Remove unnecessary weak selfs * Various tweaks following code review: * add start and stop sync client proxy methods * move ss proxy url the build settings * made media provider load results discardable * added publishers for the roomSummaryProvider's total number of rooms and state * Fix when sender details are shown * Disable sync v2, causes duplicates in the timeline (as expected) * Move ClientProxy media loading off the main queue and into a detached task * Another attempt at moving image loading off the main queue * Moved home screen diffing and latest room fetching to the background * Prevent the timeline composer from becoming the first responder when not needed * Bump to a newer version of the RustSDK * Fixes vector-im/element-x-ios/issues/107 - New home screen design * Implement thumbnail loading instead of full image avatars. * Revert "Disable sync v2, causes duplicates in the timeline (as expected)" * Add support for local echoes, dispatching detached tasks to a concurrenc GCD queue * Move the session verification banner to a List Section to avoid UI glitches * Optimise room mapping after sliding sync updates and thumbnail fetching * Replace home screen List with a LazyVStack in an attempt to fix performance. Moved move summary provider room updating to a background thread * Fixes vector-im/element-x-ios/issues/177 - New Bubbles Design * Define in group state for timeline items * Add replies into the bubble * Add timeline width environment value * Add `RoundedCorner` shape with specific corners rounding * Add in group state for previews * Implement bubble grouping logic * Timeline avatar layout changes * Fix placeholder avatars for dark mode * New bubbles design * Update mock timeline items * Update timeline separator design * Update room screen reference screenshots * Add changelog * Formatting fixes * Add some space before single or beginning outgoing items * Redesign the message composer * Handle the msgtype enum. * Update room name label line limit and incoming bubble background. Disabled syncv2, ss withCommonExtensions and session verification controller checking * Increase default back pagination limit. * Stop parsing links and tidy up composer button. * Also fix the frame of an image whilst loading. * Bump SDK package version. * Remove app states about settings * Add strings * Use colors on placeholder avatars * Tiny changes for placeholder avatars * Update settings screen design * Provide a user display name from the mock client * Settings screen presentation logic * Add changelog * Update reference screenshots Co-authored-by: Doug <douglase@element.io> Co-authored-by: ismailgulek <ismailgulek@users.noreply.github.com> Co-authored-by: ismailgulek <ismailg@matrix.org>
2022-09-21 11:21:58 +03:00
override func setUp() {
cancellables.removeAll()
AppSettings.resetAllSettings()
appSettings = AppSettings()
ServiceLocator.shared.register(appSettings: appSettings)
2022-06-06 12:38:07 +03:00
}
Sliding Sync + New Timeline API (#189) * Begin adopting new Timeline API. * Add edited indicator and reactions. * vector-im/element-x-ios/issues/65 - Sliding sync support * Fix missing room display name, wrong placeholder avatar text color and various other warnings that would fail the build on the CI * Various tweaks: * using release version of the demo branch of the sdk * enabled home screen last room messages * switched debug mode rust logging to warn * enabled redactions * enabled new logout flows and soft logout * enabled replies * Fix room member display name and avatar crashes / race condition, fix unit tests * Make the ClientProxy and the UserSession MainActors * Remove unused MatrixRustSDK imports, we should strive to keep these only in top level services and proxies * Don't start either of the syncs while in soft logout * #181: Style the session verification banner to match Figma. * #181: Update verification modal. * #181: Update snapshot tests. * Make session verification state machine less pedantic * Remove unnecessary weak selfs * Various tweaks following code review: * add start and stop sync client proxy methods * move ss proxy url the build settings * made media provider load results discardable * added publishers for the roomSummaryProvider's total number of rooms and state * Fix when sender details are shown * Disable sync v2, causes duplicates in the timeline (as expected) * Move ClientProxy media loading off the main queue and into a detached task * Another attempt at moving image loading off the main queue * Moved home screen diffing and latest room fetching to the background * Prevent the timeline composer from becoming the first responder when not needed * Bump to a newer version of the RustSDK * Fixes vector-im/element-x-ios/issues/107 - New home screen design * Implement thumbnail loading instead of full image avatars. * Revert "Disable sync v2, causes duplicates in the timeline (as expected)" * Add support for local echoes, dispatching detached tasks to a concurrenc GCD queue * Move the session verification banner to a List Section to avoid UI glitches * Optimise room mapping after sliding sync updates and thumbnail fetching * Replace home screen List with a LazyVStack in an attempt to fix performance. Moved move summary provider room updating to a background thread * Fixes vector-im/element-x-ios/issues/177 - New Bubbles Design * Define in group state for timeline items * Add replies into the bubble * Add timeline width environment value * Add `RoundedCorner` shape with specific corners rounding * Add in group state for previews * Implement bubble grouping logic * Timeline avatar layout changes * Fix placeholder avatars for dark mode * New bubbles design * Update mock timeline items * Update timeline separator design * Update room screen reference screenshots * Add changelog * Formatting fixes * Add some space before single or beginning outgoing items * Redesign the message composer * Handle the msgtype enum. * Update room name label line limit and incoming bubble background. Disabled syncv2, ss withCommonExtensions and session verification controller checking * Increase default back pagination limit. * Stop parsing links and tidy up composer button. * Also fix the frame of an image whilst loading. * Bump SDK package version. * Remove app states about settings * Add strings * Use colors on placeholder avatars * Tiny changes for placeholder avatars * Update settings screen design * Provide a user display name from the mock client * Settings screen presentation logic * Add changelog * Update reference screenshots Co-authored-by: Doug <douglase@element.io> Co-authored-by: ismailgulek <ismailgulek@users.noreply.github.com> Co-authored-by: ismailgulek <ismailg@matrix.org>
2022-09-21 11:21:58 +03:00
override func tearDown() {
AppSettings.resetAllSettings()
}
func testSelectRoom() async throws {
setupViewModel()
let mockRoomID = "mock_room_id"
2022-06-06 12:38:07 +03:00
var correctResult = false
var selectedRoomID = ""
viewModel.actions
.sink { action in
switch action {
case .presentRoom(let roomID):
correctResult = true
selectedRoomID = roomID
default:
break
}
2022-06-06 12:38:07 +03:00
}
.store(in: &cancellables)
context.send(viewAction: .selectRoom(roomIdentifier: mockRoomID))
2022-06-06 12:38:07 +03:00
await Task.yield()
XCTAssert(correctResult)
XCTAssertEqual(mockRoomID, selectedRoomID)
2022-02-14 18:05:21 +02:00
}
2022-06-06 12:38:07 +03:00
func testTapUserAvatar() async throws {
setupViewModel()
2022-06-06 12:38:07 +03:00
var correctResult = false
viewModel.actions
.sink { action in
switch action {
case .presentSettingsScreen:
correctResult = true
default:
break
}
2022-06-06 12:38:07 +03:00
}
.store(in: &cancellables)
context.send(viewAction: .showSettings)
2022-06-06 12:38:07 +03:00
await Task.yield()
XCTAssert(correctResult)
}
func testLeaveRoomAlert() async throws {
setupViewModel()
let mockRoomID = "1"
clientProxy.roomForIdentifierClosure = { _ in .joined(JoinedRoomProxyMock(.init(id: mockRoomID, name: "Some room"))) }
let deferred = deferFulfillment(context.$viewState) { value in
value.bindings.leaveRoomAlertItem != nil
}
context.send(viewAction: .leaveRoom(roomIdentifier: mockRoomID))
try await deferred.fulfill()
XCTAssertEqual(context.leaveRoomAlertItem?.roomID, mockRoomID)
}
func testLeaveRoomError() async throws {
setupViewModel()
let mockRoomID = "1"
let room = JoinedRoomProxyMock(.init(id: mockRoomID, name: "Some room"))
room.leaveRoomClosure = { .failure(.sdkError(ClientProxyMockError.generic)) }
clientProxy.roomForIdentifierClosure = { _ in .joined(room) }
let deferred = deferFulfillment(context.$viewState) { value in
value.bindings.alertInfo != nil
}
context.send(viewAction: .confirmLeaveRoom(roomIdentifier: mockRoomID))
try await deferred.fulfill()
XCTAssertNotNil(context.alertInfo)
}
func testLeaveRoomSuccess() async throws {
setupViewModel()
let mockRoomID = "1"
var correctResult = false
let expectation = expectation(description: #function)
viewModel.actions
.sink { action in
switch action {
case .roomLeft(let roomIdentifier):
correctResult = roomIdentifier == mockRoomID
default:
break
}
expectation.fulfill()
}
.store(in: &cancellables)
let room = JoinedRoomProxyMock(.init(id: mockRoomID, name: "Some room"))
room.leaveRoomClosure = { .success(()) }
clientProxy.roomForIdentifierClosure = { _ in .joined(room) }
context.send(viewAction: .confirmLeaveRoom(roomIdentifier: mockRoomID))
await fulfillment(of: [expectation])
XCTAssertNil(context.alertInfo)
XCTAssertTrue(correctResult)
}
func testShowRoomDetails() async throws {
setupViewModel()
let mockRoomID = "1"
var correctResult = false
viewModel.actions
.sink { action in
switch action {
case .presentRoomDetails(let roomIdentifier):
correctResult = roomIdentifier == mockRoomID
default:
break
}
}
.store(in: &cancellables)
context.send(viewAction: .showRoomDetails(roomIdentifier: mockRoomID))
await Task.yield()
XCTAssertNil(context.alertInfo)
XCTAssertTrue(correctResult)
}
func testFilters() async throws {
setupViewModel()
context.filtersState.activateFilter(.people)
try await Task.sleep(for: .milliseconds(100))
XCTAssertEqual(roomSummaryProvider.roomListPublisher.value.count, 2)
XCTAssertEqual(roomSummaryProvider.roomListPublisher.value.first?.name, "Foundation and Earth")
2024-03-06 11:02:30 +01:00
}
func testSearch() async throws {
setupViewModel()
context.isSearchFieldFocused = true
context.searchQuery = "lude to Found"
try await Task.sleep(for: .milliseconds(100))
XCTAssertEqual(roomSummaryProvider.roomListPublisher.value.first?.name, "Prelude to Foundation")
XCTAssertEqual(roomSummaryProvider.roomListPublisher.value.count, 1)
2024-03-06 11:02:30 +01:00
}
func testFiltersEmptyState() async throws {
setupViewModel()
2024-03-06 11:02:30 +01:00
context.filtersState.activateFilter(.people)
context.filtersState.activateFilter(.favourites)
try await Task.sleep(for: .milliseconds(100))
XCTAssertTrue(context.viewState.shouldShowEmptyFilterState)
context.isSearchFieldFocused = true
XCTAssertFalse(context.viewState.shouldShowEmptyFilterState)
}
func testSetUpRecoveryBannerState() async throws {
// Given a view model without a visible security banner.
let securityStateStateSubject = CurrentValueSubject<SessionSecurityState, Never>(.init(verificationState: .verified, recoveryState: .unknown))
setupViewModel(securityStatePublisher: securityStateStateSubject.asCurrentValuePublisher())
XCTAssertEqual(context.viewState.securityBannerMode, .none)
// When the recovery state comes through as disabled.
var deferred = deferFulfillment(context.$viewState) { $0.requiresExtraAccountSetup == true }
securityStateStateSubject.send(.init(verificationState: .verified, recoveryState: .disabled))
try await deferred.fulfill()
// Then the banner should be shown to set up recovery.
XCTAssertEqual(context.viewState.securityBannerMode, .show(.setUpRecovery))
// When the recovery is enabled.
deferred = deferFulfillment(context.$viewState) { $0.requiresExtraAccountSetup == false }
securityStateStateSubject.send(.init(verificationState: .verified, recoveryState: .enabled))
try await deferred.fulfill()
// Then the banner should no longer be shown.
XCTAssertEqual(context.viewState.securityBannerMode, .none)
}
func testDismissSetUpRecoveryBannerState() async throws {
// Given a view model with the setup recovery banner shown.
let securityStateStateSubject = CurrentValueSubject<SessionSecurityState, Never>(.init(verificationState: .verified, recoveryState: .unknown))
setupViewModel(securityStatePublisher: securityStateStateSubject.asCurrentValuePublisher())
var deferred = deferFulfillment(context.$viewState) { $0.securityBannerMode == .show(.setUpRecovery) }
securityStateStateSubject.send(.init(verificationState: .verified, recoveryState: .disabled))
try await deferred.fulfill()
// When the banner is dismissed.
deferred = deferFulfillment(context.$viewState) { $0.securityBannerMode == .dismissed }
context.send(viewAction: .skipRecoveryKeyConfirmation)
// Then the banner should no longer be shown.
try await deferred.fulfill()
// And when the recovery state comes through a second time the banner should still not be shown.
let failure = deferFailure(context.$viewState, timeout: 1) { $0.securityBannerMode != .dismissed }
securityStateStateSubject.send(.init(verificationState: .verified, recoveryState: .disabled))
try await failure.fulfill()
}
func testOutOfSyncRecoveryBannerState() async throws {
// Given a view model without a visible security banner.
let securityStateStateSubject = CurrentValueSubject<SessionSecurityState, Never>(.init(verificationState: .verified, recoveryState: .unknown))
setupViewModel(securityStatePublisher: securityStateStateSubject.asCurrentValuePublisher())
XCTAssertEqual(context.viewState.securityBannerMode, .none)
// When the recovery state comes through as incomplete.
var deferred = deferFulfillment(context.$viewState) { $0.requiresExtraAccountSetup == true }
securityStateStateSubject.send(.init(verificationState: .verified, recoveryState: .incomplete))
try await deferred.fulfill()
// Then the banner should be shown for out of sync recovery.
XCTAssertEqual(context.viewState.securityBannerMode, .show(.recoveryOutOfSync))
// When the recovery is enabled.
deferred = deferFulfillment(context.$viewState) { $0.requiresExtraAccountSetup == false }
securityStateStateSubject.send(.init(verificationState: .verified, recoveryState: .enabled))
try await deferred.fulfill()
// Then the banner should no longer be shown.
XCTAssertEqual(context.viewState.securityBannerMode, .none)
}
func testInviteUnreadBadge() async throws {
setupViewModel(withInvites: true)
var invites = context.viewState.rooms.invites
XCTAssertEqual(invites.count, 2)
for invite in invites {
XCTAssertTrue(invite.badges.isDotShown)
}
let deferred = deferFulfillment(context.$viewState) { state in
state.rooms.contains { room in
room.roomID == invites[0].roomID && room.badges.isDotShown == false
}
}
appSettings.seenInvites = Set(invites.compactMap(\.roomID))
try await deferred.fulfill()
invites = context.viewState.rooms.invites
for invite in invites {
XCTAssertFalse(invite.badges.isDotShown)
}
}
func testAcceptInvite() async throws {
setupViewModel(withInvites: true)
let invitedRoomIDs = context.viewState.rooms.invites.compactMap(\.roomID)
appSettings.seenInvites = Set(invitedRoomIDs)
XCTAssertEqual(invitedRoomIDs.count, 2)
let deferred = deferFulfillment(viewModel.actions) { $0 == .presentRoom(roomIdentifier: invitedRoomIDs[0]) }
context.send(viewAction: .acceptInvite(roomIdentifier: invitedRoomIDs[0]))
try await deferred.fulfill()
XCTAssertEqual(appSettings.seenInvites, [invitedRoomIDs[1]])
}
func testDeclineInvite() async throws {
setupViewModel(withInvites: true)
let invitedRoomIDs = context.viewState.rooms.invites.compactMap(\.roomID)
appSettings.seenInvites = Set(invitedRoomIDs)
XCTAssertEqual(invitedRoomIDs.count, 2)
let deferred = deferFulfillment(context.$viewState) { $0.bindings.alertInfo != nil }
context.send(viewAction: .declineInvite(roomIdentifier: invitedRoomIDs[0]))
try await deferred.fulfill()
let rejectExpectation = expectation(description: "Expected rejectInvitation to be called.")
clientProxy.roomForIdentifierClosure = { _ in
let roomProxy = InvitedRoomProxyMock(.init())
roomProxy.rejectInvitationClosure = {
rejectExpectation.fulfill()
return .success(())
}
return .invited(roomProxy)
}
context.viewState.bindings.alertInfo?.primaryButton.action?()
await fulfillment(of: [rejectExpectation], timeout: 1.0)
XCTAssertEqual(appSettings.seenInvites, [invitedRoomIDs[1]])
}
// MARK: - Helpers
private func setupViewModel(securityStatePublisher: CurrentValuePublisher<SessionSecurityState, Never>? = nil, withInvites: Bool = false) {
var rooms: [RoomSummary] = .mockRooms
if withInvites {
rooms += .mockInvites
}
roomSummaryProvider = RoomSummaryProviderMock(.init(state: .loaded(rooms)))
clientProxy = ClientProxyMock(.init(userID: "@mock:client.com",
roomSummaryProvider: roomSummaryProvider))
if withInvites {
clientProxy.joinRoomViaReturnValue = .success(())
clientProxy.joinRoomAliasReturnValue = .success(())
clientProxy.roomForIdentifierClosure = { _ in .invited(InvitedRoomProxyMock(.init())) }
}
let userSession = UserSessionMock(.init(clientProxy: clientProxy))
if let securityStatePublisher {
userSession.sessionSecurityStatePublisher = securityStatePublisher
}
viewModel = HomeScreenViewModel(userSession: userSession,
analyticsService: ServiceLocator.shared.analytics,
appSettings: appSettings,
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
userIndicatorController: ServiceLocator.shared.userIndicatorController)
}
2022-02-14 18:05:21 +02:00
}
private extension [HomeScreenRoom] {
var invites: [HomeScreenRoom] {
filter { room in
if case .invite = room.type {
true
} else {
false
}
}
}
}