1 /*
2  * Copyright 2023 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.compose.foundation.text.input
18 
19 import android.view.View
20 import androidx.compose.foundation.text.input.internal.ComposeInputMethodManager
21 import androidx.compose.foundation.text.input.internal.overrideComposeInputMethodManagerFactoryForTests
22 import org.junit.rules.TestRule
23 import org.junit.runner.Description
24 import org.junit.runners.model.Statement
25 
26 /**
27  * Rule to help setting the factory used to create [ComposeInputMethodManager] instances for tests.
28  * Restores the previous factory after the test finishes.
29  */
30 internal class ComposeInputMethodManagerTestRule : TestRule {
31     private var initialFactory: ((View) -> ComposeInputMethodManager)? = null
32 
33     /**
34      * Replaces the [ComposeInputMethodManager] factory with the given [factory].
35      *
36      * @return The initial factory that can be used to delegate select calls to not fully override
37      *   the default [ComposeInputMethodManager].
38      */
setFactorynull39     fun setFactory(
40         factory: (View) -> ComposeInputMethodManager
41     ): ((View) -> ComposeInputMethodManager) {
42         val previousFactory = overrideComposeInputMethodManagerFactoryForTests(factory)
43         if (initialFactory == null) {
44             initialFactory = previousFactory
45         }
46         return initialFactory!!
47     }
48 
applynull49     override fun apply(base: Statement, description: Description): Statement =
50         object : Statement() {
51             override fun evaluate() {
52                 try {
53                     base.evaluate()
54                 } finally {
55                     // Reset the factory if it was set during the test so the next test gets the
56                     // default behavior.
57                     initialFactory?.let(::overrideComposeInputMethodManagerFactoryForTests)
58                 }
59             }
60         }
61 }
62