This repository was archived by the owner on Feb 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSubscriptionPagesUseSubscriptionFeatureTestsForStripe.swift
409 lines (326 loc) · 20 KB
/
SubscriptionPagesUseSubscriptionFeatureTestsForStripe.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//
// SubscriptionPagesUseSubscriptionFeatureTestsForStripe.swift
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// 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 XCTest
@testable import DuckDuckGo_Privacy_Browser
@testable import Subscription
import SubscriptionTestingUtilities
import Common
import WebKit
import UserScript
@testable import PixelKit
import PixelKitTestingUtilities
import os.log
@available(macOS 12.0, *)
final class SubscriptionPagesUseSubscriptionFeatureTestsForStripe: XCTestCase {
private struct Constants {
static let userDefaultsSuiteName = "SubscriptionPagesUseSubscriptionFeatureTests"
static let authToken = UUID().uuidString
static let accessToken = UUID().uuidString
static let externalID = UUID().uuidString
static let email = "dax@duck.com"
static let entitlements = [Entitlement(product: .dataBrokerProtection),
Entitlement(product: .identityTheftRestoration),
Entitlement(product: .networkProtection)]
static let mostRecentTransactionJWS = "dGhpcyBpcyBub3QgYSByZWFsIEFw(...)cCBTdG9yZSB0cmFuc2FjdGlvbiBKV1M="
static let productItems = [GetProductsItem(productId: "1",
productLabel: "Monthly subscription",
billingPeriod: "monthly",
price: "9",
currency: "USD"),
GetProductsItem(productId: "2",
productLabel: "Annual subscription",
billingPeriod: "yearly",
price: "99",
currency: "USD")]
static let subscriptionOptions = SubscriptionOptions(platform: SubscriptionPlatformName.stripe,
options: [
SubscriptionOption(id: "1",
cost: SubscriptionOptionCost(displayPrice: "$9.00", recurrence: "monthly")),
SubscriptionOption(id: "2",
cost: SubscriptionOptionCost(displayPrice: "$99.00", recurrence: "yearly"))
],
features: [
SubscriptionFeature(name: .networkProtection),
SubscriptionFeature(name: .dataBrokerProtection),
SubscriptionFeature(name: .identityTheftRestoration)
])
static let validateTokenResponse = ValidateTokenResponse(account: ValidateTokenResponse.Account(email: Constants.email,
entitlements: Constants.entitlements,
externalID: Constants.externalID))
static let mockParams: [String: String] = [:]
@MainActor static let mockScriptMessage = MockWKScriptMessage(name: "", body: "", webView: WKWebView() )
static let invalidTokenError = APIServiceError.serverError(statusCode: 401, error: "invalid_token")
}
var userDefaults: UserDefaults!
var broker: UserScriptMessageBroker = UserScriptMessageBroker(context: "testBroker")
var uiHandler: SubscriptionUIHandlerMock!
var pixelKit: PixelKit!
var accountStorage: AccountKeychainStorageMock!
var accessTokenStorage: SubscriptionTokenKeychainStorageMock!
var entitlementsCache: UserDefaultsCache<[Entitlement]>!
var subscriptionService: SubscriptionEndpointServiceMock!
var authService: AuthEndpointServiceMock!
var storePurchaseManager: StorePurchaseManagerMock!
var subscriptionEnvironment: SubscriptionEnvironment!
var subscriptionFeatureMappingCache: SubscriptionFeatureMappingCacheMock!
var subscriptionFeatureFlagger: FeatureFlaggerMapping<SubscriptionFeatureFlags>!
var appStorePurchaseFlow: AppStorePurchaseFlow!
var appStoreRestoreFlow: AppStoreRestoreFlow!
var appStoreAccountManagementFlow: AppStoreAccountManagementFlow!
var stripePurchaseFlow: StripePurchaseFlow!
var subscriptionFeatureAvailability: SubscriptionFeatureAvailabilityMock!
var accountManager: AccountManager!
var subscriptionManager: SubscriptionManager!
var mockFreemiumDBPExperimentManager: MockFreemiumDBPExperimentManager!
var feature: SubscriptionPagesUseSubscriptionFeature!
var pixelsFired: [String] = []
var uiEventsHappened: [SubscriptionUIHandlerMock.UIHandlerMockPerformedAction] = []
@MainActor override func setUpWithError() throws {
// Mocks
userDefaults = UserDefaults(suiteName: Constants.userDefaultsSuiteName)!
userDefaults.removePersistentDomain(forName: Constants.userDefaultsSuiteName)
pixelKit = PixelKit(dryRun: false,
appVersion: "1.0.0",
defaultHeaders: [:],
defaults: userDefaults) { pixelName, _, _, _, _, _ in
self.pixelsFired.append(pixelName)
}
pixelKit.clearFrequencyHistoryForAllPixels()
PixelKit.setSharedForTesting(pixelKit: pixelKit)
uiHandler = SubscriptionUIHandlerMock { action in
self.uiEventsHappened.append(action)
}
subscriptionService = SubscriptionEndpointServiceMock()
authService = AuthEndpointServiceMock()
storePurchaseManager = StorePurchaseManagerMock()
subscriptionEnvironment = SubscriptionEnvironment(serviceEnvironment: .production,
purchasePlatform: .stripe)
accountStorage = AccountKeychainStorageMock()
accessTokenStorage = SubscriptionTokenKeychainStorageMock()
entitlementsCache = UserDefaultsCache<[Entitlement]>(userDefaults: userDefaults,
key: UserDefaultsCacheKey.subscriptionEntitlements,
settings: UserDefaultsCacheSettings(defaultExpirationInterval: .minutes(20)))
subscriptionFeatureMappingCache = SubscriptionFeatureMappingCacheMock()
subscriptionFeatureFlagger = FeatureFlaggerMapping<SubscriptionFeatureFlags>(mapping: { $0.defaultState })
// Real AccountManager
accountManager = DefaultAccountManager(storage: accountStorage,
accessTokenStorage: accessTokenStorage,
entitlementsCache: entitlementsCache,
subscriptionEndpointService: subscriptionService,
authEndpointService: authService)
// Real Flows
appStoreRestoreFlow = DefaultAppStoreRestoreFlow(accountManager: accountManager,
storePurchaseManager: storePurchaseManager,
subscriptionEndpointService: subscriptionService,
authEndpointService: authService)
appStorePurchaseFlow = DefaultAppStorePurchaseFlow(subscriptionEndpointService: subscriptionService,
storePurchaseManager: storePurchaseManager,
accountManager: accountManager,
appStoreRestoreFlow: appStoreRestoreFlow,
authEndpointService: authService)
appStoreAccountManagementFlow = DefaultAppStoreAccountManagementFlow(authEndpointService: authService,
storePurchaseManager: storePurchaseManager,
accountManager: accountManager)
stripePurchaseFlow = DefaultStripePurchaseFlow(subscriptionEndpointService: subscriptionService,
authEndpointService: authService,
accountManager: accountManager)
subscriptionFeatureAvailability = SubscriptionFeatureAvailabilityMock(isSubscriptionPurchaseAllowed: true,
usesUnifiedFeedbackForm: false)
// Real SubscriptionManager
subscriptionManager = DefaultSubscriptionManager(storePurchaseManager: storePurchaseManager,
accountManager: accountManager,
subscriptionEndpointService: subscriptionService,
authEndpointService: authService,
subscriptionFeatureMappingCache: subscriptionFeatureMappingCache,
subscriptionEnvironment: subscriptionEnvironment)
mockFreemiumDBPExperimentManager = MockFreemiumDBPExperimentManager()
feature = SubscriptionPagesUseSubscriptionFeature(subscriptionManager: subscriptionManager,
stripePurchaseFlow: stripePurchaseFlow,
uiHandler: uiHandler,
subscriptionFeatureAvailability: subscriptionFeatureAvailability,
freemiumDBPPixelExperimentManager: mockFreemiumDBPExperimentManager)
feature.with(broker: broker)
}
override func tearDownWithError() throws {
userDefaults = nil
pixelsFired.removeAll()
uiEventsHappened.removeAll()
subscriptionService = nil
authService = nil
storePurchaseManager = nil
subscriptionEnvironment = nil
accountStorage = nil
accessTokenStorage = nil
entitlementsCache.reset()
entitlementsCache = nil
accountManager = nil
// Real Flows
appStorePurchaseFlow = nil
appStoreRestoreFlow = nil
appStoreAccountManagementFlow = nil
stripePurchaseFlow = nil
subscriptionFeatureAvailability = nil
subscriptionManager = nil
feature = nil
}
// MARK: - Tests for getSubscriptionOptions
func testGetSubscriptionOptionsSuccess() async throws {
// Given
XCTAssertEqual(subscriptionEnvironment.purchasePlatform, .stripe)
subscriptionService.getProductsResult = .success(Constants.productItems)
// When
let result = try await feature.getSubscriptionOptions(params: Constants.mockParams, original: Constants.mockScriptMessage)
// Then
let subscriptionOptionsResult = try XCTUnwrap(result as? SubscriptionOptions)
XCTAssertEqual(subscriptionOptionsResult.options, Constants.subscriptionOptions.options)
XCTAssertEqual(subscriptionOptionsResult.platform, Constants.subscriptionOptions.platform)
XCTAssertPrivacyPixelsFired([])
}
func testGetSubscriptionOptionsReturnsEmptyOptionsWhenNoSubscriptionOptions() async throws {
// Given
XCTAssertEqual(subscriptionEnvironment.purchasePlatform, .stripe)
subscriptionService.getProductsResult = .success([])
storePurchaseManager.subscriptionOptionsResult = nil
// When
let result = try await feature.getSubscriptionOptions(params: Constants.mockParams, original: Constants.mockScriptMessage)
// Then
let subscriptionOptionsResult = try XCTUnwrap(result as? SubscriptionOptions)
XCTAssertEqual(subscriptionOptionsResult, SubscriptionOptions.empty)
XCTAssertPrivacyPixelsFired([])
}
func testGetSubscriptionOptionsReturnsEmptyOptionsWhenSubscriptionOptionsDidNotFetch() async throws {
// Given
XCTAssertEqual(subscriptionEnvironment.purchasePlatform, .stripe)
subscriptionService.getProductsResult = .failure(Constants.invalidTokenError)
storePurchaseManager.subscriptionOptionsResult = nil
// When
let result = try await feature.getSubscriptionOptions(params: Constants.mockParams, original: Constants.mockScriptMessage)
// Then
let subscriptionOptionsResult = try XCTUnwrap(result as? SubscriptionOptions)
XCTAssertEqual(subscriptionOptionsResult, SubscriptionOptions.empty)
XCTAssertPrivacyPixelsFired([])
}
// MARK: - Tests for subscriptionSelected
func testSubscriptionSelectedSuccessWhenPurchasingFirstTime() async throws {
// Given
ensureUserUnauthenticatedState()
XCTAssertEqual(subscriptionEnvironment.purchasePlatform, .stripe)
XCTAssertFalse(accountManager.isUserAuthenticated)
authService.createAccountResult = .success(CreateAccountResponse(authToken: Constants.authToken,
externalID: Constants.externalID,
status: "created"))
// When
let subscriptionSelectedParams = ["id": "some-subscription-id"]
let result = try await feature.subscriptionSelected(params: subscriptionSelectedParams, original: Constants.mockScriptMessage)
// Then
XCTAssertEqual(uiEventsHappened, [.didDismissProgressViewController])
XCTAssertNil(result)
XCTAssertPrivacyPixelsFired([PrivacyProPixel.privacyProPurchaseAttempt.name + "_d",
PrivacyProPixel.privacyProPurchaseAttempt.name + "_c"])
}
func testSubscriptionSelectedSuccessWhenRepurchasingForExpiredAppleSubscription() async throws {
// Given
ensureUserAuthenticatedState()
XCTAssertEqual(subscriptionEnvironment.purchasePlatform, .stripe)
XCTAssertTrue(accountManager.isUserAuthenticated)
subscriptionService.getSubscriptionResult = .success(SubscriptionMockFactory.expiredSubscription)
// When
let subscriptionSelectedParams = ["id": "some-subscription-id"]
let result = try await feature.subscriptionSelected(params: subscriptionSelectedParams, original: Constants.mockScriptMessage)
// Then
XCTAssertFalse(authService.createAccountCalled)
XCTAssertEqual(uiEventsHappened, [.didDismissProgressViewController])
XCTAssertNil(result)
XCTAssertPrivacyPixelsFired([PrivacyProPixel.privacyProPurchaseAttempt.name + "_d",
PrivacyProPixel.privacyProPurchaseAttempt.name + "_c"])
}
func testSubscriptionSelectedErrorWhenUnauthenticatedAndAccountCreationFails() async throws {
// Given
ensureUserUnauthenticatedState()
XCTAssertEqual(subscriptionEnvironment.purchasePlatform, .stripe)
authService.createAccountResult = .failure(Constants.invalidTokenError)
await uiHandler.setAlertResponse(alertResponse: .alertFirstButtonReturn)
// When
let subscriptionSelectedParams = ["id": "some-subscription-id"]
let result = try await feature.subscriptionSelected(params: subscriptionSelectedParams, original: Constants.mockScriptMessage)
// Then
XCTAssertFalse(storePurchaseManager.purchaseSubscriptionCalled)
XCTAssertEqual(uiEventsHappened, [.didDismissProgressViewController,
.didShowAlert(.somethingWentWrong),
.didShowTab(.subscription(subscriptionManager.url(for: .purchase))),
.didDismissProgressViewController])
XCTAssertNil(result)
XCTAssertPrivacyPixelsFired([PrivacyProPixel.privacyProPurchaseAttempt.name + "_d",
PrivacyProPixel.privacyProPurchaseAttempt.name + "_c",
PrivacyProPixel.privacyProPurchaseFailureAccountNotCreated.name + "_d",
PrivacyProPixel.privacyProPurchaseFailureAccountNotCreated.name + "_c",
PrivacyProPixel.privacyProPurchaseFailure.name + "_d",
PrivacyProPixel.privacyProPurchaseFailure.name + "_c",
PrivacyProPixel.privacyProOfferScreenImpression.name])
}
// MARK: - Tests for completeStripePayment
func testCompleteStripePaymentSuccess() async throws {
// Given
ensureUserAuthenticatedState()
authService.getAccessTokenResult = .success(AccessTokenResponse(accessToken: Constants.accessToken))
authService.validateTokenResult = .success(Constants.validateTokenResponse)
// When
let result = try await feature.completeStripePayment(params: Constants.mockParams, original: Constants.mockScriptMessage)
// Then
XCTAssertEqual(uiEventsHappened, [.didPresentProgressViewController,
.didDismissProgressViewController])
let dictionaryResult = try XCTUnwrap(result as? [String: String])
XCTAssertTrue(dictionaryResult.isEmpty)
XCTAssertPrivacyPixelsFired([PrivacyProPixel.privacyProPurchaseStripeSuccess.name + "_d",
PrivacyProPixel.privacyProPurchaseStripeSuccess.name + "_c"])
}
}
@available(macOS 12.0, *)
extension SubscriptionPagesUseSubscriptionFeatureTestsForStripe {
func ensureUserAuthenticatedState() {
accountStorage.authToken = Constants.authToken
accountStorage.email = Constants.email
accountStorage.externalID = Constants.externalID
accessTokenStorage.accessToken = Constants.accessToken
}
func ensureUserUnauthenticatedState() {
try? accessTokenStorage.removeAccessToken()
try? accountStorage.clearAuthenticationState()
}
public func XCTAssertPrivacyPixelsFired(_ pixels: [String], file: StaticString = #file, line: UInt = #line) {
let pixelsFired = Set(pixelsFired)
let expectedPixels = Set(pixels)
// Assert expected pixels were fired
XCTAssertTrue(expectedPixels.isSubset(of: pixelsFired),
"Expected Privacy Pro pixels were not fired: \(expectedPixels.subtracting(pixelsFired))",
file: file,
line: line)
// Assert no other Privacy Pro pixels were fired except the expected
#if APPSTORE
let privacyProPixelPrefix = "m_mac_store_privacy-pro"
#else
let privacyProPixelPrefix = "m_mac_direct_privacy-pro"
#endif
let otherPixels = pixelsFired.subtracting(expectedPixels)
let otherPrivacyProPixels = otherPixels.filter { $0.hasPrefix(privacyProPixelPrefix) }
XCTAssertTrue(otherPrivacyProPixels.isEmpty,
"Unexpected Privacy Pro pixels fired: \(otherPrivacyProPixels)",
file: file,
line: line)
}
}