1 /*
2  * Copyright (C) 2017 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 androidx.core.content
18 
19 import android.content.ContextWrapper
20 import android.support.test.InstrumentationRegistry
21 import android.support.test.filters.SdkSuppress
22 import androidx.core.ktx.test.R
23 import androidx.core.getAttributeSet
24 import org.junit.Assert.assertEquals
25 import org.junit.Assert.assertSame
26 import org.junit.Assert.assertTrue
27 import org.junit.Test
28 
29 class ContextTest {
30     private val context = InstrumentationRegistry.getContext()
31 
32     @SdkSuppress(minSdkVersion = 23)
systemServicenull33     @Test fun systemService() {
34         var lookup: Class<*>? = null
35         val context = object : ContextWrapper(context) {
36             override fun getSystemServiceName(serviceClass: Class<*>): String? {
37                 lookup = serviceClass
38                 return if (serviceClass == Unit::class.java) "unit" else null
39             }
40 
41             override fun getSystemService(name: String): Any? {
42                 return if (name == "unit") Unit else null
43             }
44         }
45         val actual = context.getSystemService<Unit>()
46         assertEquals(Unit::class.java, lookup)
47         assertSame(Unit, actual)
48     }
49 
withStyledAttributesnull50     @Test fun withStyledAttributes() {
51         context.withStyledAttributes(attrs = intArrayOf(android.R.attr.textColorPrimary)) {
52             val resourceId = getResourceId(0, -1)
53             assertTrue(resourceId != 1)
54         }
55 
56         context.withStyledAttributes(
57             android.R.style.Theme_Light,
58             intArrayOf(android.R.attr.textColorPrimary)
59         ) {
60             val resourceId = getResourceId(0, -1)
61             assertTrue(resourceId != 1)
62         }
63 
64         val attrs = context.getAttributeSet(R.layout.test_attrs)
65         context.withStyledAttributes(attrs, R.styleable.SampleAttrs) {
66             assertTrue(getInt(R.styleable.SampleAttrs_sample, -1) != -1)
67         }
68 
69         context.withStyledAttributes(attrs, R.styleable.SampleAttrs, 0, 0) {
70             assertTrue(getInt(R.styleable.SampleAttrs_sample, -1) != -1)
71         }
72     }
73 }
74