384 lines
17 KiB
Swift
384 lines
17 KiB
Swift
import Foundation
|
|
import XCTest
|
|
@testable import suixinkan
|
|
|
|
/// 验证独立套餐收款状态、报价校验与会话隔离,不调用真实付款服务。
|
|
@MainActor
|
|
final class DroneDockPaymentViewModelTests: XCTestCase {
|
|
/// 成功空列表与请求失败分开表达,并允许明确重试。
|
|
func testProjectsEmptyFailureAndRetryAreDistinct() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try ImmediatePaymentService()
|
|
let model = makeModel(scope, service)
|
|
service.projectsResult = .success([])
|
|
await model.loadProjects()
|
|
XCTAssertTrue(model.projects.isEmpty)
|
|
XCTAssertNil(model.projectError)
|
|
XCTAssertFalse(model.isLoadingProjects)
|
|
|
|
service.projectsResult = .failure(APIError.networkFailed("套餐读取超时"))
|
|
await model.loadProjects()
|
|
XCTAssertTrue(model.projects.isEmpty)
|
|
XCTAssertTrue(model.projectError?.contains("套餐读取超时") == true)
|
|
|
|
service.projectsResult = .success(try projects())
|
|
await model.loadProjects()
|
|
XCTAssertEqual(model.projects.map(\.id), [101, 102])
|
|
XCTAssertNil(model.projectError)
|
|
XCTAssertNil(model.payCode)
|
|
}
|
|
|
|
/// 默认价格留给后端确定;显式改价采用规范化字符串并接受后端确认值。
|
|
func testDefaultAndCustomQuotesUseServerConfirmedResult() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try ImmediatePaymentService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
await model.generateCode(projectID: 101)
|
|
XCTAssertNil(service.codeRequests.first?.price)
|
|
XCTAssertEqual(model.payCode?.price, Decimal(88))
|
|
XCTAssertFalse(model.isGenerating)
|
|
XCTAssertNil(model.payCodeError)
|
|
|
|
service.codeResult = .success(try code(price: "88.10"))
|
|
await model.generateCode(projectID: 101, price: " 88.1 ")
|
|
XCTAssertEqual(service.codeRequests.last?.price, "88.10")
|
|
XCTAssertEqual(model.payCode?.price, Decimal(string: "88.10"))
|
|
XCTAssertEqual(service.codeRequests.last?.scenicID, 128)
|
|
}
|
|
|
|
/// 生成失败或输入无效时不能留下可保存、可扫码的旧付款链接。
|
|
func testGeneratingFailureAndInvalidInputClearOldCode() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try ImmediatePaymentService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
await model.generateCode(projectID: 101)
|
|
XCTAssertNotNil(model.payCode)
|
|
|
|
service.codeResult = .failure(APIError.serverCode(160001, "套餐已下架"))
|
|
await model.generateCode(projectID: 102)
|
|
XCTAssertNil(model.payCode)
|
|
XCTAssertEqual(model.payCodeError, "套餐已下架")
|
|
XCTAssertFalse(model.isGenerating)
|
|
let count = service.codeRequests.count
|
|
await model.generateCode(projectID: 101, price: "0")
|
|
XCTAssertEqual(service.codeRequests.count, count)
|
|
XCTAssertNil(model.payCode)
|
|
XCTAssertNotNil(model.payCodeError)
|
|
}
|
|
|
|
/// 所选套餐、当前门店和显式金额任一不一致都拒绝回包。
|
|
func testMismatchedProjectStoreOrExplicitPriceIsRejected() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try ImmediatePaymentService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
for result in [try code(projectID: 102), try code(storeID: 999), try code(price: "89.00")] {
|
|
service.codeResult = .success(result)
|
|
await model.generateCode(projectID: 101, price: "88.00")
|
|
XCTAssertNil(model.payCode)
|
|
XCTAssertNotNil(model.payCodeError)
|
|
XCTAssertFalse(model.isGenerating)
|
|
}
|
|
}
|
|
|
|
/// 缺失登录范围或未加载的套餐不能创建付款链接。
|
|
func testInvalidContextAndUnknownProjectNeverCallCodeService() async throws {
|
|
let scope = PaymentContextBox(context(token: ""))
|
|
let service = try ImmediatePaymentService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
await model.generateCode(projectID: 101)
|
|
XCTAssertTrue(service.projectRequests.isEmpty)
|
|
XCTAssertTrue(service.codeRequests.isEmpty)
|
|
XCTAssertNotNil(model.projectError)
|
|
XCTAssertNotNil(model.payCodeError)
|
|
|
|
scope.value = context()
|
|
await model.loadProjects()
|
|
await model.generateCode(projectID: 999)
|
|
XCTAssertTrue(service.codeRequests.isEmpty)
|
|
XCTAssertNil(model.payCode)
|
|
}
|
|
|
|
/// 同一在途报价重复点击只发一次;换套餐后的迟到旧结果不能覆盖新二维码。
|
|
func testDuplicateSubmissionAndOutOfOrderQuotes() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try SuspendedPaymentCodeService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
let firstStarted = expectation(description: "第一个报价请求")
|
|
let secondStarted = expectation(description: "换套餐报价请求")
|
|
service.requestStarted = { index in
|
|
if index == 0 { firstStarted.fulfill() }
|
|
if index == 1 { secondStarted.fulfill() }
|
|
}
|
|
defer { service.cancelAll() }
|
|
let first = Task { await model.generateCode(projectID: 101, price: "88") }
|
|
await fulfillment(of: [firstStarted], timeout: 2)
|
|
XCTAssertTrue(model.isGenerating)
|
|
XCTAssertNil(model.payCode)
|
|
await model.generateCode(projectID: 101, price: "88.00")
|
|
XCTAssertEqual(service.requests.count, 1)
|
|
|
|
let second = Task { await model.generateCode(projectID: 102, price: "199.99") }
|
|
await fulfillment(of: [secondStarted], timeout: 2)
|
|
service.finish(1, .success(try code(projectID: 102, price: "199.99")))
|
|
await second.value
|
|
XCTAssertEqual(model.payCode?.projectID, 102)
|
|
service.finish(0, .success(try code()))
|
|
await first.value
|
|
XCTAssertEqual(model.payCode?.projectID, 102)
|
|
XCTAssertEqual(model.payCode?.price, Decimal(string: "199.99"))
|
|
XCTAssertFalse(model.isGenerating)
|
|
XCTAssertNil(model.payCodeError)
|
|
}
|
|
|
|
/// 开始新报价就撤下旧码,旧请求失败也不能终止新请求的加载状态。
|
|
func testOldFailureDoesNotOverwriteNewQuoteLoadingState() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try SuspendedPaymentCodeService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
let firstStarted = expectation(description: "首个请求")
|
|
let secondStarted = expectation(description: "新的报价请求")
|
|
service.requestStarted = { index in
|
|
if index == 0 { firstStarted.fulfill() }
|
|
if index == 1 { secondStarted.fulfill() }
|
|
}
|
|
defer { service.cancelAll() }
|
|
let first = Task { await model.generateCode(projectID: 101) }
|
|
await fulfillment(of: [firstStarted], timeout: 2)
|
|
let second = Task { await model.generateCode(projectID: 101, price: "80.00") }
|
|
await fulfillment(of: [secondStarted], timeout: 2)
|
|
service.finish(0, .failure(APIError.networkFailed("旧报价失败")))
|
|
await first.value
|
|
XCTAssertTrue(model.isGenerating)
|
|
XCTAssertNil(model.payCodeError)
|
|
XCTAssertNil(model.payCode)
|
|
service.finish(1, .success(try code(price: "80.00")))
|
|
await second.value
|
|
XCTAssertEqual(model.payCode?.price, Decimal(80))
|
|
}
|
|
|
|
/// 更换登录凭证、账号、景区或门店后,旧会话付款链接均不能回填。
|
|
func testChangedIdentityRejectsInFlightQuoteAndClearsProjects() async throws {
|
|
for changed in [context(token: "another-test-token"), context(userID: "other-user"),
|
|
context(scenicID: 129), context(storeID: 38)] {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try SuspendedPaymentCodeService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
let started = expectation(description: "旧身份报价已发送")
|
|
service.requestStarted = { _ in started.fulfill() }
|
|
let task = Task { await model.generateCode(projectID: 101) }
|
|
await fulfillment(of: [started], timeout: 2)
|
|
scope.value = changed
|
|
service.finish(0, .success(try code()))
|
|
await task.value
|
|
XCTAssertEqual(model.context, changed)
|
|
XCTAssertNil(model.payCode)
|
|
XCTAssertTrue(model.projects.isEmpty)
|
|
XCTAssertFalse(model.isGenerating)
|
|
XCTAssertNotNil(model.payCodeError)
|
|
}
|
|
}
|
|
|
|
/// 页面退出后成功回包无效,下一次重新加载仍能工作。
|
|
func testInvalidateRejectsPendingQuote() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try SuspendedPaymentCodeService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
let started = expectation(description: "待取消报价请求")
|
|
service.requestStarted = { _ in started.fulfill() }
|
|
defer { service.cancelAll() }
|
|
let task = Task { await model.generateCode(projectID: 101) }
|
|
await fulfillment(of: [started], timeout: 2)
|
|
model.invalidate()
|
|
service.finish(0, .success(try code()))
|
|
await task.value
|
|
XCTAssertTrue(model.projects.isEmpty)
|
|
XCTAssertNil(model.payCode)
|
|
XCTAssertFalse(model.isGenerating)
|
|
XCTAssertNil(model.payCodeError)
|
|
await model.loadProjects()
|
|
XCTAssertEqual(model.projects.count, 2)
|
|
}
|
|
|
|
/// 取消的报价即使网络仍成功完成,也不显示链接或取消错误。
|
|
func testTaskCancellationDoesNotPublishCode() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = try SuspendedPaymentCodeService()
|
|
let model = makeModel(scope, service)
|
|
await model.loadProjects()
|
|
let started = expectation(description: "待取消任务")
|
|
service.requestStarted = { _ in started.fulfill() }
|
|
defer { service.cancelAll() }
|
|
let task = Task { await model.generateCode(projectID: 101) }
|
|
await fulfillment(of: [started], timeout: 2)
|
|
task.cancel()
|
|
service.finish(0, .success(try code()))
|
|
await task.value
|
|
XCTAssertNil(model.payCode)
|
|
XCTAssertNil(model.payCodeError)
|
|
XCTAssertFalse(model.isGenerating)
|
|
}
|
|
|
|
/// 套餐加载防重复,切换范围后可以发新请求,旧列表不能覆盖新的空态。
|
|
func testProjectsDeduplicateAndRejectPreviousContextResponse() async throws {
|
|
let scope = PaymentContextBox(context())
|
|
let service = SuspendedPaymentProjectsService()
|
|
let model = makeModel(scope, service)
|
|
let firstStarted = expectation(description: "旧景区套餐请求")
|
|
let secondStarted = expectation(description: "新景区套餐请求")
|
|
service.requestStarted = { index in
|
|
if index == 0 { firstStarted.fulfill() }
|
|
if index == 1 { secondStarted.fulfill() }
|
|
}
|
|
defer { service.cancelAll() }
|
|
let first = Task { await model.loadProjects() }
|
|
await fulfillment(of: [firstStarted], timeout: 2)
|
|
await model.loadProjects()
|
|
XCTAssertEqual(service.requests.count, 1)
|
|
scope.value = context(scenicID: 129)
|
|
let second = Task { await model.loadProjects() }
|
|
await fulfillment(of: [secondStarted], timeout: 2)
|
|
service.finish(1, .success([]))
|
|
await second.value
|
|
service.finish(0, .success(try projects()))
|
|
await first.value
|
|
XCTAssertEqual(model.context.scenicID, 129)
|
|
XCTAssertTrue(model.projects.isEmpty)
|
|
XCTAssertFalse(model.isLoadingProjects)
|
|
XCTAssertNil(model.projectError)
|
|
}
|
|
|
|
private func context(userID: String = "test-user", scenicID: Int = 128, storeID: Int = 37,
|
|
token: String = "test-payment-session") -> DroneDockHomeContext {
|
|
DroneDockHomeContext(userID: userID, accountType: "photographer", scenicID: scenicID,
|
|
scenicName: "测试景区", storeID: storeID, photographerName: "测试员工", token: token)
|
|
}
|
|
|
|
private func makeModel(_ scope: PaymentContextBox, _ service: any DroneDockPaymentServing) -> DroneDockPaymentViewModel {
|
|
DroneDockPaymentViewModel(context: scope.value, service: service, currentContext: { scope.value })
|
|
}
|
|
|
|
private func projects() throws -> [DroneDockProject] {
|
|
try DroneDockPaymentTestFixtures.decode([DroneDockProject].self, DroneDockPaymentTestFixtures.projects)
|
|
}
|
|
|
|
private func code(projectID: Int = 101, price: String = "88.00", storeID: Int = 37) throws -> DroneDockPayCode {
|
|
try DroneDockPaymentTestFixtures.decode(DroneDockPayCode.self, DroneDockPaymentTestFixtures.code(projectID: projectID, price: price, storeID: storeID))
|
|
}
|
|
}
|
|
|
|
/// 测试中可切换的账号范围,仅由主 Actor 访问。
|
|
@MainActor
|
|
private final class PaymentContextBox {
|
|
var value: DroneDockHomeContext
|
|
init(_ value: DroneDockHomeContext) { self.value = value }
|
|
}
|
|
|
|
/// 立即完成的收款服务替身,记录真实请求参数供断言。
|
|
@MainActor
|
|
private final class ImmediatePaymentService: DroneDockPaymentServing {
|
|
var projectsResult: Result<[DroneDockProject], Error>
|
|
var codeResult: Result<DroneDockPayCode, Error>
|
|
var projectRequests: [Int] = []
|
|
var codeRequests: [(scenicID: Int, projectID: Int, price: String?)] = []
|
|
|
|
init() throws {
|
|
projectsResult = .success(try DroneDockPaymentTestFixtures.decode([DroneDockProject].self, DroneDockPaymentTestFixtures.projects))
|
|
codeResult = .success(try DroneDockPaymentTestFixtures.decode(DroneDockPayCode.self, DroneDockPaymentTestFixtures.code()))
|
|
}
|
|
|
|
func projects(scenicID: Int) async throws -> [DroneDockProject] {
|
|
projectRequests.append(scenicID)
|
|
return try projectsResult.get()
|
|
}
|
|
|
|
func payCode(scenicID: Int, projectID: Int, price: String?) async throws -> DroneDockPayCode {
|
|
codeRequests.append((scenicID, projectID, price))
|
|
return try codeResult.get()
|
|
}
|
|
|
|
func receipts(scenicID: Int, projectID: Int?, page: Int) async throws -> DroneDockReceiptsResponse {
|
|
throw APIError.networkFailed("主收款 ViewModel 不应请求收款记录")
|
|
}
|
|
}
|
|
|
|
/// 可指定响应顺序的报价服务,用于验证重复提交和旧请求隔离。
|
|
@MainActor
|
|
private final class SuspendedPaymentCodeService: DroneDockPaymentServing {
|
|
var requestStarted: ((Int) -> Void)?
|
|
var requests: [(projectID: Int, price: String?)] = []
|
|
private var continuations: [Int: CheckedContinuation<DroneDockPayCode, Error>] = [:]
|
|
private let availableProjects: [DroneDockProject]
|
|
|
|
init() throws {
|
|
availableProjects = try DroneDockPaymentTestFixtures.decode([DroneDockProject].self, DroneDockPaymentTestFixtures.projects)
|
|
}
|
|
|
|
func projects(scenicID: Int) async throws -> [DroneDockProject] { availableProjects }
|
|
|
|
func payCode(scenicID: Int, projectID: Int, price: String?) async throws -> DroneDockPayCode {
|
|
let index = requests.count
|
|
requests.append((projectID, price))
|
|
return try await withCheckedThrowingContinuation { continuation in
|
|
continuations[index] = continuation
|
|
requestStarted?(index)
|
|
}
|
|
}
|
|
|
|
func receipts(scenicID: Int, projectID: Int?, page: Int) async throws -> DroneDockReceiptsResponse {
|
|
throw APIError.networkFailed("不应查询收款记录")
|
|
}
|
|
|
|
func finish(_ index: Int, _ result: Result<DroneDockPayCode, Error>) {
|
|
continuations.removeValue(forKey: index)?.resume(with: result)
|
|
}
|
|
|
|
func cancelAll() {
|
|
let pending = continuations.values
|
|
continuations.removeAll()
|
|
for continuation in pending { continuation.resume(throwing: CancellationError()) }
|
|
}
|
|
}
|
|
|
|
/// 可控制列表完成顺序的服务,用于验证切换景区后的数据隔离。
|
|
@MainActor
|
|
private final class SuspendedPaymentProjectsService: DroneDockPaymentServing {
|
|
var requestStarted: ((Int) -> Void)?
|
|
var requests: [Int] = []
|
|
private var continuations: [Int: CheckedContinuation<[DroneDockProject], Error>] = [:]
|
|
|
|
func projects(scenicID: Int) async throws -> [DroneDockProject] {
|
|
let index = requests.count
|
|
requests.append(scenicID)
|
|
return try await withCheckedThrowingContinuation { continuation in
|
|
continuations[index] = continuation
|
|
requestStarted?(index)
|
|
}
|
|
}
|
|
|
|
func payCode(scenicID: Int, projectID: Int, price: String?) async throws -> DroneDockPayCode {
|
|
throw APIError.networkFailed("列表测试不应生成付款链接")
|
|
}
|
|
|
|
func receipts(scenicID: Int, projectID: Int?, page: Int) async throws -> DroneDockReceiptsResponse {
|
|
throw APIError.networkFailed("不应查询收款记录")
|
|
}
|
|
|
|
func finish(_ index: Int, _ result: Result<[DroneDockProject], Error>) {
|
|
continuations.removeValue(forKey: index)?.resume(with: result)
|
|
}
|
|
|
|
func cancelAll() {
|
|
let pending = continuations.values
|
|
continuations.removeAll()
|
|
for continuation in pending { continuation.resume(throwing: CancellationError()) }
|
|
}
|
|
}
|