Repository navigation
Expand file tree
/
Copy pathSentryApolloInterceptorTest.kt
More file actions
390 lines (354 loc) · 12 KB
/
Copy pathSentryApolloInterceptorTest.kt
File metadata and controls
390 lines (354 loc) · 12 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
package io.sentry.apollo
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.coroutines.await
import com.apollographql.apollo.exception.ApolloException
import com.google.common.truth.Truth.assertThat
import io.sentry.BaggageHeader
import io.sentry.Breadcrumb
import io.sentry.DataCategory
import io.sentry.ILogger
import io.sentry.IScopes
import io.sentry.ITransaction
import io.sentry.Scope
import io.sentry.ScopeCallback
import io.sentry.ScopeType
import io.sentry.SentryLevel
import io.sentry.SentryOptions
import io.sentry.SentryTraceHeader
import io.sentry.SentryTracer
import io.sentry.SpanDataConvention
import io.sentry.SpanStatus
import io.sentry.TraceContext
import io.sentry.TracesSamplingDecision
import io.sentry.TransactionContext
import io.sentry.clientreport.DiscardReason
import io.sentry.mockServerRequestTimeoutMillis
import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryTransaction
import io.sentry.util.ApolloPlatformTestManipulator
import java.util.concurrent.TimeUnit
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.verifyNoMoreInteractions
import org.mockito.kotlin.whenever
class SentryApolloInterceptorTest {
class Fixture {
val server = MockWebServer()
val options =
SentryOptions().apply {
dsn = "https://key@sentry.io/proj"
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())
doAnswer { (it.arguments[1] as ScopeCallback).run(scope) }
.whenever(it)
.configureScope(anyOrNull<ScopeType>(), any())
}
private var interceptor = SentryApolloInterceptor(scopes)
@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,
beforeSpan: SentryApolloInterceptor.BeforeSpanCallback? = null,
): ApolloClient {
server.enqueue(
MockResponse()
.setBody(responseBody)
.setSocketPolicy(socketPolicy)
.setResponseCode(httpStatusCode)
)
if (beforeSpan != null) {
interceptor = SentryApolloInterceptor(scopes, beforeSpan)
}
return ApolloClient.builder()
.serverUrl(server.url("/"))
.addApplicationInterceptor(interceptor)
.build()
}
}
private val fixture = Fixture()
@Before
fun setup() {
ApolloPlatformTestManipulator.pretendIsAndroid(false)
}
@Test
fun `creates a span around the successful request`() {
executeQuery()
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it)
assertEquals(SpanStatus.OK, it.spans.first().status)
assertEquals("POST", it.spans.first().data?.get(SpanDataConvention.HTTP_METHOD_KEY))
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `does not attach GraphQL variables when data collection disables them`() {
fixture.options.dataCollection.graphql.setVariables(false)
executeQuery()
verify(fixture.scopes)
.captureTransaction(
check {
assertNull(it.spans.first().data?.get("variables"))
assertNotNull(it.spans.first().data?.get("operationId"))
},
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)
assertEquals(SpanStatus.PERMISSION_DENIED, it.spans.first().status)
assertEquals(403, it.spans.first().data?.get(SpanDataConvention.HTTP_STATUS_CODE_KEY))
// we do not have access to the request and method in case of an error
assertNull(it.spans.first().data?.get(SpanDataConvention.HTTP_METHOD_KEY))
},
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)
assertEquals(SpanStatus.INTERNAL_ERROR, it.spans.first().status)
assertNull(it.spans.first().data?.get(SpanDataConvention.HTTP_STATUS_CODE_KEY))
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `when there is no active span, adds sentry trace header to the request from scope`() {
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.apollo"))
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 `customizer modifies span`() {
executeQuery(
fixture.getSut { span, _, _ ->
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 `when beforeSpan callback returns null, span is dropped`() {
val onDiscard = mock<SentryOptions.OnDiscardCallback>()
fixture.options.onDiscard = onDiscard
executeQuery(fixture.getSut { _, _, _ -> null })
verifyNoMoreInteractions(onDiscard)
verify(fixture.scopes)
.captureTransaction(
check { assertTrue(it.spans.isEmpty()) },
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `reports callback errors only for sampled spans`(): Unit = runBlocking {
for (sampled in listOf(true, false, null)) {
val onDiscard = mock<SentryOptions.OnDiscardCallback>()
fixture.options.onDiscard = onDiscard
val tx = SentryTracer(TransactionContext("op", "desc"), fixture.scopes)
tx.spanContext.sampled = sampled
whenever(fixture.scopes.span).thenReturn(tx)
val sut = fixture.getSut { span, _, _ ->
span.spanContext.sampled = false
error("callback failed")
}
assertThat(sut.query(LaunchDetailsQuery.builder().id("83").build()).await().data).isNotNull()
tx.finish()
if (sampled == true) {
verify(onDiscard).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Span, 1)
}
verifyNoMoreInteractions(onDiscard)
}
}
@Test
fun `when beforeSpan throws, drops span and preserves response`(): Unit = runBlocking {
val failure = IllegalStateException("callback failed")
val logger = mock<ILogger>()
fixture.options.isDebug = true
fixture.options.setLogger(logger)
val tx =
SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes)
whenever(fixture.scopes.span).thenReturn(tx)
val sut = fixture.getSut { span, _, _ ->
span.description = "partially modified"
throw failure
}
val response = sut.query(LaunchDetailsQuery.builder().id("83").build()).await()
assertThat(response.data).isNotNull()
val span = tx.children.single()
assertThat(span.isSampled).isFalse()
assertThat(span.isFinished).isTrue()
tx.finish()
verify(fixture.scopes)
.captureTransaction(
check { assertThat(it.spans).isEmpty() },
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
verify(fixture.scopes).addBreadcrumb(any<Breadcrumb>(), anyOrNull())
verify(logger)
.log(
SentryLevel.ERROR,
"An error occurred while executing beforeSpan on ApolloInterceptor",
failure,
)
}
@Test
fun `adds breadcrumb when http calls succeeds`() {
executeQuery()
verify(fixture.scopes)
.addBreadcrumb(
check<Breadcrumb> {
assertEquals("http", it.type)
assertEquals(280L, 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("Apollo"))
val packageInfo =
fixture.scopes.options.sdkVersion!!.packageSet.firstOrNull { pkg ->
pkg.name == "maven:io.sentry:sentry-apollo"
}
assertNotNull(packageInfo)
assert(packageInfo.version == BuildConfig.VERSION_NAME)
}
@Test
fun `attaches to root transaction on Android`() {
ApolloPlatformTestManipulator.pretendIsAndroid(true)
executeQuery(fixture.getSut())
verify(fixture.scopes).transaction
}
@Test
fun `attaches to child span on non-Android`() {
ApolloPlatformTestManipulator.pretendIsAndroid(false)
executeQuery(fixture.getSut())
verify(fixture.scopes).span
}
private fun assertTransactionDetails(it: SentryTransaction) {
assertEquals(1, it.spans.size)
val httpClientSpan = it.spans.first()
assertEquals("http.graphql.query", httpClientSpan.op)
assertEquals("query LaunchDetails", httpClientSpan.description)
assertEquals("auto.graphql.apollo", httpClientSpan.origin)
assertNotNull(httpClientSpan.data) {
assertNotNull(it["operationId"])
assertEquals("{id=83}", it["variables"])
}
}
private fun executeQuery(sut: ApolloClient = fixture.getSut(), isSpanActive: Boolean = true) =
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 {
sut.query(LaunchDetailsQuery.builder().id("83").build()).await()
} catch (e: ApolloException) {
return@launch
}
}
coroutine.join()
tx?.finish()
}
}