Auto-Mocking with Sourcery (#597)

* work in progress, was able to generate a mock for the RoomProxyProtocol, I'll try if I can swap the mock we have with this one

* removing swiftformat from generated

* added the disable of swiftlint directly into the .stencil

* testing if danger still complains

* improved the stencil

* session verification controller proxy using auto mockable

* BugReport mocks and tests added

* changelog

* fixing a typo

Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com>

* fix typo in the test

Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com>

* removing the Protocol word from the type if present

* using extension in place of a subclass

* removed unused imports

* improved the yielding code

* moved Sourcery files

* stencil master

---------

Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com>
This commit is contained in:
Mauro
2023-03-08 17:04:31 +01:00
committed by GitHub
parent 7d35876753
commit c67c4e362e
20 changed files with 554 additions and 148 deletions
@@ -1,5 +1,5 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2023 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.
@@ -14,18 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
class MockBugReportService: BugReportServiceProtocol {
func submitBugReport(_ bugReport: BugReport,
progressListener: ProgressListener?) async throws -> SubmitBugReportResponse {
SubmitBugReportResponse(reportUrl: "https://www.example/com/123")
}
var crashedLastRun = false
func crash() {
// no-op
}
}
// This protocol is used only as a marker
// to mark protocols that can be auto-mocked by Sourcery
protocol AutoMockable { }
@@ -0,0 +1,143 @@
// Generated using Sourcery 2.0.1 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// swiftlint:disable all
import Combine
import MatrixRustSDK
class BugReportServiceMock: BugReportServiceProtocol {
var crashedLastRun: Bool {
get { return underlyingCrashedLastRun }
set(value) { underlyingCrashedLastRun = value }
}
var underlyingCrashedLastRun: Bool!
// MARK: - crash
var crashCallsCount = 0
var crashCalled: Bool {
return crashCallsCount > 0
}
var crashClosure: (() -> Void)?
func crash() {
crashCallsCount += 1
crashClosure?()
}
// MARK: - submitBugReport
var submitBugReportProgressListenerThrowableError: Error?
var submitBugReportProgressListenerCallsCount = 0
var submitBugReportProgressListenerCalled: Bool {
return submitBugReportProgressListenerCallsCount > 0
}
var submitBugReportProgressListenerReceivedArguments: (bugReport: BugReport, progressListener: ProgressListener?)?
var submitBugReportProgressListenerReceivedInvocations: [(bugReport: BugReport, progressListener: ProgressListener?)] = []
var submitBugReportProgressListenerReturnValue: SubmitBugReportResponse!
var submitBugReportProgressListenerClosure: ((BugReport, ProgressListener?) async throws -> SubmitBugReportResponse)?
func submitBugReport(_ bugReport: BugReport, progressListener: ProgressListener?) async throws -> SubmitBugReportResponse {
if let error = submitBugReportProgressListenerThrowableError {
throw error
}
submitBugReportProgressListenerCallsCount += 1
submitBugReportProgressListenerReceivedArguments = (bugReport: bugReport, progressListener: progressListener)
submitBugReportProgressListenerReceivedInvocations.append((bugReport: bugReport, progressListener: progressListener))
if let submitBugReportProgressListenerClosure = submitBugReportProgressListenerClosure {
return try await submitBugReportProgressListenerClosure(bugReport, progressListener)
} else {
return submitBugReportProgressListenerReturnValue
}
}
}
class SessionVerificationControllerProxyMock: SessionVerificationControllerProxyProtocol {
var callbacks: PassthroughSubject<SessionVerificationControllerProxyCallback, Never> {
get { return underlyingCallbacks }
set(value) { underlyingCallbacks = value }
}
var underlyingCallbacks: PassthroughSubject<SessionVerificationControllerProxyCallback, Never>!
var isVerified: Bool {
get { return underlyingIsVerified }
set(value) { underlyingIsVerified = value }
}
var underlyingIsVerified: Bool!
// MARK: - requestVerification
var requestVerificationCallsCount = 0
var requestVerificationCalled: Bool {
return requestVerificationCallsCount > 0
}
var requestVerificationReturnValue: Result<Void, SessionVerificationControllerProxyError>!
var requestVerificationClosure: (() async -> Result<Void, SessionVerificationControllerProxyError>)?
func requestVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
requestVerificationCallsCount += 1
if let requestVerificationClosure = requestVerificationClosure {
return await requestVerificationClosure()
} else {
return requestVerificationReturnValue
}
}
// MARK: - startSasVerification
var startSasVerificationCallsCount = 0
var startSasVerificationCalled: Bool {
return startSasVerificationCallsCount > 0
}
var startSasVerificationReturnValue: Result<Void, SessionVerificationControllerProxyError>!
var startSasVerificationClosure: (() async -> Result<Void, SessionVerificationControllerProxyError>)?
func startSasVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
startSasVerificationCallsCount += 1
if let startSasVerificationClosure = startSasVerificationClosure {
return await startSasVerificationClosure()
} else {
return startSasVerificationReturnValue
}
}
// MARK: - approveVerification
var approveVerificationCallsCount = 0
var approveVerificationCalled: Bool {
return approveVerificationCallsCount > 0
}
var approveVerificationReturnValue: Result<Void, SessionVerificationControllerProxyError>!
var approveVerificationClosure: (() async -> Result<Void, SessionVerificationControllerProxyError>)?
func approveVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
approveVerificationCallsCount += 1
if let approveVerificationClosure = approveVerificationClosure {
return await approveVerificationClosure()
} else {
return approveVerificationReturnValue
}
}
// MARK: - declineVerification
var declineVerificationCallsCount = 0
var declineVerificationCalled: Bool {
return declineVerificationCallsCount > 0
}
var declineVerificationReturnValue: Result<Void, SessionVerificationControllerProxyError>!
var declineVerificationClosure: (() async -> Result<Void, SessionVerificationControllerProxyError>)?
func declineVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
declineVerificationCallsCount += 1
if let declineVerificationClosure = declineVerificationClosure {
return await declineVerificationClosure()
} else {
return declineVerificationReturnValue
}
}
// MARK: - cancelVerification
var cancelVerificationCallsCount = 0
var cancelVerificationCalled: Bool {
return cancelVerificationCallsCount > 0
}
var cancelVerificationReturnValue: Result<Void, SessionVerificationControllerProxyError>!
var cancelVerificationClosure: (() async -> Result<Void, SessionVerificationControllerProxyError>)?
func cancelVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
cancelVerificationCallsCount += 1
if let cancelVerificationClosure = cancelVerificationClosure {
return await cancelVerificationClosure()
} else {
return cancelVerificationReturnValue
}
}
}
// swiftlint:enable all
@@ -0,0 +1,87 @@
//
// Copyright 2023 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
extension SessionVerificationControllerProxyMock {
static let emojis = [SessionVerificationEmoji(symbol: "🦋", description: "Butterfly"),
SessionVerificationEmoji(symbol: "🐘", description: "Elephant"),
SessionVerificationEmoji(symbol: "🦋", description: "Butterfly"),
SessionVerificationEmoji(symbol: "🎂", description: "Cake"),
SessionVerificationEmoji(symbol: "🎂", description: "Cake"),
SessionVerificationEmoji(symbol: "🏁", description: "Flag"),
SessionVerificationEmoji(symbol: "🌏", description: "Globe")]
static func configureMock(callbacks: PassthroughSubject<SessionVerificationControllerProxyCallback, Never> = .init(),
isVerified: Bool = false,
requestDelay: Duration = .seconds(1)) -> SessionVerificationControllerProxyMock {
let mock = SessionVerificationControllerProxyMock()
mock.underlyingCallbacks = callbacks
mock.underlyingIsVerified = isVerified
mock.requestVerificationClosure = { [unowned mock] in
Task.detached {
try await Task.sleep(for: requestDelay)
mock.callbacks.send(.acceptedVerificationRequest)
}
return .success(())
}
mock.startSasVerificationClosure = { [unowned mock] in
Task.detached {
try await Task.sleep(for: requestDelay)
mock.callbacks.send(.startedSasVerification)
Task.detached {
try await Task.sleep(for: requestDelay)
mock.callbacks.send(.receivedVerificationData(Self.emojis))
}
}
return .success(())
}
mock.approveVerificationClosure = { [unowned mock] in
Task.detached {
try await Task.sleep(for: requestDelay)
mock.callbacks.send(.finished)
}
return .success(())
}
mock.declineVerificationClosure = { [unowned mock] in
Task.detached {
try await Task.sleep(for: requestDelay)
mock.callbacks.send(.cancelled)
}
return .success(())
}
mock.cancelVerificationClosure = { [unowned mock] in
Task.detached {
try await Task.sleep(for: requestDelay)
mock.callbacks.send(.cancelled)
}
return .success(())
}
return mock
}
}
@@ -146,7 +146,7 @@ struct BugReportScreen: View {
// MARK: - Previews
struct BugReport_Previews: PreviewProvider {
static let viewModel = BugReportViewModel(bugReportService: MockBugReportService(),
static let viewModel = BugReportViewModel(bugReportService: BugReportServiceMock(),
userID: "@mock.client.com",
deviceID: nil,
screenshot: nil,
@@ -154,7 +154,7 @@ struct BugReport_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
BugReportScreen(context: BugReportViewModel(bugReportService: MockBugReportService(),
BugReportScreen(context: BugReportViewModel(bugReportService: BugReportServiceMock(),
userID: "@mock.client.com",
deviceID: nil,
screenshot: nil,
@@ -163,7 +163,7 @@ struct BugReport_Previews: PreviewProvider {
}
NavigationStack {
BugReportScreen(context: BugReportViewModel(bugReportService: MockBugReportService(),
BugReportScreen(context: BugReportViewModel(bugReportService: BugReportServiceMock(),
userID: "@mock.client.com",
deviceID: nil,
screenshot: Asset.Images.appLogo.image,
@@ -231,14 +231,14 @@ struct SessionVerification_Previews: PreviewProvider {
sessionVerificationScreen(state: .requestingVerification)
sessionVerificationScreen(state: .cancelled)
sessionVerificationScreen(state: .showingChallenge(emojis: MockSessionVerificationControllerProxy.emojis))
sessionVerificationScreen(state: .showingChallenge(emojis: SessionVerificationControllerProxyMock.emojis))
sessionVerificationScreen(state: .verified)
}
.tint(Color.element.accent)
}
static func sessionVerificationScreen(state: SessionVerificationStateMachine.State) -> some View {
let viewModel = SessionVerificationViewModel(sessionVerificationControllerProxy: MockSessionVerificationControllerProxy(),
let viewModel = SessionVerificationViewModel(sessionVerificationControllerProxy: SessionVerificationControllerProxyMock.configureMock(),
initialState: SessionVerificationViewState(verificationState: state))
return SessionVerificationScreen(context: viewModel.context)
@@ -17,7 +17,7 @@
import Foundation
import UIKit
struct BugReport {
struct BugReport: Equatable {
let userID: String
let deviceID: String?
let text: String
@@ -31,7 +31,7 @@ struct SubmitBugReportResponse: Decodable {
var reportUrl: String
}
protocol BugReportServiceProtocol {
protocol BugReportServiceProtocol: AutoMockable {
var crashedLastRun: Bool { get }
func crash()
@@ -1,90 +0,0 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Foundation
import MatrixRustSDK
struct MockSessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol {
var callbacks = PassthroughSubject<SessionVerificationControllerProxyCallback, Never>()
var isVerified = false
var requestDelay: Duration = .seconds(1)
func requestVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
Task.detached {
try await Task.sleep(for: requestDelay)
callbacks.send(.acceptedVerificationRequest)
}
return .success(())
}
func startSasVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
Task.detached {
try await Task.sleep(for: requestDelay)
callbacks.send(.startedSasVerification)
Task.detached {
try await Task.sleep(for: requestDelay)
callbacks.send(.receivedVerificationData(Self.emojis))
}
}
return .success(())
}
func approveVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
Task.detached {
try await Task.sleep(for: requestDelay)
callbacks.send(.finished)
}
return .success(())
}
func declineVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
Task.detached {
try await Task.sleep(for: requestDelay)
callbacks.send(.cancelled)
}
return .success(())
}
func cancelVerification() async -> Result<Void, SessionVerificationControllerProxyError> {
Task.detached {
try await Task.sleep(for: requestDelay)
callbacks.send(.cancelled)
}
return .success(())
}
// MARK: - Private
static var emojis: [SessionVerificationEmoji] {
[
SessionVerificationEmoji(symbol: "🦋", description: "Butterfly"),
SessionVerificationEmoji(symbol: "🐘", description: "Elephant"),
SessionVerificationEmoji(symbol: "🦋", description: "Butterfly"),
SessionVerificationEmoji(symbol: "🎂", description: "Cake"),
SessionVerificationEmoji(symbol: "🎂", description: "Cake"),
SessionVerificationEmoji(symbol: "🏁", description: "Flag"),
SessionVerificationEmoji(symbol: "🌏", description: "Globe")
]
}
}
@@ -39,7 +39,7 @@ struct SessionVerificationEmoji: Hashable {
let description: String
}
protocol SessionVerificationControllerProxyProtocol {
protocol SessionVerificationControllerProxyProtocol: AutoMockable {
var callbacks: PassthroughSubject<SessionVerificationControllerProxyCallback, Never> { get }
var isVerified: Bool { get }
@@ -105,7 +105,7 @@ class MockScreen: Identifiable {
mediaProvider: MockMediaProvider())
let coordinator = HomeScreenCoordinator(parameters: .init(userSession: session,
attributedStringBuilder: AttributedStringBuilder(),
bugReportService: MockBugReportService(),
bugReportService: BugReportServiceMock(),
navigationStackCoordinator: navigationStackCoordinator))
navigationStackCoordinator.setRootCoordinator(coordinator)
return navigationStackCoordinator
@@ -115,12 +115,12 @@ class MockScreen: Identifiable {
userIndicatorController: nil,
userSession: MockUserSession(clientProxy: MockClientProxy(userID: "@mock:client.com"),
mediaProvider: MockMediaProvider()),
bugReportService: MockBugReportService()))
bugReportService: BugReportServiceMock()))
navigationStackCoordinator.setRootCoordinator(coordinator)
return navigationStackCoordinator
case .bugReport:
let navigationStackCoordinator = NavigationStackCoordinator()
let coordinator = BugReportCoordinator(parameters: .init(bugReportService: MockBugReportService(),
let coordinator = BugReportCoordinator(parameters: .init(bugReportService: BugReportServiceMock(),
userID: "@mock:client.com",
deviceID: nil,
userIndicatorController: nil,
@@ -130,7 +130,7 @@ class MockScreen: Identifiable {
return navigationStackCoordinator
case .bugReportWithScreenshot:
let navigationStackCoordinator = NavigationStackCoordinator()
let coordinator = BugReportCoordinator(parameters: .init(bugReportService: MockBugReportService(),
let coordinator = BugReportCoordinator(parameters: .init(bugReportService: BugReportServiceMock(),
userID: "@mock:client.com",
deviceID: nil,
userIndicatorController: nil,
@@ -250,8 +250,7 @@ class MockScreen: Identifiable {
navigationStackCoordinator.setRootCoordinator(coordinator)
return navigationStackCoordinator
case .sessionVerification:
var sessionVerificationControllerProxy = MockSessionVerificationControllerProxy()
sessionVerificationControllerProxy.requestDelay = .seconds(2)
var sessionVerificationControllerProxy = SessionVerificationControllerProxyMock.configureMock(requestDelay: .seconds(2))
let parameters = SessionVerificationCoordinatorParameters(sessionVerificationControllerProxy: sessionVerificationControllerProxy)
return SessionVerificationCoordinator(parameters: parameters)
case .userSessionScreen:
@@ -261,7 +260,7 @@ class MockScreen: Identifiable {
let coordinator = UserSessionFlowCoordinator(userSession: MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider()),
navigationSplitCoordinator: navigationSplitCoordinator,
bugReportService: MockBugReportService(),
bugReportService: BugReportServiceMock(),
roomTimelineControllerFactory: MockRoomTimelineControllerFactory())
coordinator.start()
+11
View File
@@ -87,6 +87,17 @@ targets:
else
echo "warning: SwiftGen not installed, download from https://github.com/SwiftGen/SwiftGen"
fi
- name: 🧙 Sourcery
runOnlyWhenInstalling: false
basedOnDependencyAnalysis: false
shell: /bin/sh
script: |
export PATH="$PATH:/opt/homebrew/bin"
if which sourcery >/dev/null; then
sourcery --config Tools/Sourcery/sourcery_automockable_config.yml
else
echo "warning: Sourcert not installed, run swift run tools setup-project"
fi
postBuildScripts:
- name: ⚠️ SwiftLint