blob: 4e8ee5cf3c3b62d56638c052ba16c98a7834c950 [file] [log] [blame]
Winson9947f1e2019-08-16 10:20:39 -07001/*
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
17package android.content.res.loader.test
18
19import android.content.Context
20import android.content.res.AssetFileDescriptor
21import android.content.res.Resources
22import android.os.ParcelFileDescriptor
23import android.util.TypedValue
24import org.mockito.Answers
25import org.mockito.stubbing.Answer
26import org.xmlpull.v1.XmlPullParser
27import java.io.File
28
Winson9947f1e2019-08-16 10:20:39 -070029object Utils {
30 val ANSWER_THROWS = Answer<Any> {
31 when (val name = it.method.name) {
32 "toString" -> return@Answer Answers.CALLS_REAL_METHODS.answer(it)
33 else -> throw UnsupportedOperationException("$name with " +
34 "${it.arguments?.joinToString()} should not be called")
35 }
36 }
37}
38
39fun Int.dpToPx(resources: Resources) = TypedValue.applyDimension(
40 TypedValue.COMPLEX_UNIT_DIP,
41 this.toFloat(),
42 resources.displayMetrics
43).toInt()
44
45fun AssetFileDescriptor.readText() = createInputStream().reader().readText()
46
47fun rawFile(fileName: String) = R.raw::class.java.getDeclaredField(fileName).getInt(null)
48
49fun XmlPullParser.advanceToRoot() = apply {
50 while (next() != XmlPullParser.START_TAG) {
51 // Empty
52 }
53}
54
55fun Context.copiedRawFile(fileName: String): ParcelFileDescriptor {
56 return resources.openRawResourceFd(rawFile(fileName)).use { asset ->
57 // AssetManager doesn't expose a direct file descriptor to the asset, so copy it to
58 // an individual file so one can be created manually.
59 val copiedFile = File(filesDir, fileName)
60 asset.createInputStream().use { input ->
61 copiedFile.outputStream().use { output ->
62 input.copyTo(output)
63 }
64 }
65
66 ParcelFileDescriptor.open(copiedFile, ParcelFileDescriptor.MODE_READ_WRITE)
67 }
68}