blob: 14ed8e9e3ad66e52034f1b7049cbc1b178f59a53 [file] [log] [blame]
Chalard Jean48c6c7d2020-06-25 23:39:15 +09001/*
2 * 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
Chalard Jeanb1856fe2020-06-26 00:42:01 +090017@file:JvmName("ParcelUtils")
18
Chalard Jean48c6c7d2020-06-25 23:39:15 +090019package com.android.testutils
20
21import android.os.Parcel
22import android.os.Parcelable
23import kotlin.test.assertTrue
24import kotlin.test.fail
25
26/**
27 * Return a new instance of `T` after being parceled then unparceled.
28 */
29fun <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
54fun <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
63fun <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}