-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathOneSignalUserTests.swift
More file actions
251 lines (196 loc) · 10.6 KB
/
Copy pathOneSignalUserTests.swift
File metadata and controls
251 lines (196 loc) · 10.6 KB
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
/*
Modified MIT License
Copyright 2024 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import XCTest
import OneSignalCore
import OneSignalCoreMocks
import OneSignalUserMocks
// Testable import OSCore to allow setting a different poll flush interval
@testable import OneSignalOSCore
@testable import OneSignalUser
final class OneSignalUserTests: XCTestCase {
override func setUpWithError() throws {
// TODO: Something like the existing [UnitTestCommonMethods beforeEachTest:self];
// TODO: Need to clear all data between tests for client, user manager, models, etc.
OneSignalCoreMocks.clearUserDefaults()
OneSignalUserMocks.reset()
// App ID is set because User Manager has guards against nil App ID
OneSignalIdentifiers.currentAppId = "test-app-id"
// Temp. logging to help debug during testing
OneSignalLog.setLogLevel(.LL_VERBOSE)
}
override func tearDownWithError() throws { }
// Comparable to Android test: "externalId is backed by the identity model"
func testLoginSetsExternalId() throws {
/* Setup */
OneSignalCoreImpl.setSharedClient(MockOneSignalClient())
/* When */
OneSignalUserManagerImpl.sharedInstance.login(externalId: "my-external-id", token: nil)
/* Then */
let identityModelStoreExternalId = OneSignalUserManagerImpl.sharedInstance.identityModelStore.getModel(key: OS_IDENTITY_MODEL_KEY)?.externalId
let userInstanceExternalId = OneSignalUserManagerImpl.sharedInstance.user.identityModel.externalId
XCTAssertEqual(identityModelStoreExternalId, "my-external-id")
XCTAssertEqual(userInstanceExternalId, "my-external-id")
}
/**
Regression test for the iOS prewarm fix (SDK-4725).
`start()` is gated by `OneSignalConfig.shouldAwaitAppIdAndLogMissingPrivacyConsent`, which now
also defers while device-protected storage is unreadable (iOS app prewarm before first unlock).
This verifies the contract the fix depends on: a `start()` that is gated out must be a no-op —
`hasCalledStart` stays false and no user is half-initialized — and a later `start()`, once
protected data is available, must proceed. The main app relies on that re-drive after it seeds
the protected-data flag and on `UIApplicationProtectedDataDidBecomeAvailable`; if the re-drive
ever stops taking effect (as it did when the flag was seeded asynchronously after the
synchronous `start()` during init), the user module never starts on a normal launch.
*/
func testStartDefersUntilProtectedDataAvailableThenProceeds() throws {
/* Setup */
let client = MockOneSignalClient()
MockUserRequests.setDefaultCreateAnonUserResponses(with: client)
OneSignalCoreImpl.setSharedClient(client)
let manager = OneSignalUserManagerImpl.sharedInstance
// Simulate protected data being unavailable (iOS prewarm before first unlock).
var protectedDataAvailable = false
OneSignalConfig.isProtectedDataAvailableProvider = { protectedDataAvailable }
defer { OneSignalConfig.isProtectedDataAvailableProvider = nil }
/* When protected data is unavailable, start() must be a no-op */
manager.start()
XCTAssertFalse(manager.hasCalledStart)
XCTAssertNil(manager._user)
/* When protected data becomes available, the re-driven start() must proceed */
protectedDataAvailable = true
manager.start()
XCTAssertTrue(manager.hasCalledStart)
XCTAssertNotNil(manager._user)
}
/**
Tests multiple user updates should be combined and sent together.
Multiple session times should be added.
Adding and removing multiple tags should be combined correctly.
Language uses the last language that is set.
Location uses the last point that is set.
*/
func testBasicCombiningUserUpdateDeltas_resultsInOneRequest() throws {
/* Setup */
OneSignalUserManagerImpl.sharedInstance.start()
let client = MockOneSignalClient()
MockUserRequests.setDefaultCreateAnonUserResponses(with: client)
OneSignalCoreImpl.setSharedClient(client)
// Increase flush interval to allow all the updates to batch
OSOperationRepo.sharedInstance.pollIntervalMilliseconds = 300
// Wait to let any pending flushes in the Operation Repo to run
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.1)
/* When */
OneSignalUserManagerImpl.sharedInstance.sendSessionTime(100)
OneSignalUserManagerImpl.sharedInstance.updatePropertiesDeltas(property: .session_count, value: 1, flush: false)
OneSignalUserManagerImpl.sharedInstance.setLanguage("lang_1")
OneSignalUserManagerImpl.sharedInstance.addTag(key: "tag_1", value: "value_1")
OneSignalUserManagerImpl.sharedInstance.setLanguage("lang_2")
OneSignalUserManagerImpl.sharedInstance.addTag(key: "tag_2", value: "value_2")
OneSignalUserManagerImpl.sharedInstance.sendSessionTime(50)
OneSignalUserManagerImpl.sharedInstance.setLocation(latitude: 123.123, longitude: 145.145)
OneSignalUserManagerImpl.sharedInstance.removeTag("tag_1")
OneSignalUserManagerImpl.sharedInstance.addTags(["a": "a", "b": "b", "c": "c"])
let purchases = [
["sku": "sku1", "amount": "1.25", "iso": "USD"],
["sku": "sku2", "amount": "3.99", "iso": "USD"]
]
OneSignalUserManagerImpl.sharedInstance.sendPurchases(purchases as [[String: AnyObject]])
OneSignalUserManagerImpl.sharedInstance.setLocation(latitude: 111.111, longitude: 222.222)
// This adds a `session_count` property with value of 1
// It also sets `refresh_device_metadata` to `true`
OneSignalUserManagerImpl.sharedInstance.startNewSession()
/* Then */
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 1)
let expectedPayload: [String: Any] = [
"deltas": [
"session_time": 150, // addition of 2 session times
"session_count": 2, // addition of 2 session counts
"purchases": purchases
],
"properties": [
"lat": 111.111,
"long": 222.222,
"language": "lang_2",
"tags": [
"tag_1": "",
"tag_2": "value_2",
"a": "a",
"b": "b",
"c": "c"
]
],
"refresh_device_metadata": true
]
// Assert there is an update user request with the expected payload
XCTAssertTrue(client.onlyOneRequest(
contains: "apps/test-app-id/users/by/onesignal_id/\(anonUserOSID)",
contains: expectedPayload)
)
}
/**
Unit test for the tag-merge primitive.
`mergeConfirmedTags` must overlay only the provided keys onto the local model: update existing
values, remove keys whose value is `""`, add new keys, and leave all other (e.g. backend-managed)
tags untouched. It must never wholesale-replace the tag dictionary.
*/
func testMergeConfirmedTags_mergesAndRemovesWithoutTouchingOtherTags() throws {
/* Setup */
let model = OSPropertiesModel(changeNotifier: OSEventProducer())
model.hydrate(["tags": ["keep": "1", "update": "old", "remove": "2"]])
/* When */
// "update" changes, "remove" is deleted (""), "add" is new; "keep" must be left untouched
model.mergeConfirmedTags(["update": "new", "remove": "", "add": "3"])
/* Then */
XCTAssertEqual(model.tags, ["keep": "1", "update": "new", "add": "3"])
}
/**
Regression test: `getTags()` returns `{}` after a concurrent, stale `FetchUser` overwrites the
local tag model.
A concurrent `FetchUser` whose response is missing a recently written tag clears the local tag
cache (`clearUserData()`) and hydrates without it. The `OSRequestUpdateProperties` 202 response
echoes the tags the server just confirmed, so merging those back into the local model must restore
the tags that the stale fetch cleared.
*/
func testUpdatePropertiesResponse_restoresTagsClearedByConcurrentFetch() throws {
/* Setup */
let client = MockOneSignalClient()
MockUserRequests.setDefaultCreateAnonUserResponses(with: client)
let tags = ["tag_a": "value_a", "tag_b": "value_b"]
MockUserRequests.setAddTagsResponse(with: client, tags: tags)
OneSignalCoreImpl.setSharedClient(client)
OneSignalUserManagerImpl.sharedInstance.start()
// Let the anonymous user be created so it has a OneSignal ID for the update request
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)
/* When */
// Tags are applied optimistically to the local model and queued as an update request
OneSignalUserManagerImpl.sharedInstance.addTags(tags)
// Simulate a concurrent, stale FetchUser clearing the local tag cache before the
// UpdateProperties 202 response is processed
OneSignalUserManagerImpl.sharedInstance.user.propertiesModel.clearData()
XCTAssertTrue(OneSignalUserManagerImpl.sharedInstance.getTags().isEmpty)
// Let the queued UpdateProperties request flush and its 202 echo be processed
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 1)
/* Then */
// The confirmed tags from the 202 response are merged back into the local model
XCTAssertEqual(OneSignalUserManagerImpl.sharedInstance.getTags(), tags)
}
}