RavenTest::testTag()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
dl 11
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dziki\MonologSentryBundle\Tests\Unit\Handler;
6
7
use Dziki\MonologSentryBundle\Handler\Raven;
8
use Monolog\Formatter\FormatterInterface;
9
use Monolog\Formatter\LineFormatter;
10
use Monolog\Logger;
11
use PHPUnit\Framework\TestCase;
12
use Raven_Client;
13
14
/**
15
 * @covers \Dziki\MonologSentryBundle\Handler\Raven
16
 */
17
class RavenTest extends TestCase
18
{
19
    public function setUp(): void
20
    {
21
        if (!class_exists('Raven_Client')) {
22
            $this->markTestSkipped('sentry/sentry not installed');
23
        }
24
    }
25
26
    public function testConstruct()
27
    {
28
        $handler = new Raven($this->getRavenClient());
29
        $this->assertInstanceOf(Raven::class, $handler);
30
    }
31
32
    protected function getRavenClient()
33
    {
34
        $dsn = 'http://43f6017361224d098402974103bfc53d:[email protected]:9000/1';
35
36
        return new MockRavenClient($dsn);
37
    }
38
39 View Code Duplication
    public function testDebug()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40
    {
41
        $ravenClient = $this->getRavenClient();
42
        $handler = $this->getHandler($ravenClient);
43
44
        $record = $this->getRecord(Logger::DEBUG, 'A test debug message');
45
        $handler->handle($record);
46
47
        $this->assertEquals($ravenClient::DEBUG, $ravenClient->lastData['level']);
48
        $this->assertStringContainsString($record['message'], $ravenClient->lastData['message']);
49
    }
50
51
    protected function getHandler($ravenClient)
52
    {
53
        $handler = new Raven($ravenClient);
54
55
        return $handler;
56
    }
57
58
    /**
59
     * @param int    $level
60
     * @param string $message
61
     * @param array  $context
62
     * @param string $channel
63
     * @param array  $extra
64
     *
65
     * @return array Record
66
     *
67
     * @throws \Exception
68
     */
69
    protected function getRecord($level = Logger::WARNING, $message = 'test', array $context = [], $channel = 'test', $extra = []): array
70
    {
71
        return [
72
            'message' => (string) $message,
73
            'context' => $context,
74
            'level' => $level,
75
            'level_name' => Logger::getLevelName($level),
76
            'channel' => $channel,
77
            'datetime' => new \DateTimeImmutable(),
78
            'extra' => $extra,
79
        ];
80
    }
81
82 View Code Duplication
    public function testWarning()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
83
    {
84
        $ravenClient = $this->getRavenClient();
85
        $handler = $this->getHandler($ravenClient);
86
87
        $record = $this->getRecord(Logger::WARNING, 'A test warning message');
88
        $handler->handle($record);
89
90
        $this->assertEquals($ravenClient::WARNING, $ravenClient->lastData['level']);
91
        $this->assertStringContainsString($record['message'], $ravenClient->lastData['message']);
92
    }
93
94 View Code Duplication
    public function testTag()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
    {
96
        $ravenClient = $this->getRavenClient();
97
        $handler = $this->getHandler($ravenClient);
98
99
        $tags = [1, 2, 'foo'];
100
        $record = $this->getRecord(Logger::INFO, 'test', ['tags' => $tags]);
101
        $handler->handle($record);
102
103
        $this->assertEquals($tags, $ravenClient->lastData['tags']);
104
    }
105
106
    public function testExtraParameters()
107
    {
108
        $ravenClient = $this->getRavenClient();
109
        $handler = $this->getHandler($ravenClient);
110
111
        $checksum = '098f6bcd4621d373cade4e832627b4f6';
112
        $release = '05a671c66aefea124cc08b76ea6d30bb';
113
        $eventId = '31423';
114
        $record = $this->getRecord(
115
            Logger::INFO,
116
            'test',
117
            ['checksum' => $checksum, 'release' => $release, 'event_id' => $eventId]
118
        );
119
        $handler->handle($record);
120
121
        $this->assertEquals($checksum, $ravenClient->lastData['checksum']);
122
        $this->assertEquals($release, $ravenClient->lastData['release']);
123
        $this->assertEquals(
124
            $eventId,
125
            $ravenClient->lastData['event_id'] ?? $ravenClient->lastData['extra']['context']['event_id']
126
        );
127
    }
128
129 View Code Duplication
    public function testFingerprint()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
    {
131
        $ravenClient = $this->getRavenClient();
132
        $handler = $this->getHandler($ravenClient);
133
134
        $fingerprint = ['{{ default }}', 'other value'];
135
        $record = $this->getRecord(Logger::INFO, 'test', ['fingerprint' => $fingerprint]);
136
        $handler->handle($record);
137
138
        $this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']);
139
    }
140
141
    public function testUserContext()
142
    {
143
        $ravenClient = $this->getRavenClient();
144
        $handler = $this->getHandler($ravenClient);
145
146
        $recordWithNoContext = $this->getRecord(Logger::ERROR, 'test with default user context');
147
        // set user context 'externally'
148
149
        $user = [
150
            'id' => '123',
151
            'email' => '[email protected]',
152
        ];
153
154
        $recordWithContext = $this->getRecord(
155
            Logger::ERROR,
156
            'test',
157
            [
158
                'user' => $user,
159
                'tags' => ['another_tag' => 'null_value'],
160
                'something' => 'anything',
161
                'exception' => new \Exception('test exception'),
162
                'logger' => 'logger',
163
            ],
164
            'any',
165
            [
166
                'tags' => ['tag_name' => 'value'],
167
                'some_additional_data_key' => 'some_additional_data',
168
            ]
169
        );
170
171
        // handle with null context
172
        $ravenClient->user_context(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
173
        $handler->handle($recordWithContext);
174
175
        $this->assertEquals($user, $ravenClient->lastData['user']);
176
177
        $ravenClient->user_context(['id' => 'test_user_id']);
178
        // handle context
179
        $handler->handle($recordWithContext);
180
        $this->assertEquals($user, $ravenClient->lastData['user']);
181
182
        // check to see if its reset
183
        $handler->handle($recordWithNoContext);
184
        $this->assertIsArray($ravenClient->context->user);
185
        $this->assertSame('test_user_id', $ravenClient->context->user['id']);
186
    }
187
188
    public function testException()
189
    {
190
        $ravenClient = $this->getRavenClient();
191
        $handler = $this->getHandler($ravenClient);
192
193
        try {
194
            $this->methodThatThrowsAnException();
195
        } catch (\Exception $e) {
196
            $record = $this->getRecord(Logger::ERROR, $e->getMessage(), ['context' => ['exception' => $e]]);
197
            $handler->handle($record);
198
        }
199
200
        $this->assertEquals('[test] '.$record['message'], $ravenClient->lastData['message']);
201
    }
202
203
    private function methodThatThrowsAnException()
204
    {
205
        throw new \Exception('This is an exception');
206
    }
207
208
    public function testHandleBatch()
209
    {
210
        $records = $this->getMultipleRecords();
211
        $records[] = $this->getRecord(Logger::WARNING, 'warning');
212
        $records[] = $this->getRecord(Logger::WARNING, 'warning');
213
214
        $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
215
216
        $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
217
        $formatter->expects($this->once())->method('format')->with(
218
            $this->callback(
219
                function ($record) {
220
                    return 400 == $record['level'];
221
                }
222
            )
223
        )
224
        ;
225
226
        $handler = $this->getHandler($this->getRavenClient());
227
        $handler->setBatchFormatter($logFormatter);
228
        $handler->setFormatter($formatter);
229
        $handler->handleBatch($records);
230
231
        $handler->handleBatch([]);
232
    }
233
234
    protected function getMultipleRecords(): array
235
    {
236
        return [
237
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
238
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
239
            $this->getRecord(Logger::INFO, 'information'),
240
            $this->getRecord(Logger::WARNING, 'warning'),
241
            $this->getRecord(Logger::ERROR, 'error'),
242
        ];
243
    }
244
245
    /**
246
     * @test
247
     */
248
    public function doNothingOnEmptyBatch(): void
249
    {
250
        $logFormatter = $this->createMock(FormatterInterface::class);
251
        $logFormatter->expects($this->never())
252
                     ->method('format')
253
        ;
254
255
        $logFormatter->expects($this->never())
256
                     ->method('formatBatch')
257
        ;
258
259
        $handler = $this->getHandler($this->getRavenClient());
260
        $handler->setBatchFormatter($logFormatter);
261
        $handler->setFormatter($logFormatter);
262
        $handler->handleBatch([]);
263
    }
264
265
    /**
266
     * @test
267
     */
268
    public function addContextsIfProvided(): void
269
    {
270
        $logFormatter = $this->createMock(FormatterInterface::class);
271
        $logFormatter->expects($this->once())
272
                     ->method('format')
273
                     ->willReturnArgument(0)
274
        ;
275
276
        $ravenClient = $this->getRavenClient();
277
278
        $handler = $this->getHandler($ravenClient);
279
        $handler->setBatchFormatter($logFormatter);
280
        $handler->setFormatter($logFormatter);
281
282
        $record = $this->getRecord();
283
        $record['contexts'] = ['browser_context'];
284
        $handler->handle($record);
285
286
        $this->assertSame(['browser_context'], $ravenClient->lastData['contexts']);
287
    }
288
289
    public function testHandleBatchDoNothingIfRecordsAreBelowLevel()
290
    {
291
        $records = [
292
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
293
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
294
            $this->getRecord(Logger::INFO, 'information'),
295
        ];
296
297
        $handler = $this->getMockBuilder('Monolog\Handler\RavenHandler')
298
                        ->setMethods(['handle'])
299
                        ->setConstructorArgs([$this->getRavenClient()])
300
                        ->getMock()
301
        ;
302
        $handler->expects($this->never())->method('handle');
303
        $handler->setLevel(Logger::ERROR);
304
        $handler->handleBatch($records);
305
    }
306
307
    public function testHandleBatchPicksProperMessage()
308
    {
309
        $records = [
310
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
311
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
312
            $this->getRecord(Logger::INFO, 'information 1'),
313
            $this->getRecord(Logger::ERROR, 'error 1'),
314
            $this->getRecord(Logger::WARNING, 'warning'),
315
            $this->getRecord(Logger::ERROR, 'error 2'),
316
            $this->getRecord(Logger::INFO, 'information 2'),
317
        ];
318
319
        $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
320
321
        $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
322
        $formatter->expects($this->once())->method('format')->with(
323
            $this->callback(
324
                function ($record) use ($records) {
325
                    return 'error 1' == $record['message'];
326
                }
327
            )
328
        )
329
        ;
330
331
        $handler = $this->getHandler($this->getRavenClient());
332
        $handler->setBatchFormatter($logFormatter);
333
        $handler->setFormatter($formatter);
334
        $handler->handleBatch($records);
335
    }
336
337
    public function testGetSetBatchFormatter()
338
    {
339
        $ravenClient = $this->getRavenClient();
340
        $handler = $this->getHandler($ravenClient);
341
342
        $handler->setBatchFormatter($formatter = new LineFormatter());
343
        $this->assertSame($formatter, $handler->getBatchFormatter());
344
    }
345
346
    public function testRelease()
347
    {
348
        $ravenClient = $this->getRavenClient();
349
        $handler = $this->getHandler($ravenClient);
350
        $release = 'v42.42.42';
351
        $handler->setRelease($release);
352
        $record = $this->getRecord(Logger::INFO, 'test');
353
        $handler->handle($record);
354
355
        $this->assertEquals($release, $ravenClient->lastData['release']);
356
357
        $localRelease = 'v41.41.41';
358
        $record = $this->getRecord(Logger::INFO, 'test', ['release' => $localRelease]);
359
        $handler->handle($record);
360
        $this->assertEquals($localRelease, $ravenClient->lastData['release']);
361
    }
362
363
    public function testHandleBatchBreadcrumbsSecurityAndRouting(): void
364
    {
365
        $records = $this->getMultipleRecords();
366
        $records[] = $this->getRecord(
367
            Logger::WARNING,
368
            'warning',
369
            ['route_parameters' => [
370
                '_route' => 'foo_bar_route',
371
                '_controller' => 'Foo\Bar\Controller',
372
            ],
373
                'request_uri' => 'foo.bar',
374
            ],
375
            'request'
376
        );
377
        $records[] = $this->getRecord(Logger::WARNING, 'warning', ['user' => ['username' => 'foobar']], 'security');
378
379
        $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
380
381
        $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
382
        $formatter->expects($this->once())->method('format')->with(
383
            $this->callback(
384
                function ($record) {
385
                    return 400 == $record['level'];
386
                }
387
            )
388
        )
389
        ;
390
391
        $handler = $this->getHandler($this->getRavenClient());
392
        $handler->setBatchFormatter($logFormatter);
393
        $handler->setFormatter($formatter);
394
        $handler->handleBatch($records);
395
    }
396
397
    protected function getIdentityFormatter(): FormatterInterface
398
    {
399
        $formatter = $this->createMock(FormatterInterface::class);
400
        $formatter->expects($this->any())
401
                  ->method('format')
402
                  ->will(
403
                      $this->returnCallback(
404
                          function ($record) {
405
                              return $record['message'];
406
                          }
407
                      )
408
                  )
409
        ;
410
411
        return $formatter;
412
    }
413
}
414
415
class MockRavenClient extends Raven_Client
416
{
417
    public $lastData;
418
    public $lastStack;
419
420
    public function capture($data, $stack = null, $vars = null)
421
    {
422
        $data = array_merge($this->get_user_data(), $data);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $data. This often makes code more readable.
Loading history...
423
        $this->lastData = $data;
424
        $this->lastStack = $stack;
425
    }
426
}
427