forked from PhilJay/MPAndroidChart
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathStartTest.kt
More file actions
362 lines (322 loc) · 16.8 KB
/
StartTest.kt
File metadata and controls
362 lines (322 loc) · 16.8 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
package info.appdev.chartexample
import android.graphics.Bitmap
import android.util.Log
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToIndex
import androidx.test.core.graphics.writeToTestStorage
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.GeneralClickAction
import androidx.test.espresso.action.Press
import androidx.test.espresso.action.Tap
import androidx.test.espresso.action.ViewActions.captureToBitmap
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import info.appdev.chartexample.compose.HorizontalBarComposeActivity
import info.appdev.chartexample.compose.HorizontalBarFullComposeActivity
import info.appdev.chartexample.compose.MultiLineComposeActivity
import info.appdev.chartexample.fragments.ViewPagerSimpleChartDemo
import info.appdev.chartexample.notimportant.ContentItem
import info.appdev.chartexample.notimportant.DemoBase
import info.appdev.chartexample.notimportant.DemoBase.Companion.optionMenus
import info.appdev.chartexample.notimportant.DemoBaseCompose
import info.appdev.chartexample.notimportant.MainActivity
import info.hannes.timber.DebugFormatTree
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
import org.junit.runner.RunWith
import timber.log.Timber
import kotlin.jvm.java
@RunWith(AndroidJUnit4::class)
class StartTest {
@get:Rule
val activityScenarioRule = activityScenarioRule<MainActivity>()
@get:Rule
val composeTestRule = createEmptyComposeRule()
@get:Rule
var nameRule = TestName()
@Before
fun setUp() {
Intents.init()
Log.d("StartTest", "Timber tree count before setUp: ${Timber.treeCount}")
// Remove all existing trees to prevent double logging
// Store them so we can restore after test if needed
if (Timber.treeCount > 0) {
// Uproot all existing trees to prevent double logging
Timber.uprootAll()
}
// Plant a single test tree
Timber.plant(DebugFormatTree())
Log.d("StartTest", "Timber tree count after setUp: ${Timber.treeCount}")
}
@After
fun cleanUp() {
// release() may have already been called by the last loop iteration
try {
Intents.release()
} catch (_: IllegalStateException) { /* not initialised, nothing to do */ }
// Clean up test timber tree
Timber.uprootAll()
}
@Test
fun smokeTestStart() {
// Wait for Compose to be ready
composeTestRule.waitForIdle()
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap -> bitmap.writeToTestStorage("${javaClass.simpleName}_${nameRule.methodName}") })
var compose: Boolean
var optionMenu = ""
// iterate samples - only items with classes (not section headers)
MainActivity.menuItems.forEachIndexed { index, contentItem ->
contentItem.clazz?.let { contentClass ->
compose = false
Timber.d("Intended ${index}-${contentClass.simpleName}: ${contentItem.name}")
if (contentItem.clazz == ViewPagerSimpleChartDemo::class.java || contentItem.clazz == ListViewBarChartActivity::class.java)
return@forEachIndexed
try {
// Use description to uniquely identify items since names can be duplicated
// If description exists, use it; otherwise fall back to name
val searchText = contentItem.desc.ifEmpty {
contentItem.name
}
Timber.d("Searching for #$index: '$searchText'")
// Scroll to the item in the LazyColumn by index
// This ensures the item is composed and visible
try {
composeTestRule
.onNodeWithTag("menuList")
.performScrollToIndex(index)
composeTestRule.waitForIdle()
} catch (e: Exception) {
Timber.w("Could not scroll to index $index: ${e.message}")
}
// Now click the item using its test tag
composeTestRule
.onNodeWithTag("menuItem_$index")
.assertExists("Could not find menu item at index $index")
.performClick()
// Wait for the new activity to start
composeTestRule.waitForIdle()
Thread.sleep(300) // Increased delay for activity transition
Intents.intended(hasComponent(contentClass.name))
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-${contentItem.name}-1SampleClick"
.replace(" ", "")
)
})
// Test option menus based on activity type
if (DemoBase::class.java.isAssignableFrom(contentClass)) {
// Test traditional ActionBar menu for DemoBase activities
optionMenu = ""
optionMenus.filter { plain -> plain.isNotEmpty() && Character.isDigit(plain.first()) }.forEach { filteredTitle ->
optionMenu = "$index->$filteredTitle"
Timber.d("optionMenu=$optionMenu")
openActionBarOverflowOrOptionsMenu(getInstrumentation().targetContext)
Timber.d("screenshot optionMenu=$optionMenu")
screenshotOfOptionMenu(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-${contentItem.name}",
filteredTitle
)
}
} else if (DemoBaseCompose::class.java.isAssignableFrom(contentClass)) {
compose = true
// Test Compose dropdown menu for DemoBaseCompose activities
Timber.d("Testing Compose menu for: ${contentClass.simpleName}")
optionMenu = ""
try {
// Click the menu button to open dropdown
composeTestRule
.onNodeWithTag("menuButton")
.assertIsDisplayed()
.performClick()
composeTestRule.waitForIdle()
Thread.sleep(100) // Wait for dropdown to appear
// Define menu items to test (those starting with numbers in traditional menus)
val composeMenuItems = listOf(
"Toggle Values",
"Toggle Icons",
"Toggle Highlight",
"Toggle Pinch Zoom",
"Toggle Auto Scale MinMax",
"Toggle Bar Borders",
// "Animate X",
// "Animate Y",
// "Animate XY",
// "Save to Gallery"
)
composeMenuItems.forEach { menuTitle ->
try {
optionMenu = "$index->$menuTitle"
Timber.d("Testing Compose menu item: $optionMenu")
// Check if menu item exists first
try {
composeTestRule
.onNodeWithTag("menuItem_$menuTitle")
.assertExists()
} catch (_: AssertionError) {
Timber.e("Menu item '$menuTitle' not found for ${contentClass.simpleName}, skipping")
return@forEach
}
// Click the menu item
composeTestRule
.onNodeWithTag("menuItem_$menuTitle")
.performClick()
composeTestRule.waitForIdle()
Thread.sleep(150) // Wait for action to complete
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-${contentItem.name}-${menuTitle}"
.replace(" ", "")
)
})
// Reopen menu for next item
composeTestRule
.onNodeWithTag("menuButton")
.performClick()
composeTestRule.waitForIdle()
Thread.sleep(100)
} catch (e: Exception) {
Timber.w("Could not test menu item '$menuTitle': ${e.message}")
// Try to reopen menu if it closed unexpectedly
try {
composeTestRule
.onNodeWithTag("menuButton")
.performClick()
composeTestRule.waitForIdle()
} catch (_: Exception) {
// Menu button might not be available
}
}
}
// Close the menu before going back
try {
// Click outside to close menu or press back
Espresso.pressBack()
composeTestRule.waitForIdle()
} catch (_: Exception) {
// Menu might already be closed
}
} catch (e: Exception) {
Timber.e("Error testing Compose menu: ${e.message}", e)
}
} else {
Timber.d("Unknown activity type: ${contentClass.simpleName}")
}
if (!compose)
doClickTest(index, contentClass, contentItem)
Espresso.pressBack()
// Wait for MainActivity to be visible again
composeTestRule.waitForIdle()
Thread.sleep(200) // Small delay for back navigation
// Reset intent recording for next iteration; otherwise intents accumulate
// across the loop and Intents.intended() can no longer find a fresh
// unverified match for the current activity.
Intents.release()
Intents.init()
} catch (e: Exception) {
Timber.e("#$index/'${contentClass.simpleName}'->'$optionMenu' ${e.message}", e)
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-Error"
.replace(" ", "")
)
})
// Navigate back so subsequent iterations start from MainActivity
try {
Espresso.pressBack()
composeTestRule.waitForIdle()
} catch (_: Exception) { /* already on MainActivity */ }
// Reset intents so the next iteration starts clean
try {
Intents.release()
Intents.init()
} catch (_: Exception) { /* ignore if already released */ }
}
}
}
}
private fun doClickTest(index: Int, contentClass: Class<out DemoBase>, contentItem: ContentItem<out DemoBase>) {
if (contentItem.clazz == ScrollViewActivity::class.java ||
contentItem.clazz == DynamicalAddingActivity::class.java ||
contentItem.clazz == RealtimeLineChartActivity::class.java ||
contentItem.clazz == LineChartTimeActivity::class.java ||
contentItem.clazz == HorizontalBarComposeActivity::class.java ||
contentItem.clazz == HorizontalBarFullComposeActivity::class.java ||
contentItem.clazz == MultiLineComposeActivity::class.java ||
contentItem.clazz == GradientActivity::class.java ||
contentItem.clazz == TimeBarActivity::class.java ||
// contentItem.clazz == TimeIntervalChartActivity::class.java ||
contentItem.clazz == TimeLineActivity::class.java
) {
// These charts have less clickable area, so skip further clicks
return
}
onView(withId(R.id.chart1)).perform(click())
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-${contentItem.name}-click"
.replace(" ", "")
)
})
onView(withId(R.id.chart1)).perform(clickXY(20, 20))
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-${contentItem.name}-click2020"
.replace(" ", "")
)
})
onView(withId(R.id.chart1)).perform(clickXY(70, 70))
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage(
"${javaClass.simpleName}_${nameRule.methodName}-${index}-${contentClass.simpleName}-${contentItem.name}-click7070"
.replace(" ", "")
)
})
}
private fun screenshotOfOptionMenu(simpleName: String, menuTitle: String) {
onView(withText(menuTitle)).perform(click())
Timber.d("screenshotOfOptionMenu ${menuTitle}-${simpleName}")
onView(ViewMatchers.isRoot())
.perform(captureToBitmap { bitmap: Bitmap ->
bitmap.writeToTestStorage("${simpleName}-2menu-click-${menuTitle}".replace(" ", ""))
}
)
}
fun clickXY(x: Int, y: Int): ViewAction {
return GeneralClickAction(
Tap.SINGLE,
{ view ->
val location = IntArray(2)
view!!.getLocationOnScreen(location)
val screenX = (location[0] + x).toFloat()
val screenY = (location[1] + y).toFloat()
floatArrayOf(screenX, screenY)
},
Press.FINGER,
0, // inputDevice
0 // deviceState
)
}
}