Repository navigation
Expand file tree
/
Copy pathSentryReporterTest.php
More file actions
747 lines (599 loc) · 31.8 KB
/
Copy pathSentryReporterTest.php
File metadata and controls
747 lines (599 loc) · 31.8 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
<?php
declare(strict_types=1);
namespace Test\TinyBlocks\Http\ErrorHandler\Unit\Reporters;
use Exception;
use GuzzleHttp\Psr7\ServerRequest;
use LogicException;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
use Sentry\Event;
use Sentry\SentrySdk;
use Sentry\Severity;
use Sentry\UserDataBag;
use Test\TinyBlocks\Http\ErrorHandler\Unit\ContextualException;
use Test\TinyBlocks\Http\ErrorHandler\Unit\PrioritizedException;
use Test\TinyBlocks\Http\ErrorHandler\Unit\RecordingSentry;
use Test\TinyBlocks\Http\ErrorHandler\Unit\RoutingHandler;
use Test\TinyBlocks\Http\ErrorHandler\Unit\TaggingHandler;
use Test\TinyBlocks\Http\ErrorHandler\Unit\UnavailableExceptions;
use Test\TinyBlocks\Http\ErrorHandler\Unit\UnmappedExceptions;
use Test\TinyBlocks\Http\ErrorHandler\Unit\UnprocessableExceptions;
use TinyBlocks\Http\Code;
use TinyBlocks\Http\CorrelationId\CorrelationId;
use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
use TinyBlocks\Http\ErrorHandler\ErrorMiddleware;
use TinyBlocks\Http\ErrorHandler\MappedError;
use TinyBlocks\Http\ErrorHandler\Reporters\SentryReporter;
use TinyBlocks\Http\ErrorHandler\ReportingFilter;
use TinyBlocks\Http\ErrorHandler\ReportingPriority;
use TinyBlocks\Http\ErrorHandler\RouteMiddleware;
final class SentryReporterTest extends TestCase
{
public static function setUpBeforeClass(): void
{
SentryReporter::initializedWith(
dsn: 'https://examplePublicKey@o0.ingest.sentry.io/1',
release: '',
environment: 'local'
);
}
public function testReportWhenServerErrorThenEventReachesSentry(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the event carries the exception the middleware handled */
self::assertNotNull($sentry->sent);
self::assertSame('Boom', $sentry->sent->getExceptions()[0]->getValue());
self::assertSame(Exception::class, $sentry->sent->getExceptions()[0]->getType());
}
public function testReportWhenClientErrorThenNothingReachesSentry(): void
{
/** @Given a request */
$request = new ServerRequest('PUT', '/v1/orders/1');
/** @And a handler that throws an exception a rule maps to 422 */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new LogicException('Invalid payload'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub under the default filter */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnprocessableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the quota is spared, because a 4xx is the described outcome of a client mistake */
self::assertNull($sentry->sent);
}
public function testInitializedWithThenTheSdkNeverReadsTheRequestBody(): void
{
/** @Given the deployment values an application resolves from its environment */
$dsn = 'https://examplePublicKey@o0.ingest.sentry.io/1';
/** @When a reporter is built from them */
SentryReporter::initializedWith(dsn: $dsn, release: 'client-gateway@1.0.0', environment: 'development');
/** @Then the SDK is told never to read a body, so a password in one is never gathered */
$options = SentrySdk::getCurrentHub()->getClient()?->getOptions();
self::assertNotNull($options);
self::assertSame('never', $options->getMaxRequestBodySize());
self::assertFalse($options->shouldSendDefaultPii());
}
public function testInitializedWithWhenDsnIsEmptyThenTheSdkStaysDisabled(): void
{
/** @Given an environment with reporting switched off */
$dsn = '';
/** @When a reporter is built from it */
SentryReporter::initializedWith(dsn: $dsn, release: 'client-gateway@1.0.0', environment: 'local');
/** @Then the SDK holds no DSN, so nothing is ever sent */
self::assertNull(SentrySdk::getCurrentHub()->getClient()?->getOptions()->getDsn());
}
public function testReportWhenServerErrorThenContextCarriesMethodAndPath(): void
{
/** @Given a request carrying a method and a path */
$request = new ServerRequest('POST', '/v1/orders');
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the path travels as context, never as a tag, because a tag is an index */
self::assertNotNull($sentry->sent);
self::assertSame('POST', $sentry->sent->getContexts()['http']['method']);
self::assertSame('/v1/orders', $sentry->sent->getContexts()['http']['path']);
self::assertArrayNotHasKey('path', $sentry->sent->getTags());
}
public function testReportWhenMappedServerErrorThenTagsCarryTheMappedCode(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler that throws an exception a rule maps to 503 */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new RuntimeException('Upstream down'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the tags carry the rule that matched, which groups the issue by domain outcome */
self::assertNotNull($sentry->sent);
self::assertSame('503', $sentry->sent->getTags()['status_code']);
self::assertSame('true', $sentry->sent->getTags()['error_mapped']);
self::assertSame('UPSTREAM_UNAVAILABLE', $sentry->sent->getTags()['error_code']);
}
public function testReportWhenRequestCarriesCorrelationIdThenEventIsTagged(): void
{
/** @Given a correlation identifier the request carries */
$correlationId = new readonly class implements CorrelationId {
public function toString(): string
{
return '0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b';
}
};
/** @And a request carrying it */
$request = new ServerRequest('GET', '/v1/orders')
->withAttribute(CorrelationIdMiddleware::ATTRIBUTE_NAME, $correlationId);
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the issue and the log entries of every service share one identifier */
self::assertNotNull($sentry->sent);
self::assertSame('0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b', $sentry->sent->getTags()['correlation_id']);
}
public function testReportWhenRequestCarriesNoCorrelationIdThenTagIsAbsent(): void
{
/** @Given a request with no correlation identifier */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the tag is absent instead of invented */
self::assertNotNull($sentry->sent);
self::assertArrayNotHasKey('correlation_id', $sentry->sent->getTags());
}
public function testReportWhenUnmappedFilterThenMappedClientErrorIsDropped(): void
{
/** @Given a request */
$request = new ServerRequest('PUT', '/v1/orders/1');
/** @And a handler that throws an exception a rule maps to 422 */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new LogicException('Invalid payload'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware whose filter adds back what no rule described */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnprocessableExceptions())
->withReporter(
reporter: SentryReporter::from(
hub: $sentry->hub(),
filter: ReportingFilter::SERVER_ERRORS_AND_UNMAPPED
)
)
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then a described client error stays out, because validation is expected behavior */
self::assertNull($sentry->sent);
}
public function testReportWhenUnmappedServerErrorThenTagsDescribeTheStatus(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the tags state the status and that no rule described the exception */
self::assertNotNull($sentry->sent);
self::assertSame('500', $sentry->sent->getTags()['status_code']);
self::assertSame('false', $sentry->sent->getTags()['error_mapped']);
self::assertArrayNotHasKey('error_code', $sentry->sent->getTags());
}
public function testInitializedWithWhenReleaseIsEmptyThenNoReleaseIsReported(): void
{
/** @Given a deployment that carries no version, as a working tree does not */
$release = '';
/** @When a reporter is built from it */
SentryReporter::initializedWith(
dsn: 'https://examplePublicKey@o0.ingest.sentry.io/1',
release: $release,
environment: 'local'
);
/** @Then the release is absent instead of an empty one */
self::assertNull(SentrySdk::getCurrentHub()->getClient()?->getOptions()->getRelease());
}
public function testReportWhenALayerBelowTagsTheRequestThenTheEventCarriesIt(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a layer that learns the tenant while handling it, then fails */
$handler = new TaggingHandler(
key: 'organization_id',
value: '0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b',
failure: new RuntimeException('Upstream down')
);
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then what the request accumulated below survives the immutable copies above it */
self::assertNotNull($sentry->sent);
self::assertSame('0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b', $sentry->sent->getTags()['organization_id']);
}
public function testReportWhenContextDeclaresNoPriorityThenTheStatusDecidesIt(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/unknown');
/** @And a handler throwing a 4xx no rule describes, whose context declares no priority */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(
new ContextualException(tags: ['service' => 'identity'], status: Code::NOT_FOUND->value)
);
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware whose filter adds back what no rule described */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(
reporter: SentryReporter::from(
hub: $sentry->hub(),
filter: ReportingFilter::SERVER_ERRORS_AND_UNMAPPED
)
)
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the client error falls back to the middle of the scale, and the tags still travel */
self::assertNotNull($sentry->sent);
self::assertSame('identity', $sentry->sent->getTags()['service']);
self::assertEquals(Severity::warning(), $sentry->sent->getLevel());
}
public function testReportWhenExceptionCarriesContextThenItsTagsReachTheEvent(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler throwing an exception that names the service that refused */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new ContextualException(tags: ['service' => 'payment']));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then what only the raising site knew becomes an index at the provider */
self::assertNotNull($sentry->sent);
self::assertSame('payment', $sentry->sent->getTags()['service']);
self::assertEquals(Severity::fatal(), $sentry->sent->getLevel());
}
public function testReportWhenUndescribedServerErrorThenEventIsLeveledAsFatal(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then a condition nobody described reaches the provider at the top of the scale */
self::assertNotNull($sentry->sent);
self::assertEquals(Severity::fatal(), $sentry->sent->getLevel());
}
public function testInitializedWithThenTheCurrentHubCarriesTheDeploymentValues(): void
{
/** @Given the deployment values an application resolves from its environment */
$dsn = 'https://examplePublicKey@o0.ingest.sentry.io/1';
/** @When a reporter is built from them */
SentryReporter::initializedWith(dsn: $dsn, release: 'client-gateway@1.0.0', environment: 'development');
/** @Then the SDK is booted and its hub is the current one, carrying those values */
$options = SentrySdk::getCurrentHub()->getClient()?->getOptions();
self::assertNotNull($options);
self::assertSame('client-gateway@1.0.0', $options->getRelease());
self::assertSame('development', $options->getEnvironment());
self::assertSame('1', $options->getDsn()?->getProjectId());
}
public function testReportWhenTheConsumerReplacesTheRuleThenItsPriorityDecides(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler throwing a server error the library would call high */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new RuntimeException('Upstream down'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware whose consumer decided a 5xx deserves no interruption */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withPriority(
resolver: static fn(?MappedError $mapped, Code $status): ReportingPriority => ReportingPriority::LOW
)
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the rule the consumer registered replaces the one the library ships */
self::assertNotNull($sentry->sent);
self::assertEquals(Severity::info(), $sentry->sent->getLevel());
}
public function testReportWhenUnmappedFilterThenMappedServerErrorReachesSentry(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler that throws an exception a rule maps to 503 */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new RuntimeException('Upstream down'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware whose filter adds back what no rule described */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(
reporter: SentryReporter::from(
hub: $sentry->hub(),
filter: ReportingFilter::SERVER_ERRORS_AND_UNMAPPED
)
)
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then a described server failure still reaches the provider */
self::assertNotNull($sentry->sent);
self::assertSame('503', $sentry->sent->getTags()['status_code']);
}
public function testReportWhenClientErrorIsForwardedThenEventIsLeveledAsWarning(): void
{
/** @Given a request */
$request = new ServerRequest('PUT', '/v1/orders/1');
/** @And a handler that throws an exception a rule maps to 422 */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new LogicException('Invalid payload'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware whose filter keeps every handled error */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnprocessableExceptions())
->withReporter(
reporter: SentryReporter::from(
hub: $sentry->hub(),
filter: ReportingFilter::EVERY_ERROR
)
)
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then a client error is a warning, the same split the log entry uses */
self::assertNotNull($sentry->sent);
self::assertEquals(Severity::warning(), $sentry->sent->getLevel());
}
public function testReportWhenTheRouteIsNamedThenTheEventCarriesItAsTransaction(): void
{
/** @Given a request whose path carries an identifier */
$request = new ServerRequest('POST', '/v1/orders/1');
/** @And a handler that throws an exception no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request through a stack that names the route */
$middleware->process($request, new RoutingHandler(
handler: $handler,
middleware: RouteMiddleware::resolvedBy(
resolver: static fn(ServerRequestInterface $request): string => 'POST /v1/orders/{id}'
)
));
/** @Then the transaction is the pattern, which is what keeps the dimension low cardinality */
self::assertNotNull($sentry->sent);
self::assertSame('POST /v1/orders/{id}', $sentry->sent->getTransaction());
}
public function testReportWhenContextDeclaresACriticalFailureThenSeverityIsFatal(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler throwing a failure the raising site considers the worst it can name */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(
new PrioritizedException(priority: ReportingPriority::CRITICAL)
);
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the top of the neutral scale reaches the provider as the top of its own */
self::assertNotNull($sentry->sent);
self::assertEquals(Severity::fatal(), $sentry->sent->getLevel());
}
public function testReportWhenUnmappedFilterThenUnmappedClientErrorReachesSentry(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/unknown');
/** @And a handler that throws an exception declaring a 4xx that no rule describes */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new Exception('Boom', Code::NOT_FOUND->value));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware whose filter adds back what no rule described */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnmappedExceptions())
->withReporter(
reporter: SentryReporter::from(
hub: $sentry->hub(),
filter: ReportingFilter::SERVER_ERRORS_AND_UNMAPPED
)
)
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the gap in the mapping table surfaces even though the status is a 4xx */
self::assertNotNull($sentry->sent);
self::assertSame('404', $sentry->sent->getTags()['status_code']);
}
public function testReportWhenExceptionCarriesNoContextThenNothingIsAddedToTheEvent(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler throwing an exception that carries no supplement */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(new RuntimeException('Upstream down'));
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the event carries the request tags alone, the behavior every exception had before */
self::assertNotNull($sentry->sent);
self::assertArrayNotHasKey('service', $sentry->sent->getTags());
self::assertEquals(Severity::error(), $sentry->sent->getLevel());
}
public function testReportWhenContextOverridesPriorityThenSeverityFollowsTheOverride(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a handler throwing a server error the raising site considers unremarkable */
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willThrowException(
new PrioritizedException(priority: ReportingPriority::LOW)
);
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the declared priority wins over the one a 503 would have yielded */
self::assertNotNull($sentry->sent);
self::assertEquals(Severity::info(), $sentry->sent->getLevel());
}
public function testInitializedWithWhenTheSdkGathersTheRequestAndTheUserThenNeitherIsSent(): void
{
/** @Given a reporter built from the deployment values */
SentryReporter::initializedWith(
dsn: 'https://examplePublicKey@o0.ingest.sentry.io/1',
release: 'client-gateway@1.0.0',
environment: 'development'
);
/** @And an event carrying what the SDK gathers on its own while a login fails */
$user = UserDataBag::createFromUserIdentifier(id: '0199a1b2-7c3d-7e4f-8a5b-6c7d8e9f0a1b')
->setEmail(email: 'ana@example.com');
$event = Event::createEvent()
->setUser(user: $user)
->setRequest(request: [
'url' => 'https://api.example.com/v1/sessions?phone=5511999999999',
'data' => ['email' => 'ana@example.com', 'password' => 'correct horse'],
'method' => 'POST',
'headers' => ['Authorization' => ['Bearer token']],
'query_string' => 'phone=5511999999999'
]);
/** @When the SDK runs the hook it calls before sending */
$options = SentrySdk::getCurrentHub()->getClient()?->getOptions();
self::assertNotNull($options);
$sent = ($options->getBeforeSendCallback())($event, null);
/** @Then the event leaves without the request and without the user */
self::assertNotNull($sent);
self::assertNull($sent->getUser());
self::assertSame([], $sent->getRequest());
}
public function testReportWhenBothTheRequestAndTheExceptionTagTheSameNameThenTheExceptionWins(): void
{
/** @Given a request */
$request = new ServerRequest('GET', '/v1/orders');
/** @And a layer tagging a name the exception also carries */
$handler = new TaggingHandler(
key: 'service',
value: 'organization',
failure: new ContextualException(tags: ['service' => 'payment'])
);
/** @And a Sentry transport recording whatever the hub sends */
$sentry = new RecordingSentry();
/** @And a middleware reporting to that hub */
$middleware = ErrorMiddleware::create()
->withMapping(mapping: new UnavailableExceptions())
->withReporter(reporter: SentryReporter::from(hub: $sentry->hub()))
->build();
/** @When the middleware processes the request */
$middleware->process($request, $handler);
/** @Then the one that describes this failure beats the one that describes the request */
self::assertNotNull($sentry->sent);
self::assertSame('payment', $sentry->sent->getTags()['service']);
}
}