-
Notifications
You must be signed in to change notification settings - Fork 638
/
AsyncImageTest.kt
754 lines (639 loc) · 24.4 KB
/
AsyncImageTest.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
package coil.compose
import android.graphics.BitmapFactory
import android.view.View
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap
import coil.ImageLoader
import coil.compose.AsyncImagePainter.State
import coil.compose.base.test.R
import coil.compose.utils.ImageLoaderIdlingResource
import coil.compose.utils.ImageMockWebServer
import coil.compose.utils.assertHeightIsEqualTo
import coil.compose.utils.assertIsSimilarTo
import coil.compose.utils.assertWidthIsEqualTo
import coil.compose.utils.assumeSupportsCaptureToImage
import coil.decode.DecodeUtils
import coil.fetch.FetchResult
import coil.fetch.Fetcher
import coil.memory.MemoryCache
import coil.request.CachePolicy
import coil.request.ImageRequest
import coil.request.Options
import coil.request.SuccessResult
import coil.size.Scale
import coil.util.TestActivity
import kotlinx.coroutines.delay
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNull
import kotlin.test.fail
class AsyncImageTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<TestActivity>()
private lateinit var server: MockWebServer
private lateinit var requestTracker: ImageLoaderIdlingResource
private lateinit var imageLoader: ImageLoader
@Before
fun before() {
server = ImageMockWebServer()
requestTracker = ImageLoaderIdlingResource()
imageLoader = ImageLoader.Builder(composeTestRule.activity)
.memoryCachePolicy(CachePolicy.DISABLED)
.diskCachePolicy(CachePolicy.DISABLED)
.networkObserverEnabled(false)
.eventListener(requestTracker)
.build()
composeTestRule.registerIdlingResource(requestTracker)
server.start()
}
@After
fun after() {
composeTestRule.unregisterIdlingResource(requestTracker)
server.shutdown()
}
@Test
fun fixedSize() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.size(128.dp, 166.dp)
.testTag(Image),
)
}
waitForRequestComplete()
assertLoadedBitmapSize(128.dp.toPx(), 166.dp.toPx())
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(166.dp)
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun fillMaxWidth_boundedConstraint() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.fillMaxWidth()
.testTag(Image),
)
}
waitForRequestComplete()
val expectedWidthPx = displaySize.width.toDouble()
val expectedHeightPx = expectedWidthPx * SampleHeight / SampleWidth
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun fillMaxWidth_infiniteConstraint() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
Column(Modifier.verticalScroll(rememberScrollState())) {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth()
.testTag(Image),
)
}
}
waitForRequestComplete()
val expectedWidthPx = displaySize.width.toDouble()
val expectedHeightPx = expectedWidthPx * SampleHeight / SampleWidth
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun fillMaxHeight() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.fillMaxHeight()
.testTag(Image),
)
}
waitForRequestComplete()
val expectedHeightPx = displaySize.height.toDouble()
val expectedWidthPx = (expectedHeightPx * SampleWidth / SampleHeight)
.coerceAtMost(displaySize.width.toDouble())
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun dynamicSize() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.testTag(Image),
)
}
waitForRequestComplete()
val expectedWidthPx = displaySize.width.toDouble().coerceAtMost(SampleWidth.toDouble())
val expectedHeightPx = expectedWidthPx * SampleHeight / SampleWidth
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun dynamicHeight() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
LazyColumn(
content = {
item {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
contentScale = ContentScale.Crop,
modifier = Modifier.testTag(Image),
)
}
},
modifier = Modifier
.fillMaxWidth(fraction = 0.5f)
)
}
waitForRequestComplete()
val expectedWidthPx = (displaySize.width / 2.0).coerceAtMost(SampleWidth.toDouble())
val expectedHeightPx = expectedWidthPx * SampleHeight / SampleWidth
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp(), tolerance = 1.dp)
.assertHeightIsEqualTo(expectedHeightPx.toDp(), tolerance = 1.dp)
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun overwriteLoading() {
assumeSupportsCaptureToImage()
// Remove this or `setContent` will timeout.
composeTestRule.unregisterIdlingResource(requestTracker)
composeTestRule.setContent {
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(server.url("/image"))
.fetcherFactory(LoadingFetcher.Factory())
.build(),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.size(128.dp, 128.dp)
.testTag(Image),
loading = {
Box(
modifier = Modifier
.background(color = Color.Blue)
)
}
)
Spacer(
modifier = Modifier
.height(8.dp)
.fillMaxWidth()
)
Box(
modifier = Modifier
.size(128.dp, 128.dp)
.background(color = Color.Blue)
.testTag(Loading),
)
}
composeTestRule.waitUntil(10_000) {
requestTracker.startedRequests >= 1
}
val actual = composeTestRule.onNodeWithTag(Image).captureToImage()
val expected = composeTestRule.onNodeWithTag(Loading).captureToImage()
actual.assertIsSimilarTo(expected)
}
@Test
fun overwriteError() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(server.url("/image"))
.fetcherFactory(ErrorFetcher.Factory())
.build(),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.size(128.dp, 128.dp)
.testTag(Image),
error = {
Box(
modifier = Modifier
.background(color = Color.Blue)
)
}
)
Spacer(
modifier = Modifier
.height(8.dp)
.fillMaxWidth()
)
Box(
modifier = Modifier
.size(128.dp, 128.dp)
.background(color = Color.Blue)
.testTag(Error),
)
}
waitForRequestComplete()
val actual = composeTestRule.onNodeWithTag(Image).captureToImage()
val expected = composeTestRule.onNodeWithTag(Error).captureToImage()
actual.assertIsSimilarTo(expected)
}
@Test
fun overwriteSuccess() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
SubcomposeAsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.size(128.dp, 128.dp)
.testTag(Image),
success = {
Box(
modifier = Modifier
.background(color = Color.Blue)
)
}
)
Spacer(
modifier = Modifier
.height(8.dp)
.fillMaxWidth()
)
Box(
modifier = Modifier
.size(128.dp, 128.dp)
.background(color = Color.Blue)
.testTag(Success),
)
}
waitForRequestComplete()
val actual = composeTestRule.onNodeWithTag(Image).captureToImage()
val expected = composeTestRule.onNodeWithTag(Success).captureToImage()
actual.assertIsSimilarTo(expected)
}
@Test
fun overwriteContent() {
assumeSupportsCaptureToImage()
var index = 0
composeTestRule.setContent {
SubcomposeAsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.size(100.dp)
.testTag(Image)
) {
val state = painter.state
SideEffect {
when (index) {
0 -> {
assertIs<State.Loading>(state)
assertEquals(painter.state, state)
assertNull(state.painter)
}
1 -> {
assertIs<State.Success>(state)
assertEquals(painter.state, state)
}
else -> fail("Recomposed too many times. State: $state")
}
index++
}
SubcomposeAsyncImageContent(
modifier = Modifier.clip(CircleShape)
)
}
Spacer(
modifier = Modifier
.height(8.dp)
.fillMaxWidth()
)
Box(
modifier = Modifier
.size(100.dp)
.testTag(Content),
) {
Image(
painter = painterResource(id = R.drawable.sample),
contentDescription = null,
modifier = Modifier
.matchParentSize()
.clip(CircleShape)
)
}
}
waitForRequestComplete()
val actual = composeTestRule.onNodeWithTag(Image).captureToImage()
val expected = composeTestRule.onNodeWithTag(Content).captureToImage()
actual.assertIsSimilarTo(expected)
}
@Test
fun listener() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
val value = "" // Use a fake value inside the listener to make it stateful.
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(server.url("/image"))
// Ensure this doesn't constantly recompose or restart image requests.
.listener { _, _ -> value + "" }
.build(),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.testTag(Image),
)
}
waitForRequestComplete()
val expectedWidthPx = displaySize.width.toDouble().coerceAtMost(SampleWidth.toDouble())
val expectedHeightPx = expectedWidthPx * SampleHeight / SampleWidth
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample)
}
@Test
fun fillMaxSize_scaleFill() {
assumeSupportsCaptureToImage()
composeTestRule.setContent {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.fillMaxSize()
.testTag(Image),
contentScale = ContentScale.Crop
)
}
waitForRequestComplete()
val expectedWidthPx = displaySize.width.toDouble()
val expectedHeightPx = displaySize.height.toDouble()
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx, scale = Scale.FILL)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample, scale = Scale.FILL)
}
@Test
fun doesNotRecompose() {
val compositionCount = AtomicInteger()
composeTestRule.setContent {
compositionCount.getAndIncrement()
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader
)
}
waitForRequestComplete()
assertEquals(1, compositionCount.get())
}
@Test
fun painterState_notMemoryCached() {
val outerCompositionCount = AtomicInteger()
val innerCompositionCount = AtomicInteger()
composeTestRule.setContent {
outerCompositionCount.getAndIncrement()
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(server.url("/image"))
.memoryCachePolicy(CachePolicy.ENABLED)
.build(),
contentDescription = null,
imageLoader = imageLoader
) {
when (innerCompositionCount.getAndIncrement()) {
0 -> assertIs<State.Loading>(painter.state)
else -> assertIs<State.Success>(painter.state)
}
SubcomposeAsyncImageContent()
}
}
waitForRequestComplete()
assertEquals(1, outerCompositionCount.get())
assertEquals(2, innerCompositionCount.get())
}
@Test
fun painterState_memoryCached() {
val url = server.url("/image")
val bitmap = BitmapFactory.decodeResource(composeTestRule.activity.resources, R.drawable.sample)
imageLoader.memoryCache!![MemoryCache.Key(url.toString())] = MemoryCache.Value(bitmap)
val outerCompositionCount = AtomicInteger()
val innerCompositionCount = AtomicInteger()
composeTestRule.setContent {
outerCompositionCount.getAndIncrement()
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(url)
.memoryCachePolicy(CachePolicy.ENABLED)
.build(),
contentDescription = null,
imageLoader = imageLoader
) {
innerCompositionCount.getAndIncrement()
assertIs<State.Success>(painter.state)
SubcomposeAsyncImageContent()
}
}
waitForRequestComplete()
assertEquals(1, outerCompositionCount.get())
assertEquals(1, innerCompositionCount.get())
}
/** Regression test: https://github.com/coil-kt/coil/issues/1133 */
@Test
fun infiniteConstraint() {
assumeSupportsCaptureToImage()
val expectedWidthDp = 32.dp
composeTestRule.setContent {
Column(Modifier.verticalScroll(rememberScrollState())) {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier
.width(expectedWidthDp)
.testTag(Image),
contentScale = ContentScale.Crop
)
}
}
waitForRequestComplete()
val expectedWidthPx = expectedWidthDp.toPx().toDouble()
val expectedHeightPx = expectedWidthPx * SampleHeight / SampleWidth
assertSampleLoadedBitmapSize(expectedWidthPx, expectedHeightPx)
composeTestRule.onNodeWithTag(Image)
.assertIsDisplayed()
.assertWidthIsEqualTo(expectedWidthPx.toDp())
.assertHeightIsEqualTo(expectedHeightPx.toDp())
.captureToImage()
.assertIsSimilarTo(R.drawable.sample, threshold = 0.85)
}
/** Regression test: https://github.com/coil-kt/coil/issues/1217 */
@Test
fun noneContentScaleShouldLoadAtOriginalSize() {
composeTestRule.setContent {
AsyncImage(
model = server.url("/image"),
contentDescription = null,
imageLoader = imageLoader,
modifier = Modifier.width(30.dp),
contentScale = ContentScale.None
)
}
waitForRequestComplete()
assertLoadedBitmapSize(SampleWidth, SampleHeight)
}
private fun waitForRequestComplete(finishedRequests: Int = 1) {
composeTestRule.waitForIdle()
composeTestRule.waitUntil(10_000) {
requestTracker.finishedRequests >= finishedRequests
}
composeTestRule.waitForIdle()
}
private fun assertLoadedBitmapSize(width: Int, height: Int, requestNumber: Int = 0) {
val result = requestTracker.results[requestNumber]
assertIs<SuccessResult>(result)
val bitmap = result.drawable.toBitmap()
assertContains((width - 1)..(width + 1), bitmap.width)
assertContains((height - 1)..(height + 1), bitmap.height)
}
private fun assertSampleLoadedBitmapSize(
composableWidth: Double,
composableHeight: Double,
scale: Scale = Scale.FIT,
requestNumber: Int = 0
) {
val multiplier = DecodeUtils.computeSizeMultiplier(
srcWidth = SampleWidth.toDouble(),
srcHeight = SampleHeight.toDouble(),
dstWidth = composableWidth,
dstHeight = composableHeight,
scale = scale
).coerceAtMost(1.0)
assertLoadedBitmapSize(
width = (multiplier * SampleWidth).toInt(),
height = (multiplier * SampleHeight).toInt(),
requestNumber = requestNumber
)
}
private fun Dp.toPx() = with(composeTestRule.density) { toPx().toInt() }
private fun Double.toDp() = with(composeTestRule.density) { toInt().toDp() }
private val displaySize: IntSize
get() = composeTestRule.activity.findViewById<View>(android.R.id.content)!!
.run { IntSize(width, height) }
private class LoadingFetcher : Fetcher {
override suspend fun fetch(): FetchResult? {
while (true) delay(100)
}
class Factory : Fetcher.Factory<Any> {
override fun create(data: Any, options: Options, imageLoader: ImageLoader) = LoadingFetcher()
}
}
private class ErrorFetcher : Fetcher {
override suspend fun fetch(): FetchResult? {
throw IllegalStateException()
}
class Factory : Fetcher.Factory<Any> {
override fun create(data: Any, options: Options, imageLoader: ImageLoader) = ErrorFetcher()
}
}
companion object {
private const val Image = "image"
private const val Loading = "loading"
private const val Error = "error"
private const val Success = "success"
private const val Content = "content"
private const val SampleWidth = 1024
private const val SampleHeight = 1326
}
}