|
| 1 | +/* |
| 2 | + Modified MIT License |
| 3 | + |
| 4 | + Copyright 2026 OneSignal |
| 5 | + |
| 6 | + Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | + of this software and associated documentation files (the "Software"), to deal |
| 8 | + in the Software without restriction, including without limitation the rights |
| 9 | + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | + copies of the Software, and to permit persons to whom the Software is |
| 11 | + furnished to do so, subject to the following conditions: |
| 12 | + |
| 13 | + 1. The above copyright notice and this permission notice shall be included in |
| 14 | + all copies or substantial portions of the Software. |
| 15 | + |
| 16 | + 2. All copies of substantial portions of the Software may only be used in connection |
| 17 | + with services provided by OneSignal. |
| 18 | + |
| 19 | + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 20 | + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 21 | + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 22 | + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 23 | + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 24 | + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 25 | + THE SOFTWARE. |
| 26 | + */ |
| 27 | + |
| 28 | +import XCTest |
| 29 | +import OneSignalCore |
| 30 | +import OneSignalCoreMocks |
| 31 | +import OneSignalUserMocks |
| 32 | +@testable import OneSignalOSCore |
| 33 | +@testable import OneSignalUser |
| 34 | + |
| 35 | +/** |
| 36 | + How the subscription executor handles a CreateSubscription success response. |
| 37 | + */ |
| 38 | +final class SubscriptionCreateResponseTests: XCTestCase { |
| 39 | + |
| 40 | + private let email = "test@example.com" |
| 41 | + private let onesignalId = "test-onesignal-id" |
| 42 | + |
| 43 | + override func setUpWithError() throws { |
| 44 | + OneSignalCoreMocks.clearUserDefaults() |
| 45 | + OneSignalUserMocks.reset() |
| 46 | + OSConsistencyManager.shared.reset() |
| 47 | + OneSignalIdentifiers.currentAppId = "test-app-id" |
| 48 | + OneSignalLog.setLogLevel(.LL_VERBOSE) |
| 49 | + } |
| 50 | + |
| 51 | + override func tearDownWithError() throws { } |
| 52 | + |
| 53 | + /** |
| 54 | + The server answers a create for a subscription that already exists on the user with a 2xx and no |
| 55 | + subscription object. The request is finished, not retried, the model is left as it was, and a |
| 56 | + fetch waiting on this user's read-your-write token is released because none is coming. |
| 57 | + */ |
| 58 | + func testResponseWithoutSubscription_completesWithoutHydratingAndReleasesWaiters() throws { |
| 59 | + let client = MockOneSignalClient() |
| 60 | + OneSignalCoreImpl.setSharedClient(client) |
| 61 | + client.setMockResponseForRequest(request: createRequestKey, response: [:]) |
| 62 | + |
| 63 | + let executor = OSSubscriptionOperationExecutor(newRecordsState: OSNewRecordsState(), auth: OneSignalUserManagerImpl.sharedInstance.requestAuth) |
| 64 | + let user = OneSignalUserMocks.setUserManagerInternalUser(onesignalId: onesignalId) |
| 65 | + let model = makeEmailSubscriptionModel() |
| 66 | + |
| 67 | + // Only a resolve can release this waiter, so it stays blocked if the response is dropped instead of handled. |
| 68 | + let released = expectation(description: "IAM fetch waiter was not released") |
| 69 | + DispatchQueue.global().async { |
| 70 | + _ = OSConsistencyManager.shared.getRywTokenFromAwaitableCondition(UnmetIamFetchCondition(), forId: self.onesignalId) |
| 71 | + released.fulfill() |
| 72 | + } |
| 73 | + OneSignalCoreMocks.waitUntil("Waiter was not registered") { self.waiterCount(forId: self.onesignalId) == 1 } |
| 74 | + |
| 75 | + executor.enqueueDelta(addDelta(for: model, identityModel: user.identityModel)) |
| 76 | + executor.processDeltaQueue(inBackground: false) |
| 77 | + OneSignalCoreMocks.waitUntil("Create subscription request did not complete") { |
| 78 | + client.hasCompletedRequestOfType(OSRequestCreateSubscription.self) |
| 79 | + } |
| 80 | + waitForAddRequestQueueToDrain() |
| 81 | + |
| 82 | + XCTAssertTrue(client.allRequestsHandled) |
| 83 | + XCTAssertTrue(client.hasExecutedRequestOfType(OSRequestCreateSubscription.self, expectedCount: 1)) |
| 84 | + XCTAssertNil(model.subscriptionId) |
| 85 | + wait(for: [released], timeout: 3.0) |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + `ryw_token` and `ryw_delay` are siblings of the subscription object, not fields of it. |
| 90 | + */ |
| 91 | + func testResponseWithSubscription_hydratesModelAndRecordsTopLevelRywToken() throws { |
| 92 | + let client = MockOneSignalClient() |
| 93 | + OneSignalCoreImpl.setSharedClient(client) |
| 94 | + client.setMockResponseForRequest( |
| 95 | + request: createRequestKey, |
| 96 | + response: [ |
| 97 | + "subscription": ["id": "email-subscription-id", "type": "Email", "token": email], |
| 98 | + "ryw_token": "ryw-token-1", |
| 99 | + "ryw_delay": 250 |
| 100 | + ] |
| 101 | + ) |
| 102 | + |
| 103 | + let executor = OSSubscriptionOperationExecutor(newRecordsState: OSNewRecordsState(), auth: OneSignalUserManagerImpl.sharedInstance.requestAuth) |
| 104 | + let user = OneSignalUserMocks.setUserManagerInternalUser(onesignalId: onesignalId) |
| 105 | + let model = makeEmailSubscriptionModel() |
| 106 | + |
| 107 | + executor.enqueueDelta(addDelta(for: model, identityModel: user.identityModel)) |
| 108 | + executor.processDeltaQueue(inBackground: false) |
| 109 | + // Hydration is the last step of the success handler, after the token is recorded. |
| 110 | + OneSignalCoreMocks.waitUntil("Subscription model was not hydrated") { |
| 111 | + model.subscriptionId == "email-subscription-id" |
| 112 | + } |
| 113 | + |
| 114 | + XCTAssertTrue(client.allRequestsHandled) |
| 115 | + let recorded = OSConsistencyManager.shared.getRywTokenFromAwaitableCondition( |
| 116 | + SubscriptionUpdateTokenCondition(id: onesignalId), |
| 117 | + forId: onesignalId |
| 118 | + ) |
| 119 | + XCTAssertEqual(recorded?.rywToken, "ryw-token-1") |
| 120 | + XCTAssertEqual(recorded?.rywDelay?.intValue, 250) |
| 121 | + } |
| 122 | + |
| 123 | + // MARK: - Helpers |
| 124 | + |
| 125 | + private var createRequestKey: String { |
| 126 | + "<OSRequestCreateSubscription with token: \(email)>" |
| 127 | + } |
| 128 | + |
| 129 | + private func makeEmailSubscriptionModel() -> OSSubscriptionModel { |
| 130 | + OSSubscriptionModel( |
| 131 | + type: .email, |
| 132 | + address: email, |
| 133 | + subscriptionId: nil, |
| 134 | + reachable: true, |
| 135 | + isDisabled: false, |
| 136 | + changeNotifier: OSEventProducer() |
| 137 | + ) |
| 138 | + } |
| 139 | + |
| 140 | + private func addDelta(for model: OSSubscriptionModel, identityModel: OSIdentityModel) -> OSDelta { |
| 141 | + OSDelta( |
| 142 | + name: OS_ADD_SUBSCRIPTION_DELTA, |
| 143 | + identityModelId: identityModel.modelId, |
| 144 | + externalId: identityModel.externalId, |
| 145 | + model: model, |
| 146 | + property: model.type.rawValue, |
| 147 | + value: model.address ?? "" |
| 148 | + ) |
| 149 | + } |
| 150 | + |
| 151 | + private func waiterCount(forId id: String) -> Int { |
| 152 | + OSConsistencyManager.shared.queue.sync { |
| 153 | + OSConsistencyManager.shared.indexedConditions[id]?.count ?? 0 |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + private func waitForAddRequestQueueToDrain() { |
| 158 | + OneSignalCoreMocks.waitUntil("Create subscription request was not removed from the cache") { |
| 159 | + let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( |
| 160 | + forKey: OS_SUBSCRIPTION_EXECUTOR_ADD_REQUEST_QUEUE_KEY, |
| 161 | + defaultValue: [] |
| 162 | + ) as? [OSRequestCreateSubscription] |
| 163 | + return requests?.isEmpty == true |
| 164 | + } |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +/// Reads back the subscription-update token recorded for an id without waiting on anything. |
| 169 | +private final class SubscriptionUpdateTokenCondition: NSObject, OSCondition { |
| 170 | + private let id: String |
| 171 | + |
| 172 | + init(id: String) { |
| 173 | + self.id = id |
| 174 | + } |
| 175 | + |
| 176 | + var conditionId: String { "SubscriptionUpdateTokenCondition" } |
| 177 | + |
| 178 | + func isMet(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> Bool { |
| 179 | + true |
| 180 | + } |
| 181 | + |
| 182 | + func getNewestToken(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> OSReadYourWriteData? { |
| 183 | + indexedTokens[id]?[NSNumber(value: OSIamFetchOffsetKey.subscriptionUpdate.rawValue)] |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +/// Never met on its own and carries the IAM fetch condition id, so only the executor's resolve releases it. |
| 188 | +private final class UnmetIamFetchCondition: NSObject, OSCondition { |
| 189 | + var conditionId: String { OSIamFetchReadyCondition.CONDITIONID } |
| 190 | + |
| 191 | + func isMet(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> Bool { |
| 192 | + false |
| 193 | + } |
| 194 | + |
| 195 | + func getNewestToken(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> OSReadYourWriteData? { |
| 196 | + nil |
| 197 | + } |
| 198 | +} |
0 commit comments