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