-
Notifications
You must be signed in to change notification settings - Fork 585
/
GlideTest.kt
506 lines (431 loc) · 17.5 KB
/
GlideTest.kt
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.chrisbanes.accompanist.glide
import android.graphics.drawable.Drawable
import androidx.compose.foundation.Image
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.preferredSize
import androidx.compose.runtime.Providers
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.onCommit
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.platform.ViewAmbient
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import androidx.ui.test.assertHeightIsAtLeast
import androidx.ui.test.assertHeightIsEqualTo
import androidx.ui.test.assertIsDisplayed
import androidx.ui.test.assertPixels
import androidx.ui.test.assertWidthIsAtLeast
import androidx.ui.test.assertWidthIsEqualTo
import androidx.ui.test.captureToBitmap
import androidx.ui.test.createComposeRule
import androidx.ui.test.onNodeWithTag
import androidx.ui.test.onNodeWithText
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.google.common.truth.Truth.assertThat
import dev.chrisbanes.accompanist.glide.test.R
import dev.chrisbanes.accompanist.imageloading.ImageLoadState
import dev.chrisbanes.accompanist.imageloading.test.ImageMockWebServer
import dev.chrisbanes.accompanist.imageloading.test.awaitNext
import dev.chrisbanes.accompanist.imageloading.test.receiveBlocking
import dev.chrisbanes.accompanist.imageloading.test.resourceUri
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@LargeTest
@RunWith(JUnit4::class)
class GlideTest {
@get:Rule
val composeTestRule = createComposeRule()
// Our MockWebServer. We use a response delay to simulate real-world conditions
private val server = ImageMockWebServer()
@Before
fun setup() {
// Start our mock web server
server.start()
}
@After
fun teardown() {
// Shutdown our mock web server
server.shutdown()
}
@Test
fun onRequestCompleted() {
val results = ArrayList<ImageLoadState>()
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = server.url("/image").toString(),
requestBuilder = {
listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
exception: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
latch.countDown()
// False so that Glide still invokes the Target
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
source: DataSource?,
isFirstResource: Boolean
): Boolean {
latch.countDown()
// False so that Glide still invokes the Target
return false
}
})
},
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { results += it }
)
}
// Wait for the Glide request listener to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.runOnIdle {
// And assert that we got a single successful result
assertThat(results).hasSize(1)
assertThat(results[0]).isInstanceOf(ImageLoadState.Success::class.java)
}
}
@Test
fun basicLoad_http() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = server.url("/image").toString(),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(GlideTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
}
@Test
@SdkSuppress(minSdkVersion = 26) // captureToBitmap is SDK 26+
fun basicLoad_drawable() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = resourceUri(R.drawable.red_rectangle),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(GlideTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Red }
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
@SdkSuppress(minSdkVersion = 26) // captureToBitmap is SDK 26+
fun basicLoad_switchData() {
val loadCompleteSignal = Channel<Unit>(Channel.UNLIMITED)
val data = MutableStateFlow(server.url("/red"))
composeTestRule.setContent {
val resId = data.collectAsState()
GlideImage(
data = resId.value.toString(),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(GlideTestTags.Image),
onRequestCompleted = { loadCompleteSignal.offer(Unit) }
)
}
// Await the first load
loadCompleteSignal.awaitNext(5, TimeUnit.SECONDS)
// Assert that the content is completely Red
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Red }
// Now switch the data URI to the blue drawable
data.value = server.url("/blue")
// Await the second load
loadCompleteSignal.awaitNext(5, TimeUnit.SECONDS)
// Assert that the content is completely Blue
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Blue }
// Close the signal channel
loadCompleteSignal.close()
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun basicLoad_changeSize() {
val loadCompleteSignal = Channel<ImageLoadState>(Channel.UNLIMITED)
val sizeFlow = MutableStateFlow(128.dp)
composeTestRule.setContent {
val size = sizeFlow.collectAsState()
GlideImage(
data = server.url("/red").toString(),
modifier = Modifier.preferredSize(size.value).testTag(GlideTestTags.Image),
onRequestCompleted = { loadCompleteSignal.offer(it) }
)
}
// Await the first load
assertThat(loadCompleteSignal.receiveBlocking())
.isInstanceOf(ImageLoadState.Success::class.java)
// Now change the size
sizeFlow.value = 256.dp
// Await the potential second load (which shouldn't come)
runBlocking {
val result = withTimeoutOrNull(3000) { loadCompleteSignal.receive() }
assertThat(result).isNull()
}
// Close the signal channel
loadCompleteSignal.close()
}
@Test
fun basicLoad_nosize() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = server.url("/image").toString(),
modifier = Modifier.testTag(GlideTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertWidthIsAtLeast(1.dp)
.assertHeightIsAtLeast(1.dp)
.assertIsDisplayed()
}
@Test
fun customRequestManager_param() {
val latch = CountDownLatch(1)
val loaded = mutableListOf<Any>()
composeTestRule.setContent {
// Create a RequestManager with a listener which updates our loaded list
val glide = Glide.with(ViewAmbient.current)
.addDefaultRequestListener(SimpleRequestListener { model -> loaded += model })
GlideImage(
data = server.url("/image").toString(),
requestManager = glide,
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Assert that the listener was called
assertThat(loaded).hasSize(1)
}
@Test
fun customRequestManager_ambient() {
val latch = CountDownLatch(1)
val loaded = mutableListOf<Any>()
composeTestRule.setContent {
// Create a RequestManager with a listener which updates our loaded list
val glide = Glide.with(ViewAmbient.current)
.addDefaultRequestListener(SimpleRequestListener { model -> loaded += model })
Providers(AmbientRequestManager provides glide) {
GlideImage(
data = server.url("/image").toString(),
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { latch.countDown() }
)
}
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Assert that the listener was called
assertThat(loaded).hasSize(1)
}
@Test
fun errorStillHasSize() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = server.url("/noimage").toString(),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(GlideTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Assert that the layout is in the tree and has the correct size
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
}
@Test
fun content_error() {
val latch = CountDownLatch(1)
val states = ArrayList<ImageLoadState>()
composeTestRule.setContent {
GlideImage(
data = server.url("/noimage").toString(),
requestBuilder = {
// Disable memory cache. If the item is in the cache, the fetch is
// synchronous and the dispatcher pause has no effect
skipMemoryCache(true)
},
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { latch.countDown() }
) { state ->
states.add(state)
}
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.runOnIdle {
assertThat(states).hasSize(3)
assertThat(states[0]).isEqualTo(ImageLoadState.Empty)
assertThat(states[1]).isEqualTo(ImageLoadState.Loading)
assertThat(states[2]).isInstanceOf(ImageLoadState.Error::class.java)
}
}
@Test
fun content_success() {
val latch = CountDownLatch(1)
val states = ArrayList<ImageLoadState>()
composeTestRule.setContent {
GlideImage(
data = server.url("/image").toString(),
requestBuilder = {
// Disable memory cache. If the item is in the cache, the fetch is
// synchronous and the dispatcher pause has no effect
skipMemoryCache(true)
},
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { latch.countDown() }
) { state ->
states.add(state)
}
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.runOnIdle {
assertThat(states).hasSize(3)
assertThat(states[0]).isEqualTo(ImageLoadState.Empty)
assertThat(states[1]).isEqualTo(ImageLoadState.Loading)
assertThat(states[2]).isInstanceOf(ImageLoadState.Success::class.java)
}
}
@Test
@SdkSuppress(minSdkVersion = 26) // captureToBitmap is SDK 26+
fun content_custom() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = server.url("/image").toString(),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(GlideTestTags.Image),
onRequestCompleted = { latch.countDown() }
) { _ ->
// Return an Image which just draws cyan
Image(painter = ColorPainter(Color.Cyan))
}
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Assert that the whole layout is drawn cyan
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Cyan }
}
@Test
fun loading_slot() {
val loadLatch = CountDownLatch(1)
val glide = Glide.with(InstrumentationRegistry.getInstrumentation().targetContext)
composeTestRule.setContent {
onCommit {
// Pause all requests so that the request doesn't complete. This needs to be done
// inside our content because Glide automatically resumeRequests() in onStart
glide.pauseAllRequests()
}
GlideImage(
data = server.url("/image").toString(),
requestManager = glide,
modifier = Modifier.preferredSize(128.dp, 128.dp),
loading = { Text(text = "Loading") },
onRequestCompleted = { loadLatch.countDown() }
)
}
// Assert that the loading component is displayed
composeTestRule.onNodeWithText("Loading").assertIsDisplayed()
// Now resume all requests
glide.resumeRequests()
// We now wait for the request to complete
loadLatch.await(5, TimeUnit.SECONDS)
// And assert that the loading component no longer exists
composeTestRule.onNodeWithText("Loading").assertDoesNotExist()
}
@Test
@SdkSuppress(minSdkVersion = 26) // captureToBitmap is SDK 26+
fun error_slot() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
GlideImage(
data = server.url("/noimage").toString(),
error = {
// Return failure content which just draws red
Image(painter = ColorPainter(Color.Red))
},
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(GlideTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Assert that the whole layout is drawn red
composeTestRule.onNodeWithTag(GlideTestTags.Image)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Red }
}
}