1 /*
<lambda>null2  * Copyright (C) 2024 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 platform.test.motion.testing
18 
19 import com.google.common.truth.FailureMetadata
20 import com.google.common.truth.Subject
21 import com.google.common.truth.Truth
22 import org.json.JSONArray
23 import org.json.JSONObject
24 
25 /** [Truth] subject for org.json. */
26 class JsonSubject private constructor(failureMetadata: FailureMetadata, private val actual: Any?) :
27     Subject(failureMetadata, actual) {
28 
29     /**
30      * Verifies the subject is a [JSONObject] that matches the [expected] json.
31      *
32      * Note that this verifications does assert the (meaningless) order of properties. This subject
33      * needs to be re-written if that turns out to be a problem. For now, this simply hides that
34      * hack within this implementation.
35      */
36     override fun isEqualTo(expected: Any?) {
37         if (actual is JSONObject && expected is JSONObject) {
38             check("serializedJson")
39                 .that(actual.toString(PRETTY_PRINT_INDENT))
40                 .isEqualTo(expected.toString(PRETTY_PRINT_INDENT))
41         } else if (actual is JSONArray && expected is JSONArray) {
42             check("serializedJson")
43                 .that(actual.toString(PRETTY_PRINT_INDENT))
44                 .isEqualTo(expected.toString(PRETTY_PRINT_INDENT))
45         } else {
46             super.isEqualTo(expected)
47         }
48     }
49 
50     companion object {
51         private const val PRETTY_PRINT_INDENT = 2
52 
53         /** Returns a factory to be used with [Truth.assertAbout]. */
54         fun json(): Factory<JsonSubject, Any> {
55             return Factory { failureMetadata: FailureMetadata, subject: Any? ->
56                 JsonSubject(failureMetadata, subject)
57             }
58         }
59 
60         /** Shortcut for `Truth.assertAbout(json()).that(json)`. */
61         fun assertThat(json: JSONObject): JsonSubject = Truth.assertAbout(json()).that(json)
62     }
63 }
64