1 /*
<lambda>null2 * Copyright (C) 2019 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 @file:JvmName("ParcelUtils")
18
19 package com.android.testutils
20
21 import android.os.Parcel
22 import android.os.Parcelable
23 import kotlin.test.assertTrue
24 import kotlin.test.fail
25
26 /**
27 * Return a new instance of `T` after being parceled then unparceled.
28 */
29 fun <T : Parcelable> parcelingRoundTrip(source: T): T {
30 val creator: Parcelable.Creator<T>
31 try {
32 creator = source.javaClass.getField("CREATOR").get(null) as Parcelable.Creator<T>
33 } catch (e: IllegalAccessException) {
34 fail("Missing CREATOR field: " + e.message)
35 } catch (e: NoSuchFieldException) {
36 fail("Missing CREATOR field: " + e.message)
37 }
38
39 var p = Parcel.obtain()
40 source.writeToParcel(p, /* flags */ 0)
41 p.setDataPosition(0)
42 val marshalled = p.marshall()
43 p = Parcel.obtain()
44 p.unmarshall(marshalled, 0, marshalled.size)
45 p.setDataPosition(0)
46 return creator.createFromParcel(p)
47 }
48
49 /**
50 * Assert that after being parceled then unparceled, `source` is equal to the original
51 * object. If a customized equals function is provided, uses the provided one.
52 */
53 @JvmOverloads
assertParcelingIsLosslessnull54 fun <T : Parcelable> assertParcelingIsLossless(
55 source: T,
56 equals: (T, T) -> Boolean = { a, b -> a == b }
57 ) {
58 val actual = parcelingRoundTrip(source)
59 assertTrue(equals(source, actual), "Expected $source, but was $actual")
60 }
61
62 @JvmOverloads
assertParcelSanenull63 fun <T : Parcelable> assertParcelSane(
64 obj: T,
65 fieldCount: Int,
66 equals: (T, T) -> Boolean = { a, b -> a == b }
67 ) {
68 assertFieldCountEquals(fieldCount, obj::class.java)
69 assertParcelingIsLossless(obj, equals)
70 }
71