/
RecordingConnectionListener.kt
185 lines (161 loc) · 5.58 KB
/
RecordingConnectionListener.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import assertk.assertThat
import assertk.assertions.isCloseTo
import assertk.assertions.isFalse
import assertk.assertions.isInstanceOf
import assertk.assertions.matchesPredicate
import java.util.Deque
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.concurrent.TimeUnit
import okhttp3.ConnectionEvent.NoNewExchanges
import okhttp3.internal.connection.RealConnection
import okio.IOException
import org.junit.jupiter.api.Assertions
open class RecordingConnectionListener(
/**
* An override to ignore the normal order that is enforced.
* EventListeners added by Interceptors will not see all events.
*/
private val enforceOrder: Boolean = true,
) : ConnectionListener() {
val eventSequence: Deque<ConnectionEvent> = ConcurrentLinkedDeque()
private val forbiddenLocks = mutableSetOf<Any>()
/** The timestamp of the last taken event, used to measure elapsed time between events. */
private var lastTimestampNs: Long? = null
/** Confirm that the thread does not hold a lock on `lock` during the callback. */
fun forbidLock(lock: Any) {
forbiddenLocks.add(lock)
}
/**
* Removes recorded events up to (and including) an event is found whose class equals [eventClass]
* and returns it.
*/
fun <T : ConnectionEvent> removeUpToEvent(eventClass: Class<T>): T {
val fullEventSequence = eventSequence.toList()
try {
while (true) {
val event = takeEvent()
if (eventClass.isInstance(event)) {
return eventClass.cast(event)
}
}
} catch (e: NoSuchElementException) {
throw AssertionError("full event sequence: $fullEventSequence", e)
}
}
/**
* Remove and return the next event from the recorded sequence.
*
* @param eventClass a class to assert that the returned event is an instance of, or null to
* take any event class.
* @param elapsedMs the time in milliseconds elapsed since the immediately-preceding event, or
* -1L to take any duration.
*/
fun takeEvent(
eventClass: Class<out ConnectionEvent>? = null,
elapsedMs: Long = -1L,
): ConnectionEvent {
val result = eventSequence.remove()
val actualElapsedNs = result.timestampNs - (lastTimestampNs ?: result.timestampNs)
lastTimestampNs = result.timestampNs
if (eventClass != null) {
assertThat(result).isInstanceOf(eventClass)
}
if (elapsedMs != -1L) {
assertThat(
TimeUnit.NANOSECONDS.toMillis(actualElapsedNs)
.toDouble(),
)
.isCloseTo(elapsedMs.toDouble(), 100.0)
}
return result
}
fun recordedEventTypes() = eventSequence.map { it.name }
fun clearAllEvents() {
while (eventSequence.isNotEmpty()) {
takeEvent()
}
}
private fun logEvent(e: ConnectionEvent) {
if (e.connection != null) {
assertThat(Thread.holdsLock(e.connection), "Called with lock $${e.connection}")
.isFalse()
}
for (lock in forbiddenLocks) {
assertThat(Thread.holdsLock(lock), "Called with lock $lock")
.isFalse()
}
if (enforceOrder) {
checkForStartEvent(e)
}
eventSequence.offer(e)
}
private fun checkForStartEvent(e: ConnectionEvent) {
if (eventSequence.isEmpty()) {
assertThat(e).isInstanceOf(ConnectionEvent.ConnectStart::class.java)
} else {
eventSequence.forEach loop@{
when (e.closes(it)) {
null -> return // no open event
true -> return // found open event
false -> return@loop // this is not the open event so continue
}
}
Assertions.fail<Any>("event $e without matching start event")
}
}
override fun connectStart(
route: Route,
call: Call,
) = logEvent(ConnectionEvent.ConnectStart(System.nanoTime(), route, call))
override fun connectFailed(
route: Route,
call: Call,
failure: IOException,
) = logEvent(
ConnectionEvent.ConnectFailed(System.nanoTime(), route, call, failure),
)
override fun connectEnd(
connection: Connection,
route: Route,
call: Call,
) {
logEvent(ConnectionEvent.ConnectEnd(System.nanoTime(), connection, route, call))
}
override fun connectionClosed(connection: Connection) = logEvent(ConnectionEvent.ConnectionClosed(System.nanoTime(), connection))
override fun connectionAcquired(
connection: Connection,
call: Call,
) {
logEvent(ConnectionEvent.ConnectionAcquired(System.nanoTime(), connection, call))
}
override fun connectionReleased(
connection: Connection,
call: Call,
) {
if (eventSequence.find { it is ConnectionEvent.ConnectStart && it.connection == connection } != null && connection is RealConnection) {
if (connection.noNewExchanges) {
assertThat(eventSequence).matchesPredicate { deque ->
deque.any { it is NoNewExchanges && it.connection == connection }
}
}
}
logEvent(ConnectionEvent.ConnectionReleased(System.nanoTime(), connection, call))
}
override fun noNewExchanges(connection: Connection) = logEvent(NoNewExchanges(System.nanoTime(), connection))
}