-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathSentryApollo4HttpInterceptorTest.kt
More file actions
434 lines (389 loc) · 14.1 KB
/
SentryApollo4HttpInterceptorTest.kt
File metadata and controls
434 lines (389 loc) · 14.1 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package io.sentry.apollo4
import com.apollographql.apollo.ApolloCall
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.ApolloResponse
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.http.HttpRequest
import com.apollographql.apollo.api.http.HttpResponse
import com.apollographql.apollo.exception.ApolloException
import com.apollographql.apollo.exception.ApolloHttpException
import com.apollographql.apollo.network.http.HttpInterceptor
import com.apollographql.apollo.network.http.HttpInterceptorChain
import io.sentry.BaggageHeader
import io.sentry.Breadcrumb
import io.sentry.IScopes
import io.sentry.ITransaction
import io.sentry.Scope
import io.sentry.ScopeCallback
import io.sentry.SentryOptions
import io.sentry.SentryOptions.DEFAULT_PROPAGATION_TARGETS
import io.sentry.SentryTraceHeader
import io.sentry.SentryTracer
import io.sentry.SpanDataConvention
import io.sentry.SpanDataConvention.HTTP_METHOD_KEY
import io.sentry.SpanStatus
import io.sentry.TraceContext
import io.sentry.TracesSamplingDecision
import io.sentry.TransactionContext
import io.sentry.W3CTraceparentHeader
import io.sentry.apollo4.SentryApollo4HttpInterceptor.BeforeSpanCallback
import io.sentry.apollo4.generated.LaunchDetailsQuery
import io.sentry.mockServerRequestTimeoutMillis
import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryTransaction
import io.sentry.util.Apollo4PlatformTestManipulator
import java.util.concurrent.TimeUnit
import kotlin.reflect.KSuspendFunction1
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy
import org.junit.Before
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.check
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
class SentryApollo4HttpInterceptorTestWithV4Implementation :
SentryApollo4HttpInterceptorTest(ApolloCall<*>::execute)
class SentryApollo4HttpInterceptorTestWithV3Implementation :
SentryApollo4HttpInterceptorTest(ApolloCall<*>::executeV3)
abstract class SentryApollo4HttpInterceptorTest(
private val executeQueryImplementation:
KSuspendFunction1<ApolloCall<*>, ApolloResponse<out Operation.Data>>
) {
class Fixture {
val server = MockWebServer()
val options =
SentryOptions().apply {
dsn = "https://key@sentry.io/proj"
setTracePropagationTargets(listOf(DEFAULT_PROPAGATION_TARGETS))
sdkVersion = SdkVersion("test", "1.2.3")
}
val scope = Scope(options)
val scopes =
mock<IScopes>().also {
whenever(it.options).thenReturn(options)
doAnswer { (it.arguments[0] as ScopeCallback).run(scope) }
.whenever(it)
.configureScope(any())
}
private var httpInterceptor =
SentryApollo4HttpInterceptor(scopes, captureFailedRequests = false)
@SuppressWarnings("LongParameterList")
fun getSut(
httpStatusCode: Int = 200,
responseBody: String =
"""{
"data": {
"launch": {
"__typename": "Launch",
"id": "83",
"site": "CCAFS SLC 40",
"mission": {
"__typename": "Mission",
"name": "Amos-17",
"missionPatch": "https://images2.imgbox.com/a0/ab/XUoByiuR_o.png"
}
}
}
}""",
socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN,
interceptor: HttpInterceptor? = null,
addThirdPartyBaggageHeader: Boolean = false,
beforeSpan: BeforeSpanCallback? = null,
): ApolloClient {
server.enqueue(
MockResponse()
.setBody(responseBody)
.setSocketPolicy(socketPolicy)
.setResponseCode(httpStatusCode)
)
if (beforeSpan != null) {
httpInterceptor =
SentryApollo4HttpInterceptor(scopes, beforeSpan, captureFailedRequests = false)
}
val builder =
ApolloClient.Builder()
.serverUrl(server.url("/").toString())
.addHttpInterceptor(httpInterceptor)
interceptor?.let { builder.addHttpInterceptor(interceptor) }
if (addThirdPartyBaggageHeader) {
builder
.addHttpHeader("baggage", "thirdPartyBaggage=someValue")
.addHttpHeader(
"baggage",
"secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue",
)
}
return builder.build()
}
}
private val fixture = Fixture()
@Before
fun setup() {
Apollo4PlatformTestManipulator.pretendIsAndroid(false)
}
@Test
fun `creates a span around the successful request`() {
executeQuery()
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = 200)
assertEquals(SpanStatus.OK, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `creates a span around the failed request`() {
executeQuery(fixture.getSut(httpStatusCode = 403))
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = 403)
assertEquals(SpanStatus.PERMISSION_DENIED, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `get http status from ApolloHttpException in failed request`() {
val failingInterceptor =
object : HttpInterceptor {
override suspend fun intercept(
request: HttpRequest,
chain: HttpInterceptorChain,
): HttpResponse = throw ApolloHttpException(404, mock(), mock(), "")
}
executeQuery(fixture.getSut(interceptor = failingInterceptor))
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = 404, contentLength = null)
assertEquals("POST", it.spans.first().data?.get(SpanDataConvention.HTTP_METHOD_KEY))
assertEquals(404, it.spans.first().data?.get(SpanDataConvention.HTTP_STATUS_CODE_KEY))
assertEquals(SpanStatus.NOT_FOUND, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `creates a span around the request failing with network error`() {
executeQuery(fixture.getSut(socketPolicy = SocketPolicy.DISCONNECT_DURING_REQUEST_BODY))
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = null, contentLength = null)
assertEquals(SpanStatus.INTERNAL_ERROR, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `does not add sentry trace header to the request if host is disallowed`() {
fixture.options.setTracePropagationTargets(listOf("some-host-that-does-not-exist"))
executeQuery(isSpanActive = false)
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `when there is no active span, does not add sentry trace header to the request`() {
executeQuery(isSpanActive = false)
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `does not add sentry-trace header when span origin is ignored`() {
fixture.options.setIgnoredSpanOrigins(listOf("auto.graphql.apollo4"))
executeQuery(isSpanActive = false)
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `when there is an active span, adds sentry trace headers to the request`() {
executeQuery()
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `when there is an active span, existing baggage headers are merged with sentry baggage into single header`() {
executeQuery(sut = fixture.getSut(addThirdPartyBaggageHeader = true))
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
val baggageHeaderValues = recorderRequest.headers.values(BaggageHeader.BAGGAGE_HEADER)
assertEquals(baggageHeaderValues.size, 1)
assertTrue(
baggageHeaderValues[0].startsWith(
"thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue"
)
)
assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key"))
assertTrue(baggageHeaderValues[0].contains("sentry-transaction=op"))
assertTrue(baggageHeaderValues[0].contains("sentry-trace_id"))
}
@Test
fun `customizer modifies span`() {
executeQuery(
fixture.getSut(
beforeSpan = { span, request, response ->
span.description = "overwritten description"
span
}
)
)
verify(fixture.scopes)
.captureTransaction(
check {
assertEquals(1, it.spans.size)
val httpClientSpan = it.spans.first()
assertEquals("overwritten description", httpClientSpan.description)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `returning null in beforeSpan callback drops span`() {
executeQuery(fixture.getSut(beforeSpan = { _, _, _ -> null }))
verify(fixture.scopes)
.captureTransaction(
check { assertEquals(0, it.spans.size) },
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `when customizer throws, exception is handled`() {
executeQuery(fixture.getSut(beforeSpan = { _, _, _ -> throw RuntimeException() }))
verify(fixture.scopes)
.captureTransaction(
check { assertEquals(1, it.spans.size) },
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `adds breadcrumb when http calls succeeds`() {
executeQuery(fixture.getSut())
verify(fixture.scopes)
.addBreadcrumb(
check<Breadcrumb> {
assertEquals("http", it.type)
// response_body_size is added but mock webserver returns 0 always
assertEquals(0L, it.data["response_body_size"])
assertEquals(193L, it.data["request_body_size"])
},
anyOrNull(),
)
}
@Test
fun `sets SDKVersion Info`() {
assertNotNull(fixture.scopes.options.sdkVersion)
assert(fixture.scopes.options.sdkVersion!!.integrationSet.contains("Apollo4"))
}
@Test
fun `attaches to root transaction on Android`() {
Apollo4PlatformTestManipulator.pretendIsAndroid(true)
executeQuery(fixture.getSut())
verify(fixture.scopes).transaction
}
@Test
fun `attaches to child span on non-Android`() {
Apollo4PlatformTestManipulator.pretendIsAndroid(false)
executeQuery(fixture.getSut())
verify(fixture.scopes).span
}
@Test
fun `adds W3C traceparent header when propagateTraceparent is enabled`() {
fixture.options.isPropagateTraceparent = true
executeQuery()
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[W3CTraceparentHeader.TRACEPARENT_HEADER])
}
@Test
fun `does not add W3C traceparent header when propagateTraceparent is disabled`() {
fixture.options.isPropagateTraceparent = false
executeQuery()
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNull(recorderRequest.headers[W3CTraceparentHeader.TRACEPARENT_HEADER])
}
private fun assertTransactionDetails(
it: SentryTransaction,
httpStatusCode: Int? = 200,
contentLength: Long? = 0L,
) {
assertEquals(1, it.spans.size)
val httpClientSpan = it.spans.first()
assertEquals("http.graphql", httpClientSpan.op)
assertEquals(
"Post http://${fixture.server.hostName}:${fixture.server.port}/",
httpClientSpan.description,
)
assertNotNull(httpClientSpan.data) {
assertEquals("POST", it[HTTP_METHOD_KEY])
httpStatusCode?.let { code ->
assertEquals(code, it[SpanDataConvention.HTTP_STATUS_CODE_KEY])
}
contentLength?.let { contentLength ->
assertEquals(contentLength, it[SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY])
}
}
}
private fun executeQuery(
sut: ApolloClient = fixture.getSut(),
isSpanActive: Boolean = true,
id: String = "83",
) = runBlocking {
var tx: ITransaction? = null
if (isSpanActive) {
tx =
SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes)
whenever(fixture.scopes.transaction).thenReturn(tx)
whenever(fixture.scopes.span).thenReturn(tx)
}
val coroutine = launch {
try {
executeQueryImplementation(sut.query(LaunchDetailsQuery(id)))
} catch (e: ApolloException) {
return@launch
}
}
coroutine.join()
tx?.finish()
}
}