1 /*
2  * Copyright (C) 2024 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.test.tracing.coroutines.util
18 
19 import org.junit.Assert.assertFalse
20 
21 object FakeTraceState {
22 
23     var isTracingEnabled: Boolean = true
24 
25     private val allThreadStates = hashMapOf<Long, MutableList<String>>()
26 
beginnull27     fun begin(sectionName: String) {
28         val threadId = currentThreadId()
29         synchronized(allThreadStates) {
30             if (allThreadStates.containsKey(threadId)) {
31                 allThreadStates[threadId]!!.add(sectionName)
32             } else {
33                 allThreadStates[threadId] = mutableListOf(sectionName)
34             }
35         }
36     }
37 
endnull38     fun end() {
39         val threadId = currentThreadId()
40         synchronized(allThreadStates) {
41             assertFalse(
42                 "Attempting to close trace section on thread=$threadId, " +
43                     "but there are no open sections",
44                 allThreadStates[threadId].isNullOrEmpty(),
45             )
46             allThreadStates[threadId]!!.removeLast()
47         }
48     }
49 
getOpenTraceSectionsOnCurrentThreadnull50     fun getOpenTraceSectionsOnCurrentThread(): Array<String> {
51         val threadId = currentThreadId()
52         synchronized(allThreadStates) {
53             return allThreadStates[threadId]?.toTypedArray() ?: emptyArray()
54         }
55     }
56 
57     /**
58      * Helper function for debugging; use as follows:
59      * ```
60      * println(FakeThreadStateLocal)
61      * ```
62      */
toStringnull63     override fun toString(): String {
64         val sb = StringBuilder()
65         synchronized(allThreadStates) {
66             allThreadStates.entries.forEach { sb.appendLine("${it.key} -> ${it.value}") }
67         }
68         return sb.toString()
69     }
70 }
71