-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
OkHttpClientTestRule.kt
167 lines (150 loc) · 5.28 KB
/
OkHttpClientTestRule.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
/*
* Copyright (C) 2019 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 java.net.InetAddress
import java.util.concurrent.TimeUnit
import java.util.logging.Logger
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.testing.Flaky
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* Apply this rule to all tests. It adds additional checks for leaked resources and uncaught
* exceptions.
*
* Use [newClient] as a factory for a OkHttpClient instances. These instances are specifically
* configured for testing.
*/
class OkHttpClientTestRule : TestRule {
private val clientEventsList = mutableListOf<String>()
private var testClient: OkHttpClient? = null
private var uncaughtException: Throwable? = null
var logger: Logger? = null
fun wrap(eventListener: EventListener) =
EventListener.Factory { ClientRuleEventListener(eventListener, ::addEvent) }
fun wrap(eventListenerFactory: EventListener.Factory) =
EventListener.Factory { call -> ClientRuleEventListener(eventListenerFactory.create(call), ::addEvent) }
/**
* Returns an OkHttpClient for tests to use as a starting point.
*
* The returned client installs a default event listener that gathers debug information. This will
* be logged if the test fails.
*
* This client is also configured to be slightly more deterministic, returning a single IP
* address for all hosts, regardless of the actual number of IP addresses reported by DNS.
*/
fun newClient(): OkHttpClient {
var client = testClient
if (client == null) {
client = OkHttpClient.Builder()
.dns(SINGLE_INET_ADDRESS_DNS) // Prevent unexpected fallback addresses.
.eventListenerFactory(
EventListener.Factory { ClientRuleEventListener(logger = ::addEvent) })
.build()
testClient = client
}
return client
}
fun newClientBuilder(): OkHttpClient.Builder {
return newClient().newBuilder()
}
@Synchronized private fun addEvent(event: String) {
logger?.info(event)
clientEventsList.add(event)
}
@Synchronized private fun initUncaughtException(throwable: Throwable) {
if (uncaughtException == null) {
uncaughtException = throwable
}
}
fun ensureAllConnectionsReleased() {
testClient?.let {
val connectionPool = it.connectionPool
connectionPool.evictAll()
assertEquals(0, connectionPool.connectionCount())
}
}
private fun ensureAllTaskQueuesIdle() {
for (queue in TaskRunner.INSTANCE.activeQueues()) {
if (!queue.idleLatch().await(1_000L, TimeUnit.MILLISECONDS)) {
TaskRunner.INSTANCE.cancelAll()
fail("Queue still active after 1000 ms")
}
}
}
override fun apply(
base: Statement,
description: Description
): Statement {
return object : Statement() {
override fun evaluate() {
val defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { _, throwable ->
initUncaughtException(throwable)
}
try {
base.evaluate()
if (uncaughtException != null) {
throw AssertionError("uncaught exception thrown during test", uncaughtException)
}
logEventsIfFlaky(description)
} catch (t: Throwable) {
logEvents()
throw t
} finally {
Thread.setDefaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler)
ensureAllConnectionsReleased()
releaseClient()
ensureAllTaskQueuesIdle()
}
}
private fun releaseClient() {
testClient?.dispatcher?.executorService?.shutdown()
}
}
}
private fun logEventsIfFlaky(description: Description) {
if (isTestFlaky(description)) {
logEvents()
}
}
private fun isTestFlaky(description: Description): Boolean {
return description.annotations.any { it.annotationClass == Flaky::class } ||
description.testClass.annotations.any { it.annotationClass == Flaky::class }
}
@Synchronized private fun logEvents() {
// Will be ineffective if test overrides the listener
println("Events (${clientEventsList.size})")
for (e in clientEventsList) {
println(e)
}
}
companion object {
/**
* A network that resolves only one IP address per host. Use this when testing route selection
* fallbacks to prevent the host machine's various IP addresses from interfering.
*/
private val SINGLE_INET_ADDRESS_DNS = object : Dns {
override fun lookup(hostname: String): List<InetAddress> {
val addresses = Dns.SYSTEM.lookup(hostname)
return listOf(addresses[0])
}
}
}
}