1 /*
<lambda>null2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.compose.test.subjects
18 
19 import androidx.compose.ui.test.assertIsEqualTo
20 import androidx.compose.ui.unit.Dp
21 import androidx.compose.ui.unit.DpOffset
22 import com.google.common.truth.FailureMetadata
23 import com.google.common.truth.Subject
24 import com.google.common.truth.Subject.Factory
25 import com.google.common.truth.Truth.assertAbout
26 
27 /** Assert on a [DpOffset]. */
28 fun assertThat(dpOffset: DpOffset): DpOffsetSubject {
29     return assertAbout(DpOffsetSubject.dpOffsets()).that(dpOffset)
30 }
31 
32 /** A Truth subject to assert on [DpOffset] with some tolerance. Inspired by FloatSubject. */
33 class DpOffsetSubject(
34     metadata: FailureMetadata,
35     private val actual: DpOffset,
36 ) : Subject(metadata, actual) {
isWithinnull37     fun isWithin(tolerance: Dp): TolerantDpOffsetComparison {
38         return object : TolerantDpOffsetComparison {
39             override fun of(expected: DpOffset) {
40                 actual.x.assertIsEqualTo(expected.x, "offset.x", tolerance)
41                 actual.y.assertIsEqualTo(expected.y, "offset.y", tolerance)
42             }
43         }
44     }
45 
46     interface TolerantDpOffsetComparison {
ofnull47         fun of(expected: DpOffset)
48     }
49 
50     companion object {
51         val DefaultTolerance = Dp(.5f)
52 
53         fun dpOffsets() =
54             Factory<DpOffsetSubject, DpOffset> { metadata, actual ->
55                 DpOffsetSubject(metadata, actual)
56             }
57     }
58 }
59