-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathEmbeddedMessageIntegrationTest.kt
More file actions
298 lines (242 loc) · 13.6 KB
/
EmbeddedMessageIntegrationTest.kt
File metadata and controls
298 lines (242 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
package com.iterable.integration.tests
import android.content.Intent
import android.util.Log
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiSelector
import androidx.test.uiautomator.Until
import com.iterable.integration.tests.activities.EmbeddedMessageTestActivity
import com.iterable.iterableapi.IterableApi
import com.iterable.iterableapi.ui.embedded.IterableEmbeddedView
import com.iterable.iterableapi.ui.embedded.IterableEmbeddedViewType
import org.json.JSONObject
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class EmbeddedMessageIntegrationTest : BaseIntegrationTest() {
companion object {
private const val TAG = "EmbeddedMessageIntegrationTest"
private const val TEST_PLACEMENT_ID = TestConstants.TEST_EMBEDDED_PLACEMENT_ID
}
private lateinit var uiDevice: UiDevice
private lateinit var mainActivityScenario: ActivityScenario<MainActivity>
@Before
override fun setUp() {
Log.d(TAG, "🔧 Test setup starting...")
uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
// Call super.setUp() to initialize SDK with BaseIntegrationTest's config
// This sets test mode flag and initializes SDK with test handlers (including urlHandler)
super.setUp()
Log.d(TAG, "🔧 Base setup complete, SDK initialized with test handlers")
// Add small delay to ensure SDK is fully ready after background initialization
Thread.sleep(500)
// Disable in-app auto display and clear existing messages BEFORE launching app
// This prevents in-app messages from obscuring the embedded message test screen
Log.d(TAG, "🔧 Disabling in-app auto display and clearing existing messages...")
IterableApi.getInstance().inAppManager.setAutoDisplayPaused(true)
Log.d(TAG, "✅ In-app auto display paused")
// Clear all existing in-app messages
IterableApi.getInstance().inAppManager.messages.forEach {
Log.d(TAG, "Clearing existing in-app message: ${it.messageId}")
IterableApi.getInstance().inAppManager.removeMessage(it)
}
Log.d(TAG, "✅ All in-app messages cleared")
Log.d(TAG, "🔧 MainActivity will skip initialization due to test mode flag")
// Now launch the app flow with custom handlers already configured
launchAppAndNavigateToEmbeddedTesting()
}
@After
override fun tearDown() {
super.tearDown()
}
private fun launchAppAndNavigateToEmbeddedTesting() {
// Step 1: Launch MainActivity (the home page)
Log.d(TAG, "🔧 Step 1: Launching MainActivity...")
val mainIntent = Intent(InstrumentationRegistry.getInstrumentation().targetContext, MainActivity::class.java)
mainActivityScenario = ActivityScenario.launch(mainIntent)
Log.d(TAG, "🔧 MainActivity launched")
// Step 2: Click the "Embedded Messages" button to navigate to EmbeddedMessageTestActivity
Log.d(TAG, "🔧 Step 2: Waiting for and clicking 'Embedded Messages' button...")
// Use UiDevice.wait() with generous timeout for slow emulators
val embeddedButton = uiDevice.wait(
Until.findObject(By.res("com.iterable.integration.tests", "btnEmbeddedMessages")),
10000 // 10 second timeout for slow CI
)
if (embeddedButton == null) {
Log.e(TAG, "❌ Embedded Messages button not found after waiting 10 seconds!")
Log.e(TAG, "Current activity: " + uiDevice.currentPackageName)
}
Assert.assertNotNull("Embedded Messages button should be found", embeddedButton)
embeddedButton.click()
Log.d(TAG, "🔧 Clicked Embedded Messages button successfully")
// Step 3: Wait for EmbeddedMessageTestActivity to load
Log.d(TAG, "🔧 Step 3: Waiting for EmbeddedMessageTestActivity to load...")
Thread.sleep(2000) // Give time for navigation
Log.d(TAG, "🔧 App navigation complete: Now on EmbeddedMessageTestActivity!")
}
@Test
fun testEmbeddedMessageMVP() {
// Step 1: Ensure user is signed in
Log.d(TAG, "📧 Step 1: Ensuring user is signed in...")
val userSignedIn = testUtils.ensureUserSignedIn(TestConstants.TEST_USER_EMAIL)
Assert.assertTrue("User should be signed in", userSignedIn)
Log.d(TAG, "✅ User signed in successfully: ${TestConstants.TEST_USER_EMAIL}")
// Step 2: Preliminary check - verify view is ready with placement ID
Log.d(TAG, "🔍 Step 2: Checking view readiness with placement ID...")
var viewReady = false
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val activity = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(Stage.RESUMED)
.firstOrNull() as? EmbeddedMessageTestActivity
activity?.let {
val fragmentContainer = it.findViewById<androidx.fragment.app.FragmentContainerView>(R.id.embedded_message_container)
viewReady = fragmentContainer != null
if (viewReady) {
Log.d(TAG, "✅ View is ready with placementID - $TEST_PLACEMENT_ID")
}
}
}
Assert.assertTrue("FragmentContainerView should exist in EmbeddedMessageTestActivity", viewReady)
// Step 3: Get initial placement IDs before updating user properties
val initialPlacementIds = IterableApi.getInstance().embeddedManager.getPlacementIds().toSet()
Log.d(TAG, "📊 Initial placement IDs: $initialPlacementIds")
// Reset embedded push tracking to detect UpdateEmbedded push
testUtils.setEmbeddedPushProcessed(false)
// Step 4: Update user properties to make user eligible
Log.d(TAG, "📝 Step 4: Updating user properties (isPremium = true)...")
val dataFields = JSONObject().apply {
put("isPremium", true)
}
IterableApi.getInstance().updateUser(dataFields)
Log.d(TAG, "✅ User properties updated")
// Step 5: Wait for backend to process and make user eligible
Log.d(TAG, "⏳ Step 5: Waiting for backend to process user update...")
Thread.sleep(3000)
// Step 6: Wait for push-triggered sync (primary path)
Log.d(TAG, "🔄 Step 6: Waiting for UpdateEmbedded push to trigger automatic sync...")
val syncViaPush = waitForEmbeddedSyncViaPush(
initialPlacementIds = initialPlacementIds,
expectedPlacementId = TEST_PLACEMENT_ID,
pushTimeoutSeconds = 10
)
var placementIds = IterableApi.getInstance().embeddedManager.getPlacementIds()
var hasExpectedPlacement = placementIds.contains(TEST_PLACEMENT_ID)
// Step 6b: Fallback to manual sync if push didn't work
if (!syncViaPush || !hasExpectedPlacement) {
Log.d(TAG, "⚠️ Push-triggered sync did not complete, falling back to manual sync...")
Log.d(TAG, "🔄 Step 6b: Manually syncing embedded messages...")
Thread.sleep(2000) // Give a bit more time in case push is still arriving
// Check again before manual sync
placementIds = IterableApi.getInstance().embeddedManager.getPlacementIds()
hasExpectedPlacement = placementIds.contains(TEST_PLACEMENT_ID)
if (!hasExpectedPlacement) {
IterableApi.getInstance().embeddedManager.syncMessages()
Thread.sleep(2000) // Wait for sync to complete
placementIds = IterableApi.getInstance().embeddedManager.getPlacementIds()
hasExpectedPlacement = placementIds.contains(TEST_PLACEMENT_ID)
Log.d(TAG, "🔄 Placement IDs after manual sync: $placementIds")
} else {
Log.d(TAG, "✅ Messages synced via push (delayed), placement IDs: $placementIds")
}
} else {
Log.d(TAG, "✅ Messages synced via push-triggered automatic sync, placement IDs: $placementIds")
}
// Step 7: Verify expected placement ID exists
Log.d(TAG, "🔍 Step 7: Verifying placement ID exists...")
Log.d(TAG, "📋 Found placement IDs: $placementIds")
Assert.assertTrue(
"Placement ID $TEST_PLACEMENT_ID should exist, but found: $placementIds",
hasExpectedPlacement
)
Log.d(TAG, "✅ Placement ID $TEST_PLACEMENT_ID found")
// Step 8: Get messages for the placement ID
Log.d(TAG, "📨 Step 8: Getting messages for placement ID $TEST_PLACEMENT_ID...")
val messages = IterableApi.getInstance().embeddedManager.getMessages(TEST_PLACEMENT_ID)
Assert.assertTrue("Should have at least 1 message for placement $TEST_PLACEMENT_ID", messages!!.isNotEmpty())
val message = messages.first()
Log.d(TAG, "✅ Found message: ${message.metadata.messageId}")
// Step 9: Display message using IterableEmbeddedView
Log.d(TAG, "🎨 Step 9: Displaying message using IterableEmbeddedView...")
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val activity = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(Stage.RESUMED)
.firstOrNull() as? EmbeddedMessageTestActivity
if (activity != null) {
val fragment = IterableEmbeddedView(IterableEmbeddedViewType.BANNER, message, null)
activity.supportFragmentManager.beginTransaction()
.replace(R.id.embedded_message_container, fragment)
.commitNow()
Log.d(TAG, "✅ Fragment added to FragmentManager")
} else {
Assert.fail("EmbeddedMessageTestActivity not found in RESUMED stage")
}
}
// Wait for fragment to be displayed
Thread.sleep(1000)
// Step 10: Verify display - check fragment exists
Log.d(TAG, "✅ Step 10: Verifying embedded message is displayed...")
var isEmbeddedFragmentDisplayed = false
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val activity = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(Stage.RESUMED)
.firstOrNull() as? EmbeddedMessageTestActivity
activity?.let { act ->
val fragmentManager = act.supportFragmentManager
fragmentManager.fragments.forEach { fragment ->
if (fragment is IterableEmbeddedView) {
isEmbeddedFragmentDisplayed = true
Log.d(TAG, "✅ Found IterableEmbeddedView fragment")
}
}
}
}
Assert.assertTrue(
"IterableEmbeddedView fragment should be displayed",
isEmbeddedFragmentDisplayed
)
Log.d(TAG, "✅ Embedded message is displayed, now interacting with button...")
// Step 11: Interact with button - find and click first button
Log.d(TAG, "🎯 Step 11: Clicking button in the embedded message...")
// Try to find button by resource ID first
val button = uiDevice.findObject(UiSelector().resourceId("com.iterable.iterableapi.ui:id/embedded_message_first_button"))
if (button.exists()) {
button.click()
Log.d(TAG, "✅ Clicked embedded message button")
} else {
// Try to find by button text if available
val buttonText = message.elements?.buttons?.firstOrNull()?.title
if (buttonText != null) {
val buttonByText = uiDevice.findObject(By.text(buttonText))
if (buttonByText != null) {
buttonByText.click()
Log.d(TAG, "✅ Clicked embedded message button by text: $buttonText")
} else {
Assert.fail("Button not found in the embedded message (tried resource ID and text: $buttonText)")
}
} else {
Assert.fail("Button not found in the embedded message (tried resource ID, but no button text available)")
}
}
// Step 12: Verify URL handler was called
Log.d(TAG, "🎯 Step 12: Verifying URL handler was called after button click...")
val urlHandlerCalled = waitForUrlHandler(timeoutSeconds = 3)
Assert.assertTrue(
"URL handler should have been called after clicking the button",
urlHandlerCalled
)
// Step 13: Verify the correct URL was handled
val handledUrl = getLastHandledUrl()
Log.d(TAG, "🎯 URL handler received: $handledUrl")
Assert.assertNotNull("Handled URL should not be null", handledUrl)
Log.d(TAG, "✅ URL handler was called with URL: $handledUrl")
Log.d(TAG, "✅✅✅ Test completed successfully! All steps passed.")
}
}