-
-
Notifications
You must be signed in to change notification settings - Fork 426
/
SentrySpringIntegrationTest.kt
254 lines (211 loc) · 8.52 KB
/
SentrySpringIntegrationTest.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
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
package io.sentry.spring.boot.it
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.reset
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import io.sentry.IHub
import io.sentry.ITransportFactory
import io.sentry.Sentry
import io.sentry.spring.tracing.SentrySpan
import io.sentry.test.checkEvent
import io.sentry.transport.ITransport
import java.lang.RuntimeException
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.kotlin.await
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.SpyBean
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.factory.PasswordEncoderFactories
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.stereotype.Service
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RunWith(SpringRunner::class)
@SpringBootTest(
classes = [App::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = ["sentry.dsn=http://key@localhost/proj", "sentry.send-default-pii=true", "sentry.enable-tracing=true"]
)
class SentrySpringIntegrationTest {
@Autowired
lateinit var transport: ITransport
@SpyBean
lateinit var hub: IHub
@LocalServerPort
lateinit var port: Integer
@Before
fun reset() {
reset(transport)
}
@Test
fun `attaches request and user information to SentryEvents`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders()
headers["X-FORWARDED-FOR"] = listOf("169.128.0.1")
val entity = HttpEntity<Void>(headers)
restTemplate.exchange("http://localhost:$port/hello", HttpMethod.GET, entity, Void::class.java)
await.untilAsserted {
verify(transport).send(checkEvent { event ->
assertThat(event.request).isNotNull()
assertThat(event.request!!.url).isEqualTo("http://localhost:$port/hello")
assertThat(event.user).isNotNull()
assertThat(event.user.username).isEqualTo("user")
assertThat(event.user.ipAddress).isEqualTo("169.128.0.1")
}, anyOrNull())
}
}
@Test
fun `attaches first ip address if multiple addresses exist in a header`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders()
headers["X-FORWARDED-FOR"] = listOf("169.128.0.1, 192.168.0.1")
val entity = HttpEntity<Void>(headers)
restTemplate.exchange("http://localhost:$port/hello", HttpMethod.GET, entity, Void::class.java)
await.untilAsserted {
verify(transport).send(checkEvent { event ->
assertThat(event.user.ipAddress).isEqualTo("169.128.0.1")
}, anyOrNull())
}
}
@Test
fun `sends events for unhandled exceptions`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/throws", String::class.java)
await.untilAsserted {
verify(transport).send(checkEvent { event ->
assertThat(event.exceptions).isNotEmpty
val ex = event.exceptions.first()
assertThat(ex.value).isEqualTo("something went wrong")
assertThat(ex.mechanism.isHandled).isFalse()
}, anyOrNull())
}
}
@Test
fun `sends events for error logs`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/logging", String::class.java)
await.untilAsserted {
verify(transport).send(checkEvent { event ->
assertThat(event.message.message).isEqualTo("event from logger")
}, anyOrNull())
}
}
@Test
fun `attaches span context to events triggered within transaction`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/performance", String::class.java)
await.untilAsserted {
verify(transport).send(checkEvent { event ->
assertThat(event.contexts.trace).isNotNull()
}, anyOrNull())
}
}
@Test
fun `tracing filter does not overwrite resposne status code`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val response = restTemplate.getForEntity("http://localhost:$port/performance", String::class.java)
assertThat(response.statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
}
@Test
fun `does not send events for handled exceptions`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/throws-handled", String::class.java)
verify(hub, never()).captureEvent(any())
}
}
@SpringBootApplication
open class App {
private val transport = mock<ITransport>()
@Bean
open fun mockTransportFactory(): ITransportFactory {
val factory = mock<ITransportFactory>()
whenever(factory.create(any(), any())).thenReturn(transport)
return factory
}
@Bean
open fun mockTransport() = transport
}
@RestController
class HelloController(private val helloService: HelloService) {
private val logger = LoggerFactory.getLogger(HelloController::class.java)
@GetMapping("/hello")
fun hello() {
Sentry.captureMessage("hello")
}
@GetMapping("/throws")
fun throws() {
throw RuntimeException("something went wrong")
}
@GetMapping("/throws-handled")
fun throwsHandled() {
throw CustomException("handled exception")
}
@GetMapping("/performance")
fun performance() {
helloService.throws()
}
@GetMapping("/logging")
fun logging() {
logger.error("event from logger")
}
}
@Service
open class HelloService {
@SentrySpan
open fun throws() {
throw RuntimeException("something went wrong")
}
}
@Configuration
open class SecurityConfiguration : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic()
}
@Bean
override fun userDetailsService(): UserDetailsService {
val encoder: PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
val user: UserDetails = User
.builder()
.passwordEncoder { rawPassword -> encoder.encode(rawPassword) }
.username("user")
.password("password")
.roles("USER")
.build()
return InMemoryUserDetailsManager(user)
}
}
class CustomException(message: String) : RuntimeException(message)
@ControllerAdvice
class ExceptionHandlers {
@ExceptionHandler(CustomException::class)
fun handle(e: CustomException) = ResponseEntity.badRequest().build<Void>()
}