-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathMParticleTest.kt
More file actions
408 lines (377 loc) · 17.1 KB
/
MParticleTest.kt
File metadata and controls
408 lines (377 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package com.mparticle
import android.content.Context
import android.location.Location
import android.os.Handler
import android.os.Looper
import android.webkit.WebView
import com.mparticle.identity.IdentityApiRequest
import com.mparticle.identity.IdentityStateListener
import com.mparticle.internal.ConfigManager
import com.mparticle.internal.KitFrameworkWrapper
import com.mparticle.internal.MParticleJSInterface
import com.mparticle.internal.MessageManager
import com.mparticle.internal.PushRegistrationHelper.PushRegistration
import com.mparticle.networking.Matcher
import com.mparticle.networking.MockServer.JSONMatch
import com.mparticle.testutils.AndroidUtils
import com.mparticle.testutils.BaseCleanStartedEachTest
import com.mparticle.testutils.MPLatch
import com.mparticle.testutils.TestingUtils
import org.json.JSONException
import org.json.JSONObject
import org.junit.Assert
import org.junit.Test
import java.io.File
import java.util.Arrays
import java.util.concurrent.CountDownLatch
class MParticleTest : BaseCleanStartedEachTest() {
private val configResponse =
"{\"dt\":\"ac\", \"id\":\"fddf1f96-560e-41f6-8f9b-ddd070be0765\", \"ct\":1434392412994, \"dbg\":false, \"cue\":\"appdefined\", \"pmk\":[\"mp_message\", \"com.urbanairship.push.ALERT\", \"alert\", \"a\", \"message\"], \"cnp\":\"appdefined\", \"soc\":0, \"oo\":false, \"eks\":[] }, \"pio\":30 }"
@Test
fun testEnsureSessionActive() {
MParticle.getInstance()!!.mAppStateManager.ensureActiveSession()
ensureSessionActive()
}
@Test
fun testEnsureSessionActiveAtStart() {
Assert.assertFalse(MParticle.getInstance()!!.isSessionActive)
}
@Test
fun testSessionEndsOnOptOut() {
MParticle.getInstance()!!.mAppStateManager.ensureActiveSession()
Assert.assertTrue(MParticle.getInstance()!!.mAppStateManager.session.isActive)
MParticle.getInstance()!!.optOut = true
Assert.assertFalse(MParticle.getInstance()!!.mAppStateManager.session.isActive)
}
@Test
fun testSetIntervalValue() {
restartWithOptions(baseMParticleOptionBuilder.uploadInterval(20))
val mp = MParticle.getInstance()
Assert.assertEquals(20.toMillis(), mp?.mConfigManager?.uploadInterval)
mp?.setUpdateInterval(30)
Assert.assertEquals(30.toMillis(), mp?.mConfigManager?.uploadInterval)
}
@Test
fun testSetIntervalValueInvalidNEgativeValue() {
restartWithOptions(baseMParticleOptionBuilder.uploadInterval(20))
val mp = MParticle.getInstance()
Assert.assertEquals(20.toMillis(), mp?.mConfigManager?.uploadInterval)
mp?.setUpdateInterval(-1)
Assert.assertEquals(20.toMillis(), mp?.mConfigManager?.uploadInterval)
}
@Test
fun testSetIntervalValueInvalidZeroValue() {
restartWithOptions(baseMParticleOptionBuilder.uploadInterval(20))
val mp = MParticle.getInstance()
Assert.assertEquals(20.toMillis(), mp?.mConfigManager?.uploadInterval)
mp?.setUpdateInterval(0)
Assert.assertEquals(20.toMillis(), mp?.mConfigManager?.uploadInterval)
}
private fun Int.toMillis() = this * 1000L
@Test
fun testSetInstallReferrer() {
MParticle.getInstance()!!.installReferrer = "foo install referrer"
Assert.assertEquals("foo install referrer", MParticle.getInstance()!!.installReferrer)
}
@Test
fun testInstallReferrerUpdate() {
val randomName = mRandomUtils.getAlphaNumericString(mRandomUtils.randomInt(4, 64))
MParticle.getInstance()!!.installReferrer = randomName
Assert.assertTrue(MParticle.getInstance()!!.installReferrer == randomName)
}
/**
* These tests are to make sure that we are not missing any instances of the InstallReferrer
* being set at any of the entry points, without the corresponding installReferrerUpdated() calls
* being made.
* @throws Exception
*/
@Test
@Throws(Exception::class)
fun testCalledUpdateInstallReferrer() {
val called = BooleanArray(2)
MParticle.getInstance()!!.mMessageManager = object : MessageManager() {
override fun installReferrerUpdated() {
called[0] = true
}
}
MParticle.getInstance()!!.mKitManager =
object : KitFrameworkWrapper(mContext, null, null, null, true, null) {
override fun installReferrerUpdated() {
called[1] = true
}
}
// Test when the InstallReferrer is set directly on the InstallReferrerHelper.
var installReferrer = mRandomUtils.getAlphaNumericString(10)
InstallReferrerHelper.setInstallReferrer(mContext, installReferrer)
Assert.assertTrue(called[0])
Assert.assertTrue(called[1])
Arrays.fill(called, false)
// Test when it is set through the MParticle object in the public API.
installReferrer = mRandomUtils.getAlphaNumericString(10)
MParticle.getInstance()!!.installReferrer = installReferrer
Assert.assertTrue(called[0])
Assert.assertTrue(called[1])
Arrays.fill(called, false)
// Just a sanity check, if Context is null, it should not set mark the InstallReferrer as updated.
installReferrer = mRandomUtils.getAlphaNumericString(10)
// InstallReferrerHelper.setInstallReferrer(null, installReferrer) //function does nothing when context is null
Assert.assertFalse(called[0])
Assert.assertFalse(called[1])
}
@Test
@Throws(JSONException::class, InterruptedException::class)
fun testRegisterWebView() {
MParticle.setInstance(null)
val token = mRandomUtils.getAlphaNumericString(15)
mServer.setupConfigResponse(
JSONObject().put(ConfigManager.WORKSPACE_TOKEN, token).toString()
)
startMParticle()
val jsInterfaces: MutableMap<String, Any> = HashMap()
val latch = MPLatch(1)
Handler(Looper.getMainLooper()).post {
val webView: WebView = object : WebView(mContext) {
override fun addJavascriptInterface(`object`: Any, name: String) {
jsInterfaces[name] = `object`
}
}
MParticle.getInstance()!!.registerWebView(webView)
Assert.assertTrue(jsInterfaces[MParticleJSInterface.INTERFACE_BASE_NAME + "_" + token + "_v2"] is MParticleJSInterface)
val clientToken = mRandomUtils.getAlphaNumericString(15)
MParticle.getInstance()!!.registerWebView(webView, clientToken)
Assert.assertTrue(jsInterfaces[MParticleJSInterface.INTERFACE_BASE_NAME + "_" + clientToken + "_v2"] is MParticleJSInterface)
latch.countDown()
}
latch.await()
Assert.assertEquals(2, jsInterfaces.size.toLong())
}
private fun ensureSessionActive() {
if (!MParticle.getInstance()!!.isSessionActive) {
MParticle.getInstance()!!.logEvent(TestingUtils.getInstance().randomMPEventSimple)
Assert.assertTrue(MParticle.getInstance()!!.isSessionActive)
}
}
@OrchestratorOnly
@Test
@Throws(JSONException::class, InterruptedException::class)
fun testResetIdentitySync() {
testResetIdentityCall { MParticle.reset(mContext) }
}
// @OrchestratorOnly
// @Test
// @Throws(JSONException::class, InterruptedException::class)
// fun testResetIdentityAsync() {
// testResetIdentityCall {
// val latch: CountDownLatch = MPLatch(1)
// MParticle.reset(mContext) { latch.countDown() }
// try {
// latch.await()
// } catch (e: InterruptedException) {
// e.printStackTrace()
// }
// }
// }
@OrchestratorOnly
@Test
@Throws(InterruptedException::class)
fun testResetConfigCall() {
mServer.setupConfigResponse(configResponse, 100)
MParticle.getInstance()!!.refreshConfiguration()
MParticle.reset(mContext)
// This sleep is here just to
Thread.sleep(100)
assertSDKGone()
}
/**
* Test that Identity calls in progress will exit gracefully, and not trigger any callbacks.
*/
@Throws(InterruptedException::class)
fun testResetIdentityCall(resetRunnable: Runnable) {
val called = BooleanArray(2)
val crashListener = IdentityStateListener { user, previousUser ->
Assert.assertTrue(called[0])
throw IllegalStateException("Should not be getting callbacks after reset")
}
mServer.setupHappyIdentify(ran.nextLong(), 100)
MParticle.getInstance()!!.Identity().addIdentityStateListener(crashListener)
MParticle.getInstance()!!.Identity().identify(IdentityApiRequest.withEmptyUser().build())
called[0] = true
mServer.waitForVerify(Matcher(mServer.Endpoints().identifyUrl))
resetRunnable.run()
assertSDKGone()
}
@Test
@Throws(InterruptedException::class)
fun testPushEnabledApi() {
val senderId = "senderId"
startMParticle()
MParticle.getInstance()!!.Messaging().enablePushNotifications(senderId)
var fetchedSenderId: String? =
MParticle.getInstance()!!.mInternal.getConfigManager().pushSenderId
Assert.assertTrue(
MParticle.getInstance()!!.mInternal.getConfigManager().isPushEnabled ?: false
)
Assert.assertEquals(senderId, fetchedSenderId)
val otherSenderId = "senderIdLogPushRegistration"
MParticle.getInstance()!!.logPushRegistration("instanceId", otherSenderId)
fetchedSenderId = MParticle.getInstance()!!.mInternal.getConfigManager().pushSenderId
Assert.assertEquals(otherSenderId, fetchedSenderId)
MParticle.getInstance()!!.Messaging().disablePushNotifications()
fetchedSenderId = MParticle.getInstance()!!.mInternal.getConfigManager().pushSenderId
Assert.assertFalse(
MParticle.getInstance()!!.mInternal.getConfigManager().isPushEnabled ?: false
)
Assert.assertNull(fetchedSenderId)
}
@Test
@Throws(InterruptedException::class)
fun testLogPushRegistrationModifyMessages() {
val pushRegistrationTest = PushRegistrationTest().setServer(mServer)
pushRegistrationTest.setContext(mContext)
for (setPush in pushRegistrationTest.setPushes) {
val oldRegistration = PushRegistration(
mRandomUtils.getAlphaNumericString(10),
mRandomUtils.getAlphaNumericString(15)
)
setPush.setPushRegistration(oldRegistration)
val newPushRegistration = PushRegistration(
mRandomUtils.getAlphaNumericString(10),
mRandomUtils.getAlphaNumericString(15)
)
val latch: CountDownLatch = MPLatch(1)
val received = AndroidUtils.Mutable(false)
mServer.waitForVerify(
Matcher(mServer.Endpoints().getModifyUrl(mStartingMpid)).bodyMatch(
JSONMatch { jsonObject ->
if (jsonObject.has("identity_changes")) {
try {
val identityChanges = jsonObject.getJSONArray("identity_changes")
Assert.assertEquals(1, identityChanges.length().toLong())
val identityChange = identityChanges.getJSONObject(0)
val failureMessage =
"When " + oldRegistration + " set with: " + setPush.name
// This is a wierd case. We might be setting the old pushRegistration with "logPushRegistration()",
// which will kick of its own modify request. We want to ignore this if this is the case.
if (identityChange.getString("new_value") == oldRegistration.instanceId) {
return@JSONMatch false
}
Assert.assertEquals(
failureMessage,
oldRegistration.instanceId,
identityChange.getString("old_value")
)
Assert.assertEquals(
failureMessage,
newPushRegistration.instanceId,
identityChange.getString("new_value")
)
Assert.assertEquals(
failureMessage,
"push_token",
identityChange.getString("identity_type")
)
} catch (jse: JSONException) {
jse.toString()
}
return@JSONMatch true
}
false
}
)
) {
received.value = true
latch.countDown()
}
MParticle.getInstance()!!
.logPushRegistration(newPushRegistration.instanceId, newPushRegistration.senderId)
latch.await()
}
}
@Test
fun testWrapperSdkVersionWithoutBeingSet() {
val instance = MParticle.getInstance()!!
Assert.assertNotNull(instance.wrapperSdkVersion)
Assert.assertEquals(WrapperSdk.WrapperNone, instance.wrapperSdkVersion.sdk)
Assert.assertNull(instance.wrapperSdkVersion.version)
}
@Test
fun testSetLocation() {
val location = Location("")
MParticle.getInstance()!!.setLocation(location)
Assert.assertEquals(location, MParticle.getInstance()!!.mMessageManager.location)
MParticle.getInstance()!!.setLocation(null)
Assert.assertNull(MParticle.getInstance()!!.mMessageManager.location)
}
@Throws(JSONException::class, InterruptedException::class)
private fun testReset(resetRunnable: Runnable) {
for (i in 0..9) {
MParticle.getInstance()!!.logEvent(TestingUtils.getInstance().randomMPEventRich)
}
for (i in 0..9) {
MParticle.getInstance()!!.mInternal.getConfigManager()
.setMpid(ran.nextLong(), ran.nextBoolean())
}
val databaseJson = getDatabaseContents(listOf("messages"))
Assert.assertTrue(databaseJson.getJSONArray("messages").length() > 0)
Assert.assertEquals(6, allTables.size.toLong())
Assert.assertTrue(
10 < (MParticle.getInstance()!!.mInternal.getConfigManager().mpids?.size ?: 0)
)
// Set strict mode, so if we get any warning or error messages during the reset/restart phase,
// it will throw an exception.
TestingUtils.setStrictMode(MParticle.LogLevel.WARNING)
resetRunnable.run()
assertSDKGone()
// Restart the SDK, to the point where the initial Identity call returns, make sure there are no errors on startup.
TestingUtils.setStrictMode(
MParticle.LogLevel.WARNING,
"Failed to get MParticle instance, getInstance() called prior to start()."
)
beforeBase()
}
private fun assertSDKGone() {
// Check post-reset state:
// should be 2 entries in default SharedPreferences (the install boolean and the original install time)
// and 0 other SharedPreferences tables.
// Make sure the 2 entries in default SharedPreferences are the correct values.
// 0 tables should exist.
// Then we call DatabaseHelper.getInstance(Context).openDatabase, which should create the database,
// and make sure it is created without an error message, and that all the tables are empty.
val sharedPrefsDirectory = mContext.filesDir.path.replace("files", "shared_prefs/")
val files = File(sharedPrefsDirectory).listFiles()
files?.iterator()?.forEach { file ->
val sharedPreferenceName =
file.path.replace(sharedPrefsDirectory, "").replace(".xml", "")
if (sharedPreferenceName != "WebViewChromiumPrefs" && sharedPreferenceName != "com.mparticle.test_preferences") {
Assert.fail(
"""
SharedPreference file failed to clear:
${getSharedPrefsContents(sharedPreferenceName)}
""".trimIndent()
)
}
}
Assert.assertEquals(0, mContext.databaseList().size.toLong())
try {
val databaseJson = databaseContents
val keys = databaseJson.keys()
while (keys.hasNext()) {
val key = keys.next()
Assert.assertEquals(key, 0, databaseJson.getJSONArray(key).length().toLong())
}
} catch (e: JSONException) {
Assert.fail(e.message)
}
}
private fun getSharedPrefsContents(name: String): String {
return try {
val prefs = mContext.getSharedPreferences(name, Context.MODE_PRIVATE)
"""
$name:
${JSONObject(prefs.all).toString(4)}
""".trimIndent()
} catch (e: JSONException) {
"error printing SharedPrefs :/"
}
}
}