@capgo/capacitor-updater 9.0.0 → 9.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CapgoCapacitorUpdater.podspec +3 -6
- package/Package.swift +30 -0
- package/README.md +2382 -292
- package/android/build.gradle +37 -15
- package/android/consumer-rules.pro +48 -0
- package/android/proguard-rules.pro +23 -0
- package/android/src/main/AndroidManifest.xml +0 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
- package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
- package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
- package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
- package/dist/docs.json +4431 -840
- package/dist/esm/definitions.d.ts +2607 -225
- package/dist/esm/definitions.js +103 -1
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/history.d.ts +1 -0
- package/dist/esm/history.js +283 -0
- package/dist/esm/history.js.map +1 -0
- package/dist/esm/index.d.ts +3 -2
- package/dist/esm/index.js +5 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/web.d.ts +53 -42
- package/dist/esm/web.js +180 -37
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +570 -37
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +570 -37
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
- package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
- package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
- package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
- package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
- package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
- package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
- package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
- package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
- package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
- package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
- package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
- package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
- package/package.json +80 -43
- package/scripts/builtin-hashes-lib.mjs +148 -0
- package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
- package/scripts/resolve-real-path.mjs +25 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
- package/ios/Plugin/BundleInfo.swift +0 -113
- package/ios/Plugin/BundleStatus.swift +0 -48
- package/ios/Plugin/CapacitorUpdater.swift +0 -858
- package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
- package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
- package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
- package/ios/Plugin/CryptoCipher.swift +0 -240
- /package/{LICENCE → LICENSE} +0 -0
- /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
- /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
- /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
|
@@ -0,0 +1,3905 @@
|
|
|
1
|
+
import XCTest
|
|
2
|
+
@testable import CapacitorUpdaterPlugin
|
|
3
|
+
import Capacitor
|
|
4
|
+
|
|
5
|
+
/// Since 9.0.0 the plugin emits every event as `updaterEvent` with `{ type, data }`. Test doubles
|
|
6
|
+
/// record the inner type and payload so assertions keep naming the event (`download`, `appReady`, ...).
|
|
7
|
+
func decodeUpdaterEvent(_ eventName: String, data: [String: Any]?) -> (name: String, data: [String: Any]?) {
|
|
8
|
+
guard eventName == CapacitorUpdaterPlugin.updaterEvent, let type = data?["type"] as? String else {
|
|
9
|
+
return (eventName, data)
|
|
10
|
+
}
|
|
11
|
+
return (type, data?["data"] as? [String: Any])
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
private let channelSelfTestURLString = "https://example.com/channel"
|
|
15
|
+
|
|
16
|
+
private func channelSelfTestURL() throws -> URL {
|
|
17
|
+
try XCTUnwrap(URL(string: channelSelfTestURLString))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
private func persistDefaultChannelTestUpdater(defaultChannel: String) -> ChannelRequestCapgoUpdater {
|
|
21
|
+
let updater = ChannelRequestCapgoUpdater()
|
|
22
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
23
|
+
updater.defaultChannel = defaultChannel
|
|
24
|
+
return updater
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
private class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
|
|
28
|
+
private(set) var notifiedEventNames: [String] = []
|
|
29
|
+
private(set) var notifiedEventPayloads: [String: [String: Any]] = [:]
|
|
30
|
+
private(set) var notifiedEventRetainValues: [String: Bool] = [:]
|
|
31
|
+
/// Raw bridge calls, before decoding the `updaterEvent` envelope.
|
|
32
|
+
private(set) var notifiedEvents: [(name: String, data: [String: Any]?, retain: Bool)] = []
|
|
33
|
+
|
|
34
|
+
/// Records the decoded updaterEvent type and payload; `notifiedEvents` keeps the raw bridge call.
|
|
35
|
+
override func notifyListeners(_ eventName: String, data: [String: Any]?, retainUntilConsumed retain: Bool) {
|
|
36
|
+
notifiedEvents.append((name: eventName, data: data, retain: retain))
|
|
37
|
+
let event = decodeUpdaterEvent(eventName, data: data)
|
|
38
|
+
notifiedEventNames.append(event.name)
|
|
39
|
+
notifiedEventRetainValues[event.name] = retain
|
|
40
|
+
if let payload = event.data {
|
|
41
|
+
notifiedEventPayloads[event.name] = payload
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
override func endBackGroundTask() {
|
|
46
|
+
// Intentionally blank: tests avoid touching UIApplication background-task APIs.
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
|
|
50
|
+
work()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
override func runGetLatestWork(_ work: @escaping () -> Void) {
|
|
54
|
+
work()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
override func sendReadyToJs(current: BundleInfo, msg: String) {
|
|
58
|
+
// Intentionally blank: tests assert native state transitions without JS bridge side effects.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private final class RealSendReadyCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
|
|
63
|
+
private let eventLock = NSLock()
|
|
64
|
+
private var _notifiedEventNames: [String] = []
|
|
65
|
+
private var _notifiedEventPayloads: [String: [String: Any]] = [:]
|
|
66
|
+
private var _appReadyNotifiedAt: Date?
|
|
67
|
+
private var _appReadyNotifiedOnMainThread: Bool?
|
|
68
|
+
private var _appReadyRetainUntilConsumed: Bool?
|
|
69
|
+
|
|
70
|
+
var appReadyNotifiedOnMainThread: Bool? {
|
|
71
|
+
eventLock.lock()
|
|
72
|
+
defer { eventLock.unlock() }
|
|
73
|
+
return _appReadyNotifiedOnMainThread
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
var appReadyRetainUntilConsumed: Bool? {
|
|
77
|
+
eventLock.lock()
|
|
78
|
+
defer { eventLock.unlock() }
|
|
79
|
+
return _appReadyRetainUntilConsumed
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
var appReadyNotifiedAt: Date? {
|
|
83
|
+
eventLock.lock()
|
|
84
|
+
defer { eventLock.unlock() }
|
|
85
|
+
return _appReadyNotifiedAt
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
var notifiedEventNames: [String] {
|
|
89
|
+
eventLock.lock()
|
|
90
|
+
defer { eventLock.unlock() }
|
|
91
|
+
return _notifiedEventNames
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
var notifiedEventPayloads: [String: [String: Any]] {
|
|
95
|
+
eventLock.lock()
|
|
96
|
+
defer { eventLock.unlock() }
|
|
97
|
+
return _notifiedEventPayloads
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// Records the decoded updaterEvent type and payload; `notifiedEvents` keeps the raw bridge call.
|
|
101
|
+
override func notifyListeners(_ eventName: String, data: [String: Any]?, retainUntilConsumed retain: Bool) {
|
|
102
|
+
let event = decodeUpdaterEvent(eventName, data: data)
|
|
103
|
+
eventLock.lock()
|
|
104
|
+
_notifiedEventNames.append(event.name)
|
|
105
|
+
if event.name == "appReady" {
|
|
106
|
+
_appReadyNotifiedAt = Date()
|
|
107
|
+
_appReadyNotifiedOnMainThread = Thread.isMainThread
|
|
108
|
+
_appReadyRetainUntilConsumed = retain
|
|
109
|
+
}
|
|
110
|
+
if let payload = event.data {
|
|
111
|
+
_notifiedEventPayloads[event.name] = payload
|
|
112
|
+
}
|
|
113
|
+
eventLock.unlock()
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
override func endBackGroundTask() {
|
|
117
|
+
// Intentionally blank: tests avoid touching UIApplication background-task APIs.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private class FreshDownloadCapgoUpdater: CapgoUpdater {
|
|
122
|
+
var currentBundleValue: BundleInfo!
|
|
123
|
+
var latestResponse = AppVersion()
|
|
124
|
+
var existingBundleValue: BundleInfo?
|
|
125
|
+
var downloadedBundleValue: BundleInfo?
|
|
126
|
+
var builtinBundleValue = BundleInfo(
|
|
127
|
+
id: BundleInfo.ID_BUILTIN,
|
|
128
|
+
version: "builtin",
|
|
129
|
+
status: .SUCCESS,
|
|
130
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
131
|
+
checksum: "builtin"
|
|
132
|
+
)
|
|
133
|
+
var onDownloadStart: (() -> Void)?
|
|
134
|
+
var onGetLatest: (() -> Void)?
|
|
135
|
+
var downloadCalls = 0
|
|
136
|
+
var deleteCalls = 0
|
|
137
|
+
var lastDeletedId: String?
|
|
138
|
+
var setNextBundleCalls = 0
|
|
139
|
+
var lastStatsVersionName: String?
|
|
140
|
+
var lastStatsMetadata: [String: String]?
|
|
141
|
+
var lastSetNextBundleId: String?
|
|
142
|
+
var setNextBundleSucceeds = true
|
|
143
|
+
var sentStatsActions: [String] = []
|
|
144
|
+
|
|
145
|
+
override func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
|
|
146
|
+
onGetLatest?()
|
|
147
|
+
return latestResponse
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
override func getCurrentBundle() -> BundleInfo {
|
|
151
|
+
currentBundleValue
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
override func getBundleInfoByVersionName(version: String) -> BundleInfo? {
|
|
155
|
+
guard existingBundleValue?.getVersionName() == version else {
|
|
156
|
+
return nil
|
|
157
|
+
}
|
|
158
|
+
return existingBundleValue
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
override func getBundleInfo(id: String?) -> BundleInfo {
|
|
162
|
+
if id == BundleInfo.ID_BUILTIN {
|
|
163
|
+
return builtinBundleValue
|
|
164
|
+
}
|
|
165
|
+
return currentBundleValue
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
override func downloadVerified(
|
|
169
|
+
url _: URL,
|
|
170
|
+
version _: String,
|
|
171
|
+
sessionKey _: String,
|
|
172
|
+
expectedChecksum _: String,
|
|
173
|
+
link _: String? = nil,
|
|
174
|
+
comment _: String? = nil
|
|
175
|
+
) throws -> BundleInfo {
|
|
176
|
+
downloadCalls += 1
|
|
177
|
+
onDownloadStart?()
|
|
178
|
+
if let downloadedBundleValue {
|
|
179
|
+
return downloadedBundleValue
|
|
180
|
+
}
|
|
181
|
+
throw NSError(domain: "CapacitorUpdaterPluginTests", code: 1)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
override func delete(id: String, removeInfo _: Bool) -> Bool {
|
|
185
|
+
deleteCalls += 1
|
|
186
|
+
lastDeletedId = id
|
|
187
|
+
if existingBundleValue?.getId() == id {
|
|
188
|
+
existingBundleValue = nil
|
|
189
|
+
}
|
|
190
|
+
return true
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
override func setNextBundle(next: String?) -> Bool {
|
|
194
|
+
setNextBundleCalls += 1
|
|
195
|
+
lastSetNextBundleId = next
|
|
196
|
+
return setNextBundleSucceeds
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
|
|
200
|
+
sentStatsActions.append(action)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String]) {
|
|
204
|
+
sentStatsActions.append(action)
|
|
205
|
+
lastStatsVersionName = versionName
|
|
206
|
+
lastStatsMetadata = metadata
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private final class SplashTimeoutCapgoUpdater: FreshDownloadCapgoUpdater {
|
|
211
|
+
var stagePendingReloadCalls = 0
|
|
212
|
+
private var queuedBundle: BundleInfo?
|
|
213
|
+
|
|
214
|
+
override func getNextBundle() -> BundleInfo? {
|
|
215
|
+
queuedBundle
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
override func setNextBundle(next: String?) -> Bool {
|
|
219
|
+
guard super.setNextBundle(next: next) else {
|
|
220
|
+
return false
|
|
221
|
+
}
|
|
222
|
+
guard let next else {
|
|
223
|
+
queuedBundle = nil
|
|
224
|
+
return true
|
|
225
|
+
}
|
|
226
|
+
let bundles = [existingBundleValue, downloadedBundleValue, builtinBundleValue].compactMap { $0 }
|
|
227
|
+
guard let bundle = bundles.first(where: { $0.getId() == next }) else {
|
|
228
|
+
return false
|
|
229
|
+
}
|
|
230
|
+
queuedBundle = bundle
|
|
231
|
+
return true
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
override func set(bundle: BundleInfo) -> Bool {
|
|
235
|
+
currentBundleValue = bundle
|
|
236
|
+
return true
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
override func stagePendingReload(bundle: BundleInfo) -> Bool {
|
|
240
|
+
stagePendingReloadCalls += 1
|
|
241
|
+
return true
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
override func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {
|
|
245
|
+
currentBundleValue = bundle
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private final class SplashTimeoutCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
|
|
250
|
+
var reloadCalls = 0
|
|
251
|
+
var resetCalls = 0
|
|
252
|
+
|
|
253
|
+
override func beginDownloadBackgroundTask() {}
|
|
254
|
+
override func checkAppReady() {}
|
|
255
|
+
|
|
256
|
+
override func reloadCurrentBundle() -> Bool {
|
|
257
|
+
reloadCalls += 1
|
|
258
|
+
return true
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
override func _reset(toLastSuccessful: Bool, usePendingBundle: Bool) -> Bool {
|
|
262
|
+
resetCalls += 1
|
|
263
|
+
return true
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private class HealthStatsCapgoUpdater: CapgoUpdater {
|
|
268
|
+
var currentBundleValue = BundleInfo(
|
|
269
|
+
id: "current-id",
|
|
270
|
+
version: "1.0.0",
|
|
271
|
+
status: .SUCCESS,
|
|
272
|
+
downloaded: Date(),
|
|
273
|
+
checksum: "abc123"
|
|
274
|
+
)
|
|
275
|
+
var sentStatsActions: [String] = []
|
|
276
|
+
var sentStatsMetadata: [[String: String]?] = []
|
|
277
|
+
var lastStatsVersionName: String?
|
|
278
|
+
var lastStatsOldVersionName: String?
|
|
279
|
+
var lastStatsMetadata: [String: String]?
|
|
280
|
+
var acknowledgeStats = true
|
|
281
|
+
|
|
282
|
+
override func getCurrentBundle() -> BundleInfo {
|
|
283
|
+
currentBundleValue
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
|
|
287
|
+
sentStatsActions.append(action)
|
|
288
|
+
sentStatsMetadata.append(nil)
|
|
289
|
+
lastStatsVersionName = versionName
|
|
290
|
+
lastStatsOldVersionName = oldVersionName
|
|
291
|
+
lastStatsMetadata = nil
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String]) {
|
|
295
|
+
sentStatsActions.append(action)
|
|
296
|
+
sentStatsMetadata.append(metadata)
|
|
297
|
+
lastStatsVersionName = versionName
|
|
298
|
+
lastStatsOldVersionName = oldVersionName
|
|
299
|
+
lastStatsMetadata = metadata
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String], onSent: @escaping () -> Void) {
|
|
303
|
+
sendStats(action: action, versionName: versionName, oldVersionName: oldVersionName, metadata: metadata)
|
|
304
|
+
if acknowledgeStats {
|
|
305
|
+
onSent()
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private final class ResettingHealthStatsCapgoUpdater: HealthStatsCapgoUpdater {
|
|
311
|
+
private let builtinBundle = BundleInfo(
|
|
312
|
+
id: BundleInfo.ID_BUILTIN,
|
|
313
|
+
version: "builtin",
|
|
314
|
+
status: .SUCCESS,
|
|
315
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
316
|
+
checksum: "builtin"
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
private(set) var autoResetCallCount = 0
|
|
320
|
+
private(set) var resetCallCount = 0
|
|
321
|
+
|
|
322
|
+
override func autoReset() {
|
|
323
|
+
// Keep the OTA fixture active: only the native-build reset may switch to builtin,
|
|
324
|
+
// so the test fails if app_launch_start is reported before that reset.
|
|
325
|
+
autoResetCallCount += 1
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
override func reset(isInternal _: Bool) {
|
|
329
|
+
resetCallCount += 1
|
|
330
|
+
currentBundleValue = builtinBundle
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private final class ChannelRequestCapgoUpdater: CapgoUpdater {
|
|
335
|
+
var requestResult: CapgoUpdater.RequestResult!
|
|
336
|
+
|
|
337
|
+
override func performRequest(_ request: URLRequest, label: String) -> CapgoUpdater.RequestResult {
|
|
338
|
+
requestResult
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private final class ResetTrackingCapgoUpdater: CapgoUpdater {
|
|
343
|
+
var currentBundleValue = BundleInfo(
|
|
344
|
+
id: "current-id",
|
|
345
|
+
version: "1.0.0",
|
|
346
|
+
status: .SUCCESS,
|
|
347
|
+
downloaded: Date(),
|
|
348
|
+
checksum: "abc123"
|
|
349
|
+
)
|
|
350
|
+
var fallbackBundleValue = BundleInfo(
|
|
351
|
+
id: BundleInfo.ID_BUILTIN,
|
|
352
|
+
version: "builtin",
|
|
353
|
+
status: .SUCCESS,
|
|
354
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
355
|
+
checksum: "builtin"
|
|
356
|
+
)
|
|
357
|
+
var nextBundleValue: BundleInfo?
|
|
358
|
+
var previewFallbackBundleValue: BundleInfo?
|
|
359
|
+
var stagedPreviewFallbackBundle: BundleInfo?
|
|
360
|
+
var resetCalled = false
|
|
361
|
+
var resetIsInternal = false
|
|
362
|
+
var prepareResetStateForTransitionCalled = false
|
|
363
|
+
var prepareResetStateForTransitionCalls = 0
|
|
364
|
+
var finalizeResetTransitionCalled = false
|
|
365
|
+
var finalizeResetTransitionCalls = 0
|
|
366
|
+
var finalizeResetTransitionPreviousBundleName: String?
|
|
367
|
+
var finalizeResetTransitionIsInternal = true
|
|
368
|
+
var canSetResult = true
|
|
369
|
+
var setResult = true
|
|
370
|
+
var canSetCalls = 0
|
|
371
|
+
var setCalls = 0
|
|
372
|
+
var listedBundles: [BundleInfo] = []
|
|
373
|
+
var stagePendingReloadResult = true
|
|
374
|
+
var stagePendingReloadCalls = 0
|
|
375
|
+
var stagePreviewFallbackReloadResult = true
|
|
376
|
+
var stagePreviewFallbackReloadCalls = 0
|
|
377
|
+
var finalizePendingReloadCalls = 0
|
|
378
|
+
var finalizedPendingReloadBundle: BundleInfo?
|
|
379
|
+
var finalizePendingReloadPreviousBundleName: String?
|
|
380
|
+
var setPreviewFallbackBundleCalls = 0
|
|
381
|
+
var lastPreviewFallbackBundle: String?
|
|
382
|
+
var restoreResetStateCalls = 0
|
|
383
|
+
let capturedState = ResetState(
|
|
384
|
+
currentBundlePath: "/stored/current",
|
|
385
|
+
fallbackBundleId: "fallback-id",
|
|
386
|
+
nextBundleId: "next-id"
|
|
387
|
+
)
|
|
388
|
+
var restoredState: ResetState?
|
|
389
|
+
|
|
390
|
+
override func getCurrentBundle() -> BundleInfo {
|
|
391
|
+
currentBundleValue
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
override func getCurrentBundleId() -> String {
|
|
395
|
+
currentBundleValue.getId()
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
override func getFallbackBundle() -> BundleInfo {
|
|
399
|
+
fallbackBundleValue
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
override func getNextBundle() -> BundleInfo? {
|
|
403
|
+
nextBundleValue
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
override func list(raw _: Bool = false) -> [BundleInfo] {
|
|
407
|
+
listedBundles
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
override func getPreviewFallbackBundle() -> BundleInfo? {
|
|
411
|
+
previewFallbackBundleValue
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
override func getBundleInfo(id: String?) -> BundleInfo {
|
|
415
|
+
if id == BundleInfo.ID_BUILTIN {
|
|
416
|
+
return BundleInfo(
|
|
417
|
+
id: BundleInfo.ID_BUILTIN,
|
|
418
|
+
version: "builtin",
|
|
419
|
+
status: .SUCCESS,
|
|
420
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
421
|
+
checksum: "builtin"
|
|
422
|
+
)
|
|
423
|
+
}
|
|
424
|
+
if id == currentBundleValue.getId() {
|
|
425
|
+
return currentBundleValue
|
|
426
|
+
}
|
|
427
|
+
if id == fallbackBundleValue.getId() {
|
|
428
|
+
return fallbackBundleValue
|
|
429
|
+
}
|
|
430
|
+
if let previewFallbackBundleValue, id == previewFallbackBundleValue.getId() {
|
|
431
|
+
return previewFallbackBundleValue
|
|
432
|
+
}
|
|
433
|
+
return BundleInfo(id: id ?? "missing-id", version: id ?? "missing", status: .PENDING, downloaded: Date(), checksum: "")
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
override func canSet(bundle: BundleInfo) -> Bool {
|
|
437
|
+
canSetCalls += 1
|
|
438
|
+
return canSetResult
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
override func captureResetState() -> ResetState {
|
|
442
|
+
capturedState
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
override func restoreResetState(_ state: ResetState) {
|
|
446
|
+
restoreResetStateCalls += 1
|
|
447
|
+
restoredState = state
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
override func set(bundle: BundleInfo) -> Bool {
|
|
451
|
+
setCalls += 1
|
|
452
|
+
return setResult
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
override func setNextBundle(next: String?) -> Bool {
|
|
456
|
+
true
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
override func stagePendingReload(bundle: BundleInfo) -> Bool {
|
|
460
|
+
stagePendingReloadCalls += 1
|
|
461
|
+
return stagePendingReloadResult
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
override func stagePreviewFallbackReload(bundle: BundleInfo) -> Bool {
|
|
465
|
+
stagePreviewFallbackReloadCalls += 1
|
|
466
|
+
stagedPreviewFallbackBundle = bundle
|
|
467
|
+
return stagePreviewFallbackReloadResult
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
override func setPreviewFallbackBundle(fallback: String?) -> Bool {
|
|
471
|
+
setPreviewFallbackBundleCalls += 1
|
|
472
|
+
lastPreviewFallbackBundle = fallback
|
|
473
|
+
if let fallback {
|
|
474
|
+
previewFallbackBundleValue = getBundleInfo(id: fallback)
|
|
475
|
+
} else {
|
|
476
|
+
previewFallbackBundleValue = nil
|
|
477
|
+
}
|
|
478
|
+
return true
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
override func delete(id _: String, removeInfo _: Bool) -> Bool {
|
|
482
|
+
true
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
override func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {
|
|
486
|
+
finalizePendingReloadCalls += 1
|
|
487
|
+
finalizedPendingReloadBundle = bundle
|
|
488
|
+
finalizePendingReloadPreviousBundleName = previousBundleName
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
override func reset(isInternal: Bool) {
|
|
492
|
+
resetCalled = true
|
|
493
|
+
resetIsInternal = isInternal
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
override func prepareResetStateForTransition() {
|
|
497
|
+
prepareResetStateForTransitionCalled = true
|
|
498
|
+
prepareResetStateForTransitionCalls += 1
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
override func finalizeResetTransition(previousBundleName: String, isInternal: Bool) {
|
|
502
|
+
finalizeResetTransitionCalled = true
|
|
503
|
+
finalizeResetTransitionCalls += 1
|
|
504
|
+
finalizeResetTransitionPreviousBundleName = previousBundleName
|
|
505
|
+
finalizeResetTransitionIsInternal = isInternal
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
private final class ResetTestableCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
|
|
510
|
+
override func canPerformResetTransition() -> Bool {
|
|
511
|
+
true
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
override func reloadCurrentBundle() -> Bool {
|
|
515
|
+
true
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
override func reloadWithoutWaitingForAppReady() -> Bool {
|
|
519
|
+
true
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
private final class ReloadBypassCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
|
|
524
|
+
override func reloadCurrentBundle() -> Bool {
|
|
525
|
+
true
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
override func reloadWithoutWaitingForAppReady() -> Bool {
|
|
529
|
+
true
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
private final class ReloadFailureCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
|
|
534
|
+
var restoreLiveBundleStateAfterFailedReloadCalls = 0
|
|
535
|
+
|
|
536
|
+
override func canPerformResetTransition() -> Bool {
|
|
537
|
+
true
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
override func reloadCurrentBundle() -> Bool {
|
|
541
|
+
false
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
override func reloadWithoutWaitingForAppReady() -> Bool {
|
|
545
|
+
false
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
override func restoreLiveBundleStateAfterFailedReload() {
|
|
549
|
+
restoreLiveBundleStateAfterFailedReloadCalls += 1
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
private final class SequenceReloadCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
|
|
554
|
+
var reloadResults = [false]
|
|
555
|
+
private var reloadCallCount = 0
|
|
556
|
+
var restoreLiveBundleStateAfterFailedReloadCalls = 0
|
|
557
|
+
|
|
558
|
+
override func canPerformResetTransition() -> Bool {
|
|
559
|
+
true
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
override func reloadCurrentBundle() -> Bool {
|
|
563
|
+
let resultIndex = min(reloadCallCount, reloadResults.count - 1)
|
|
564
|
+
reloadCallCount += 1
|
|
565
|
+
return reloadResults[resultIndex]
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
override func restoreLiveBundleStateAfterFailedReload() {
|
|
569
|
+
restoreLiveBundleStateAfterFailedReloadCalls += 1
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
private final class PendingReloadFinalizeCapgoUpdater: CapgoUpdater {
|
|
574
|
+
var bundleInfos: [String: BundleInfo] = [:]
|
|
575
|
+
var lastStatsAction: String?
|
|
576
|
+
var lastStatsVersionName: String?
|
|
577
|
+
var lastStatsOldVersionName: String?
|
|
578
|
+
|
|
579
|
+
override func getBundleInfo(id: String?) -> BundleInfo {
|
|
580
|
+
bundleInfos[id!]!
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
override func saveBundleInfo(id: String, bundle: BundleInfo?) -> Bool {
|
|
584
|
+
bundleInfos[id] = bundle
|
|
585
|
+
return true
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
|
|
589
|
+
lastStatsAction = action
|
|
590
|
+
lastStatsVersionName = versionName
|
|
591
|
+
lastStatsOldVersionName = oldVersionName
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
class CapacitorUpdaterTests: XCTestCase {
|
|
596
|
+
|
|
597
|
+
var plugin: CapacitorUpdaterPlugin!
|
|
598
|
+
var implementation: CapgoUpdater!
|
|
599
|
+
private let delayPreferencesKey = DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
|
|
600
|
+
private let backgroundTimestampKey = DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY
|
|
601
|
+
private let onlyDownloadChecksum = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
|
602
|
+
|
|
603
|
+
override func setUp() {
|
|
604
|
+
super.setUp()
|
|
605
|
+
plugin = TestableCapacitorUpdaterPlugin()
|
|
606
|
+
implementation = CapgoUpdater()
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
override func tearDown() {
|
|
610
|
+
plugin = nil
|
|
611
|
+
implementation = nil
|
|
612
|
+
super.tearDown()
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/// Clearing a session-only ID must also remove an ID saved before persistence was disabled.
|
|
616
|
+
func testSetCustomIdClearsStoredValueRegardlessOfPersistence() throws {
|
|
617
|
+
let defaults = UserDefaults.standard
|
|
618
|
+
let key = "CapacitorUpdater.customId"
|
|
619
|
+
let previousValue = defaults.object(forKey: key)
|
|
620
|
+
defer {
|
|
621
|
+
defaults.set(previousValue, forKey: key)
|
|
622
|
+
defaults.synchronize()
|
|
623
|
+
}
|
|
624
|
+
for persistAfterSaving in [false, true] {
|
|
625
|
+
let testPlugin = CapacitorUpdaterPlugin()
|
|
626
|
+
var resolved = 0
|
|
627
|
+
for customId in ["alice", "bob", ""] {
|
|
628
|
+
if customId != "alice" {
|
|
629
|
+
testPlugin.persistCustomId = persistAfterSaving
|
|
630
|
+
}
|
|
631
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
632
|
+
callbackId: "custom-id-test",
|
|
633
|
+
options: ["customId": customId],
|
|
634
|
+
success: { _, _ in resolved += 1 },
|
|
635
|
+
error: { _ in XCTFail("setCustomId should resolve") }
|
|
636
|
+
))
|
|
637
|
+
testPlugin.setCustomId(call)
|
|
638
|
+
XCTAssertEqual(testPlugin.implementation.customId, customId)
|
|
639
|
+
if customId.isEmpty {
|
|
640
|
+
testPlugin.persistCustomId = true
|
|
641
|
+
XCTAssertNil(defaults.string(forKey: key))
|
|
642
|
+
} else {
|
|
643
|
+
let expected = persistAfterSaving || customId == "alice" ? customId : "alice"
|
|
644
|
+
XCTAssertEqual(defaults.string(forKey: key), expected)
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
XCTAssertEqual(resolved, 3)
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
private func makeOnlyDownloadBundle(
|
|
652
|
+
id: String = "downloaded-id",
|
|
653
|
+
version: String = "2.0.0",
|
|
654
|
+
status: BundleStatus = .PENDING,
|
|
655
|
+
checksum: String? = nil
|
|
656
|
+
) -> BundleInfo {
|
|
657
|
+
BundleInfo(
|
|
658
|
+
id: id,
|
|
659
|
+
version: version,
|
|
660
|
+
status: status,
|
|
661
|
+
downloaded: Date(),
|
|
662
|
+
checksum: checksum ?? onlyDownloadChecksum
|
|
663
|
+
)
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
private func makeOnlyDownloadLatest() -> AppVersion {
|
|
667
|
+
let latest = AppVersion()
|
|
668
|
+
latest.version = "2.0.0"
|
|
669
|
+
latest.url = "https://example.com/update.zip"
|
|
670
|
+
latest.checksum = onlyDownloadChecksum
|
|
671
|
+
return latest
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
private func makeOnlyDownloadPlugin(
|
|
675
|
+
current: BundleInfo? = nil,
|
|
676
|
+
existing: BundleInfo? = nil,
|
|
677
|
+
downloaded: BundleInfo? = nil
|
|
678
|
+
) -> (TestableCapacitorUpdaterPlugin, FreshDownloadCapgoUpdater) {
|
|
679
|
+
let freshDownloadImplementation = FreshDownloadCapgoUpdater()
|
|
680
|
+
freshDownloadImplementation.currentBundleValue = current ?? makeOnlyDownloadBundle(
|
|
681
|
+
id: "test-id",
|
|
682
|
+
version: "1.0.0",
|
|
683
|
+
status: .SUCCESS,
|
|
684
|
+
checksum: "abc123"
|
|
685
|
+
)
|
|
686
|
+
freshDownloadImplementation.latestResponse = makeOnlyDownloadLatest()
|
|
687
|
+
freshDownloadImplementation.existingBundleValue = existing
|
|
688
|
+
freshDownloadImplementation.downloadedBundleValue = downloaded
|
|
689
|
+
|
|
690
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
691
|
+
testPlugin.implementation = freshDownloadImplementation
|
|
692
|
+
testPlugin.setAutoUpdateModeForTesting("onlyDownload")
|
|
693
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
694
|
+
CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
|
|
695
|
+
|
|
696
|
+
return (testPlugin, freshDownloadImplementation)
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
private func makeAtBackgroundPlugin(
|
|
700
|
+
existing: BundleInfo? = nil,
|
|
701
|
+
downloaded: BundleInfo? = nil,
|
|
702
|
+
implementation: FreshDownloadCapgoUpdater = FreshDownloadCapgoUpdater()
|
|
703
|
+
) -> (TestableCapacitorUpdaterPlugin, FreshDownloadCapgoUpdater) {
|
|
704
|
+
implementation.currentBundleValue = BundleInfo(
|
|
705
|
+
id: "test-id",
|
|
706
|
+
version: "1.0.0",
|
|
707
|
+
status: .SUCCESS,
|
|
708
|
+
downloaded: Date(),
|
|
709
|
+
checksum: "abc123"
|
|
710
|
+
)
|
|
711
|
+
implementation.latestResponse = makeOnlyDownloadLatest()
|
|
712
|
+
implementation.existingBundleValue = existing
|
|
713
|
+
implementation.downloadedBundleValue = downloaded
|
|
714
|
+
|
|
715
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
716
|
+
testPlugin.implementation = implementation
|
|
717
|
+
testPlugin.setAutoUpdateModeForTesting("atBackground")
|
|
718
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
719
|
+
CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
|
|
720
|
+
|
|
721
|
+
return (testPlugin, implementation)
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
private func assertOnlyDownloadLeavesUpdateManual(
|
|
725
|
+
plugin testPlugin: TestableCapacitorUpdaterPlugin,
|
|
726
|
+
implementation freshDownloadImplementation: FreshDownloadCapgoUpdater
|
|
727
|
+
) {
|
|
728
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateAvailable"))
|
|
729
|
+
XCTAssertEqual(testPlugin.notifiedEventRetainValues["updateAvailable"], true)
|
|
730
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("noNeedUpdate"))
|
|
731
|
+
XCTAssertEqual(freshDownloadImplementation.setNextBundleCalls, 0)
|
|
732
|
+
XCTAssertNil(freshDownloadImplementation.lastSetNextBundleId)
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
private func makeDelayUpdateUtils() throws -> DelayUpdateUtils {
|
|
736
|
+
let logger = Logger(withTag: "TestLogger")
|
|
737
|
+
let version = try CapgoSemanticVersion("1.0.0")
|
|
738
|
+
return DelayUpdateUtils(currentVersionNative: version, logger: logger)
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
private let delayConditionModeKey = DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES
|
|
742
|
+
|
|
743
|
+
private func clearDelayStorage() {
|
|
744
|
+
UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
|
|
745
|
+
UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
|
|
746
|
+
UserDefaults.standard.removeObject(forKey: backgroundTimestampKey)
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
func testShouldReportUncleanForegroundExitOnlyOnce() {
|
|
750
|
+
XCTAssertTrue(AppHealthTracker.shouldReportUncleanForegroundExit(
|
|
751
|
+
previousSessionId: "session-1",
|
|
752
|
+
lastReportedSessionId: nil,
|
|
753
|
+
wasForeground: true
|
|
754
|
+
))
|
|
755
|
+
XCTAssertFalse(AppHealthTracker.shouldReportUncleanForegroundExit(
|
|
756
|
+
previousSessionId: "session-1",
|
|
757
|
+
lastReportedSessionId: "session-1",
|
|
758
|
+
wasForeground: true
|
|
759
|
+
))
|
|
760
|
+
XCTAssertFalse(AppHealthTracker.shouldReportUncleanForegroundExit(
|
|
761
|
+
previousSessionId: "session-2",
|
|
762
|
+
lastReportedSessionId: nil,
|
|
763
|
+
wasForeground: false
|
|
764
|
+
))
|
|
765
|
+
XCTAssertFalse(AppHealthTracker.shouldReportUncleanForegroundExit(
|
|
766
|
+
previousSessionId: "",
|
|
767
|
+
lastReportedSessionId: nil,
|
|
768
|
+
wasForeground: true
|
|
769
|
+
))
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
func testReportsPreviousUncleanForegroundExitAsAppCrashStat() {
|
|
773
|
+
let defaults = UserDefaults.standard
|
|
774
|
+
let keys = [
|
|
775
|
+
"CapacitorUpdater.appSessionId",
|
|
776
|
+
"CapacitorUpdater.appSessionForeground",
|
|
777
|
+
"CapacitorUpdater.appSessionStartedAt",
|
|
778
|
+
"CapacitorUpdater.lastReportedUncleanSessionId"
|
|
779
|
+
]
|
|
780
|
+
keys.forEach { defaults.removeObject(forKey: $0) }
|
|
781
|
+
defer { keys.forEach { defaults.removeObject(forKey: $0) } }
|
|
782
|
+
|
|
783
|
+
defaults.set("session-unclean", forKey: "CapacitorUpdater.appSessionId")
|
|
784
|
+
defaults.set(true, forKey: "CapacitorUpdater.appSessionForeground")
|
|
785
|
+
defaults.set("1760000000000", forKey: "CapacitorUpdater.appSessionStartedAt")
|
|
786
|
+
|
|
787
|
+
let implementation = HealthStatsCapgoUpdater()
|
|
788
|
+
let tracker = AppHealthTracker(implementation: implementation)
|
|
789
|
+
|
|
790
|
+
tracker.reportPreviousUncleanForegroundExit()
|
|
791
|
+
|
|
792
|
+
XCTAssertEqual(implementation.sentStatsActions, ["app_crash"])
|
|
793
|
+
XCTAssertEqual(implementation.lastStatsVersionName, "1.0.0")
|
|
794
|
+
XCTAssertEqual(implementation.lastStatsOldVersionName, "")
|
|
795
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["exit_reason"], "unclean_foreground_exit")
|
|
796
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["exit_source"], "ios_session_marker")
|
|
797
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["previous_session_id"], "session-unclean")
|
|
798
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["session_started_at"], "1760000000000")
|
|
799
|
+
|
|
800
|
+
implementation.sentStatsActions.removeAll()
|
|
801
|
+
tracker.reportPreviousUncleanForegroundExit()
|
|
802
|
+
|
|
803
|
+
XCTAssertTrue(implementation.sentStatsActions.isEmpty)
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
func testReportsMemoryWarningAsHealthStat() {
|
|
807
|
+
let implementation = HealthStatsCapgoUpdater()
|
|
808
|
+
let tracker = AppHealthTracker(implementation: implementation)
|
|
809
|
+
|
|
810
|
+
tracker.reportMemoryWarning()
|
|
811
|
+
|
|
812
|
+
XCTAssertEqual(implementation.sentStatsActions, ["app_memory_warning"])
|
|
813
|
+
XCTAssertEqual(implementation.lastStatsVersionName, "1.0.0")
|
|
814
|
+
XCTAssertEqual(implementation.lastStatsOldVersionName, "")
|
|
815
|
+
XCTAssertEqual(implementation.lastStatsMetadata, ["source": "ios_memory_warning"])
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
func testMapsWebViewErrorTypesToStatsActions() {
|
|
819
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "javascript_error"), "webview_javascript_error")
|
|
820
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "unhandled_rejection"), "webview_unhandled_rejection")
|
|
821
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "resource_error"), "webview_resource_error")
|
|
822
|
+
XCTAssertEqual(
|
|
823
|
+
WebViewStatsReporter.statsAction(for: "security_policy_violation"),
|
|
824
|
+
"webview_security_policy_violation"
|
|
825
|
+
)
|
|
826
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "webview_unclean_restart"), "webview_unclean_restart")
|
|
827
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "render_process_gone"), "webview_render_process_gone")
|
|
828
|
+
XCTAssertEqual(
|
|
829
|
+
WebViewStatsReporter.statsAction(for: "web_content_process_terminated"),
|
|
830
|
+
"webview_content_process_terminated"
|
|
831
|
+
)
|
|
832
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "webview_dom_content_loaded"), "webview_dom_content_loaded")
|
|
833
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "webview_page_loaded"), "webview_page_loaded")
|
|
834
|
+
XCTAssertEqual(WebViewStatsReporter.statsAction(for: "unknown"), "webview_javascript_error")
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
func testBuildWebViewErrorMetadataKeepsUsefulFields() {
|
|
838
|
+
let metadata = WebViewStatsReporter.buildMetadata([
|
|
839
|
+
"type": "javascript_error",
|
|
840
|
+
"message": "boom",
|
|
841
|
+
"source": "app.js",
|
|
842
|
+
"line": "10",
|
|
843
|
+
"column": "20",
|
|
844
|
+
"stack": String(repeating: "x", count: 3_000),
|
|
845
|
+
"href": "capacitor://localhost",
|
|
846
|
+
"session_id": "session-1",
|
|
847
|
+
"duration_ms": "123",
|
|
848
|
+
"page_started_at": "456"
|
|
849
|
+
])
|
|
850
|
+
|
|
851
|
+
XCTAssertEqual(metadata["error_type"], "javascript_error")
|
|
852
|
+
XCTAssertEqual(metadata["message"], "boom")
|
|
853
|
+
XCTAssertEqual(metadata["source"], "app.js")
|
|
854
|
+
XCTAssertEqual(metadata["line"], "10")
|
|
855
|
+
XCTAssertEqual(metadata["column"], "20")
|
|
856
|
+
XCTAssertEqual(metadata["href"], "capacitor://localhost")
|
|
857
|
+
XCTAssertEqual(metadata["session_id"], "session-1")
|
|
858
|
+
XCTAssertEqual(metadata["duration_ms"], "123")
|
|
859
|
+
XCTAssertEqual(metadata["page_started_at"], "456")
|
|
860
|
+
XCTAssertEqual(metadata["stack"]?.count, 2_048)
|
|
861
|
+
XCTAssertNil(metadata["tag_name"])
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
func testReportWebViewLoadStatsForwardsTimingMetadata() throws {
|
|
865
|
+
let implementation = HealthStatsCapgoUpdater()
|
|
866
|
+
let reporter = WebViewStatsReporter(implementation: implementation)
|
|
867
|
+
var resolved = false
|
|
868
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
869
|
+
callbackId: "webview-load-stat",
|
|
870
|
+
options: [
|
|
871
|
+
"type": "webview_dom_content_loaded",
|
|
872
|
+
"message": "WebView DOM content loaded",
|
|
873
|
+
"duration_ms": "123",
|
|
874
|
+
"page_started_at": "456",
|
|
875
|
+
"session_id": "session-1"
|
|
876
|
+
],
|
|
877
|
+
success: { _, _ in
|
|
878
|
+
resolved = true
|
|
879
|
+
},
|
|
880
|
+
error: { _ in
|
|
881
|
+
XCTFail("reportError should resolve successful WebView load stats")
|
|
882
|
+
}
|
|
883
|
+
))
|
|
884
|
+
|
|
885
|
+
reporter.reportError(call)
|
|
886
|
+
|
|
887
|
+
XCTAssertTrue(resolved)
|
|
888
|
+
XCTAssertEqual(implementation.sentStatsActions, ["webview_dom_content_loaded"])
|
|
889
|
+
XCTAssertEqual(implementation.lastStatsVersionName, "1.0.0")
|
|
890
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["duration_ms"], "123")
|
|
891
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["page_started_at"], "456")
|
|
892
|
+
XCTAssertEqual(implementation.lastStatsMetadata?["session_id"], "session-1")
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
func testBuildWebViewErrorMetadataSanitizesUrlValues() {
|
|
896
|
+
let scheme = "https"
|
|
897
|
+
let host = "example.com"
|
|
898
|
+
let userInfo = ["user", "value"].joined(separator: ":") + "@"
|
|
899
|
+
let sourceQuery = "cache=123"
|
|
900
|
+
let hrefQuery = "debug=true"
|
|
901
|
+
let metadata = WebViewStatsReporter.buildMetadata([
|
|
902
|
+
"source": "\(scheme)://\(userInfo)\(host):8443/assets/app.js?\(sourceQuery)#L10",
|
|
903
|
+
"href": "\(scheme)://\(host)/users/123456/dashboard?\(hrefQuery)#frag",
|
|
904
|
+
"previous_href": "app.js?\(sourceQuery)#frag"
|
|
905
|
+
])
|
|
906
|
+
|
|
907
|
+
XCTAssertEqual(metadata["source"], "\(scheme)://\(host):8443/assets/app.js")
|
|
908
|
+
XCTAssertEqual(metadata["href"], "\(scheme)://\(host)/users/redacted/dashboard")
|
|
909
|
+
XCTAssertEqual(metadata["previous_href"], "app.js")
|
|
910
|
+
XCTAssertFalse(metadata["source"]?.contains(sourceQuery) ?? true)
|
|
911
|
+
XCTAssertFalse(metadata["href"]?.contains(hrefQuery) ?? true)
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
func testWebViewStatsReporterScriptCapturesRuntimeAndRestartSignals() {
|
|
915
|
+
let script = WebViewStatsReporter.script
|
|
916
|
+
|
|
917
|
+
XCTAssertTrue(script.contains("unhandledrejection"))
|
|
918
|
+
XCTAssertTrue(script.contains("resource_error"))
|
|
919
|
+
XCTAssertTrue(script.contains("securitypolicyviolation"))
|
|
920
|
+
XCTAssertTrue(script.contains("webview_unclean_restart"))
|
|
921
|
+
XCTAssertTrue(script.contains("webview_dom_content_loaded"))
|
|
922
|
+
XCTAssertTrue(script.contains("webview_page_loaded"))
|
|
923
|
+
XCTAssertTrue(script.contains("reportWebViewError"))
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
private func makeDelayConditionsJSON() throws -> String {
|
|
927
|
+
let conditions = [
|
|
928
|
+
["kind": "kill", "value": ""],
|
|
929
|
+
["kind": "background", "value": "5000"]
|
|
930
|
+
]
|
|
931
|
+
let data = try JSONSerialization.data(withJSONObject: conditions)
|
|
932
|
+
return try XCTUnwrap(String(data: data, encoding: .utf8))
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// MARK: - BundleInfo Tests
|
|
936
|
+
|
|
937
|
+
func testBundleInfoInitialization() {
|
|
938
|
+
let bundleInfo = BundleInfo(
|
|
939
|
+
id: "test-id",
|
|
940
|
+
version: "1.0.0",
|
|
941
|
+
status: .PENDING,
|
|
942
|
+
downloaded: Date(),
|
|
943
|
+
checksum: "abc123"
|
|
944
|
+
)
|
|
945
|
+
|
|
946
|
+
XCTAssertEqual(bundleInfo.getId(), "test-id")
|
|
947
|
+
XCTAssertEqual(bundleInfo.getVersionName(), "1.0.0")
|
|
948
|
+
XCTAssertEqual(bundleInfo.getStatus(), "pending")
|
|
949
|
+
XCTAssertEqual(bundleInfo.getChecksum(), "abc123")
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
func testBundleInfoBuiltin() {
|
|
953
|
+
let bundleInfo = BundleInfo(
|
|
954
|
+
id: BundleInfo.ID_BUILTIN,
|
|
955
|
+
version: "1.0.0",
|
|
956
|
+
status: .SUCCESS,
|
|
957
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
958
|
+
checksum: "abc123"
|
|
959
|
+
)
|
|
960
|
+
|
|
961
|
+
XCTAssertTrue(bundleInfo.isBuiltin())
|
|
962
|
+
XCTAssertFalse(bundleInfo.isUnknown())
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
func testBundleInfoUnknown() {
|
|
966
|
+
let bundleInfo = BundleInfo(
|
|
967
|
+
id: BundleInfo.VERSION_UNKNOWN,
|
|
968
|
+
version: "1.0.0",
|
|
969
|
+
status: .SUCCESS,
|
|
970
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
971
|
+
checksum: "abc123"
|
|
972
|
+
)
|
|
973
|
+
|
|
974
|
+
XCTAssertTrue(bundleInfo.isUnknown())
|
|
975
|
+
XCTAssertFalse(bundleInfo.isBuiltin())
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
func testBundleInfoErrorStatus() {
|
|
979
|
+
let bundleInfo = BundleInfo(
|
|
980
|
+
id: "test-id",
|
|
981
|
+
version: "1.0.0",
|
|
982
|
+
status: .ERROR,
|
|
983
|
+
downloaded: Date(),
|
|
984
|
+
checksum: "abc123"
|
|
985
|
+
)
|
|
986
|
+
|
|
987
|
+
XCTAssertTrue(bundleInfo.isErrorStatus())
|
|
988
|
+
XCTAssertFalse(bundleInfo.isDeleted())
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
func testBundleInfoDeletedStatus() {
|
|
992
|
+
let bundleInfo = BundleInfo(
|
|
993
|
+
id: "test-id",
|
|
994
|
+
version: "1.0.0",
|
|
995
|
+
status: .DELETED,
|
|
996
|
+
downloaded: Date(),
|
|
997
|
+
checksum: "abc123"
|
|
998
|
+
)
|
|
999
|
+
|
|
1000
|
+
XCTAssertTrue(bundleInfo.isDeleted())
|
|
1001
|
+
XCTAssertFalse(bundleInfo.isErrorStatus())
|
|
1002
|
+
XCTAssertFalse(bundleInfo.isDownloading())
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
func testBundleInfoDownloadingStatus() {
|
|
1006
|
+
let bundleInfo = BundleInfo(
|
|
1007
|
+
id: "stale-id",
|
|
1008
|
+
version: "2.0.0",
|
|
1009
|
+
status: .DOWNLOADING,
|
|
1010
|
+
downloaded: Date(),
|
|
1011
|
+
checksum: ""
|
|
1012
|
+
)
|
|
1013
|
+
|
|
1014
|
+
XCTAssertTrue(bundleInfo.isDownloading())
|
|
1015
|
+
XCTAssertTrue(bundleInfo.isDownloaded())
|
|
1016
|
+
XCTAssertFalse(bundleInfo.isDeleted())
|
|
1017
|
+
XCTAssertFalse(bundleInfo.isDeleting())
|
|
1018
|
+
XCTAssertFalse(bundleInfo.isErrorStatus())
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
func testShouldRetryDownloadForIncompleteExistingBundles() {
|
|
1022
|
+
let pending = BundleInfo(
|
|
1023
|
+
id: "pending-id",
|
|
1024
|
+
version: "2.0.0",
|
|
1025
|
+
status: .PENDING,
|
|
1026
|
+
downloaded: Date(),
|
|
1027
|
+
checksum: "abc123"
|
|
1028
|
+
)
|
|
1029
|
+
let downloading = BundleInfo(
|
|
1030
|
+
id: "downloading-id",
|
|
1031
|
+
version: "2.0.0",
|
|
1032
|
+
status: .DOWNLOADING,
|
|
1033
|
+
downloaded: Date(),
|
|
1034
|
+
checksum: ""
|
|
1035
|
+
)
|
|
1036
|
+
let deleting = BundleInfo(
|
|
1037
|
+
id: "deleting-id",
|
|
1038
|
+
version: "2.0.0",
|
|
1039
|
+
status: .DELETING,
|
|
1040
|
+
downloaded: Date(),
|
|
1041
|
+
checksum: "abc123"
|
|
1042
|
+
)
|
|
1043
|
+
let deleted = BundleInfo(
|
|
1044
|
+
id: "deleted-id",
|
|
1045
|
+
version: "2.0.0",
|
|
1046
|
+
status: .DELETED,
|
|
1047
|
+
downloaded: Date(),
|
|
1048
|
+
checksum: "abc123"
|
|
1049
|
+
)
|
|
1050
|
+
|
|
1051
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(pending))
|
|
1052
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(downloading))
|
|
1053
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(deleting))
|
|
1054
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(deleted))
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
func testBuildUserAgentStripsNonIsoCharacters() {
|
|
1058
|
+
let ua = CapgoUpdater.buildUserAgent(appId: "com.example.Тест", pluginVersion: "1.2.3🔥", versionOs: "18 😊")
|
|
1059
|
+
XCTAssertEqual(ua, "CapacitorUpdater/1.2.3 (com.example.) ios/18")
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
func testBuildUserAgentFallsBackToUnknown() {
|
|
1063
|
+
let ua = CapgoUpdater.buildUserAgent(appId: "", pluginVersion: "", versionOs: "")
|
|
1064
|
+
XCTAssertEqual(ua, "CapacitorUpdater/unknown (unknown) ios/unknown")
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
func testBundleInfoEncodeDecode() throws {
|
|
1068
|
+
let originalBundle = BundleInfo(
|
|
1069
|
+
id: "test-id",
|
|
1070
|
+
version: "1.0.0",
|
|
1071
|
+
status: .SUCCESS,
|
|
1072
|
+
downloaded: Date(),
|
|
1073
|
+
checksum: "abc123"
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
// Encode
|
|
1077
|
+
let encoder = JSONEncoder()
|
|
1078
|
+
let data = try encoder.encode(originalBundle)
|
|
1079
|
+
|
|
1080
|
+
// Decode
|
|
1081
|
+
let decoder = JSONDecoder()
|
|
1082
|
+
let decodedBundle = try decoder.decode(BundleInfo.self, from: data)
|
|
1083
|
+
|
|
1084
|
+
XCTAssertEqual(decodedBundle.getId(), originalBundle.getId())
|
|
1085
|
+
XCTAssertEqual(decodedBundle.getVersionName(), originalBundle.getVersionName())
|
|
1086
|
+
XCTAssertEqual(decodedBundle.getStatus(), originalBundle.getStatus())
|
|
1087
|
+
XCTAssertEqual(decodedBundle.getChecksum(), originalBundle.getChecksum())
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
func testShouldResetForForeignBundleWhenPathIsSetButBundleIsNotStored() {
|
|
1091
|
+
XCTAssertTrue(CapgoUpdater.shouldResetForForeignBundle(
|
|
1092
|
+
bundlePath: "/data/user/0/app/files/versions/abc123",
|
|
1093
|
+
isBuiltin: false,
|
|
1094
|
+
hasStoredBundleInfo: false
|
|
1095
|
+
))
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
func testShouldNotResetForForeignBundleWhenBundleIsBuiltin() {
|
|
1099
|
+
XCTAssertFalse(CapgoUpdater.shouldResetForForeignBundle(
|
|
1100
|
+
bundlePath: "public",
|
|
1101
|
+
isBuiltin: true,
|
|
1102
|
+
hasStoredBundleInfo: false
|
|
1103
|
+
))
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
func testShouldNotResetForForeignBundleWhenBundleIsStored() {
|
|
1107
|
+
XCTAssertFalse(CapgoUpdater.shouldResetForForeignBundle(
|
|
1108
|
+
bundlePath: "/data/user/0/app/files/versions/abc123",
|
|
1109
|
+
isBuiltin: false,
|
|
1110
|
+
hasStoredBundleInfo: true
|
|
1111
|
+
))
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// MARK: - BundleStatus Tests
|
|
1115
|
+
|
|
1116
|
+
func testBundleStatusLocalization() {
|
|
1117
|
+
XCTAssertEqual(BundleStatus.SUCCESS.localizedString, "success")
|
|
1118
|
+
XCTAssertEqual(BundleStatus.ERROR.localizedString, "error")
|
|
1119
|
+
XCTAssertEqual(BundleStatus.PENDING.localizedString, "pending")
|
|
1120
|
+
XCTAssertEqual(BundleStatus.DELETED.localizedString, "deleted")
|
|
1121
|
+
XCTAssertEqual(BundleStatus.DELETING.localizedString, "deleting")
|
|
1122
|
+
XCTAssertEqual(BundleStatus.DOWNLOADING.localizedString, "downloading")
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
func testBundleStatusStoredValue() {
|
|
1126
|
+
XCTAssertEqual(BundleStatus.SUCCESS.storedValue, "success")
|
|
1127
|
+
XCTAssertEqual(BundleStatus.ERROR.storedValue, "error")
|
|
1128
|
+
XCTAssertEqual(BundleStatus.PENDING.storedValue, "pending")
|
|
1129
|
+
XCTAssertEqual(BundleStatus.DELETED.storedValue, "deleted")
|
|
1130
|
+
XCTAssertEqual(BundleStatus.DELETING.storedValue, "deleting")
|
|
1131
|
+
XCTAssertEqual(BundleStatus.DOWNLOADING.storedValue, "downloading")
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
func testBundleStatusFromLocalizedString() {
|
|
1135
|
+
XCTAssertEqual(BundleStatus(localizedString: "success"), BundleStatus.SUCCESS)
|
|
1136
|
+
XCTAssertEqual(BundleStatus(localizedString: "error"), BundleStatus.ERROR)
|
|
1137
|
+
XCTAssertEqual(BundleStatus(localizedString: "pending"), BundleStatus.PENDING)
|
|
1138
|
+
XCTAssertEqual(BundleStatus(localizedString: "deleted"), BundleStatus.DELETED)
|
|
1139
|
+
XCTAssertEqual(BundleStatus(localizedString: "deleting"), BundleStatus.DELETING)
|
|
1140
|
+
XCTAssertEqual(BundleStatus(localizedString: "downloading"), BundleStatus.DOWNLOADING)
|
|
1141
|
+
XCTAssertNil(BundleStatus(localizedString: "invalid"))
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
func testBundleStatusEncodesStableStoredValue() throws {
|
|
1145
|
+
let data = try JSONEncoder().encode(BundleStatus.SUCCESS)
|
|
1146
|
+
XCTAssertEqual(String(data: data, encoding: .utf8), "\"success\"")
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
func testBundleStatusEncodesDeletingStoredValue() throws {
|
|
1150
|
+
let data = try JSONEncoder().encode(BundleStatus.DELETING)
|
|
1151
|
+
let decoded = try JSONDecoder().decode(BundleStatus.self, from: data)
|
|
1152
|
+
XCTAssertEqual(decoded, BundleStatus.DELETING)
|
|
1153
|
+
XCTAssertEqual(decoded.storedValue, "deleting")
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
func testBundleStatusDecodesLegacyCaseKeyObject() throws {
|
|
1157
|
+
let data = try XCTUnwrap("""
|
|
1158
|
+
{"SUCCESS":{}}
|
|
1159
|
+
""".data(using: .utf8))
|
|
1160
|
+
|
|
1161
|
+
let decoded = try JSONDecoder().decode(BundleStatus.self, from: data)
|
|
1162
|
+
|
|
1163
|
+
XCTAssertEqual(decoded, .SUCCESS)
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
func testBundleInfoDecodesLegacyBundleStatusObject() throws {
|
|
1167
|
+
let data = try XCTUnwrap("""
|
|
1168
|
+
{"downloaded":"1970-01-01T00:00:00.000Z","id":"test-id","version":"1.0.0","checksum":"abc123","status":{"SUCCESS":{}}}
|
|
1169
|
+
""".data(using: .utf8))
|
|
1170
|
+
|
|
1171
|
+
let decodedBundle = try JSONDecoder().decode(BundleInfo.self, from: data)
|
|
1172
|
+
|
|
1173
|
+
XCTAssertEqual(decodedBundle.getId(), "test-id")
|
|
1174
|
+
XCTAssertEqual(decodedBundle.getVersionName(), "1.0.0")
|
|
1175
|
+
XCTAssertEqual(decodedBundle.getChecksum(), "abc123")
|
|
1176
|
+
XCTAssertEqual(decodedBundle.getStatus(), BundleStatus.SUCCESS.storedValue)
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
func testSetChannelRejectsNonSuccessStatusWithoutPersistingDefaultChannel() throws {
|
|
1180
|
+
let updater = ChannelRequestCapgoUpdater()
|
|
1181
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
1182
|
+
updater.channelUrl = channelSelfTestURLString
|
|
1183
|
+
updater.defaultChannel = "stable"
|
|
1184
|
+
|
|
1185
|
+
let channelURL = try channelSelfTestURL()
|
|
1186
|
+
let response = try XCTUnwrap(HTTPURLResponse(url: channelURL, statusCode: 401, httpVersion: nil, headerFields: nil))
|
|
1187
|
+
let responseData = try XCTUnwrap("""
|
|
1188
|
+
{"status":"error","message":"Unauthorized"}
|
|
1189
|
+
""".data(using: .utf8))
|
|
1190
|
+
updater.requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
|
|
1191
|
+
|
|
1192
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1193
|
+
defer {
|
|
1194
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
let fromSetKey = "\(defaultsKey).fromSet"
|
|
1198
|
+
let result = updater.setChannel(
|
|
1199
|
+
channel: "beta",
|
|
1200
|
+
defaultChannelKey: defaultsKey,
|
|
1201
|
+
defaultChannelFromSetChannelKey: fromSetKey,
|
|
1202
|
+
allowSetDefaultChannel: true
|
|
1203
|
+
)
|
|
1204
|
+
|
|
1205
|
+
XCTAssertEqual(result.error, "response_error")
|
|
1206
|
+
XCTAssertEqual(result.message, "Unauthorized")
|
|
1207
|
+
XCTAssertEqual(updater.defaultChannel, "stable")
|
|
1208
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: defaultsKey))
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
func testUnsetChannelClearsOverrideWhenAllowed() {
|
|
1212
|
+
let updater = CapgoUpdater()
|
|
1213
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
1214
|
+
updater.defaultChannel = "beta"
|
|
1215
|
+
|
|
1216
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1217
|
+
let fromSetKey = "\(defaultsKey).fromSet"
|
|
1218
|
+
UserDefaults.standard.set("beta", forKey: defaultsKey)
|
|
1219
|
+
defer {
|
|
1220
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1221
|
+
UserDefaults.standard.removeObject(forKey: fromSetKey)
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
let result = updater.unsetChannel(
|
|
1225
|
+
defaultChannelKey: defaultsKey,
|
|
1226
|
+
defaultChannelFromSetChannelKey: fromSetKey,
|
|
1227
|
+
configDefaultChannel: "stable",
|
|
1228
|
+
allowSetDefaultChannel: true
|
|
1229
|
+
)
|
|
1230
|
+
|
|
1231
|
+
XCTAssertEqual(result.status, "ok")
|
|
1232
|
+
XCTAssertEqual(result.message, "Channel override removed")
|
|
1233
|
+
XCTAssertEqual(updater.defaultChannel, "stable")
|
|
1234
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: defaultsKey))
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
func testUnsetChannelRejectsWhenDisabledByConfig() {
|
|
1238
|
+
let updater = CapgoUpdater()
|
|
1239
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
1240
|
+
updater.defaultChannel = "beta"
|
|
1241
|
+
|
|
1242
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1243
|
+
let fromSetKey = "\(defaultsKey).fromSet"
|
|
1244
|
+
UserDefaults.standard.set("beta", forKey: defaultsKey)
|
|
1245
|
+
defer {
|
|
1246
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1247
|
+
UserDefaults.standard.removeObject(forKey: fromSetKey)
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
let result = updater.unsetChannel(
|
|
1251
|
+
defaultChannelKey: defaultsKey,
|
|
1252
|
+
defaultChannelFromSetChannelKey: fromSetKey,
|
|
1253
|
+
configDefaultChannel: "stable",
|
|
1254
|
+
allowSetDefaultChannel: false
|
|
1255
|
+
)
|
|
1256
|
+
|
|
1257
|
+
XCTAssertEqual(result.error, "disabled_by_config")
|
|
1258
|
+
XCTAssertEqual(result.message, "unsetChannel is disabled by configuration")
|
|
1259
|
+
XCTAssertEqual(updater.defaultChannel, "beta")
|
|
1260
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultsKey), "beta")
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
func testDefaultChannelCleanupRunsWhenPersistenceDisabledDuringNativeBuildCleanup() {
|
|
1264
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1265
|
+
testPlugin.persistDefaultChannelOnReinstall = false
|
|
1266
|
+
|
|
1267
|
+
XCTAssertTrue(
|
|
1268
|
+
testPlugin.shouldClearPersistedDefaultChannel(
|
|
1269
|
+
nativeBuildVersionChanged: true,
|
|
1270
|
+
resetWhenUpdate: true,
|
|
1271
|
+
restoredReinstall: false
|
|
1272
|
+
)
|
|
1273
|
+
)
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
func testDefaultChannelCleanupRunsForRestoredSameVersionReinstall() {
|
|
1277
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1278
|
+
testPlugin.persistDefaultChannelOnReinstall = false
|
|
1279
|
+
|
|
1280
|
+
XCTAssertTrue(
|
|
1281
|
+
testPlugin.shouldClearPersistedDefaultChannel(
|
|
1282
|
+
nativeBuildVersionChanged: false,
|
|
1283
|
+
resetWhenUpdate: false,
|
|
1284
|
+
restoredReinstall: true
|
|
1285
|
+
)
|
|
1286
|
+
)
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
func testDefaultChannelCleanupKeepsChannelWhenPersistenceEnabled() {
|
|
1290
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1291
|
+
testPlugin.persistDefaultChannelOnReinstall = true
|
|
1292
|
+
|
|
1293
|
+
XCTAssertFalse(
|
|
1294
|
+
testPlugin.shouldClearPersistedDefaultChannel(
|
|
1295
|
+
nativeBuildVersionChanged: true,
|
|
1296
|
+
resetWhenUpdate: true,
|
|
1297
|
+
restoredReinstall: true
|
|
1298
|
+
)
|
|
1299
|
+
)
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
func testDefaultChannelCleanupKeepsChannelWhenNativeBuildDoesNotChange() {
|
|
1303
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1304
|
+
testPlugin.persistDefaultChannelOnReinstall = false
|
|
1305
|
+
|
|
1306
|
+
XCTAssertFalse(
|
|
1307
|
+
testPlugin.shouldClearPersistedDefaultChannel(
|
|
1308
|
+
nativeBuildVersionChanged: false,
|
|
1309
|
+
resetWhenUpdate: true,
|
|
1310
|
+
restoredReinstall: false
|
|
1311
|
+
)
|
|
1312
|
+
)
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
func testDefaultChannelCleanupKeepsChannelWhenNativeCleanupIsDisabled() {
|
|
1316
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1317
|
+
testPlugin.persistDefaultChannelOnReinstall = false
|
|
1318
|
+
|
|
1319
|
+
XCTAssertFalse(
|
|
1320
|
+
testPlugin.shouldClearPersistedDefaultChannel(
|
|
1321
|
+
nativeBuildVersionChanged: true,
|
|
1322
|
+
resetWhenUpdate: false,
|
|
1323
|
+
restoredReinstall: false
|
|
1324
|
+
)
|
|
1325
|
+
)
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
func testDefaultChannelCleanupClearsRestoredPreviewSnapshot() throws {
|
|
1329
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1330
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1331
|
+
let previewChannelKey = "CapacitorUpdater.previewPreviousDefaultChannel"
|
|
1332
|
+
let previewChannelWasSetKey = "CapacitorUpdater.previewPreviousDefaultChannelWasSet"
|
|
1333
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1334
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1335
|
+
let stateFile = directory.appendingPathComponent("state")
|
|
1336
|
+
let previewSnapshotFile = directory.appendingPathComponent("preview")
|
|
1337
|
+
defer {
|
|
1338
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1339
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1340
|
+
UserDefaults.standard.removeObject(forKey: previewChannelKey)
|
|
1341
|
+
UserDefaults.standard.removeObject(forKey: previewChannelWasSetKey)
|
|
1342
|
+
}
|
|
1343
|
+
UserDefaults.standard.set("stale", forKey: defaultChannelKey)
|
|
1344
|
+
UserDefaults.standard.set("stale", forKey: previewChannelKey)
|
|
1345
|
+
UserDefaults.standard.set(true, forKey: previewChannelWasSetKey)
|
|
1346
|
+
|
|
1347
|
+
XCTAssertTrue(testPlugin.clearPersistedDefaultChannel(
|
|
1348
|
+
stateFile: stateFile,
|
|
1349
|
+
previewSnapshotFile: previewSnapshotFile
|
|
1350
|
+
))
|
|
1351
|
+
let state = testPlugin.defaultChannelState(file: stateFile)
|
|
1352
|
+
XCTAssertTrue(state.exists)
|
|
1353
|
+
XCTAssertNil(state.channel)
|
|
1354
|
+
XCTAssertEqual(testPlugin.defaultChannelPreviewSnapshot(file: previewSnapshotFile), .invalidated)
|
|
1355
|
+
|
|
1356
|
+
XCTAssertNil(UserDefaults.standard.object(forKey: defaultChannelKey))
|
|
1357
|
+
XCTAssertNil(UserDefaults.standard.object(forKey: previewChannelKey))
|
|
1358
|
+
XCTAssertNil(UserDefaults.standard.object(forKey: previewChannelWasSetKey))
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
func testDefaultChannelCleanupReportsStateWriteFailure() throws {
|
|
1362
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1363
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1364
|
+
let nonDirectory = FileManager.default.temporaryDirectory
|
|
1365
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)")
|
|
1366
|
+
let stateFile = nonDirectory.appendingPathComponent("state")
|
|
1367
|
+
let previewSnapshotFile = nonDirectory.appendingPathComponent("preview")
|
|
1368
|
+
try Data().write(to: nonDirectory)
|
|
1369
|
+
defer {
|
|
1370
|
+
try? FileManager.default.removeItem(at: nonDirectory)
|
|
1371
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1372
|
+
}
|
|
1373
|
+
UserDefaults.standard.set("stale", forKey: defaultChannelKey)
|
|
1374
|
+
|
|
1375
|
+
XCTAssertFalse(testPlugin.clearPersistedDefaultChannel(
|
|
1376
|
+
stateFile: stateFile,
|
|
1377
|
+
previewSnapshotFile: previewSnapshotFile
|
|
1378
|
+
))
|
|
1379
|
+
XCTAssertFalse(FileManager.default.fileExists(atPath: stateFile.path))
|
|
1380
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultChannelKey), "stale")
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
func testDefaultChannelStatePersistsNewChannel() throws {
|
|
1384
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1385
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1386
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1387
|
+
let stateFile = directory.appendingPathComponent("state")
|
|
1388
|
+
defer {
|
|
1389
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
try testPlugin.persistDefaultChannelState(channel: "beta", file: stateFile)
|
|
1393
|
+
let state = testPlugin.defaultChannelState(file: stateFile)
|
|
1394
|
+
XCTAssertTrue(state.exists)
|
|
1395
|
+
XCTAssertEqual(state.channel, "beta")
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
func testDefaultChannelPreviewSnapshotStatesRoundTrip() throws {
|
|
1399
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1400
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1401
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1402
|
+
let snapshotFile = directory.appendingPathComponent("preview")
|
|
1403
|
+
defer {
|
|
1404
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
XCTAssertEqual(testPlugin.defaultChannelPreviewSnapshot(file: snapshotFile), .missing)
|
|
1408
|
+
|
|
1409
|
+
try testPlugin.persistDefaultChannelPreviewSnapshot(channel: nil, file: snapshotFile)
|
|
1410
|
+
XCTAssertEqual(testPlugin.defaultChannelPreviewSnapshot(file: snapshotFile), .snapshot(nil))
|
|
1411
|
+
|
|
1412
|
+
try testPlugin.persistDefaultChannelPreviewSnapshot(channel: "beta", file: snapshotFile)
|
|
1413
|
+
XCTAssertEqual(testPlugin.defaultChannelPreviewSnapshot(file: snapshotFile), .snapshot("beta"))
|
|
1414
|
+
|
|
1415
|
+
try testPlugin.invalidateDefaultChannelPreviewSnapshot(file: snapshotFile)
|
|
1416
|
+
XCTAssertEqual(testPlugin.defaultChannelPreviewSnapshot(file: snapshotFile), .invalidated)
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
func testUnreadableDefaultChannelStateFallsBackToUserDefaults() throws {
|
|
1420
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1421
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1422
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1423
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1424
|
+
let stateFile = directory.appendingPathComponent("state")
|
|
1425
|
+
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
1426
|
+
try Data([0xFF]).write(to: stateFile)
|
|
1427
|
+
defer {
|
|
1428
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1429
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1430
|
+
}
|
|
1431
|
+
UserDefaults.standard.set("beta", forKey: defaultChannelKey)
|
|
1432
|
+
|
|
1433
|
+
let state = testPlugin.defaultChannelState(file: stateFile)
|
|
1434
|
+
XCTAssertFalse(state.isReadable)
|
|
1435
|
+
XCTAssertEqual(testPlugin.persistedDefaultChannel(stateFile: stateFile), "beta")
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
func testUnreadableDefaultChannelStateDoesNotRestoreWhenPersistenceDisabled() throws {
|
|
1439
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1440
|
+
testPlugin.persistDefaultChannelOnReinstall = false
|
|
1441
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1442
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1443
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1444
|
+
let stateFile = directory.appendingPathComponent("state")
|
|
1445
|
+
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
1446
|
+
try Data([0xFF]).write(to: stateFile)
|
|
1447
|
+
defer {
|
|
1448
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1449
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1450
|
+
}
|
|
1451
|
+
UserDefaults.standard.set("stale", forKey: defaultChannelKey)
|
|
1452
|
+
|
|
1453
|
+
XCTAssertNil(testPlugin.persistedDefaultChannel(stateFile: stateFile))
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
func testDefaultChannelStateOverridesStaleUserDefaults() throws {
|
|
1457
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1458
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1459
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1460
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1461
|
+
let stateFile = directory.appendingPathComponent("state")
|
|
1462
|
+
defer {
|
|
1463
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1464
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1465
|
+
}
|
|
1466
|
+
UserDefaults.standard.set("stale", forKey: defaultChannelKey)
|
|
1467
|
+
|
|
1468
|
+
try testPlugin.persistDefaultChannelState(channel: nil, file: stateFile)
|
|
1469
|
+
|
|
1470
|
+
XCTAssertNil(testPlugin.persistedDefaultChannel(stateFile: stateFile))
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
func testDefaultChannelStateMirrorsDefaultsWithReinstallPersistenceEnabled() throws {
|
|
1474
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1475
|
+
testPlugin.persistDefaultChannelOnReinstall = true
|
|
1476
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1477
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1478
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1479
|
+
let stateFile = directory.appendingPathComponent("state")
|
|
1480
|
+
defer {
|
|
1481
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1482
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1483
|
+
}
|
|
1484
|
+
try testPlugin.persistDefaultChannelState(channel: nil, file: stateFile)
|
|
1485
|
+
UserDefaults.standard.set("beta", forKey: defaultChannelKey)
|
|
1486
|
+
|
|
1487
|
+
XCTAssertTrue(testPlugin.persistDefaultChannelStateFromDefaults(stateFile: stateFile))
|
|
1488
|
+
XCTAssertEqual(testPlugin.defaultChannelState(file: stateFile).channel, "beta")
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
func testDefaultChannelStateWriteFailureInvalidatesAuthoritativeState() throws {
|
|
1492
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1493
|
+
let defaultChannelKey = "CapacitorUpdater.defaultChannel"
|
|
1494
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1495
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1496
|
+
let stateFile = directory.appendingPathComponent("state", isDirectory: true)
|
|
1497
|
+
try FileManager.default.createDirectory(at: stateFile, withIntermediateDirectories: true)
|
|
1498
|
+
defer {
|
|
1499
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1500
|
+
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
1501
|
+
}
|
|
1502
|
+
UserDefaults.standard.set("beta", forKey: defaultChannelKey)
|
|
1503
|
+
|
|
1504
|
+
XCTAssertTrue(testPlugin.persistDefaultChannelStateFromDefaults(stateFile: stateFile))
|
|
1505
|
+
XCTAssertFalse(FileManager.default.fileExists(atPath: stateFile.path))
|
|
1506
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultChannelKey), "beta")
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
func testDefaultChannelCleanupFailurePreservesInstallMarkerRetry() throws {
|
|
1510
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1511
|
+
let marker = FileManager.default.temporaryDirectory
|
|
1512
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)")
|
|
1513
|
+
try Data().write(to: marker)
|
|
1514
|
+
defer {
|
|
1515
|
+
try? FileManager.default.removeItem(at: marker)
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
XCTAssertTrue(FileManager.default.fileExists(atPath: marker.path))
|
|
1519
|
+
try testPlugin.invalidateDefaultChannelInstallMarker(marker: marker)
|
|
1520
|
+
XCTAssertTrue(testPlugin.isRestoredReinstall(marker: marker, markerWasCreated: true))
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
func testDefaultChannelInstallMarkerFailureIsHandledOnce() throws {
|
|
1524
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1525
|
+
let markerDefaultsKey = "CapacitorUpdater.defaultChannelInstallMarkerCreated"
|
|
1526
|
+
let nonDirectory = FileManager.default.temporaryDirectory
|
|
1527
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)")
|
|
1528
|
+
let marker = nonDirectory.appendingPathComponent("marker")
|
|
1529
|
+
try Data().write(to: nonDirectory)
|
|
1530
|
+
defer {
|
|
1531
|
+
try? FileManager.default.removeItem(at: nonDirectory)
|
|
1532
|
+
UserDefaults.standard.removeObject(forKey: markerDefaultsKey)
|
|
1533
|
+
}
|
|
1534
|
+
UserDefaults.standard.set(true, forKey: markerDefaultsKey)
|
|
1535
|
+
|
|
1536
|
+
XCTAssertTrue(testPlugin.isRestoredReinstall(marker: marker, markerWasCreated: true))
|
|
1537
|
+
testPlugin.prepareDefaultChannelInstallMarker(marker: marker, markerWasCreated: true)
|
|
1538
|
+
|
|
1539
|
+
XCTAssertFalse(UserDefaults.standard.bool(forKey: markerDefaultsKey))
|
|
1540
|
+
XCTAssertFalse(testPlugin.isRestoredReinstall(marker: marker, markerWasCreated: false))
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
func testDefaultChannelInstallMarkerReappliesBackupExclusion() throws {
|
|
1544
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
1545
|
+
let markerDefaultsKey = "CapacitorUpdater.defaultChannelInstallMarkerCreated"
|
|
1546
|
+
let directory = FileManager.default.temporaryDirectory
|
|
1547
|
+
.appendingPathComponent("CapacitorUpdaterTests.\(UUID().uuidString)", isDirectory: true)
|
|
1548
|
+
let marker = directory.appendingPathComponent("marker")
|
|
1549
|
+
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
1550
|
+
try Data().write(to: marker)
|
|
1551
|
+
var markerResourceValues = URLResourceValues()
|
|
1552
|
+
markerResourceValues.isExcludedFromBackup = false
|
|
1553
|
+
var mutableMarker = marker
|
|
1554
|
+
try mutableMarker.setResourceValues(markerResourceValues)
|
|
1555
|
+
defer {
|
|
1556
|
+
try? FileManager.default.removeItem(at: directory)
|
|
1557
|
+
UserDefaults.standard.removeObject(forKey: markerDefaultsKey)
|
|
1558
|
+
}
|
|
1559
|
+
UserDefaults.standard.set(true, forKey: markerDefaultsKey)
|
|
1560
|
+
|
|
1561
|
+
testPlugin.prepareDefaultChannelInstallMarker(marker: marker, markerWasCreated: true)
|
|
1562
|
+
|
|
1563
|
+
let resourceValues = try marker.resourceValues(forKeys: [.isExcludedFromBackupKey])
|
|
1564
|
+
XCTAssertEqual(resourceValues.isExcludedFromBackup, true)
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
func testGetChannelPersistsServerChannelAsDefaultChannel() throws {
|
|
1568
|
+
let updater = ChannelRequestCapgoUpdater()
|
|
1569
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
1570
|
+
updater.channelUrl = channelSelfTestURLString
|
|
1571
|
+
|
|
1572
|
+
let channelURL = try channelSelfTestURL()
|
|
1573
|
+
let response = try XCTUnwrap(HTTPURLResponse(url: channelURL, statusCode: 200, httpVersion: nil, headerFields: nil))
|
|
1574
|
+
let responseData = try XCTUnwrap("""
|
|
1575
|
+
{"channel":"company-a","status":"ok","allowSet":true}
|
|
1576
|
+
""".data(using: .utf8))
|
|
1577
|
+
updater.requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
|
|
1578
|
+
|
|
1579
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1580
|
+
defer {
|
|
1581
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
let result = updater.getChannel(defaultChannelKey: defaultsKey)
|
|
1585
|
+
|
|
1586
|
+
XCTAssertEqual(result.channel, "company-a")
|
|
1587
|
+
XCTAssertEqual(updater.defaultChannel, "company-a")
|
|
1588
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultsKey), "company-a")
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
func testGetChannelDoesNotPersistBuiltinVersionNameAsDefaultChannel() {
|
|
1592
|
+
let updater = ChannelRequestCapgoUpdater()
|
|
1593
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
1594
|
+
updater.defaultChannel = "stable"
|
|
1595
|
+
|
|
1596
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1597
|
+
defer {
|
|
1598
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
updater.persistDefaultChannelFromResponse(channel: "builtin", status: "ok", defaultChannelKey: defaultsKey)
|
|
1602
|
+
|
|
1603
|
+
XCTAssertEqual(updater.defaultChannel, "stable")
|
|
1604
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: defaultsKey))
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
func testGetChannelDoesNotPersistDefaultStatusChannel() throws {
|
|
1608
|
+
let updater = ChannelRequestCapgoUpdater()
|
|
1609
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
1610
|
+
updater.channelUrl = channelSelfTestURLString
|
|
1611
|
+
updater.defaultChannel = ""
|
|
1612
|
+
|
|
1613
|
+
let channelURL = try channelSelfTestURL()
|
|
1614
|
+
let response = try XCTUnwrap(HTTPURLResponse(url: channelURL, statusCode: 200, httpVersion: nil, headerFields: nil))
|
|
1615
|
+
let responseData = try XCTUnwrap("""
|
|
1616
|
+
{"channel":"production","status":"default","allowSet":true}
|
|
1617
|
+
""".data(using: .utf8))
|
|
1618
|
+
updater.requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
|
|
1619
|
+
|
|
1620
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1621
|
+
defer {
|
|
1622
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
let result = updater.getChannel(defaultChannelKey: defaultsKey)
|
|
1626
|
+
|
|
1627
|
+
XCTAssertEqual(result.channel, "production")
|
|
1628
|
+
XCTAssertEqual(result.status, "default")
|
|
1629
|
+
XCTAssertEqual(updater.defaultChannel, "")
|
|
1630
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: defaultsKey))
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
func testPersistDefaultChannelFromResponseIgnoresDefaultStatus() {
|
|
1634
|
+
let updater = persistDefaultChannelTestUpdater(defaultChannel: "dev")
|
|
1635
|
+
|
|
1636
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1637
|
+
UserDefaults.standard.set("dev", forKey: defaultsKey)
|
|
1638
|
+
defer {
|
|
1639
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
updater.persistDefaultChannelFromResponse(channel: "production", status: "default", defaultChannelKey: defaultsKey)
|
|
1643
|
+
|
|
1644
|
+
XCTAssertEqual(updater.defaultChannel, "dev")
|
|
1645
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultsKey), "dev")
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
func testPersistDefaultChannelFromResponseClearsStaleDefaultFallback() {
|
|
1649
|
+
let updater = persistDefaultChannelTestUpdater(defaultChannel: "production")
|
|
1650
|
+
|
|
1651
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1652
|
+
UserDefaults.standard.set("production", forKey: defaultsKey)
|
|
1653
|
+
defer {
|
|
1654
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
updater.persistDefaultChannelFromResponse(
|
|
1658
|
+
channel: "production",
|
|
1659
|
+
status: "default",
|
|
1660
|
+
defaultChannelKey: defaultsKey,
|
|
1661
|
+
configDefaultChannel: "stable"
|
|
1662
|
+
)
|
|
1663
|
+
|
|
1664
|
+
XCTAssertEqual(updater.defaultChannel, "stable")
|
|
1665
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: defaultsKey))
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
func testPersistDefaultChannelFromResponsePreservesSetChannelOnDefaultStatus() {
|
|
1669
|
+
let updater = persistDefaultChannelTestUpdater(defaultChannel: "company-a")
|
|
1670
|
+
|
|
1671
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1672
|
+
let fromSetKey = "\(defaultsKey).fromSet"
|
|
1673
|
+
UserDefaults.standard.set("company-a", forKey: defaultsKey)
|
|
1674
|
+
UserDefaults.standard.set(true, forKey: fromSetKey)
|
|
1675
|
+
defer {
|
|
1676
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1677
|
+
UserDefaults.standard.removeObject(forKey: fromSetKey)
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
updater.persistDefaultChannelFromResponse(
|
|
1681
|
+
channel: "company-a",
|
|
1682
|
+
status: "default",
|
|
1683
|
+
defaultChannelKey: defaultsKey,
|
|
1684
|
+
defaultChannelFromSetChannelKey: fromSetKey,
|
|
1685
|
+
configDefaultChannel: "stable"
|
|
1686
|
+
)
|
|
1687
|
+
|
|
1688
|
+
XCTAssertEqual(updater.defaultChannel, "company-a")
|
|
1689
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultsKey), "company-a")
|
|
1690
|
+
XCTAssertTrue(UserDefaults.standard.bool(forKey: fromSetKey))
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
func testPersistDefaultChannelFromResponseKeepsSetChannelMarkerAfterOverrideRefresh() {
|
|
1694
|
+
let updater = persistDefaultChannelTestUpdater(defaultChannel: "company-a")
|
|
1695
|
+
|
|
1696
|
+
let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
|
|
1697
|
+
let fromSetKey = "\(defaultsKey).fromSet"
|
|
1698
|
+
UserDefaults.standard.set("company-a", forKey: defaultsKey)
|
|
1699
|
+
UserDefaults.standard.set(true, forKey: fromSetKey)
|
|
1700
|
+
defer {
|
|
1701
|
+
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
|
1702
|
+
UserDefaults.standard.removeObject(forKey: fromSetKey)
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
updater.persistDefaultChannelFromResponse(
|
|
1706
|
+
channel: "company-a",
|
|
1707
|
+
status: "ok",
|
|
1708
|
+
defaultChannelKey: defaultsKey,
|
|
1709
|
+
defaultChannelFromSetChannelKey: fromSetKey,
|
|
1710
|
+
configDefaultChannel: "stable"
|
|
1711
|
+
)
|
|
1712
|
+
updater.persistDefaultChannelFromResponse(
|
|
1713
|
+
channel: "company-a",
|
|
1714
|
+
status: "default",
|
|
1715
|
+
defaultChannelKey: defaultsKey,
|
|
1716
|
+
defaultChannelFromSetChannelKey: fromSetKey,
|
|
1717
|
+
configDefaultChannel: "stable"
|
|
1718
|
+
)
|
|
1719
|
+
|
|
1720
|
+
XCTAssertEqual(updater.defaultChannel, "company-a")
|
|
1721
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: defaultsKey), "company-a")
|
|
1722
|
+
XCTAssertTrue(UserDefaults.standard.bool(forKey: fromSetKey))
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// MARK: - DelayCondition Tests
|
|
1726
|
+
|
|
1727
|
+
func testDelayConditionInitialization() {
|
|
1728
|
+
let condition = DelayCondition(kind: .background, value: "test-value")
|
|
1729
|
+
|
|
1730
|
+
XCTAssertEqual(condition.getKind(), "background")
|
|
1731
|
+
XCTAssertEqual(condition.getValue(), "test-value")
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
func testDelayConditionWithStringInit() {
|
|
1735
|
+
let condition = DelayCondition(kind: "kill", value: "test-value")
|
|
1736
|
+
|
|
1737
|
+
XCTAssertEqual(condition.getKind(), "kill")
|
|
1738
|
+
XCTAssertEqual(condition.getValue(), "test-value")
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
func testDelayConditionToJSON() {
|
|
1742
|
+
let condition = DelayCondition(kind: .nativeVersion, value: "1.0.0")
|
|
1743
|
+
let json = condition.toJSON()
|
|
1744
|
+
|
|
1745
|
+
XCTAssertEqual(json["kind"], "nativeVersion")
|
|
1746
|
+
XCTAssertEqual(json["value"], "1.0.0")
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
func testDelayConditionEquality() {
|
|
1750
|
+
let condition1 = DelayCondition(kind: .date, value: "2023-01-01")
|
|
1751
|
+
let condition2 = DelayCondition(kind: .date, value: "2023-01-01")
|
|
1752
|
+
let condition3 = DelayCondition(kind: .date, value: "2023-01-02")
|
|
1753
|
+
|
|
1754
|
+
XCTAssertTrue(condition1 == condition2)
|
|
1755
|
+
XCTAssertFalse(condition1 == condition3)
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
func testShouldConsumeOnLaunchDirectUpdateForOnLaunchAttempt() {
|
|
1759
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.shouldConsumeOnLaunchDirectUpdate(directUpdateMode: "onLaunch", plannedDirectUpdate: true))
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
func testShouldNotConsumeOnLaunchDirectUpdateForNonLaunchAttempt() {
|
|
1763
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldConsumeOnLaunchDirectUpdate(directUpdateMode: "onLaunch", plannedDirectUpdate: false))
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
func testShouldNotConsumeOnLaunchDirectUpdateForOtherModes() {
|
|
1767
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldConsumeOnLaunchDirectUpdate(directUpdateMode: "always", plannedDirectUpdate: true))
|
|
1768
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldConsumeOnLaunchDirectUpdate(directUpdateMode: "atInstall", plannedDirectUpdate: true))
|
|
1769
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldConsumeOnLaunchDirectUpdate(directUpdateMode: "false", plannedDirectUpdate: true))
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
func testPeriodCheckDelayZeroDisablesPeriodicChecks() {
|
|
1773
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(0), 0)
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
func testPeriodCheckDelayNegativeDisablesPeriodicChecks() {
|
|
1777
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(-1), 0)
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
func testPeriodCheckDelayBelowMinimumClampsToTenMinutes() {
|
|
1781
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(1), 600)
|
|
1782
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(599), 600)
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
func testPeriodCheckDelayAtMinimumIsAllowed() {
|
|
1786
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(600), 600)
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
func testPeriodCheckDelayAboveMinimumIsPreserved() {
|
|
1790
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(3600), 3600)
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
func testCheckRevertSkipsRollbackDuringPreviewSession() {
|
|
1794
|
+
let previewPlugin = TestableCapacitorUpdaterPlugin()
|
|
1795
|
+
let previewImplementation = ResetTrackingCapgoUpdater()
|
|
1796
|
+
previewImplementation.currentBundleValue = BundleInfo(
|
|
1797
|
+
id: "preview-id",
|
|
1798
|
+
version: "preview",
|
|
1799
|
+
status: .PENDING,
|
|
1800
|
+
downloaded: Date(),
|
|
1801
|
+
checksum: "preview"
|
|
1802
|
+
)
|
|
1803
|
+
|
|
1804
|
+
previewPlugin.implementation = previewImplementation
|
|
1805
|
+
previewPlugin.previewSessionEnabled = true
|
|
1806
|
+
|
|
1807
|
+
previewPlugin.checkRevert()
|
|
1808
|
+
|
|
1809
|
+
XCTAssertFalse(previewImplementation.resetCalled)
|
|
1810
|
+
XCTAssertFalse(previewPlugin.notifiedEventNames.contains("updateFailed"))
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
func testCheckRevertSkipsRollbackDuringPreviewTransition() {
|
|
1814
|
+
let previewPlugin = TestableCapacitorUpdaterPlugin()
|
|
1815
|
+
let previewImplementation = ResetTrackingCapgoUpdater()
|
|
1816
|
+
previewImplementation.currentBundleValue = BundleInfo(
|
|
1817
|
+
id: "preview-id",
|
|
1818
|
+
version: "preview",
|
|
1819
|
+
status: .PENDING,
|
|
1820
|
+
downloaded: Date(),
|
|
1821
|
+
checksum: "preview"
|
|
1822
|
+
)
|
|
1823
|
+
previewImplementation.previewSession = true
|
|
1824
|
+
|
|
1825
|
+
previewPlugin.implementation = previewImplementation
|
|
1826
|
+
|
|
1827
|
+
previewPlugin.checkRevert()
|
|
1828
|
+
|
|
1829
|
+
XCTAssertFalse(previewImplementation.resetCalled)
|
|
1830
|
+
XCTAssertFalse(previewPlugin.notifiedEventNames.contains("updateFailed"))
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
func testTriggerUpdateCheckSkipsDuringPreviewSession() {
|
|
1834
|
+
let previewPlugin = TestableCapacitorUpdaterPlugin()
|
|
1835
|
+
let previewImplementation = ResetTrackingCapgoUpdater()
|
|
1836
|
+
previewImplementation.currentBundleValue = BundleInfo(
|
|
1837
|
+
id: "preview-id",
|
|
1838
|
+
version: "preview",
|
|
1839
|
+
status: .PENDING,
|
|
1840
|
+
downloaded: Date(),
|
|
1841
|
+
checksum: "preview"
|
|
1842
|
+
)
|
|
1843
|
+
|
|
1844
|
+
previewPlugin.implementation = previewImplementation
|
|
1845
|
+
previewPlugin.previewSessionEnabled = true
|
|
1846
|
+
previewPlugin.setUpdateUrlForTesting("https://example.com/update")
|
|
1847
|
+
|
|
1848
|
+
let status = previewPlugin.triggerBackgroundUpdateCheck()
|
|
1849
|
+
|
|
1850
|
+
XCTAssertEqual(status, "unavailable")
|
|
1851
|
+
XCTAssertFalse(previewImplementation.resetCalled)
|
|
1852
|
+
XCTAssertFalse(previewPlugin.notifiedEventNames.contains("updateAvailable"))
|
|
1853
|
+
XCTAssertFalse(previewPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
1854
|
+
XCTAssertFalse(previewPlugin.notifiedEventNames.contains("updateCheckResult"))
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
func testResetToPendingWithoutInstallablePendingBundleDoesNotResetState() {
|
|
1858
|
+
let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
|
|
1859
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
1860
|
+
resetImplementation.nextBundleValue = BundleInfo(
|
|
1861
|
+
id: "pending-id",
|
|
1862
|
+
version: "2.0.0",
|
|
1863
|
+
status: .PENDING,
|
|
1864
|
+
downloaded: Date(),
|
|
1865
|
+
checksum: "pending"
|
|
1866
|
+
)
|
|
1867
|
+
resetImplementation.canSetResult = false
|
|
1868
|
+
|
|
1869
|
+
resetPlugin.implementation = resetImplementation
|
|
1870
|
+
|
|
1871
|
+
XCTAssertFalse(resetPlugin._reset(toLastSuccessful: false, usePendingBundle: true))
|
|
1872
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
1873
|
+
XCTAssertEqual(resetImplementation.setCalls, 0)
|
|
1874
|
+
XCTAssertFalse(resetImplementation.resetCalled)
|
|
1875
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
func testResetToPendingRestoresStateWhenSwitchFails() {
|
|
1879
|
+
let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
|
|
1880
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
1881
|
+
resetImplementation.nextBundleValue = BundleInfo(
|
|
1882
|
+
id: "pending-id",
|
|
1883
|
+
version: "2.0.0",
|
|
1884
|
+
status: .PENDING,
|
|
1885
|
+
downloaded: Date(),
|
|
1886
|
+
checksum: "pending"
|
|
1887
|
+
)
|
|
1888
|
+
resetImplementation.setResult = false
|
|
1889
|
+
|
|
1890
|
+
resetPlugin.implementation = resetImplementation
|
|
1891
|
+
|
|
1892
|
+
XCTAssertFalse(resetPlugin._reset(toLastSuccessful: false, usePendingBundle: true))
|
|
1893
|
+
XCTAssertFalse(resetImplementation.resetCalled)
|
|
1894
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
1895
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionCalled)
|
|
1896
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
1897
|
+
XCTAssertEqual(resetImplementation.setCalls, 1)
|
|
1898
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 1)
|
|
1899
|
+
XCTAssertEqual(resetImplementation.restoredState?.currentBundlePath, resetImplementation.capturedState.currentBundlePath)
|
|
1900
|
+
XCTAssertEqual(resetImplementation.restoredState?.fallbackBundleId, resetImplementation.capturedState.fallbackBundleId)
|
|
1901
|
+
XCTAssertEqual(resetImplementation.restoredState?.nextBundleId, resetImplementation.capturedState.nextBundleId)
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
func testResetToPendingRestoresLiveStateWhenReloadFails() {
|
|
1905
|
+
let resetPlugin = ReloadFailureCapacitorUpdaterPlugin()
|
|
1906
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
1907
|
+
resetImplementation.nextBundleValue = BundleInfo(
|
|
1908
|
+
id: "pending-id",
|
|
1909
|
+
version: "2.0.0",
|
|
1910
|
+
status: .PENDING,
|
|
1911
|
+
downloaded: Date(),
|
|
1912
|
+
checksum: "pending"
|
|
1913
|
+
)
|
|
1914
|
+
|
|
1915
|
+
resetPlugin.implementation = resetImplementation
|
|
1916
|
+
|
|
1917
|
+
XCTAssertFalse(resetPlugin._reset(toLastSuccessful: false, usePendingBundle: true))
|
|
1918
|
+
XCTAssertFalse(resetImplementation.resetCalled)
|
|
1919
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
1920
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionCalled)
|
|
1921
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
1922
|
+
XCTAssertEqual(resetImplementation.setCalls, 1)
|
|
1923
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 1)
|
|
1924
|
+
XCTAssertEqual(resetPlugin.restoreLiveBundleStateAfterFailedReloadCalls, 1)
|
|
1925
|
+
XCTAssertEqual(resetImplementation.restoredState?.currentBundlePath, resetImplementation.capturedState.currentBundlePath)
|
|
1926
|
+
XCTAssertEqual(resetImplementation.restoredState?.fallbackBundleId, resetImplementation.capturedState.fallbackBundleId)
|
|
1927
|
+
XCTAssertEqual(resetImplementation.restoredState?.nextBundleId, resetImplementation.capturedState.nextBundleId)
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
func testResetToPendingRestoresStateWhenBuiltinPendingReloadFails() {
|
|
1931
|
+
let resetPlugin = ReloadFailureCapacitorUpdaterPlugin()
|
|
1932
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
1933
|
+
resetImplementation.nextBundleValue = BundleInfo(
|
|
1934
|
+
id: BundleInfo.ID_BUILTIN,
|
|
1935
|
+
version: "builtin",
|
|
1936
|
+
status: .SUCCESS,
|
|
1937
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
1938
|
+
checksum: "builtin"
|
|
1939
|
+
)
|
|
1940
|
+
|
|
1941
|
+
resetPlugin.implementation = resetImplementation
|
|
1942
|
+
|
|
1943
|
+
XCTAssertFalse(resetPlugin._reset(toLastSuccessful: false, usePendingBundle: true))
|
|
1944
|
+
XCTAssertFalse(resetImplementation.resetCalled)
|
|
1945
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
1946
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionCalled)
|
|
1947
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
1948
|
+
XCTAssertEqual(resetImplementation.setCalls, 0)
|
|
1949
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 1)
|
|
1950
|
+
XCTAssertEqual(resetPlugin.restoreLiveBundleStateAfterFailedReloadCalls, 1)
|
|
1951
|
+
XCTAssertEqual(resetImplementation.restoredState?.currentBundlePath, resetImplementation.capturedState.currentBundlePath)
|
|
1952
|
+
XCTAssertEqual(resetImplementation.restoredState?.fallbackBundleId, resetImplementation.capturedState.fallbackBundleId)
|
|
1953
|
+
XCTAssertEqual(resetImplementation.restoredState?.nextBundleId, resetImplementation.capturedState.nextBundleId)
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
func testLeavePreviewUsesBuiltinWhenPreviewFallbackIsMissing() {
|
|
1957
|
+
let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
|
|
1958
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
1959
|
+
resetImplementation.currentBundleValue = BundleInfo(
|
|
1960
|
+
id: "preview-id",
|
|
1961
|
+
version: "preview",
|
|
1962
|
+
status: .SUCCESS,
|
|
1963
|
+
downloaded: Date(),
|
|
1964
|
+
checksum: "preview"
|
|
1965
|
+
)
|
|
1966
|
+
resetImplementation.previewFallbackBundleValue = nil
|
|
1967
|
+
|
|
1968
|
+
resetPlugin.implementation = resetImplementation
|
|
1969
|
+
|
|
1970
|
+
XCTAssertTrue(resetPlugin.resetToPreviewFallbackBundle())
|
|
1971
|
+
XCTAssertEqual(resetImplementation.stagePreviewFallbackReloadCalls, 1)
|
|
1972
|
+
XCTAssertEqual(resetImplementation.stagedPreviewFallbackBundle?.getId(), BundleInfo.ID_BUILTIN)
|
|
1973
|
+
XCTAssertTrue(resetImplementation.finalizeResetTransitionCalled)
|
|
1974
|
+
XCTAssertEqual(resetImplementation.finalizeResetTransitionPreviousBundleName, "preview")
|
|
1975
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionIsInternal)
|
|
1976
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
func testLeavePreviewFromShakeMenuKeepsPreviewGuardUntilAppReady() {
|
|
1980
|
+
let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
|
|
1981
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
1982
|
+
resetImplementation.currentBundleValue = BundleInfo(
|
|
1983
|
+
id: "preview-id",
|
|
1984
|
+
version: "preview",
|
|
1985
|
+
status: .SUCCESS,
|
|
1986
|
+
downloaded: Date(),
|
|
1987
|
+
checksum: "preview"
|
|
1988
|
+
)
|
|
1989
|
+
resetImplementation.previewFallbackBundleValue = BundleInfo(
|
|
1990
|
+
id: "fallback-id",
|
|
1991
|
+
version: "1.0.0",
|
|
1992
|
+
status: .SUCCESS,
|
|
1993
|
+
downloaded: Date(),
|
|
1994
|
+
checksum: "fallback"
|
|
1995
|
+
)
|
|
1996
|
+
resetImplementation.previewSession = true
|
|
1997
|
+
|
|
1998
|
+
resetPlugin.implementation = resetImplementation
|
|
1999
|
+
resetPlugin.previewSessionEnabled = true
|
|
2000
|
+
|
|
2001
|
+
XCTAssertTrue(resetPlugin.leavePreviewSessionFromShakeMenu())
|
|
2002
|
+
XCTAssertFalse(resetPlugin.hasActivePreviewSession())
|
|
2003
|
+
XCTAssertTrue(resetImplementation.previewSession)
|
|
2004
|
+
XCTAssertEqual(resetImplementation.stagePreviewFallbackReloadCalls, 1)
|
|
2005
|
+
XCTAssertEqual(resetImplementation.stagedPreviewFallbackBundle?.getId(), "fallback-id")
|
|
2006
|
+
XCTAssertTrue(resetImplementation.finalizeResetTransitionCalled)
|
|
2007
|
+
XCTAssertEqual(resetImplementation.finalizeResetTransitionPreviousBundleName, "preview")
|
|
2008
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
|
|
2009
|
+
XCTAssertNil(resetImplementation.lastPreviewFallbackBundle)
|
|
2010
|
+
XCTAssertGreaterThan(resetImplementation.setPreviewFallbackBundleCalls, 0)
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
func testPreviewMenuListsStoredPreviewsAndCleansMissingBundles() throws {
|
|
2014
|
+
let previewsKey = "CapacitorUpdater.previewSessions"
|
|
2015
|
+
UserDefaults.standard.removeObject(forKey: previewsKey)
|
|
2016
|
+
defer {
|
|
2017
|
+
UserDefaults.standard.removeObject(forKey: previewsKey)
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
let previewPlugin = TestableCapacitorUpdaterPlugin()
|
|
2021
|
+
let previewImplementation = ResetTrackingCapgoUpdater()
|
|
2022
|
+
let current = BundleInfo(
|
|
2023
|
+
id: "preview-current",
|
|
2024
|
+
version: "2.0.0",
|
|
2025
|
+
status: .SUCCESS,
|
|
2026
|
+
downloaded: Date(),
|
|
2027
|
+
checksum: "current"
|
|
2028
|
+
)
|
|
2029
|
+
let other = BundleInfo(
|
|
2030
|
+
id: "preview-other",
|
|
2031
|
+
version: "1.5.0",
|
|
2032
|
+
status: .SUCCESS,
|
|
2033
|
+
downloaded: Date(),
|
|
2034
|
+
checksum: "other"
|
|
2035
|
+
)
|
|
2036
|
+
|
|
2037
|
+
previewImplementation.currentBundleValue = current
|
|
2038
|
+
previewImplementation.listedBundles = [current, other]
|
|
2039
|
+
previewPlugin.implementation = previewImplementation
|
|
2040
|
+
previewPlugin.previewSessionEnabled = true
|
|
2041
|
+
|
|
2042
|
+
UserDefaults.standard.set([
|
|
2043
|
+
"preview-current": [
|
|
2044
|
+
"name": "Current preview",
|
|
2045
|
+
"source": "qr",
|
|
2046
|
+
"createdAt": "2026-01-01T00:00:00.000Z",
|
|
2047
|
+
"updatedAt": "2026-01-02T00:00:00.000Z",
|
|
2048
|
+
"lastUsedAt": "2026-01-03T00:00:00.000Z"
|
|
2049
|
+
],
|
|
2050
|
+
"preview-other": [
|
|
2051
|
+
"name": "Other preview",
|
|
2052
|
+
"createdAt": "2026-01-01T00:00:00.000Z",
|
|
2053
|
+
"updatedAt": "2026-01-01T00:00:00.000Z",
|
|
2054
|
+
"lastUsedAt": "2026-01-02T00:00:00.000Z"
|
|
2055
|
+
],
|
|
2056
|
+
"missing-preview": [
|
|
2057
|
+
"name": "Missing preview",
|
|
2058
|
+
"lastUsedAt": "2026-01-04T00:00:00.000Z"
|
|
2059
|
+
]
|
|
2060
|
+
], forKey: previewsKey)
|
|
2061
|
+
|
|
2062
|
+
let previews = previewPlugin.previewMenuPreviews()
|
|
2063
|
+
|
|
2064
|
+
XCTAssertEqual(previews.count, 2)
|
|
2065
|
+
let first = try XCTUnwrap(previews.first)
|
|
2066
|
+
XCTAssertEqual(first["id"] as? String, "preview-current")
|
|
2067
|
+
XCTAssertEqual(first["name"] as? String, "Current preview")
|
|
2068
|
+
XCTAssertEqual(first["source"] as? String, "qr")
|
|
2069
|
+
XCTAssertEqual(first["isActive"] as? Bool, true)
|
|
2070
|
+
|
|
2071
|
+
let second = try XCTUnwrap(previews.dropFirst().first)
|
|
2072
|
+
XCTAssertEqual(second["id"] as? String, "preview-other")
|
|
2073
|
+
XCTAssertEqual(second["isActive"] as? Bool, false)
|
|
2074
|
+
|
|
2075
|
+
let savedSessions = try XCTUnwrap(UserDefaults.standard.dictionary(forKey: previewsKey))
|
|
2076
|
+
XCTAssertNil(savedSessions["missing-preview"])
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
func testNormalizeShakeMenuGestureSupportsThreeFingerPinch() {
|
|
2080
|
+
XCTAssertEqual(
|
|
2081
|
+
CapacitorUpdaterPlugin.normalizedShakeMenuGesture(nil),
|
|
2082
|
+
CapacitorUpdaterPlugin.shakeMenuGestureShake
|
|
2083
|
+
)
|
|
2084
|
+
XCTAssertEqual(
|
|
2085
|
+
CapacitorUpdaterPlugin.normalizedShakeMenuGesture("shake"),
|
|
2086
|
+
CapacitorUpdaterPlugin.shakeMenuGestureShake
|
|
2087
|
+
)
|
|
2088
|
+
XCTAssertEqual(
|
|
2089
|
+
CapacitorUpdaterPlugin.normalizedShakeMenuGesture("unknown"),
|
|
2090
|
+
CapacitorUpdaterPlugin.shakeMenuGestureShake
|
|
2091
|
+
)
|
|
2092
|
+
XCTAssertEqual(
|
|
2093
|
+
CapacitorUpdaterPlugin.normalizedShakeMenuGesture("threeFingerPinch"),
|
|
2094
|
+
CapacitorUpdaterPlugin.shakeMenuGestureThreeFingerPinch
|
|
2095
|
+
)
|
|
2096
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.isSupportedShakeMenuGesture("shake"))
|
|
2097
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.isSupportedShakeMenuGesture("threeFingerPinch"))
|
|
2098
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.isSupportedShakeMenuGesture(" "))
|
|
2099
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.isSupportedShakeMenuGesture("pinch"))
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
func testResetToLastSuccessfulWithoutInstallableFallbackFallsBackToBuiltin() {
|
|
2103
|
+
let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
|
|
2104
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
2105
|
+
resetImplementation.fallbackBundleValue = BundleInfo(
|
|
2106
|
+
id: "fallback-id",
|
|
2107
|
+
version: "1.5.0",
|
|
2108
|
+
status: .SUCCESS,
|
|
2109
|
+
downloaded: Date(),
|
|
2110
|
+
checksum: "fallback"
|
|
2111
|
+
)
|
|
2112
|
+
resetImplementation.canSetResult = false
|
|
2113
|
+
|
|
2114
|
+
resetPlugin.implementation = resetImplementation
|
|
2115
|
+
|
|
2116
|
+
XCTAssertTrue(resetPlugin._reset(toLastSuccessful: true, usePendingBundle: false))
|
|
2117
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
2118
|
+
XCTAssertEqual(resetImplementation.setCalls, 0)
|
|
2119
|
+
XCTAssertFalse(resetImplementation.resetCalled)
|
|
2120
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
2121
|
+
XCTAssertTrue(resetImplementation.finalizeResetTransitionCalled)
|
|
2122
|
+
XCTAssertEqual(resetImplementation.finalizeResetTransitionPreviousBundleName, "1.0.0")
|
|
2123
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionIsInternal)
|
|
2124
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
func testResetToLastSuccessfulRestoresStateWhenSwitchFails() {
|
|
2128
|
+
let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
|
|
2129
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
2130
|
+
resetImplementation.fallbackBundleValue = BundleInfo(
|
|
2131
|
+
id: "fallback-id",
|
|
2132
|
+
version: "1.5.0",
|
|
2133
|
+
status: .SUCCESS,
|
|
2134
|
+
downloaded: Date(),
|
|
2135
|
+
checksum: "fallback"
|
|
2136
|
+
)
|
|
2137
|
+
resetImplementation.setResult = false
|
|
2138
|
+
|
|
2139
|
+
resetPlugin.implementation = resetImplementation
|
|
2140
|
+
|
|
2141
|
+
XCTAssertFalse(resetPlugin._reset(toLastSuccessful: true, usePendingBundle: false))
|
|
2142
|
+
XCTAssertFalse(resetImplementation.resetCalled)
|
|
2143
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
2144
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionCalled)
|
|
2145
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
2146
|
+
XCTAssertEqual(resetImplementation.setCalls, 1)
|
|
2147
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 1)
|
|
2148
|
+
XCTAssertEqual(resetImplementation.restoredState?.currentBundlePath, resetImplementation.capturedState.currentBundlePath)
|
|
2149
|
+
XCTAssertEqual(resetImplementation.restoredState?.fallbackBundleId, resetImplementation.capturedState.fallbackBundleId)
|
|
2150
|
+
XCTAssertEqual(resetImplementation.restoredState?.nextBundleId, resetImplementation.capturedState.nextBundleId)
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
func testResetToLastSuccessfulRestoresStateWhenFallbackReloadFails() {
|
|
2154
|
+
let resetPlugin = SequenceReloadCapacitorUpdaterPlugin()
|
|
2155
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
2156
|
+
resetPlugin.reloadResults = [false]
|
|
2157
|
+
resetImplementation.fallbackBundleValue = BundleInfo(
|
|
2158
|
+
id: "fallback-id",
|
|
2159
|
+
version: "1.5.0",
|
|
2160
|
+
status: .SUCCESS,
|
|
2161
|
+
downloaded: Date(),
|
|
2162
|
+
checksum: "fallback"
|
|
2163
|
+
)
|
|
2164
|
+
|
|
2165
|
+
resetPlugin.implementation = resetImplementation
|
|
2166
|
+
|
|
2167
|
+
XCTAssertFalse(resetPlugin._reset(toLastSuccessful: true, usePendingBundle: false))
|
|
2168
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
2169
|
+
XCTAssertEqual(resetImplementation.prepareResetStateForTransitionCalls, 1)
|
|
2170
|
+
XCTAssertFalse(resetImplementation.finalizeResetTransitionCalled)
|
|
2171
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
2172
|
+
XCTAssertEqual(resetImplementation.setCalls, 1)
|
|
2173
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 1)
|
|
2174
|
+
XCTAssertEqual(resetPlugin.restoreLiveBundleStateAfterFailedReloadCalls, 1)
|
|
2175
|
+
XCTAssertEqual(resetImplementation.restoredState?.currentBundlePath, resetImplementation.capturedState.currentBundlePath)
|
|
2176
|
+
XCTAssertEqual(resetImplementation.restoredState?.fallbackBundleId, resetImplementation.capturedState.fallbackBundleId)
|
|
2177
|
+
XCTAssertEqual(resetImplementation.restoredState?.nextBundleId, resetImplementation.capturedState.nextBundleId)
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
func testInternalResetToLastSuccessfulFallsBackToBuiltinWhenFallbackReloadFails() {
|
|
2181
|
+
let resetPlugin = SequenceReloadCapacitorUpdaterPlugin()
|
|
2182
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
2183
|
+
resetPlugin.reloadResults = [false, true]
|
|
2184
|
+
resetImplementation.currentBundleValue = BundleInfo(
|
|
2185
|
+
id: "current-id",
|
|
2186
|
+
version: "2.0.0",
|
|
2187
|
+
status: .ERROR,
|
|
2188
|
+
downloaded: Date(),
|
|
2189
|
+
checksum: "abc123"
|
|
2190
|
+
)
|
|
2191
|
+
resetImplementation.fallbackBundleValue = BundleInfo(
|
|
2192
|
+
id: "fallback-id",
|
|
2193
|
+
version: "1.5.0",
|
|
2194
|
+
status: .SUCCESS,
|
|
2195
|
+
downloaded: Date(),
|
|
2196
|
+
checksum: "fallback"
|
|
2197
|
+
)
|
|
2198
|
+
|
|
2199
|
+
resetPlugin.implementation = resetImplementation
|
|
2200
|
+
|
|
2201
|
+
XCTAssertTrue(resetPlugin.performReset(toLastSuccessful: true, usePendingBundle: false, isInternal: true))
|
|
2202
|
+
XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
|
|
2203
|
+
XCTAssertEqual(resetImplementation.prepareResetStateForTransitionCalls, 2)
|
|
2204
|
+
XCTAssertTrue(resetImplementation.finalizeResetTransitionCalled)
|
|
2205
|
+
XCTAssertEqual(resetImplementation.finalizeResetTransitionCalls, 1)
|
|
2206
|
+
XCTAssertEqual(resetImplementation.finalizeResetTransitionPreviousBundleName, "2.0.0")
|
|
2207
|
+
XCTAssertTrue(resetImplementation.finalizeResetTransitionIsInternal)
|
|
2208
|
+
XCTAssertEqual(resetImplementation.canSetCalls, 1)
|
|
2209
|
+
XCTAssertEqual(resetImplementation.setCalls, 1)
|
|
2210
|
+
XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
|
|
2211
|
+
XCTAssertEqual(resetPlugin.restoreLiveBundleStateAfterFailedReloadCalls, 0)
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
func testFinalizePendingReloadPreservesSuccessfulBundleStatus() {
|
|
2215
|
+
let updater = PendingReloadFinalizeCapgoUpdater()
|
|
2216
|
+
let successfulBundle = BundleInfo(
|
|
2217
|
+
id: "pending-id",
|
|
2218
|
+
version: "2.0.0",
|
|
2219
|
+
status: .SUCCESS,
|
|
2220
|
+
downloaded: Date(),
|
|
2221
|
+
checksum: "pending"
|
|
2222
|
+
)
|
|
2223
|
+
let pendingBundle = BundleInfo(
|
|
2224
|
+
id: "pending-id",
|
|
2225
|
+
version: "2.0.0",
|
|
2226
|
+
status: .PENDING,
|
|
2227
|
+
downloaded: Date(),
|
|
2228
|
+
checksum: "pending"
|
|
2229
|
+
)
|
|
2230
|
+
updater.bundleInfos["pending-id"] = successfulBundle
|
|
2231
|
+
|
|
2232
|
+
updater.finalizePendingReload(bundle: pendingBundle, previousBundleName: "1.0.0")
|
|
2233
|
+
|
|
2234
|
+
XCTAssertEqual(updater.bundleInfos["pending-id"]?.getStatus(), BundleStatus.SUCCESS.storedValue)
|
|
2235
|
+
XCTAssertEqual(updater.lastStatsAction, "set")
|
|
2236
|
+
XCTAssertEqual(updater.lastStatsVersionName, "2.0.0")
|
|
2237
|
+
XCTAssertEqual(updater.lastStatsOldVersionName, "1.0.0")
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
func testReloadRestoresStateWhenPendingApplyReloadFails() throws {
|
|
2241
|
+
let reloadPlugin = ReloadFailureCapacitorUpdaterPlugin()
|
|
2242
|
+
let reloadImplementation = ResetTrackingCapgoUpdater()
|
|
2243
|
+
var rejected = false
|
|
2244
|
+
|
|
2245
|
+
reloadImplementation.nextBundleValue = BundleInfo(
|
|
2246
|
+
id: "pending-id",
|
|
2247
|
+
version: "2.0.0",
|
|
2248
|
+
status: .PENDING,
|
|
2249
|
+
downloaded: Date(),
|
|
2250
|
+
checksum: "pending"
|
|
2251
|
+
)
|
|
2252
|
+
reloadPlugin.implementation = reloadImplementation
|
|
2253
|
+
|
|
2254
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2255
|
+
callbackId: "reload-test",
|
|
2256
|
+
options: [:],
|
|
2257
|
+
success: { _, _ in
|
|
2258
|
+
XCTFail("reload should reject when the pending apply reload fails")
|
|
2259
|
+
},
|
|
2260
|
+
error: { _ in
|
|
2261
|
+
rejected = true
|
|
2262
|
+
}
|
|
2263
|
+
))
|
|
2264
|
+
|
|
2265
|
+
reloadPlugin.reload(call)
|
|
2266
|
+
|
|
2267
|
+
XCTAssertTrue(rejected)
|
|
2268
|
+
XCTAssertEqual(reloadImplementation.setCalls, 0)
|
|
2269
|
+
XCTAssertEqual(reloadImplementation.stagePendingReloadCalls, 1)
|
|
2270
|
+
XCTAssertEqual(reloadImplementation.finalizePendingReloadCalls, 0)
|
|
2271
|
+
XCTAssertEqual(reloadImplementation.restoreResetStateCalls, 1)
|
|
2272
|
+
XCTAssertEqual(reloadPlugin.restoreLiveBundleStateAfterFailedReloadCalls, 1)
|
|
2273
|
+
XCTAssertEqual(reloadImplementation.restoredState?.currentBundlePath, reloadImplementation.capturedState.currentBundlePath)
|
|
2274
|
+
XCTAssertEqual(reloadImplementation.restoredState?.fallbackBundleId, reloadImplementation.capturedState.fallbackBundleId)
|
|
2275
|
+
XCTAssertEqual(reloadImplementation.restoredState?.nextBundleId, reloadImplementation.capturedState.nextBundleId)
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
func testReloadFinalizesPendingBundleSideEffectsAfterSuccess() throws {
|
|
2279
|
+
let reloadPlugin = ReloadBypassCapacitorUpdaterPlugin()
|
|
2280
|
+
let reloadImplementation = ResetTrackingCapgoUpdater()
|
|
2281
|
+
|
|
2282
|
+
reloadImplementation.nextBundleValue = BundleInfo(
|
|
2283
|
+
id: "pending-id",
|
|
2284
|
+
version: "2.0.0",
|
|
2285
|
+
status: .PENDING,
|
|
2286
|
+
downloaded: Date(),
|
|
2287
|
+
checksum: "pending"
|
|
2288
|
+
)
|
|
2289
|
+
reloadPlugin.implementation = reloadImplementation
|
|
2290
|
+
|
|
2291
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2292
|
+
callbackId: "reload-success-test",
|
|
2293
|
+
options: [:],
|
|
2294
|
+
success: { _, _ in },
|
|
2295
|
+
error: { _ in
|
|
2296
|
+
XCTFail("reload should resolve when the pending bundle reload succeeds")
|
|
2297
|
+
}
|
|
2298
|
+
))
|
|
2299
|
+
|
|
2300
|
+
reloadPlugin.reload(call)
|
|
2301
|
+
|
|
2302
|
+
XCTAssertEqual(reloadImplementation.setCalls, 0)
|
|
2303
|
+
XCTAssertEqual(reloadImplementation.stagePendingReloadCalls, 1)
|
|
2304
|
+
XCTAssertEqual(reloadImplementation.finalizePendingReloadCalls, 1)
|
|
2305
|
+
XCTAssertEqual(reloadImplementation.finalizePendingReloadPreviousBundleName, "1.0.0")
|
|
2306
|
+
XCTAssertEqual(reloadImplementation.finalizedPendingReloadBundle?.getId(), "pending-id")
|
|
2307
|
+
}
|
|
2308
|
+
|
|
2309
|
+
func testReloadRestoresStateWhenBuiltinPendingReloadFails() throws {
|
|
2310
|
+
let reloadPlugin = ReloadFailureCapacitorUpdaterPlugin()
|
|
2311
|
+
let reloadImplementation = ResetTrackingCapgoUpdater()
|
|
2312
|
+
var rejected = false
|
|
2313
|
+
|
|
2314
|
+
reloadImplementation.nextBundleValue = BundleInfo(
|
|
2315
|
+
id: BundleInfo.ID_BUILTIN,
|
|
2316
|
+
version: "builtin",
|
|
2317
|
+
status: .SUCCESS,
|
|
2318
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
2319
|
+
checksum: "builtin"
|
|
2320
|
+
)
|
|
2321
|
+
reloadPlugin.implementation = reloadImplementation
|
|
2322
|
+
|
|
2323
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2324
|
+
callbackId: "reload-builtin-test",
|
|
2325
|
+
options: [:],
|
|
2326
|
+
success: { _, _ in
|
|
2327
|
+
XCTFail("reload should reject when the builtin pending reload fails")
|
|
2328
|
+
},
|
|
2329
|
+
error: { _ in
|
|
2330
|
+
rejected = true
|
|
2331
|
+
}
|
|
2332
|
+
))
|
|
2333
|
+
|
|
2334
|
+
reloadPlugin.reload(call)
|
|
2335
|
+
|
|
2336
|
+
XCTAssertTrue(rejected)
|
|
2337
|
+
XCTAssertEqual(reloadImplementation.setCalls, 0)
|
|
2338
|
+
XCTAssertEqual(reloadImplementation.stagePendingReloadCalls, 0)
|
|
2339
|
+
XCTAssertEqual(reloadImplementation.finalizePendingReloadCalls, 0)
|
|
2340
|
+
XCTAssertTrue(reloadImplementation.prepareResetStateForTransitionCalled)
|
|
2341
|
+
XCTAssertFalse(reloadImplementation.finalizeResetTransitionCalled)
|
|
2342
|
+
XCTAssertEqual(reloadImplementation.restoreResetStateCalls, 1)
|
|
2343
|
+
XCTAssertEqual(reloadPlugin.restoreLiveBundleStateAfterFailedReloadCalls, 1)
|
|
2344
|
+
XCTAssertEqual(reloadImplementation.restoredState?.currentBundlePath, reloadImplementation.capturedState.currentBundlePath)
|
|
2345
|
+
XCTAssertEqual(reloadImplementation.restoredState?.fallbackBundleId, reloadImplementation.capturedState.fallbackBundleId)
|
|
2346
|
+
XCTAssertEqual(reloadImplementation.restoredState?.nextBundleId, reloadImplementation.capturedState.nextBundleId)
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
func testOnLaunchCompletionConsumesWindowAfterFirstCycle() {
|
|
2350
|
+
let current = BundleInfo(
|
|
2351
|
+
id: "test-id",
|
|
2352
|
+
version: "1.0.0",
|
|
2353
|
+
status: .SUCCESS,
|
|
2354
|
+
downloaded: Date(),
|
|
2355
|
+
checksum: "abc123"
|
|
2356
|
+
)
|
|
2357
|
+
|
|
2358
|
+
plugin.configureDirectUpdateModeForTesting("onLaunch")
|
|
2359
|
+
|
|
2360
|
+
XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
|
|
2361
|
+
XCTAssertFalse(plugin.hasConsumedOnLaunchDirectUpdateForTesting)
|
|
2362
|
+
|
|
2363
|
+
plugin.endBackGroundTaskWithNotif(
|
|
2364
|
+
msg: "No need to update",
|
|
2365
|
+
latestVersionName: current.getVersionName(),
|
|
2366
|
+
current: current,
|
|
2367
|
+
error: false,
|
|
2368
|
+
plannedDirectUpdate: true
|
|
2369
|
+
)
|
|
2370
|
+
|
|
2371
|
+
XCTAssertTrue(plugin.hasConsumedOnLaunchDirectUpdateForTesting)
|
|
2372
|
+
XCTAssertFalse(plugin.shouldUseDirectUpdateForTesting())
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
func testOnLaunchFreshDownloadConsumesWindowBeforeDownloadStarts() {
|
|
2376
|
+
let downloadStarted = expectation(description: "fresh download started")
|
|
2377
|
+
let current = BundleInfo(
|
|
2378
|
+
id: "test-id",
|
|
2379
|
+
version: "1.0.0",
|
|
2380
|
+
status: .SUCCESS,
|
|
2381
|
+
downloaded: Date(),
|
|
2382
|
+
checksum: "abc123"
|
|
2383
|
+
)
|
|
2384
|
+
let latest = AppVersion()
|
|
2385
|
+
latest.version = "2.0.0"
|
|
2386
|
+
latest.url = "https://example.com/update.zip"
|
|
2387
|
+
latest.checksum = "abc123"
|
|
2388
|
+
|
|
2389
|
+
let freshDownloadImplementation = FreshDownloadCapgoUpdater()
|
|
2390
|
+
freshDownloadImplementation.currentBundleValue = current
|
|
2391
|
+
freshDownloadImplementation.latestResponse = latest
|
|
2392
|
+
|
|
2393
|
+
plugin = TestableCapacitorUpdaterPlugin()
|
|
2394
|
+
plugin.implementation = freshDownloadImplementation
|
|
2395
|
+
plugin.configureDirectUpdateModeForTesting("onLaunch")
|
|
2396
|
+
plugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2397
|
+
|
|
2398
|
+
XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
|
|
2399
|
+
XCTAssertFalse(plugin.hasConsumedOnLaunchDirectUpdateForTesting)
|
|
2400
|
+
|
|
2401
|
+
var consumedWhenDownloadStarted = false
|
|
2402
|
+
freshDownloadImplementation.onDownloadStart = {
|
|
2403
|
+
consumedWhenDownloadStarted = self.plugin.hasConsumedOnLaunchDirectUpdateForTesting
|
|
2404
|
+
downloadStarted.fulfill()
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
plugin.backgroundDownload()
|
|
2408
|
+
|
|
2409
|
+
wait(for: [downloadStarted], timeout: 5.0)
|
|
2410
|
+
XCTAssertTrue(consumedWhenDownloadStarted)
|
|
2411
|
+
XCTAssertTrue(plugin.hasConsumedOnLaunchDirectUpdateForTesting)
|
|
2412
|
+
XCTAssertFalse(plugin.shouldUseDirectUpdateForTesting())
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
func testOnlyDownloadModeDownloadsWithoutSettingNextBundle() {
|
|
2416
|
+
let (testPlugin, freshDownloadImplementation) = makeOnlyDownloadPlugin(downloaded: makeOnlyDownloadBundle())
|
|
2417
|
+
|
|
2418
|
+
XCTAssertFalse(testPlugin.shouldUseDirectUpdateForTesting())
|
|
2419
|
+
|
|
2420
|
+
testPlugin.backgroundDownload()
|
|
2421
|
+
|
|
2422
|
+
assertOnlyDownloadLeavesUpdateManual(plugin: testPlugin, implementation: freshDownloadImplementation)
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
func testOnlyDownloadModeDoesNotSetExistingDownloadedBundleNext() {
|
|
2426
|
+
let (testPlugin, freshDownloadImplementation) = makeOnlyDownloadPlugin(existing: makeOnlyDownloadBundle())
|
|
2427
|
+
|
|
2428
|
+
testPlugin.backgroundDownload()
|
|
2429
|
+
|
|
2430
|
+
assertOnlyDownloadLeavesUpdateManual(plugin: testPlugin, implementation: freshDownloadImplementation)
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
func testOnlyDownloadModeBuiltinNotifiesUpdateAvailableWithoutSettingNextBundle() {
|
|
2434
|
+
let (testPlugin, freshDownloadImplementation) = makeOnlyDownloadPlugin()
|
|
2435
|
+
let latest = AppVersion()
|
|
2436
|
+
latest.version = "builtin"
|
|
2437
|
+
freshDownloadImplementation.latestResponse = latest
|
|
2438
|
+
|
|
2439
|
+
testPlugin.backgroundDownload()
|
|
2440
|
+
|
|
2441
|
+
assertOnlyDownloadLeavesUpdateManual(plugin: testPlugin, implementation: freshDownloadImplementation)
|
|
2442
|
+
let updateBundle = testPlugin.notifiedEventPayloads["updateAvailable"]?["bundle"] as? [String: String]
|
|
2443
|
+
XCTAssertEqual(updateBundle?["id"], BundleInfo.ID_BUILTIN)
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
func testOnlyDownloadModeBuiltinDoesNotNotifyWhenBuiltinIsCurrent() {
|
|
2447
|
+
let current = BundleInfo(
|
|
2448
|
+
id: BundleInfo.ID_BUILTIN,
|
|
2449
|
+
version: "builtin",
|
|
2450
|
+
status: .SUCCESS,
|
|
2451
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
2452
|
+
checksum: "builtin"
|
|
2453
|
+
)
|
|
2454
|
+
let (testPlugin, freshDownloadImplementation) = makeOnlyDownloadPlugin(current: current)
|
|
2455
|
+
let latest = AppVersion()
|
|
2456
|
+
latest.version = "builtin"
|
|
2457
|
+
freshDownloadImplementation.latestResponse = latest
|
|
2458
|
+
|
|
2459
|
+
testPlugin.backgroundDownload()
|
|
2460
|
+
|
|
2461
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("updateAvailable"))
|
|
2462
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("noNeedUpdate"))
|
|
2463
|
+
XCTAssertEqual(freshDownloadImplementation.setNextBundleCalls, 0)
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
func testStaleDownloadingBundleIsRedownloadedInsteadOfQueued() {
|
|
2467
|
+
let stale = makeOnlyDownloadBundle(id: "stale-id", status: .DOWNLOADING, checksum: "")
|
|
2468
|
+
let downloaded = makeOnlyDownloadBundle(id: "fresh-id")
|
|
2469
|
+
let (testPlugin, implementation) = makeAtBackgroundPlugin(existing: stale, downloaded: downloaded)
|
|
2470
|
+
|
|
2471
|
+
testPlugin.backgroundDownload()
|
|
2472
|
+
|
|
2473
|
+
XCTAssertEqual(implementation.downloadCalls, 1)
|
|
2474
|
+
XCTAssertEqual(implementation.deleteCalls, 1)
|
|
2475
|
+
XCTAssertEqual(implementation.lastDeletedId, "stale-id")
|
|
2476
|
+
XCTAssertEqual(implementation.lastSetNextBundleId, "fresh-id")
|
|
2477
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateAvailable"))
|
|
2478
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
func testPendingExistingBundleIsReusedWithoutRedownload() {
|
|
2482
|
+
let existing = makeOnlyDownloadBundle()
|
|
2483
|
+
let (testPlugin, implementation) = makeAtBackgroundPlugin(existing: existing)
|
|
2484
|
+
|
|
2485
|
+
testPlugin.backgroundDownload()
|
|
2486
|
+
|
|
2487
|
+
XCTAssertEqual(implementation.downloadCalls, 0)
|
|
2488
|
+
XCTAssertEqual(implementation.deleteCalls, 0)
|
|
2489
|
+
XCTAssertEqual(implementation.setNextBundleCalls, 1)
|
|
2490
|
+
XCTAssertEqual(implementation.lastSetNextBundleId, existing.getId())
|
|
2491
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
func testFailedSetNextBundleAfterDownloadNotifiesFailure() {
|
|
2495
|
+
let downloaded = makeOnlyDownloadBundle()
|
|
2496
|
+
let implementation = FreshDownloadCapgoUpdater()
|
|
2497
|
+
implementation.setNextBundleSucceeds = false
|
|
2498
|
+
let (testPlugin, _) = makeAtBackgroundPlugin(downloaded: downloaded, implementation: implementation)
|
|
2499
|
+
|
|
2500
|
+
testPlugin.backgroundDownload()
|
|
2501
|
+
|
|
2502
|
+
XCTAssertEqual(implementation.downloadCalls, 1)
|
|
2503
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2504
|
+
XCTAssertTrue(implementation.sentStatsActions.contains("download_fail"))
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
func testNoNewVersionAvailableDoesNotNotifyDownloadFailed() {
|
|
2508
|
+
let current = BundleInfo(
|
|
2509
|
+
id: "test-id",
|
|
2510
|
+
version: "1.0.0",
|
|
2511
|
+
status: .SUCCESS,
|
|
2512
|
+
downloaded: Date(),
|
|
2513
|
+
checksum: "abc123"
|
|
2514
|
+
)
|
|
2515
|
+
let latest = AppVersion()
|
|
2516
|
+
latest.error = "no_new_version_available"
|
|
2517
|
+
latest.kind = "up_to_date"
|
|
2518
|
+
latest.message = "No new version available"
|
|
2519
|
+
latest.statusCode = 200
|
|
2520
|
+
|
|
2521
|
+
let noUpdateImplementation = FreshDownloadCapgoUpdater()
|
|
2522
|
+
noUpdateImplementation.currentBundleValue = current
|
|
2523
|
+
noUpdateImplementation.latestResponse = latest
|
|
2524
|
+
|
|
2525
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2526
|
+
testPlugin.implementation = noUpdateImplementation
|
|
2527
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2528
|
+
|
|
2529
|
+
testPlugin.backgroundDownload()
|
|
2530
|
+
|
|
2531
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("noNeedUpdate"))
|
|
2532
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateCheckResult"))
|
|
2533
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2534
|
+
XCTAssertFalse(noUpdateImplementation.sentStatsActions.contains("download_fail"))
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
func testGetLatestRejectsLegacyErrorWithoutBackendKind() throws {
|
|
2538
|
+
let latest = AppVersion()
|
|
2539
|
+
latest.error = "no_new_version_available"
|
|
2540
|
+
latest.message = "No new version available"
|
|
2541
|
+
latest.statusCode = 200
|
|
2542
|
+
|
|
2543
|
+
let noUpdateImplementation = FreshDownloadCapgoUpdater()
|
|
2544
|
+
noUpdateImplementation.latestResponse = latest
|
|
2545
|
+
|
|
2546
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2547
|
+
testPlugin.implementation = noUpdateImplementation
|
|
2548
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2549
|
+
|
|
2550
|
+
let rejected = expectation(description: "getLatest rejects legacy response without kind")
|
|
2551
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2552
|
+
callbackId: "get-latest-legacy-error-test",
|
|
2553
|
+
options: [:],
|
|
2554
|
+
success: { _, _ in
|
|
2555
|
+
XCTFail("getLatest should reject legacy error responses without backend kind")
|
|
2556
|
+
},
|
|
2557
|
+
error: { error in
|
|
2558
|
+
XCTAssertEqual(error?.message, "no_new_version_available")
|
|
2559
|
+
rejected.fulfill()
|
|
2560
|
+
}
|
|
2561
|
+
))
|
|
2562
|
+
|
|
2563
|
+
testPlugin.getLatest(call)
|
|
2564
|
+
wait(for: [rejected], timeout: 10)
|
|
2565
|
+
}
|
|
2566
|
+
|
|
2567
|
+
func testGetLatestRejectsFailedKindWithoutErrorMessage() throws {
|
|
2568
|
+
let latest = AppVersion()
|
|
2569
|
+
latest.kind = "failed"
|
|
2570
|
+
latest.statusCode = 500
|
|
2571
|
+
|
|
2572
|
+
let failedImplementation = FreshDownloadCapgoUpdater()
|
|
2573
|
+
failedImplementation.latestResponse = latest
|
|
2574
|
+
|
|
2575
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2576
|
+
testPlugin.implementation = failedImplementation
|
|
2577
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2578
|
+
|
|
2579
|
+
let rejected = expectation(description: "getLatest rejects failed kind")
|
|
2580
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2581
|
+
callbackId: "get-latest-failed-kind-test",
|
|
2582
|
+
options: [:],
|
|
2583
|
+
success: { _, _ in
|
|
2584
|
+
XCTFail("getLatest should reject failed kind responses")
|
|
2585
|
+
},
|
|
2586
|
+
error: { error in
|
|
2587
|
+
XCTAssertEqual(error?.message, "server did not provide a message")
|
|
2588
|
+
rejected.fulfill()
|
|
2589
|
+
}
|
|
2590
|
+
))
|
|
2591
|
+
|
|
2592
|
+
testPlugin.getLatest(call)
|
|
2593
|
+
wait(for: [rejected], timeout: 10)
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
func testGetLatestRejectsFailedErrorUsingBackendErrorCode() throws {
|
|
2597
|
+
let latest = AppVersion()
|
|
2598
|
+
latest.error = "response_error"
|
|
2599
|
+
latest.message = "Server returned an invalid response"
|
|
2600
|
+
latest.kind = "failed"
|
|
2601
|
+
latest.statusCode = 500
|
|
2602
|
+
|
|
2603
|
+
let failedImplementation = FreshDownloadCapgoUpdater()
|
|
2604
|
+
failedImplementation.latestResponse = latest
|
|
2605
|
+
|
|
2606
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2607
|
+
testPlugin.implementation = failedImplementation
|
|
2608
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2609
|
+
|
|
2610
|
+
let rejected = expectation(description: "getLatest rejects failed error")
|
|
2611
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2612
|
+
callbackId: "get-latest-failed-error-test",
|
|
2613
|
+
options: [:],
|
|
2614
|
+
success: { _, _ in
|
|
2615
|
+
XCTFail("getLatest should reject failed error responses")
|
|
2616
|
+
},
|
|
2617
|
+
error: { error in
|
|
2618
|
+
XCTAssertEqual(error?.message, "response_error")
|
|
2619
|
+
rejected.fulfill()
|
|
2620
|
+
}
|
|
2621
|
+
))
|
|
2622
|
+
|
|
2623
|
+
testPlugin.getLatest(call)
|
|
2624
|
+
wait(for: [rejected], timeout: 10)
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
func testGetLatestBreakingResponseNotifiesBreakingListeners() throws {
|
|
2628
|
+
let latest = AppVersion()
|
|
2629
|
+
latest.version = "2.0.0"
|
|
2630
|
+
latest.breaking = true
|
|
2631
|
+
latest.message = "store_update_required"
|
|
2632
|
+
latest.statusCode = 200
|
|
2633
|
+
|
|
2634
|
+
let breakingImplementation = FreshDownloadCapgoUpdater()
|
|
2635
|
+
breakingImplementation.latestResponse = latest
|
|
2636
|
+
|
|
2637
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2638
|
+
testPlugin.implementation = breakingImplementation
|
|
2639
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2640
|
+
|
|
2641
|
+
let rejected = expectation(description: "getLatest rejects store update response")
|
|
2642
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2643
|
+
callbackId: "get-latest-breaking-response-test",
|
|
2644
|
+
options: [:],
|
|
2645
|
+
success: { _, _ in
|
|
2646
|
+
XCTFail("getLatest should reject store update responses")
|
|
2647
|
+
},
|
|
2648
|
+
error: { error in
|
|
2649
|
+
XCTAssertEqual(error?.message, "store_update_required")
|
|
2650
|
+
rejected.fulfill()
|
|
2651
|
+
}
|
|
2652
|
+
))
|
|
2653
|
+
|
|
2654
|
+
testPlugin.getLatest(call)
|
|
2655
|
+
wait(for: [rejected], timeout: 10)
|
|
2656
|
+
|
|
2657
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("breakingAvailable"))
|
|
2658
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("majorAvailable"))
|
|
2659
|
+
XCTAssertEqual(testPlugin.notifiedEventPayloads["breakingAvailable"]?["version"] as? String, "2.0.0")
|
|
2660
|
+
}
|
|
2661
|
+
|
|
2662
|
+
func testGetLatestBreakingResponseWithoutVersionNotifiesCurrentBundleVersion() throws {
|
|
2663
|
+
let current = BundleInfo(
|
|
2664
|
+
id: "test-id",
|
|
2665
|
+
version: "1.0.0",
|
|
2666
|
+
status: .SUCCESS,
|
|
2667
|
+
downloaded: Date(),
|
|
2668
|
+
checksum: "abc123"
|
|
2669
|
+
)
|
|
2670
|
+
let latest = AppVersion()
|
|
2671
|
+
latest.error = "disable_auto_update_to_major"
|
|
2672
|
+
latest.kind = "blocked"
|
|
2673
|
+
latest.message = "Cannot upgrade major version"
|
|
2674
|
+
latest.statusCode = 200
|
|
2675
|
+
|
|
2676
|
+
let breakingImplementation = FreshDownloadCapgoUpdater()
|
|
2677
|
+
breakingImplementation.currentBundleValue = current
|
|
2678
|
+
breakingImplementation.latestResponse = latest
|
|
2679
|
+
|
|
2680
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2681
|
+
testPlugin.implementation = breakingImplementation
|
|
2682
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2683
|
+
|
|
2684
|
+
let resolved = expectation(description: "getLatest resolves blocked breaking response")
|
|
2685
|
+
let call = try XCTUnwrap(CAPPluginCall(
|
|
2686
|
+
callbackId: "get-latest-breaking-response-no-version-test",
|
|
2687
|
+
options: [:],
|
|
2688
|
+
success: { _, _ in
|
|
2689
|
+
resolved.fulfill()
|
|
2690
|
+
},
|
|
2691
|
+
error: { _ in
|
|
2692
|
+
XCTFail("getLatest should resolve blocked breaking responses")
|
|
2693
|
+
}
|
|
2694
|
+
))
|
|
2695
|
+
|
|
2696
|
+
testPlugin.getLatest(call)
|
|
2697
|
+
wait(for: [resolved], timeout: 10)
|
|
2698
|
+
|
|
2699
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("breakingAvailable"))
|
|
2700
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("majorAvailable"))
|
|
2701
|
+
XCTAssertEqual(testPlugin.notifiedEventPayloads["breakingAvailable"]?["version"] as? String, "1.0.0")
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
func testBlockedUpdateCheckDoesNotNotifyDownloadFailed() {
|
|
2705
|
+
let current = BundleInfo(
|
|
2706
|
+
id: "test-id",
|
|
2707
|
+
version: "1.0.0",
|
|
2708
|
+
status: .SUCCESS,
|
|
2709
|
+
downloaded: Date(),
|
|
2710
|
+
checksum: "abc123"
|
|
2711
|
+
)
|
|
2712
|
+
let latest = AppVersion()
|
|
2713
|
+
latest.version = "2.0.0"
|
|
2714
|
+
latest.error = "disable_auto_update_to_major"
|
|
2715
|
+
latest.kind = "blocked"
|
|
2716
|
+
latest.message = "Cannot upgrade major version"
|
|
2717
|
+
latest.statusCode = 200
|
|
2718
|
+
|
|
2719
|
+
let blockedImplementation = FreshDownloadCapgoUpdater()
|
|
2720
|
+
blockedImplementation.currentBundleValue = current
|
|
2721
|
+
blockedImplementation.latestResponse = latest
|
|
2722
|
+
|
|
2723
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2724
|
+
testPlugin.implementation = blockedImplementation
|
|
2725
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2726
|
+
|
|
2727
|
+
testPlugin.backgroundDownload()
|
|
2728
|
+
|
|
2729
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("noNeedUpdate"))
|
|
2730
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateCheckResult"))
|
|
2731
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("breakingAvailable"))
|
|
2732
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("majorAvailable"))
|
|
2733
|
+
XCTAssertEqual(testPlugin.notifiedEventPayloads["breakingAvailable"]?["version"] as? String, "2.0.0")
|
|
2734
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2735
|
+
XCTAssertFalse(blockedImplementation.sentStatsActions.contains("download_fail"))
|
|
2736
|
+
}
|
|
2737
|
+
|
|
2738
|
+
func testBreakingNoUrlUpdateCheckNotifiesBreakingListeners() {
|
|
2739
|
+
let current = BundleInfo(
|
|
2740
|
+
id: "test-id",
|
|
2741
|
+
version: "1.0.0",
|
|
2742
|
+
status: .SUCCESS,
|
|
2743
|
+
downloaded: Date(),
|
|
2744
|
+
checksum: "abc123"
|
|
2745
|
+
)
|
|
2746
|
+
let latest = AppVersion()
|
|
2747
|
+
latest.version = "2.0.0"
|
|
2748
|
+
latest.breaking = true
|
|
2749
|
+
latest.message = "store_update_required"
|
|
2750
|
+
latest.statusCode = 200
|
|
2751
|
+
|
|
2752
|
+
let breakingImplementation = FreshDownloadCapgoUpdater()
|
|
2753
|
+
breakingImplementation.currentBundleValue = current
|
|
2754
|
+
breakingImplementation.latestResponse = latest
|
|
2755
|
+
|
|
2756
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2757
|
+
testPlugin.implementation = breakingImplementation
|
|
2758
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2759
|
+
|
|
2760
|
+
testPlugin.backgroundDownload()
|
|
2761
|
+
|
|
2762
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("breakingAvailable"))
|
|
2763
|
+
XCTAssertFalse(testPlugin.notifiedEventNames.contains("majorAvailable"))
|
|
2764
|
+
XCTAssertEqual(testPlugin.notifiedEventPayloads["breakingAvailable"]?["version"] as? String, "2.0.0")
|
|
2765
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2766
|
+
XCTAssertTrue(breakingImplementation.sentStatsActions.contains("download_fail"))
|
|
2767
|
+
}
|
|
2768
|
+
|
|
2769
|
+
func testFailedUpdateCheckNotifiesDownloadFailed() {
|
|
2770
|
+
let current = BundleInfo(
|
|
2771
|
+
id: "test-id",
|
|
2772
|
+
version: "1.0.0",
|
|
2773
|
+
status: .SUCCESS,
|
|
2774
|
+
downloaded: Date(),
|
|
2775
|
+
checksum: "abc123"
|
|
2776
|
+
)
|
|
2777
|
+
let latest = AppVersion()
|
|
2778
|
+
latest.error = "response_error"
|
|
2779
|
+
latest.kind = "failed"
|
|
2780
|
+
latest.message = "Error getting Latest"
|
|
2781
|
+
latest.statusCode = 500
|
|
2782
|
+
|
|
2783
|
+
let failedImplementation = FreshDownloadCapgoUpdater()
|
|
2784
|
+
failedImplementation.currentBundleValue = current
|
|
2785
|
+
failedImplementation.latestResponse = latest
|
|
2786
|
+
|
|
2787
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2788
|
+
testPlugin.implementation = failedImplementation
|
|
2789
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
2790
|
+
|
|
2791
|
+
testPlugin.backgroundDownload()
|
|
2792
|
+
|
|
2793
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateCheckResult"))
|
|
2794
|
+
XCTAssertTrue(testPlugin.notifiedEventNames.contains("downloadFailed"))
|
|
2795
|
+
// A failed check downloaded nothing: report update_check_error, not download_fail.
|
|
2796
|
+
XCTAssertFalse(failedImplementation.sentStatsActions.contains("download_fail"))
|
|
2797
|
+
XCTAssertEqual(failedImplementation.sentStatsActions.filter { $0 == "update_check_error" }.count, 1)
|
|
2798
|
+
XCTAssertEqual(failedImplementation.lastStatsVersionName, "1.0.0")
|
|
2799
|
+
XCTAssertEqual(failedImplementation.lastStatsMetadata?["error"], "response_error")
|
|
2800
|
+
XCTAssertEqual(failedImplementation.lastStatsMetadata?["status_code"], "500")
|
|
2801
|
+
}
|
|
2802
|
+
|
|
2803
|
+
func testEveryEventIsDeliveredOnlyAsUpdaterEvent() {
|
|
2804
|
+
let testPlugin = TestableCapacitorUpdaterPlugin()
|
|
2805
|
+
testPlugin.notifyListenersOnMainForTesting("download", data: ["percent": 10], retainUntilConsumed: false)
|
|
2806
|
+
testPlugin.notifyListenersOnMainForTesting("appReady", data: ["status": "ok"], retainUntilConsumed: true)
|
|
2807
|
+
|
|
2808
|
+
// Per-event listeners were removed in 9.0.0: one bridge call per event, always as updaterEvent.
|
|
2809
|
+
XCTAssertEqual(testPlugin.notifiedEvents.map { $0.name }, ["updaterEvent", "updaterEvent"])
|
|
2810
|
+
let events = testPlugin.notifiedEvents
|
|
2811
|
+
XCTAssertEqual(events[0].data?["type"] as? String, "download")
|
|
2812
|
+
XCTAssertEqual((events[0].data?["data"] as? [String: Any])?["percent"] as? Int, 10)
|
|
2813
|
+
XCTAssertFalse(events[0].retain)
|
|
2814
|
+
XCTAssertEqual(events[1].data?["type"] as? String, "appReady")
|
|
2815
|
+
XCTAssertEqual((events[1].data?["data"] as? [String: Any])?["status"] as? String, "ok")
|
|
2816
|
+
XCTAssertTrue(events[1].retain)
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
func testUpdaterEventPayloadHelpers() {
|
|
2820
|
+
let payload = CapacitorUpdaterPlugin.updaterEventPayload(eventName: "appReloaded", data: nil)
|
|
2821
|
+
XCTAssertEqual(payload["type"] as? String, "appReloaded")
|
|
2822
|
+
XCTAssertTrue((payload["data"] as? [String: Any])?.isEmpty ?? false)
|
|
2823
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.updateCheckErrorMetadata(error: "", statusCode: 0), ["error": "unknown"])
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
func testNativeStoreUpdateBlockDetection() {
|
|
2827
|
+
let underNative = AppVersion()
|
|
2828
|
+
underNative.error = "disable_auto_update_under_native"
|
|
2829
|
+
XCTAssertTrue(NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: underNative))
|
|
2830
|
+
|
|
2831
|
+
let patch = AppVersion()
|
|
2832
|
+
patch.error = "disable_auto_update_to_patch"
|
|
2833
|
+
XCTAssertTrue(NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: patch))
|
|
2834
|
+
|
|
2835
|
+
let unrelated = AppVersion()
|
|
2836
|
+
unrelated.error = "response_error"
|
|
2837
|
+
XCTAssertFalse(NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: unrelated))
|
|
2838
|
+
}
|
|
2839
|
+
|
|
2840
|
+
func testNativeUpdatePromptCooldownAndSession() {
|
|
2841
|
+
NativeUpdatePromptCoordinator.resetSessionStateForTesting()
|
|
2842
|
+
let coordinator = NativeUpdatePromptCoordinator(plugin: nil, cooldownHours: 24)
|
|
2843
|
+
UserDefaults.standard.removeObject(forKey: NativeUpdatePromptCoordinator.lastNativeVersionDefaultsKey)
|
|
2844
|
+
UserDefaults.standard.removeObject(forKey: NativeUpdatePromptCoordinator.lastShownMsDefaultsKey)
|
|
2845
|
+
|
|
2846
|
+
XCTAssertTrue(coordinator.shouldShowForNativeVersion("100"))
|
|
2847
|
+
coordinator.recordShown(nativeVersion: "100")
|
|
2848
|
+
XCTAssertFalse(coordinator.shouldShowForNativeVersion("100"))
|
|
2849
|
+
}
|
|
2850
|
+
|
|
2851
|
+
func testHasNativeBuildVersionChangedFallsBackToLegacyStoredKey() {
|
|
2852
|
+
let nativeBuildKey = "LatestNativeBuildVersion"
|
|
2853
|
+
let legacyBuildKey = "LatestVersionNative"
|
|
2854
|
+
UserDefaults.standard.removeObject(forKey: nativeBuildKey)
|
|
2855
|
+
UserDefaults.standard.set("1", forKey: legacyBuildKey)
|
|
2856
|
+
defer {
|
|
2857
|
+
UserDefaults.standard.removeObject(forKey: nativeBuildKey)
|
|
2858
|
+
UserDefaults.standard.removeObject(forKey: legacyBuildKey)
|
|
2859
|
+
}
|
|
2860
|
+
|
|
2861
|
+
plugin.setCurrentBuildVersionForTesting("2")
|
|
2862
|
+
|
|
2863
|
+
XCTAssertTrue(plugin.hasNativeBuildVersionChanged())
|
|
2864
|
+
}
|
|
2865
|
+
|
|
2866
|
+
func testReportNativeVersionStatsPersistsFirstSnapshotWithoutEvent() {
|
|
2867
|
+
let keys = [
|
|
2868
|
+
"CapacitorUpdater.lastVersionOs",
|
|
2869
|
+
"CapacitorUpdater.lastVersionBuild",
|
|
2870
|
+
"CapacitorUpdater.lastVersionCode"
|
|
2871
|
+
]
|
|
2872
|
+
for key in keys {
|
|
2873
|
+
UserDefaults.standard.removeObject(forKey: key)
|
|
2874
|
+
}
|
|
2875
|
+
defer {
|
|
2876
|
+
for key in keys {
|
|
2877
|
+
UserDefaults.standard.removeObject(forKey: key)
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
let statsImplementation = HealthStatsCapgoUpdater()
|
|
2882
|
+
plugin.implementation = statsImplementation
|
|
2883
|
+
|
|
2884
|
+
plugin.reportNativeVersionStatsIfChanged(currentVersionBuild: "1.0.0", currentVersionCode: "100", currentVersionOs: "17.0")
|
|
2885
|
+
|
|
2886
|
+
XCTAssertTrue(statsImplementation.sentStatsActions.isEmpty)
|
|
2887
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionOs"), "17.0")
|
|
2888
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionBuild"), "1.0.0")
|
|
2889
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionCode"), "100")
|
|
2890
|
+
}
|
|
2891
|
+
|
|
2892
|
+
func testReportNativeVersionStatsSendsChangedOsAndNativeVersionEvents() {
|
|
2893
|
+
let values = [
|
|
2894
|
+
"CapacitorUpdater.lastVersionOs": "16.0",
|
|
2895
|
+
"CapacitorUpdater.lastVersionBuild": "1.0.0",
|
|
2896
|
+
"CapacitorUpdater.lastVersionCode": "100"
|
|
2897
|
+
]
|
|
2898
|
+
for (key, value) in values {
|
|
2899
|
+
UserDefaults.standard.set(value, forKey: key)
|
|
2900
|
+
}
|
|
2901
|
+
defer {
|
|
2902
|
+
for key in values.keys {
|
|
2903
|
+
UserDefaults.standard.removeObject(forKey: key)
|
|
2904
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
let statsImplementation = HealthStatsCapgoUpdater()
|
|
2908
|
+
plugin.implementation = statsImplementation
|
|
2909
|
+
|
|
2910
|
+
plugin.reportNativeVersionStatsIfChanged(currentVersionBuild: "1.1.0", currentVersionCode: "101", currentVersionOs: "17.0")
|
|
2911
|
+
|
|
2912
|
+
XCTAssertEqual(statsImplementation.sentStatsActions, ["os_version_changed", "native_app_version_changed"])
|
|
2913
|
+
XCTAssertEqual(statsImplementation.sentStatsMetadata[0]?["previous_version_os"], "16.0")
|
|
2914
|
+
XCTAssertEqual(statsImplementation.sentStatsMetadata[0]?["current_version_os"], "17.0")
|
|
2915
|
+
XCTAssertEqual(statsImplementation.sentStatsMetadata[1]?["previous_version_build"], "1.0.0")
|
|
2916
|
+
XCTAssertEqual(statsImplementation.sentStatsMetadata[1]?["current_version_build"], "1.1.0")
|
|
2917
|
+
XCTAssertEqual(statsImplementation.sentStatsMetadata[1]?["previous_version_code"], "100")
|
|
2918
|
+
XCTAssertEqual(statsImplementation.sentStatsMetadata[1]?["current_version_code"], "101")
|
|
2919
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionOs"), "17.0")
|
|
2920
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionBuild"), "1.1.0")
|
|
2921
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionCode"), "101")
|
|
2922
|
+
}
|
|
2923
|
+
|
|
2924
|
+
func testReportNativeVersionStatsKeepsChangedSnapshotPendingUntilStatsAck() {
|
|
2925
|
+
let values = [
|
|
2926
|
+
"CapacitorUpdater.lastVersionOs": "16.0",
|
|
2927
|
+
"CapacitorUpdater.lastVersionBuild": "1.0.0",
|
|
2928
|
+
"CapacitorUpdater.lastVersionCode": "100"
|
|
2929
|
+
]
|
|
2930
|
+
for (key, value) in values {
|
|
2931
|
+
UserDefaults.standard.set(value, forKey: key)
|
|
2932
|
+
}
|
|
2933
|
+
defer {
|
|
2934
|
+
for key in values.keys {
|
|
2935
|
+
UserDefaults.standard.removeObject(forKey: key)
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
let statsImplementation = HealthStatsCapgoUpdater()
|
|
2940
|
+
statsImplementation.acknowledgeStats = false
|
|
2941
|
+
plugin.implementation = statsImplementation
|
|
2942
|
+
|
|
2943
|
+
plugin.reportNativeVersionStatsIfChanged(currentVersionBuild: "1.1.0", currentVersionCode: "101", currentVersionOs: "17.0")
|
|
2944
|
+
|
|
2945
|
+
XCTAssertEqual(statsImplementation.sentStatsActions, ["os_version_changed", "native_app_version_changed"])
|
|
2946
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionOs"), "16.0")
|
|
2947
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionBuild"), "1.0.0")
|
|
2948
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: "CapacitorUpdater.lastVersionCode"), "100")
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
func testNativeVersionStatsAfterNativeBuildResetUseBuiltinBundle() {
|
|
2952
|
+
let values = [
|
|
2953
|
+
"LatestNativeBuildVersion": "1",
|
|
2954
|
+
"CapacitorUpdater.lastVersionOs": "17.0",
|
|
2955
|
+
"CapacitorUpdater.lastVersionBuild": "1.0.0",
|
|
2956
|
+
"CapacitorUpdater.lastVersionCode": "1"
|
|
2957
|
+
]
|
|
2958
|
+
for (key, value) in values {
|
|
2959
|
+
UserDefaults.standard.set(value, forKey: key)
|
|
2960
|
+
}
|
|
2961
|
+
defer {
|
|
2962
|
+
for key in values.keys {
|
|
2963
|
+
UserDefaults.standard.removeObject(forKey: key)
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
let resetPlugin = TestableCapacitorUpdaterPlugin()
|
|
2968
|
+
let statsImplementation = ResettingHealthStatsCapgoUpdater()
|
|
2969
|
+
statsImplementation.currentBundleValue = BundleInfo(
|
|
2970
|
+
id: "ota-id",
|
|
2971
|
+
version: "ota-version",
|
|
2972
|
+
status: .SUCCESS,
|
|
2973
|
+
downloaded: Date(),
|
|
2974
|
+
checksum: "ota"
|
|
2975
|
+
)
|
|
2976
|
+
resetPlugin.implementation = statsImplementation
|
|
2977
|
+
resetPlugin.setCurrentBuildVersionForTesting("2")
|
|
2978
|
+
|
|
2979
|
+
XCTAssertTrue(resetPlugin.resetCurrentBundleForNativeBuildChangeIfNeeded())
|
|
2980
|
+
resetPlugin.reportNativeVersionStatsIfChanged(currentVersionBuild: "2.0.0", currentVersionCode: "2", currentVersionOs: "17.0")
|
|
2981
|
+
|
|
2982
|
+
XCTAssertEqual(statsImplementation.sentStatsActions, ["native_app_version_changed"])
|
|
2983
|
+
XCTAssertEqual(statsImplementation.lastStatsVersionName, "builtin")
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
func testResetCurrentBundleForNativeBuildChangeIfNeededResetsSynchronously() {
|
|
2987
|
+
let nativeBuildKey = "LatestNativeBuildVersion"
|
|
2988
|
+
let resetPlugin = TestableCapacitorUpdaterPlugin()
|
|
2989
|
+
let resetImplementation = ResetTrackingCapgoUpdater()
|
|
2990
|
+
resetPlugin.implementation = resetImplementation
|
|
2991
|
+
UserDefaults.standard.set("1", forKey: nativeBuildKey)
|
|
2992
|
+
defer {
|
|
2993
|
+
UserDefaults.standard.removeObject(forKey: nativeBuildKey)
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
resetPlugin.setCurrentBuildVersionForTesting("2")
|
|
2997
|
+
|
|
2998
|
+
XCTAssertTrue(resetPlugin.resetCurrentBundleForNativeBuildChangeIfNeeded())
|
|
2999
|
+
XCTAssertTrue(resetImplementation.resetCalled)
|
|
3000
|
+
XCTAssertTrue(resetImplementation.resetIsInternal)
|
|
3001
|
+
}
|
|
3002
|
+
|
|
3003
|
+
private static let appLaunchSessionDefaultsKeys = [
|
|
3004
|
+
"CapacitorUpdater.appSessionId",
|
|
3005
|
+
"CapacitorUpdater.appSessionForeground",
|
|
3006
|
+
"CapacitorUpdater.appSessionStartedAt",
|
|
3007
|
+
"CapacitorUpdater.lastReportedUncleanSessionId"
|
|
3008
|
+
]
|
|
3009
|
+
|
|
3010
|
+
private func prepareAppLaunchStartOtaFixture(
|
|
3011
|
+
storedNativeBuild: String,
|
|
3012
|
+
currentBuild: String
|
|
3013
|
+
) -> (TestableCapacitorUpdaterPlugin, ResettingHealthStatsCapgoUpdater) {
|
|
3014
|
+
let nativeBuildKey = "LatestNativeBuildVersion"
|
|
3015
|
+
UserDefaults.standard.set(storedNativeBuild, forKey: nativeBuildKey)
|
|
3016
|
+
Self.appLaunchSessionDefaultsKeys.forEach { UserDefaults.standard.removeObject(forKey: $0) }
|
|
3017
|
+
|
|
3018
|
+
let resetPlugin = TestableCapacitorUpdaterPlugin()
|
|
3019
|
+
let statsImplementation = ResettingHealthStatsCapgoUpdater()
|
|
3020
|
+
statsImplementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
|
|
3021
|
+
statsImplementation.statsUrl = "https://example.com/stats"
|
|
3022
|
+
statsImplementation.currentBundleValue = BundleInfo(
|
|
3023
|
+
id: "ota-id",
|
|
3024
|
+
version: "2.8.35",
|
|
3025
|
+
status: .SUCCESS,
|
|
3026
|
+
downloaded: Date(),
|
|
3027
|
+
checksum: "ota"
|
|
3028
|
+
)
|
|
3029
|
+
resetPlugin.implementation = statsImplementation
|
|
3030
|
+
resetPlugin.setCurrentBuildVersionForTesting(currentBuild)
|
|
3031
|
+
return (resetPlugin, statsImplementation)
|
|
3032
|
+
}
|
|
3033
|
+
|
|
3034
|
+
private func tearDownAppLaunchStartOtaFixture() {
|
|
3035
|
+
UserDefaults.standard.removeObject(forKey: "LatestNativeBuildVersion")
|
|
3036
|
+
Self.appLaunchSessionDefaultsKeys.forEach { UserDefaults.standard.removeObject(forKey: $0) }
|
|
3037
|
+
}
|
|
3038
|
+
|
|
3039
|
+
func testAppLaunchStartReportsBuiltinAfterNativeBuildReset() {
|
|
3040
|
+
let (resetPlugin, statsImplementation) = prepareAppLaunchStartOtaFixture(
|
|
3041
|
+
storedNativeBuild: "9",
|
|
3042
|
+
currentBuild: "15"
|
|
3043
|
+
)
|
|
3044
|
+
defer { tearDownAppLaunchStartOtaFixture() }
|
|
3045
|
+
XCTAssertEqual(statsImplementation.getCurrentBundle().getVersionName(), "2.8.35")
|
|
3046
|
+
|
|
3047
|
+
XCTAssertTrue(
|
|
3048
|
+
resetPlugin.resetStartupBundleAndReportAppLaunchStartForTesting(
|
|
3049
|
+
resetWhenUpdate: true,
|
|
3050
|
+
nativeBuildVersionChanged: true
|
|
3051
|
+
)
|
|
3052
|
+
)
|
|
3053
|
+
|
|
3054
|
+
XCTAssertEqual(statsImplementation.autoResetCallCount, 1)
|
|
3055
|
+
XCTAssertEqual(statsImplementation.resetCallCount, 1)
|
|
3056
|
+
XCTAssertEqual(statsImplementation.sentStatsActions, ["app_launch_start"])
|
|
3057
|
+
XCTAssertEqual(statsImplementation.lastStatsVersionName, "builtin")
|
|
3058
|
+
XCTAssertEqual(statsImplementation.lastStatsMetadata?["source"], "plugin_load")
|
|
3059
|
+
XCTAssertNotNil(statsImplementation.lastStatsMetadata?["launch_started_at"])
|
|
3060
|
+
}
|
|
3061
|
+
|
|
3062
|
+
func testAppLaunchStartReportsOtaBundleWithoutNativeBuildChange() {
|
|
3063
|
+
let (resetPlugin, statsImplementation) = prepareAppLaunchStartOtaFixture(
|
|
3064
|
+
storedNativeBuild: "15",
|
|
3065
|
+
currentBuild: "15"
|
|
3066
|
+
)
|
|
3067
|
+
defer { tearDownAppLaunchStartOtaFixture() }
|
|
3068
|
+
|
|
3069
|
+
XCTAssertFalse(
|
|
3070
|
+
resetPlugin.resetStartupBundleAndReportAppLaunchStartForTesting(
|
|
3071
|
+
resetWhenUpdate: true,
|
|
3072
|
+
nativeBuildVersionChanged: false
|
|
3073
|
+
)
|
|
3074
|
+
)
|
|
3075
|
+
|
|
3076
|
+
// Same fixture, no native-build change: the OTA version is reported, so the builtin
|
|
3077
|
+
// result above comes from the native-build reset itself.
|
|
3078
|
+
XCTAssertEqual(statsImplementation.resetCallCount, 0)
|
|
3079
|
+
XCTAssertEqual(statsImplementation.sentStatsActions, ["app_launch_start"])
|
|
3080
|
+
XCTAssertEqual(statsImplementation.lastStatsVersionName, "2.8.35")
|
|
3081
|
+
}
|
|
3082
|
+
|
|
3083
|
+
func testLaunchSplashSchedulesAutoSplashscreenTimeoutWhenDirectUpdateIsActive() {
|
|
3084
|
+
plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
|
|
3085
|
+
plugin.configureDirectUpdateModeForTesting("onLaunch", onLaunchDirectUpdateUsed: false)
|
|
3086
|
+
|
|
3087
|
+
plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
|
|
3088
|
+
|
|
3089
|
+
XCTAssertTrue(plugin.hasSplashscreenTimeoutScheduledForTesting())
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
private func makeSplashTimeoutPlugin(mode: String = "onLaunch") throws -> (SplashTimeoutCapacitorUpdaterPlugin, SplashTimeoutCapgoUpdater) {
|
|
3093
|
+
clearDelayStorage()
|
|
3094
|
+
CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
|
|
3095
|
+
let implementation = SplashTimeoutCapgoUpdater()
|
|
3096
|
+
implementation.currentBundleValue = makeOnlyDownloadBundle(id: "current-id", version: "1.0.0", status: .SUCCESS)
|
|
3097
|
+
implementation.latestResponse = makeOnlyDownloadLatest()
|
|
3098
|
+
implementation.downloadedBundleValue = makeOnlyDownloadBundle()
|
|
3099
|
+
let testPlugin = SplashTimeoutCapacitorUpdaterPlugin()
|
|
3100
|
+
testPlugin.implementation = implementation
|
|
3101
|
+
testPlugin.configureDirectUpdateModeForTesting(mode)
|
|
3102
|
+
testPlugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
|
|
3103
|
+
testPlugin.setUpdateUrlForTesting("https://example.com/channel")
|
|
3104
|
+
testPlugin.setDelayUpdateUtilsForTesting(try makeDelayUpdateUtils())
|
|
3105
|
+
testPlugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
|
|
3106
|
+
return (testPlugin, implementation)
|
|
3107
|
+
}
|
|
3108
|
+
|
|
3109
|
+
private func resumeAfterSplashTimeout(_ testPlugin: SplashTimeoutCapacitorUpdaterPlugin) {
|
|
3110
|
+
XCTAssertTrue(testPlugin.hasSplashscreenTimeoutScheduledForTesting())
|
|
3111
|
+
testPlugin.fireSplashscreenTimeoutForTesting()
|
|
3112
|
+
XCTAssertFalse(testPlugin.shouldUseDirectUpdateForTesting())
|
|
3113
|
+
testPlugin.appMovedToBackground()
|
|
3114
|
+
testPlugin.appMovedToForeground()
|
|
3115
|
+
}
|
|
3116
|
+
|
|
3117
|
+
private func assertDeferredBundleInstallsOnNextBackground(
|
|
3118
|
+
plugin testPlugin: SplashTimeoutCapacitorUpdaterPlugin,
|
|
3119
|
+
implementation: SplashTimeoutCapgoUpdater,
|
|
3120
|
+
expectedBundleId: String,
|
|
3121
|
+
file: StaticString = #filePath,
|
|
3122
|
+
line: UInt = #line
|
|
3123
|
+
) {
|
|
3124
|
+
XCTAssertEqual(implementation.getNextBundle()?.getId(), expectedBundleId, file: file, line: line)
|
|
3125
|
+
let previousReloadCalls = testPlugin.reloadCalls
|
|
3126
|
+
|
|
3127
|
+
testPlugin.appMovedToBackground()
|
|
3128
|
+
|
|
3129
|
+
XCTAssertEqual(testPlugin.reloadCalls, previousReloadCalls + 1, file: file, line: line)
|
|
3130
|
+
XCTAssertEqual(implementation.getCurrentBundle().getId(), expectedBundleId, file: file, line: line)
|
|
3131
|
+
XCTAssertNil(implementation.getNextBundle(), file: file, line: line)
|
|
3132
|
+
XCTAssertNil(implementation.lastSetNextBundleId, file: file, line: line)
|
|
3133
|
+
}
|
|
3134
|
+
|
|
3135
|
+
func testExpiredLaunchDownloadStaysDeferredAfterBackgroundAndForeground() throws {
|
|
3136
|
+
let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
|
|
3137
|
+
defer { implementation.onDownloadStart = nil; clearDelayStorage() }
|
|
3138
|
+
implementation.onDownloadStart = {
|
|
3139
|
+
XCTAssertTrue(testPlugin.hasConsumedOnLaunchDirectUpdateForTesting)
|
|
3140
|
+
self.resumeAfterSplashTimeout(testPlugin)
|
|
3141
|
+
XCTAssertFalse(testPlugin.hasSplashscreenTimeoutScheduledForTesting())
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
testPlugin.backgroundDownload()
|
|
3145
|
+
|
|
3146
|
+
XCTAssertEqual(implementation.downloadCalls, 1)
|
|
3147
|
+
XCTAssertEqual(implementation.stagePendingReloadCalls, 0)
|
|
3148
|
+
XCTAssertEqual(testPlugin.reloadCalls, 0)
|
|
3149
|
+
XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "1.0.0")
|
|
3150
|
+
XCTAssertEqual(implementation.lastSetNextBundleId, "downloaded-id")
|
|
3151
|
+
assertDeferredBundleInstallsOnNextBackground(plugin: testPlugin, implementation: implementation, expectedBundleId: "downloaded-id")
|
|
3152
|
+
}
|
|
3153
|
+
|
|
3154
|
+
func testExpiredAlwaysDownloadInstallsOnNextBackground() throws {
|
|
3155
|
+
let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
|
|
3156
|
+
defer { implementation.onDownloadStart = nil; clearDelayStorage() }
|
|
3157
|
+
implementation.onDownloadStart = { testPlugin.fireSplashscreenTimeoutForTesting() }
|
|
3158
|
+
|
|
3159
|
+
testPlugin.backgroundDownload()
|
|
3160
|
+
|
|
3161
|
+
XCTAssertEqual(testPlugin.reloadCalls, 0)
|
|
3162
|
+
XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "1.0.0")
|
|
3163
|
+
assertDeferredBundleInstallsOnNextBackground(plugin: testPlugin, implementation: implementation, expectedBundleId: "downloaded-id")
|
|
3164
|
+
}
|
|
3165
|
+
|
|
3166
|
+
func testExpiredLaunchCachedBundleStaysDeferredAfterBackgroundAndForeground() throws {
|
|
3167
|
+
let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
|
|
3168
|
+
implementation.existingBundleValue = makeOnlyDownloadBundle()
|
|
3169
|
+
defer { implementation.onGetLatest = nil; clearDelayStorage() }
|
|
3170
|
+
implementation.onGetLatest = { self.resumeAfterSplashTimeout(testPlugin) }
|
|
3171
|
+
|
|
3172
|
+
testPlugin.backgroundDownload()
|
|
3173
|
+
|
|
3174
|
+
XCTAssertEqual(implementation.downloadCalls, 0)
|
|
3175
|
+
XCTAssertEqual(implementation.stagePendingReloadCalls, 0)
|
|
3176
|
+
XCTAssertEqual(testPlugin.reloadCalls, 0)
|
|
3177
|
+
XCTAssertEqual(implementation.lastSetNextBundleId, "downloaded-id")
|
|
3178
|
+
assertDeferredBundleInstallsOnNextBackground(plugin: testPlugin, implementation: implementation, expectedBundleId: "downloaded-id")
|
|
3179
|
+
}
|
|
3180
|
+
|
|
3181
|
+
func testExpiredLaunchBuiltinStaysDeferredAfterBackgroundAndForeground() throws {
|
|
3182
|
+
let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
|
|
3183
|
+
implementation.latestResponse.version = "builtin"
|
|
3184
|
+
defer { implementation.onGetLatest = nil; clearDelayStorage() }
|
|
3185
|
+
implementation.onGetLatest = { self.resumeAfterSplashTimeout(testPlugin) }
|
|
3186
|
+
|
|
3187
|
+
testPlugin.backgroundDownload()
|
|
3188
|
+
|
|
3189
|
+
XCTAssertEqual(testPlugin.resetCalls, 0)
|
|
3190
|
+
XCTAssertEqual(testPlugin.reloadCalls, 0)
|
|
3191
|
+
XCTAssertEqual(implementation.lastSetNextBundleId, BundleInfo.ID_BUILTIN)
|
|
3192
|
+
assertDeferredBundleInstallsOnNextBackground(plugin: testPlugin, implementation: implementation, expectedBundleId: BundleInfo.ID_BUILTIN)
|
|
3193
|
+
}
|
|
3194
|
+
|
|
3195
|
+
func testUnexpiredLaunchDownloadCanInstallAfterBackgroundAndForeground() throws {
|
|
3196
|
+
let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
|
|
3197
|
+
defer { implementation.onDownloadStart = nil; clearDelayStorage() }
|
|
3198
|
+
implementation.onDownloadStart = {
|
|
3199
|
+
testPlugin.appMovedToBackground()
|
|
3200
|
+
testPlugin.appMovedToForeground()
|
|
3201
|
+
}
|
|
3202
|
+
|
|
3203
|
+
testPlugin.backgroundDownload()
|
|
3204
|
+
|
|
3205
|
+
XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
|
|
3206
|
+
XCTAssertEqual(testPlugin.reloadCalls, 1)
|
|
3207
|
+
XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
|
|
3208
|
+
XCTAssertNil(implementation.lastSetNextBundleId)
|
|
3209
|
+
}
|
|
3210
|
+
|
|
3211
|
+
func testLaterAlwaysDownloadCanInstallAfterEarlierSplashTimeout() throws {
|
|
3212
|
+
let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
|
|
3213
|
+
defer { implementation.onDownloadStart = nil; clearDelayStorage() }
|
|
3214
|
+
implementation.onDownloadStart = { self.resumeAfterSplashTimeout(testPlugin) }
|
|
3215
|
+
testPlugin.backgroundDownload()
|
|
3216
|
+
XCTAssertEqual(testPlugin.reloadCalls, 0)
|
|
3217
|
+
|
|
3218
|
+
implementation.onDownloadStart = nil
|
|
3219
|
+
testPlugin.backgroundDownload()
|
|
3220
|
+
|
|
3221
|
+
XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
|
|
3222
|
+
XCTAssertEqual(testPlugin.reloadCalls, 1)
|
|
3223
|
+
XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
|
|
3224
|
+
}
|
|
3225
|
+
|
|
3226
|
+
func testLaunchSplashDoesNotScheduleTimeoutAfterOnLaunchDirectUpdateConsumed() {
|
|
3227
|
+
plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
|
|
3228
|
+
plugin.configureDirectUpdateModeForTesting("onLaunch", onLaunchDirectUpdateUsed: true)
|
|
3229
|
+
|
|
3230
|
+
plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
|
|
3231
|
+
|
|
3232
|
+
XCTAssertFalse(plugin.hasSplashscreenTimeoutScheduledForTesting())
|
|
3233
|
+
}
|
|
3234
|
+
|
|
3235
|
+
func testLaunchSplashTimeoutDoesNotConsumeAtInstallDirectUpdateWindow() {
|
|
3236
|
+
plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
|
|
3237
|
+
plugin.configureDirectUpdateModeForTesting("atInstall", onLaunchDirectUpdateUsed: false)
|
|
3238
|
+
plugin.setWasRecentlyInstalledOrUpdatedForTesting(true)
|
|
3239
|
+
|
|
3240
|
+
plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
|
|
3241
|
+
|
|
3242
|
+
XCTAssertTrue(plugin.hasSplashscreenTimeoutScheduledForTesting())
|
|
3243
|
+
XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3246
|
+
func testShowSplashscreenOptionsDisableAutoHide() {
|
|
3247
|
+
let options = plugin.splashscreenOptionsForTesting(methodName: "show")
|
|
3248
|
+
|
|
3249
|
+
XCTAssertEqual(options["autoHide"] as? Bool, false)
|
|
3250
|
+
XCTAssertEqual(options["fadeInDuration"] as? Int, 0)
|
|
3251
|
+
}
|
|
3252
|
+
|
|
3253
|
+
func testHideSplashscreenOptionsStayEmpty() {
|
|
3254
|
+
let options = plugin.splashscreenOptionsForTesting(methodName: "hide")
|
|
3255
|
+
|
|
3256
|
+
XCTAssertTrue(options.isEmpty)
|
|
3257
|
+
}
|
|
3258
|
+
|
|
3259
|
+
func testSplashscreenInvocationTokenRejectsStaleRequests() {
|
|
3260
|
+
XCTAssertTrue(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
|
|
3261
|
+
|
|
3262
|
+
plugin.advanceSplashscreenInvocationTokenForTesting()
|
|
3263
|
+
|
|
3264
|
+
XCTAssertFalse(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
|
|
3265
|
+
}
|
|
3266
|
+
|
|
3267
|
+
func testDelayUpdateUtilsSetMultiDelayStoresMultipleConditions() throws {
|
|
3268
|
+
let utils = try makeDelayUpdateUtils()
|
|
3269
|
+
clearDelayStorage()
|
|
3270
|
+
defer { clearDelayStorage() }
|
|
3271
|
+
let json = try makeDelayConditionsJSON()
|
|
3272
|
+
|
|
3273
|
+
XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
|
|
3274
|
+
XCTAssertEqual(UserDefaults.standard.string(forKey: delayPreferencesKey), json)
|
|
3275
|
+
}
|
|
3276
|
+
|
|
3277
|
+
func testDelayUpdateUtilsCheckCancelDelayKilledKeepsOtherConditions() throws {
|
|
3278
|
+
let utils = try makeDelayUpdateUtils()
|
|
3279
|
+
clearDelayStorage()
|
|
3280
|
+
defer { clearDelayStorage() }
|
|
3281
|
+
let json = try makeDelayConditionsJSON()
|
|
3282
|
+
XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
|
|
3283
|
+
|
|
3284
|
+
utils.checkCancelDelay(source: .killed)
|
|
3285
|
+
|
|
3286
|
+
let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
|
|
3287
|
+
let storedData = try XCTUnwrap(stored.data(using: .utf8))
|
|
3288
|
+
let parsed = try XCTUnwrap(JSONSerialization.jsonObject(with: storedData) as? [[String: String]])
|
|
3289
|
+
|
|
3290
|
+
XCTAssertEqual(parsed.count, 1)
|
|
3291
|
+
XCTAssertEqual(parsed.first?["kind"], "background")
|
|
3292
|
+
XCTAssertEqual(parsed.first?["value"], "5000")
|
|
3293
|
+
}
|
|
3294
|
+
|
|
3295
|
+
func testDelayUpdateUtilsCheckCancelDelayOrModeKilledCancelsImmediately() throws {
|
|
3296
|
+
let utils = try makeDelayUpdateUtils()
|
|
3297
|
+
clearDelayStorage()
|
|
3298
|
+
defer { clearDelayStorage() }
|
|
3299
|
+
let json = try makeDelayConditionsJSON()
|
|
3300
|
+
XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
|
|
3301
|
+
XCTAssertTrue(utils.setConditionMode(DelayUpdateUtils.DELAY_CONDITION_MODE_OR))
|
|
3302
|
+
|
|
3303
|
+
utils.checkCancelDelay(source: .killed)
|
|
3304
|
+
|
|
3305
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: delayPreferencesKey))
|
|
3306
|
+
XCTAssertNil(UserDefaults.standard.string(forKey: delayConditionModeKey))
|
|
3307
|
+
}
|
|
3308
|
+
|
|
3309
|
+
func testDelayUpdateUtilsSetConditionModePersistsValue() throws {
|
|
3310
|
+
let utils = try makeDelayUpdateUtils()
|
|
3311
|
+
clearDelayStorage()
|
|
3312
|
+
defer { clearDelayStorage() }
|
|
3313
|
+
|
|
3314
|
+
XCTAssertTrue(utils.setConditionMode(DelayUpdateUtils.DELAY_CONDITION_MODE_OR))
|
|
3315
|
+
XCTAssertEqual(utils.getConditionMode(), DelayUpdateUtils.DELAY_CONDITION_MODE_OR)
|
|
3316
|
+
}
|
|
3317
|
+
|
|
3318
|
+
// MARK: - DelayUntilNext Tests
|
|
3319
|
+
|
|
3320
|
+
func testDelayUntilNextDescription() {
|
|
3321
|
+
XCTAssertEqual(DelayUntilNext.background.description, "background")
|
|
3322
|
+
XCTAssertEqual(DelayUntilNext.kill.description, "kill")
|
|
3323
|
+
XCTAssertEqual(DelayUntilNext.nativeVersion.description, "nativeVersion")
|
|
3324
|
+
XCTAssertEqual(DelayUntilNext.date.description, "date")
|
|
3325
|
+
}
|
|
3326
|
+
|
|
3327
|
+
func testDelayUntilNextEncodeDecode() throws {
|
|
3328
|
+
let original = DelayUntilNext.background
|
|
3329
|
+
|
|
3330
|
+
// Encode
|
|
3331
|
+
let encoder = JSONEncoder()
|
|
3332
|
+
let data = try encoder.encode(original)
|
|
3333
|
+
|
|
3334
|
+
// Decode
|
|
3335
|
+
let decoder = JSONDecoder()
|
|
3336
|
+
let decoded = try decoder.decode(DelayUntilNext.self, from: data)
|
|
3337
|
+
|
|
3338
|
+
XCTAssertEqual(decoded, original)
|
|
3339
|
+
}
|
|
3340
|
+
|
|
3341
|
+
// MARK: - Logger Tests
|
|
3342
|
+
|
|
3343
|
+
func testLoggerInitialization() {
|
|
3344
|
+
let logger = Logger(withTag: "TestTag")
|
|
3345
|
+
XCTAssertNotNil(logger)
|
|
3346
|
+
|
|
3347
|
+
// Test different log levels
|
|
3348
|
+
logger.debug("Debug message")
|
|
3349
|
+
logger.info("Info message")
|
|
3350
|
+
logger.error("Error message")
|
|
3351
|
+
// No assertions here as logger just prints, but we ensure no crashes
|
|
3352
|
+
}
|
|
3353
|
+
|
|
3354
|
+
// MARK: - UserDefaults Extension Tests
|
|
3355
|
+
|
|
3356
|
+
func testSetAndGetObject() {
|
|
3357
|
+
let testObject = ["key": "value", "number": 42] as [String: Any]
|
|
3358
|
+
UserDefaults.standard.set(testObject, forKey: "test_object")
|
|
3359
|
+
|
|
3360
|
+
let retrievedObject = UserDefaults.standard.object(forKey: "test_object") as? [String: Any]
|
|
3361
|
+
XCTAssertNotNil(retrievedObject)
|
|
3362
|
+
XCTAssertEqual(retrievedObject?["key"] as? String, "value")
|
|
3363
|
+
XCTAssertEqual(retrievedObject?["number"] as? Int, 42)
|
|
3364
|
+
|
|
3365
|
+
// Clean up
|
|
3366
|
+
UserDefaults.standard.removeObject(forKey: "test_object")
|
|
3367
|
+
}
|
|
3368
|
+
|
|
3369
|
+
func testSetAndGetDictionary() {
|
|
3370
|
+
let testDict = ["id": "1", "name": "Test"]
|
|
3371
|
+
UserDefaults.standard.set(testDict, forKey: "test_dict")
|
|
3372
|
+
|
|
3373
|
+
let retrievedDict = UserDefaults.standard.dictionary(forKey: "test_dict")
|
|
3374
|
+
XCTAssertNotNil(retrievedDict)
|
|
3375
|
+
XCTAssertEqual(retrievedDict?["id"] as? String, "1")
|
|
3376
|
+
XCTAssertEqual(retrievedDict?["name"] as? String, "Test")
|
|
3377
|
+
|
|
3378
|
+
// Clean up
|
|
3379
|
+
UserDefaults.standard.removeObject(forKey: "test_dict")
|
|
3380
|
+
}
|
|
3381
|
+
|
|
3382
|
+
// MARK: - File System Tests
|
|
3383
|
+
|
|
3384
|
+
func testFileOperations() {
|
|
3385
|
+
let testPath = NSTemporaryDirectory().appending("test_file.txt")
|
|
3386
|
+
let testContent = "Test content"
|
|
3387
|
+
|
|
3388
|
+
// Test file creation
|
|
3389
|
+
let success = FileManager.default.createFile(
|
|
3390
|
+
atPath: testPath,
|
|
3391
|
+
contents: testContent.data(using: .utf8),
|
|
3392
|
+
attributes: nil
|
|
3393
|
+
)
|
|
3394
|
+
XCTAssertTrue(success)
|
|
3395
|
+
|
|
3396
|
+
// Test file existence
|
|
3397
|
+
XCTAssertTrue(FileManager.default.fileExists(atPath: testPath))
|
|
3398
|
+
|
|
3399
|
+
// Test file deletion
|
|
3400
|
+
do {
|
|
3401
|
+
try FileManager.default.removeItem(atPath: testPath)
|
|
3402
|
+
XCTAssertFalse(FileManager.default.fileExists(atPath: testPath))
|
|
3403
|
+
} catch {
|
|
3404
|
+
XCTFail("Failed to delete test file: \(error)")
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3407
|
+
|
|
3408
|
+
// MARK: - Bundle Path Tests
|
|
3409
|
+
|
|
3410
|
+
func testBundlePathGeneration() {
|
|
3411
|
+
let bundleId = "test-bundle-123"
|
|
3412
|
+
|
|
3413
|
+
// Generate a mock bundle path
|
|
3414
|
+
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
|
|
3415
|
+
let bundlePath = documentsPath.appending("/\(bundleId)")
|
|
3416
|
+
|
|
3417
|
+
XCTAssertTrue(bundlePath.contains(bundleId))
|
|
3418
|
+
XCTAssertTrue(bundlePath.contains("Documents"))
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
// MARK: - Date Extension Tests
|
|
3422
|
+
|
|
3423
|
+
func testDateISO8601Formatting() {
|
|
3424
|
+
let date = Date(timeIntervalSince1970: 0)
|
|
3425
|
+
let formatted = date.iso8601withFractionalSeconds
|
|
3426
|
+
|
|
3427
|
+
XCTAssertNotNil(formatted)
|
|
3428
|
+
XCTAssertTrue(formatted.contains("1970"))
|
|
3429
|
+
}
|
|
3430
|
+
|
|
3431
|
+
// MARK: - String Extension Tests
|
|
3432
|
+
|
|
3433
|
+
func testStringTrim() {
|
|
3434
|
+
let testString = " test string "
|
|
3435
|
+
let trimmed = testString.trim()
|
|
3436
|
+
|
|
3437
|
+
XCTAssertEqual(trimmed, "test string")
|
|
3438
|
+
}
|
|
3439
|
+
|
|
3440
|
+
func testStringTrimWithNewlines() {
|
|
3441
|
+
let testString = "\n\ntest\n\n"
|
|
3442
|
+
let trimmed = testString.trim()
|
|
3443
|
+
|
|
3444
|
+
XCTAssertEqual(trimmed, "test")
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3447
|
+
// MARK: - CapgoUpdater Tests
|
|
3448
|
+
|
|
3449
|
+
func testCapgoUpdaterInitialization() {
|
|
3450
|
+
let updater = CapgoUpdater()
|
|
3451
|
+
XCTAssertNotNil(updater)
|
|
3452
|
+
}
|
|
3453
|
+
|
|
3454
|
+
func testInfoObjectParametersIncludeInstallSource() {
|
|
3455
|
+
let info = InfoObject(
|
|
3456
|
+
platform: "ios",
|
|
3457
|
+
device_id: "device-id",
|
|
3458
|
+
app_id: "com.example.app",
|
|
3459
|
+
custom_id: "",
|
|
3460
|
+
version_build: "1.0.0",
|
|
3461
|
+
version_code: "1",
|
|
3462
|
+
version_os: "18.0",
|
|
3463
|
+
version_name: "builtin",
|
|
3464
|
+
old_version_name: "",
|
|
3465
|
+
plugin_version: "8.0.0",
|
|
3466
|
+
is_emulator: false,
|
|
3467
|
+
is_prod: true,
|
|
3468
|
+
installSource: "app_store",
|
|
3469
|
+
action: "set",
|
|
3470
|
+
channel: nil,
|
|
3471
|
+
defaultChannel: "production",
|
|
3472
|
+
key_id: nil
|
|
3473
|
+
)
|
|
3474
|
+
|
|
3475
|
+
XCTAssertEqual(info.toParameters()["install_source"] as? String, "app_store")
|
|
3476
|
+
}
|
|
3477
|
+
|
|
3478
|
+
func testZipEntryPathRejectsSiblingPrefixPathTraversal() throws {
|
|
3479
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3480
|
+
let base = root.appendingPathComponent("bundle")
|
|
3481
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3482
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3483
|
+
|
|
3484
|
+
XCTAssertThrowsError(
|
|
3485
|
+
try CapgoUpdater.resolvePathInsideDirectory(
|
|
3486
|
+
baseDirectory: base,
|
|
3487
|
+
relativePath: "../bundle-evil/pwned.txt"
|
|
3488
|
+
)
|
|
3489
|
+
)
|
|
3490
|
+
XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("bundle-evil/pwned.txt").path))
|
|
3491
|
+
}
|
|
3492
|
+
|
|
3493
|
+
func testManifestTargetPathRejectsPathTraversalAfterBrotliSuffixIsRemoved() throws {
|
|
3494
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3495
|
+
let base = root.appendingPathComponent("bundle")
|
|
3496
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3497
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3498
|
+
|
|
3499
|
+
XCTAssertThrowsError(
|
|
3500
|
+
try CapgoUpdater.resolveManifestTargetPath(
|
|
3501
|
+
baseDirectory: base,
|
|
3502
|
+
fileName: "../bundle-evil/app.js.br"
|
|
3503
|
+
)
|
|
3504
|
+
)
|
|
3505
|
+
XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("bundle-evil/app.js").path))
|
|
3506
|
+
}
|
|
3507
|
+
|
|
3508
|
+
func testManifestTargetPathAllowsNestedBrotliFileInsideBundle() throws {
|
|
3509
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3510
|
+
let base = root.appendingPathComponent("bundle")
|
|
3511
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3512
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3513
|
+
|
|
3514
|
+
let resolved = try CapgoUpdater.resolveManifestTargetPath(
|
|
3515
|
+
baseDirectory: base,
|
|
3516
|
+
fileName: "assets/app.js.br"
|
|
3517
|
+
)
|
|
3518
|
+
|
|
3519
|
+
XCTAssertEqual(
|
|
3520
|
+
resolved.standardizedFileURL.path,
|
|
3521
|
+
base.appendingPathComponent("assets/app.js").standardizedFileURL.path
|
|
3522
|
+
)
|
|
3523
|
+
}
|
|
3524
|
+
|
|
3525
|
+
func testResolvePathInsideDirectoryRejectsAbsolutePaths() throws {
|
|
3526
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3527
|
+
let base = root.appendingPathComponent("bundle")
|
|
3528
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3529
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3530
|
+
|
|
3531
|
+
XCTAssertThrowsError(
|
|
3532
|
+
try CapgoUpdater.resolvePathInsideDirectory(baseDirectory: base, relativePath: "/etc/passwd")
|
|
3533
|
+
) { error in
|
|
3534
|
+
XCTAssertEqual(error as? CapgoUpdater.SecurePathError, .absolutePath)
|
|
3535
|
+
}
|
|
3536
|
+
}
|
|
3537
|
+
|
|
3538
|
+
func testResolvePathInsideDirectoryRejectsBackslashes() throws {
|
|
3539
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3540
|
+
let base = root.appendingPathComponent("bundle")
|
|
3541
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3542
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3543
|
+
|
|
3544
|
+
XCTAssertThrowsError(
|
|
3545
|
+
try CapgoUpdater.resolvePathInsideDirectory(baseDirectory: base, relativePath: "assets\\app.js")
|
|
3546
|
+
) { error in
|
|
3547
|
+
XCTAssertEqual(error as? CapgoUpdater.SecurePathError, .windowsPath)
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
|
|
3551
|
+
func testResolvePathInsideDirectoryRejectsNullBytes() throws {
|
|
3552
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3553
|
+
let base = root.appendingPathComponent("bundle")
|
|
3554
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3555
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3556
|
+
|
|
3557
|
+
XCTAssertThrowsError(
|
|
3558
|
+
try CapgoUpdater.resolvePathInsideDirectory(baseDirectory: base, relativePath: "assets\0app.js")
|
|
3559
|
+
) { error in
|
|
3560
|
+
XCTAssertEqual(error as? CapgoUpdater.SecurePathError, .windowsPath)
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
func testResolvePathInsideDirectoryRejectsDotDotSegments() throws {
|
|
3565
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3566
|
+
let base = root.appendingPathComponent("bundle")
|
|
3567
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3568
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3569
|
+
|
|
3570
|
+
XCTAssertThrowsError(
|
|
3571
|
+
try CapgoUpdater.resolvePathInsideDirectory(baseDirectory: base, relativePath: "assets/../../secret.js")
|
|
3572
|
+
) { error in
|
|
3573
|
+
XCTAssertEqual(error as? CapgoUpdater.SecurePathError, .pathTraversal)
|
|
3574
|
+
}
|
|
3575
|
+
XCTAssertThrowsError(
|
|
3576
|
+
try CapgoUpdater.resolvePathInsideDirectory(baseDirectory: base, relativePath: "../secret.js")
|
|
3577
|
+
) { error in
|
|
3578
|
+
XCTAssertEqual(error as? CapgoUpdater.SecurePathError, .pathTraversal)
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
func testResolvePathInsideDirectoryRejectsDotAsBaseDirectory() throws {
|
|
3583
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3584
|
+
let base = root.appendingPathComponent("bundle")
|
|
3585
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3586
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3587
|
+
|
|
3588
|
+
XCTAssertThrowsError(
|
|
3589
|
+
try CapgoUpdater.resolvePathInsideDirectory(baseDirectory: base, relativePath: ".")
|
|
3590
|
+
) { error in
|
|
3591
|
+
XCTAssertEqual(error as? CapgoUpdater.SecurePathError, .pathTraversal)
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
|
|
3595
|
+
func testRememberManifestTargetRejectsDuplicateCanonicalPaths() throws {
|
|
3596
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3597
|
+
let base = root.appendingPathComponent("bundle")
|
|
3598
|
+
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
|
3599
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
3600
|
+
|
|
3601
|
+
let plain = try CapgoUpdater.resolveManifestTargetPath(baseDirectory: base, fileName: "assets/app.js")
|
|
3602
|
+
let brotli = try CapgoUpdater.resolveManifestTargetPath(baseDirectory: base, fileName: "assets/app.js.br")
|
|
3603
|
+
var seen = Set<String>()
|
|
3604
|
+
|
|
3605
|
+
XCTAssertTrue(CapgoUpdater.rememberManifestTarget(&seen, targetFile: plain))
|
|
3606
|
+
XCTAssertFalse(CapgoUpdater.rememberManifestTarget(&seen, targetFile: brotli))
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3609
|
+
func testResolveBundleDirectoryRejectsAbsolutePath() throws {
|
|
3610
|
+
let libraryDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3611
|
+
try FileManager.default.createDirectory(at: libraryDir, withIntermediateDirectories: true)
|
|
3612
|
+
defer { try? FileManager.default.removeItem(at: libraryDir) }
|
|
3613
|
+
|
|
3614
|
+
XCTAssertThrowsError(
|
|
3615
|
+
try CapgoUpdater.resolveBundleDirectory(libraryDir: libraryDir, bundleId: "/tmp/evil")
|
|
3616
|
+
)
|
|
3617
|
+
}
|
|
3618
|
+
|
|
3619
|
+
func testResolveBundleDirectoryRejectsPathTraversal() throws {
|
|
3620
|
+
let libraryDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3621
|
+
try FileManager.default.createDirectory(at: libraryDir, withIntermediateDirectories: true)
|
|
3622
|
+
defer { try? FileManager.default.removeItem(at: libraryDir) }
|
|
3623
|
+
|
|
3624
|
+
XCTAssertThrowsError(
|
|
3625
|
+
try CapgoUpdater.resolveBundleDirectory(libraryDir: libraryDir, bundleId: "../outside-target")
|
|
3626
|
+
)
|
|
3627
|
+
}
|
|
3628
|
+
|
|
3629
|
+
func testDeleteRejectsPathTraversalOutsideBundleRoot() throws {
|
|
3630
|
+
let updater = CapgoUpdater()
|
|
3631
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
3632
|
+
|
|
3633
|
+
let deleted = updater.delete(id: "../outside-target", removeInfo: true)
|
|
3634
|
+
|
|
3635
|
+
XCTAssertFalse(deleted)
|
|
3636
|
+
}
|
|
3637
|
+
|
|
3638
|
+
func testDeleteRemovesLegitimateInSandboxBundle() throws {
|
|
3639
|
+
let updater = CapgoUpdater()
|
|
3640
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
3641
|
+
let bundleId = "sandbox-\(UUID().uuidString)"
|
|
3642
|
+
let bundleDir = try updater.getBundleDirectory(id: bundleId)
|
|
3643
|
+
try FileManager.default.createDirectory(at: bundleDir, withIntermediateDirectories: true)
|
|
3644
|
+
try "<html></html>".write(to: bundleDir.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
|
|
3645
|
+
defer { try? FileManager.default.removeItem(at: bundleDir) }
|
|
3646
|
+
|
|
3647
|
+
let deleted = updater.delete(id: bundleId, removeInfo: true)
|
|
3648
|
+
|
|
3649
|
+
XCTAssertTrue(deleted)
|
|
3650
|
+
XCTAssertFalse(FileManager.default.fileExists(atPath: bundleDir.path))
|
|
3651
|
+
}
|
|
3652
|
+
|
|
3653
|
+
func testResolveBundleDirectoryRejectsDotAsBundleRoot() throws {
|
|
3654
|
+
let libraryDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
3655
|
+
try FileManager.default.createDirectory(at: libraryDir, withIntermediateDirectories: true)
|
|
3656
|
+
defer { try? FileManager.default.removeItem(at: libraryDir) }
|
|
3657
|
+
|
|
3658
|
+
XCTAssertThrowsError(
|
|
3659
|
+
try CapgoUpdater.resolveBundleDirectory(libraryDir: libraryDir, bundleId: ".")
|
|
3660
|
+
)
|
|
3661
|
+
}
|
|
3662
|
+
|
|
3663
|
+
func testDeleteRejectsDotBundleId() throws {
|
|
3664
|
+
let updater = CapgoUpdater()
|
|
3665
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
3666
|
+
|
|
3667
|
+
XCTAssertFalse(updater.delete(id: ".", removeInfo: true))
|
|
3668
|
+
}
|
|
3669
|
+
|
|
3670
|
+
// MARK: - Performance Tests
|
|
3671
|
+
|
|
3672
|
+
func testPerformanceStringTrim() {
|
|
3673
|
+
let testString = " test string with spaces "
|
|
3674
|
+
|
|
3675
|
+
self.measure {
|
|
3676
|
+
for _ in 0..<10000 {
|
|
3677
|
+
_ = testString.trim()
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
|
|
3682
|
+
func testPerformanceDateFormatting() {
|
|
3683
|
+
let date = Date()
|
|
3684
|
+
|
|
3685
|
+
self.measure {
|
|
3686
|
+
for _ in 0..<1000 {
|
|
3687
|
+
_ = date.iso8601withFractionalSeconds
|
|
3688
|
+
}
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
|
|
3692
|
+
func testPerformanceBundleInfoEncoding() {
|
|
3693
|
+
let bundleInfo = BundleInfo(
|
|
3694
|
+
id: "test-id",
|
|
3695
|
+
version: "1.0.0",
|
|
3696
|
+
status: .SUCCESS,
|
|
3697
|
+
downloaded: Date(),
|
|
3698
|
+
checksum: "abc123"
|
|
3699
|
+
)
|
|
3700
|
+
|
|
3701
|
+
self.measure {
|
|
3702
|
+
for _ in 0..<1000 {
|
|
3703
|
+
if let data = try? JSONEncoder().encode(bundleInfo) {
|
|
3704
|
+
_ = try? JSONDecoder().decode(BundleInfo.self, from: data)
|
|
3705
|
+
}
|
|
3706
|
+
}
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
|
|
3710
|
+
func testPerformanceDelayConditionOperations() {
|
|
3711
|
+
let condition = DelayCondition(kind: .background, value: "test")
|
|
3712
|
+
|
|
3713
|
+
self.measure {
|
|
3714
|
+
for _ in 0..<1000 {
|
|
3715
|
+
_ = condition.toJSON()
|
|
3716
|
+
_ = condition.toString()
|
|
3717
|
+
_ = condition.getKind()
|
|
3718
|
+
}
|
|
3719
|
+
}
|
|
3720
|
+
}
|
|
3721
|
+
|
|
3722
|
+
func testSendReadyToJsSkipsSemaphoreWaitWhenNotArmed() {
|
|
3723
|
+
let testPlugin = RealSendReadyCapacitorUpdaterPlugin()
|
|
3724
|
+
testPlugin.setAppReadyTimeoutForTesting(2000)
|
|
3725
|
+
testPlugin.resetSemaphoreWaitTestingStateForTesting()
|
|
3726
|
+
let bundle = BundleInfo(
|
|
3727
|
+
id: BundleInfo.ID_BUILTIN,
|
|
3728
|
+
version: "builtin",
|
|
3729
|
+
status: .SUCCESS,
|
|
3730
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
3731
|
+
checksum: ""
|
|
3732
|
+
)
|
|
3733
|
+
|
|
3734
|
+
let expectation = expectation(description: "appReady without wait")
|
|
3735
|
+
testPlugin.sendReadyToJs(current: bundle, msg: "disabled")
|
|
3736
|
+
|
|
3737
|
+
DispatchQueue.global().async {
|
|
3738
|
+
for _ in 0..<400 {
|
|
3739
|
+
if testPlugin.notifiedEventNames.contains("appReady") {
|
|
3740
|
+
expectation.fulfill()
|
|
3741
|
+
return
|
|
3742
|
+
}
|
|
3743
|
+
Thread.sleep(forTimeInterval: 0.025)
|
|
3744
|
+
}
|
|
3745
|
+
}
|
|
3746
|
+
|
|
3747
|
+
wait(for: [expectation], timeout: 5.0)
|
|
3748
|
+
XCTAssertFalse(testPlugin.didEnterSemaphoreWaitForTestingState)
|
|
3749
|
+
XCTAssertEqual(testPlugin.notifiedEventPayloads["appReady"]?["status"] as? String, "disabled")
|
|
3750
|
+
XCTAssertFalse(testPlugin.isPendingNotifyAppReadyForTesting)
|
|
3751
|
+
}
|
|
3752
|
+
|
|
3753
|
+
func testSendReadyToJsNotifiesAppReadyOnMainThread() {
|
|
3754
|
+
// CAPPlugin's listener storage is not thread-safe (ionic-team/capacitor#8157).
|
|
3755
|
+
// sendReadyToJs runs on a background queue, so appReady must hop to main.
|
|
3756
|
+
let testPlugin = RealSendReadyCapacitorUpdaterPlugin()
|
|
3757
|
+
testPlugin.resetSemaphoreWaitTestingStateForTesting()
|
|
3758
|
+
let bundle = BundleInfo(
|
|
3759
|
+
id: BundleInfo.ID_BUILTIN,
|
|
3760
|
+
version: "builtin",
|
|
3761
|
+
status: .SUCCESS,
|
|
3762
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
3763
|
+
checksum: ""
|
|
3764
|
+
)
|
|
3765
|
+
|
|
3766
|
+
let expectation = expectation(description: "appReady notified")
|
|
3767
|
+
testPlugin.sendReadyToJs(current: bundle, msg: "update installed")
|
|
3768
|
+
|
|
3769
|
+
DispatchQueue.global().async {
|
|
3770
|
+
for _ in 0..<40 {
|
|
3771
|
+
if testPlugin.notifiedEventNames.contains("appReady") {
|
|
3772
|
+
expectation.fulfill()
|
|
3773
|
+
return
|
|
3774
|
+
}
|
|
3775
|
+
Thread.sleep(forTimeInterval: 0.025)
|
|
3776
|
+
}
|
|
3777
|
+
}
|
|
3778
|
+
|
|
3779
|
+
wait(for: [expectation], timeout: 2.0)
|
|
3780
|
+
XCTAssertEqual(testPlugin.appReadyNotifiedOnMainThread, true)
|
|
3781
|
+
XCTAssertEqual(testPlugin.appReadyRetainUntilConsumed, true)
|
|
3782
|
+
}
|
|
3783
|
+
|
|
3784
|
+
func testSendReadyToJsWaitsOnlyWhenArmed() {
|
|
3785
|
+
let testPlugin = RealSendReadyCapacitorUpdaterPlugin()
|
|
3786
|
+
testPlugin.setAppReadyTimeoutForTesting(200)
|
|
3787
|
+
testPlugin.armPendingNotifyAppReadyForTesting()
|
|
3788
|
+
let bundle = BundleInfo(
|
|
3789
|
+
id: BundleInfo.ID_BUILTIN,
|
|
3790
|
+
version: "builtin",
|
|
3791
|
+
status: .SUCCESS,
|
|
3792
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
3793
|
+
checksum: ""
|
|
3794
|
+
)
|
|
3795
|
+
|
|
3796
|
+
let expectation = expectation(description: "appReady after armed wait timeout")
|
|
3797
|
+
let start = Date()
|
|
3798
|
+
testPlugin.sendReadyToJs(current: bundle, msg: "update installed")
|
|
3799
|
+
|
|
3800
|
+
DispatchQueue.global().async {
|
|
3801
|
+
for _ in 0..<120 {
|
|
3802
|
+
if testPlugin.notifiedEventNames.contains("appReady") {
|
|
3803
|
+
expectation.fulfill()
|
|
3804
|
+
return
|
|
3805
|
+
}
|
|
3806
|
+
Thread.sleep(forTimeInterval: 0.025)
|
|
3807
|
+
}
|
|
3808
|
+
}
|
|
3809
|
+
|
|
3810
|
+
wait(for: [expectation], timeout: 3.0)
|
|
3811
|
+
XCTAssertGreaterThanOrEqual(Date().timeIntervalSince(start), 0.15)
|
|
3812
|
+
XCTAssertFalse(testPlugin.isPendingNotifyAppReadyForTesting)
|
|
3813
|
+
}
|
|
3814
|
+
|
|
3815
|
+
func testSendReadyToJsUnblocksWhenNotifyAppReadySignals() {
|
|
3816
|
+
let testPlugin = RealSendReadyCapacitorUpdaterPlugin()
|
|
3817
|
+
testPlugin.setAppReadyTimeoutForTesting(500)
|
|
3818
|
+
testPlugin.resetSemaphoreWaitTestingStateForTesting()
|
|
3819
|
+
testPlugin.armPendingNotifyAppReadyForTesting()
|
|
3820
|
+
let bundle = BundleInfo(
|
|
3821
|
+
id: BundleInfo.ID_BUILTIN,
|
|
3822
|
+
version: "builtin",
|
|
3823
|
+
status: .SUCCESS,
|
|
3824
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
3825
|
+
checksum: ""
|
|
3826
|
+
)
|
|
3827
|
+
|
|
3828
|
+
let expectation = expectation(description: "appReady after notify")
|
|
3829
|
+
testPlugin.sendReadyToJs(current: bundle, msg: "update installed")
|
|
3830
|
+
|
|
3831
|
+
DispatchQueue.global().async {
|
|
3832
|
+
// Wait until sendReadyToJs enters semaphoreWait. The armed flag is cleared
|
|
3833
|
+
// before the wait starts, so polling that flag can signal too early.
|
|
3834
|
+
for _ in 0..<400 {
|
|
3835
|
+
if testPlugin.didEnterSemaphoreWaitForTestingState {
|
|
3836
|
+
break
|
|
3837
|
+
}
|
|
3838
|
+
Thread.sleep(forTimeInterval: 0.01)
|
|
3839
|
+
}
|
|
3840
|
+
XCTAssertTrue(testPlugin.didEnterSemaphoreWaitForTestingState)
|
|
3841
|
+
|
|
3842
|
+
let signalStart = Date()
|
|
3843
|
+
// Simulate notifyAppReady signalling the semaphore.
|
|
3844
|
+
testPlugin.semaphoreReady.signal()
|
|
3845
|
+
|
|
3846
|
+
for _ in 0..<80 {
|
|
3847
|
+
if let notifiedAt = testPlugin.appReadyNotifiedAt {
|
|
3848
|
+
XCTAssertGreaterThanOrEqual(
|
|
3849
|
+
notifiedAt.timeIntervalSince1970,
|
|
3850
|
+
signalStart.timeIntervalSince1970
|
|
3851
|
+
)
|
|
3852
|
+
XCTAssertLessThan(notifiedAt.timeIntervalSince(signalStart), 0.5)
|
|
3853
|
+
expectation.fulfill()
|
|
3854
|
+
return
|
|
3855
|
+
}
|
|
3856
|
+
Thread.sleep(forTimeInterval: 0.025)
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
|
|
3860
|
+
wait(for: [expectation], timeout: 5.0)
|
|
3861
|
+
XCTAssertFalse(testPlugin.isPendingNotifyAppReadyForTesting)
|
|
3862
|
+
}
|
|
3863
|
+
|
|
3864
|
+
func testClearPendingNotifyAppReadyPreventsWait() {
|
|
3865
|
+
let testPlugin = RealSendReadyCapacitorUpdaterPlugin()
|
|
3866
|
+
testPlugin.setAppReadyTimeoutForTesting(2000)
|
|
3867
|
+
testPlugin.armPendingNotifyAppReadyForTesting()
|
|
3868
|
+
testPlugin.clearPendingNotifyAppReadyForTesting()
|
|
3869
|
+
XCTAssertFalse(testPlugin.isPendingNotifyAppReadyForTesting)
|
|
3870
|
+
|
|
3871
|
+
let bundle = BundleInfo(
|
|
3872
|
+
id: BundleInfo.ID_BUILTIN,
|
|
3873
|
+
version: "builtin",
|
|
3874
|
+
status: .SUCCESS,
|
|
3875
|
+
downloaded: BundleInfo.DOWNLOADED_BUILTIN,
|
|
3876
|
+
checksum: ""
|
|
3877
|
+
)
|
|
3878
|
+
testPlugin.resetSemaphoreWaitTestingStateForTesting()
|
|
3879
|
+
let expectation = expectation(description: "appReady after clear is immediate")
|
|
3880
|
+
testPlugin.sendReadyToJs(current: bundle, msg: "disabled")
|
|
3881
|
+
DispatchQueue.global().async {
|
|
3882
|
+
for _ in 0..<400 {
|
|
3883
|
+
if testPlugin.notifiedEventNames.contains("appReady") {
|
|
3884
|
+
expectation.fulfill()
|
|
3885
|
+
return
|
|
3886
|
+
}
|
|
3887
|
+
Thread.sleep(forTimeInterval: 0.025)
|
|
3888
|
+
}
|
|
3889
|
+
}
|
|
3890
|
+
wait(for: [expectation], timeout: 5.0)
|
|
3891
|
+
XCTAssertFalse(testPlugin.didEnterSemaphoreWaitForTestingState)
|
|
3892
|
+
}
|
|
3893
|
+
|
|
3894
|
+
func testReadyCallFromPreviousPageIsRejected() {
|
|
3895
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.shouldAcceptReadyCall(guardArmed: false, expectedGeneration: 1, reportedGeneration: nil))
|
|
3896
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldAcceptReadyCall(guardArmed: true, expectedGeneration: 2, reportedGeneration: nil))
|
|
3897
|
+
XCTAssertFalse(CapacitorUpdaterPlugin.shouldAcceptReadyCall(guardArmed: true, expectedGeneration: 2, reportedGeneration: 1))
|
|
3898
|
+
XCTAssertTrue(CapacitorUpdaterPlugin.shouldAcceptReadyCall(guardArmed: true, expectedGeneration: 2, reportedGeneration: 2))
|
|
3899
|
+
let script = CapacitorUpdaterPlugin.readyGenerationScript(2)
|
|
3900
|
+
XCTAssertTrue(script.contains("window.__CAPGO_READY_GEN=2"))
|
|
3901
|
+
XCTAssertTrue(script.contains("cap.nativePromise"))
|
|
3902
|
+
XCTAssertFalse(script.contains("plugin.notifyAppReady="))
|
|
3903
|
+
}
|
|
3904
|
+
|
|
3905
|
+
}
|