-
Notifications
You must be signed in to change notification settings - Fork 586
/
CoilTest.kt
544 lines (462 loc) · 18.4 KB
/
CoilTest.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*
* 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.coil
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.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.platform.ContextAmbient
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 coil.EventListener
import coil.ImageLoader
import coil.annotation.ExperimentalCoilApi
import coil.decode.Options
import coil.fetch.Fetcher
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.google.common.truth.Truth.assertThat
import dev.chrisbanes.accompanist.coil.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.test.TestCoroutineDispatcher
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
import java.util.concurrent.atomic.AtomicInteger
@LargeTest
@RunWith(JUnit4::class)
class CoilTest {
@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_fromImageRequest() {
val results = ArrayList<ImageLoadState>()
val latch = CountDownLatch(1)
composeTestRule.setContent {
CoilImage(
request = ImageRequest.Builder(ContextAmbient.current)
.data(server.url("/image"))
.listener { _, _ -> latch.countDown() }
.build(),
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { results += it }
)
}
// Wait for the Coil 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 onRequestCompleted_fromBuilder() {
val results = ArrayList<ImageLoadState>()
val latch = CountDownLatch(1)
composeTestRule.setContent {
CoilImage(
data = server.url("/image"),
requestBuilder = {
listener { _, _ -> latch.countDown() }
},
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { results += it }
)
}
// Wait for the Coil 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 {
CoilImage(
data = server.url("/image"),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(CoilTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.onNodeWithTag(CoilTestTags.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 {
CoilImage(
data = resourceUri(R.drawable.red_rectangle),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(CoilTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.onNodeWithTag(CoilTestTags.Image)
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Red }
}
@OptIn(ExperimentalCoilApi::class)
@Test
fun basicLoad_customImageLoader() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val latch = CountDownLatch(1)
// Build a custom ImageLoader with a fake EventListener
val eventListener = object : EventListener {
val startCalled = AtomicInteger()
override fun fetchStart(request: ImageRequest, fetcher: Fetcher<*>, options: Options) {
startCalled.incrementAndGet()
}
}
val imageLoader = ImageLoader.Builder(context)
.eventListener(eventListener)
.build()
composeTestRule.setContent {
CoilImage(
data = server.url("/image"),
modifier = Modifier.preferredSize(128.dp, 128.dp),
imageLoader = imageLoader,
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Verify that our eventListener was invoked
assertThat(eventListener.startCalled.get()).isAtLeast(1)
}
@OptIn(ExperimentalCoilApi::class)
@Test
fun basicLoad_customImageLoader_ambient() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val latch = CountDownLatch(1)
// Build a custom ImageLoader with a fake EventListener
val eventListener = object : EventListener {
val startCalled = AtomicInteger()
override fun fetchStart(request: ImageRequest, fetcher: Fetcher<*>, options: Options) {
startCalled.incrementAndGet()
}
}
val imageLoader = ImageLoader.Builder(context)
.eventListener(eventListener)
.build()
composeTestRule.setContent {
Providers(AmbientImageLoader provides imageLoader) {
CoilImage(
data = server.url("/image"),
modifier = Modifier.preferredSize(128.dp, 128.dp),
onRequestCompleted = { latch.countDown() }
)
}
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
// Verify that our eventListener was invoked
assertThat(eventListener.startCalled.get()).isAtLeast(1)
}
@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()
CoilImage(
data = resId.value,
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(CoilTestTags.Image),
onRequestCompleted = { loadCompleteSignal.offer(Unit) }
)
}
// Await the first load
loadCompleteSignal.awaitNext(5, TimeUnit.SECONDS)
// Assert that the content is completely Red
composeTestRule.onNodeWithTag(CoilTestTags.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(CoilTestTags.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()
CoilImage(
data = server.url("/red"),
modifier = Modifier.preferredSize(size.value).testTag(CoilTestTags.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 {
CoilImage(
data = server.url("/image"),
modifier = Modifier.testTag(CoilTestTags.Image),
onRequestCompleted = { latch.countDown() }
)
}
// Wait for the onRequestCompleted to release the latch
latch.await(5, TimeUnit.SECONDS)
composeTestRule.onNodeWithTag(CoilTestTags.Image)
.assertWidthIsAtLeast(1.dp)
.assertHeightIsAtLeast(1.dp)
.assertIsDisplayed()
}
@Test
fun errorStillHasSize() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
CoilImage(
data = server.url("/noimage"),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(CoilTestTags.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(CoilTestTags.Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
}
@Test
fun content_error() {
val latch = CountDownLatch(1)
val states = ArrayList<ImageLoadState>()
composeTestRule.setContent {
CoilImage(
data = server.url("/noimage"),
modifier = Modifier.preferredSize(128.dp, 128.dp),
// Disable any caches. If the item is in the cache, the fetch is
// synchronous which means the Loading state is skipped
imageLoader = noCacheImageLoader(),
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 {
CoilImage(
data = server.url("/image"),
modifier = Modifier.preferredSize(128.dp, 128.dp),
// Disable any caches. If the item is in the cache, the fetch is
// synchronous which means the Loading state is skipped
imageLoader = noCacheImageLoader(),
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 {
CoilImage(
data = server.url("/image"),
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(CoilTestTags.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(CoilTestTags.Image)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Cyan }
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun loading_slot() {
val loadLatch = CountDownLatch(1)
// Create a test dispatcher and immediately pause it
val dispatcher = TestCoroutineDispatcher()
dispatcher.pauseDispatcher()
val context = InstrumentationRegistry.getInstrumentation().targetContext
val imageLoader = ImageLoader.Builder(context)
// Load on our test dispatcher
.dispatcher(dispatcher)
// Disable memory cache. If the item is in the cache, the fetch is
// synchronous and the dispatcher pause has no effect
.memoryCachePolicy(CachePolicy.DISABLED)
.build()
composeTestRule.setContent {
CoilImage(
data = server.url("/image"),
imageLoader = imageLoader,
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 the dispatcher to start the Coil request
dispatcher.resumeDispatcher()
// 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()
dispatcher.cleanupTestCoroutines()
}
@Test
@SdkSuppress(minSdkVersion = 26) // captureToBitmap is SDK 26+
fun error_slot() {
val latch = CountDownLatch(1)
composeTestRule.setContent {
CoilImage(
data = server.url("/noimage"),
error = {
// Return failure content which just draws red
Image(painter = ColorPainter(Color.Red))
},
modifier = Modifier.preferredSize(128.dp, 128.dp).testTag(CoilTestTags.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(CoilTestTags.Image)
.assertIsDisplayed()
.captureToBitmap()
.assertPixels { Color.Red }
}
}
/**
* [ImageLoader] which disables all caching
*/
private fun noCacheImageLoader(): ImageLoader {
val ctx = InstrumentationRegistry.getInstrumentation().targetContext
return ImageLoader.Builder(ctx)
.memoryCachePolicy(CachePolicy.DISABLED)
.diskCachePolicy(CachePolicy.DISABLED)
.build()
}