|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Sentry\Tests\Logs; |
| 6 | + |
| 7 | +use PHPUnit\Framework\TestCase; |
| 8 | +use Sentry\ClientBuilder; |
| 9 | +use Sentry\Logs\LogLevel; |
| 10 | +use Sentry\Logs\LogsAggregator; |
| 11 | +use Sentry\SentrySdk; |
| 12 | +use Sentry\State\Hub; |
| 13 | + |
| 14 | +final class LogsAggregatorTest extends TestCase |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @dataProvider messageFormattingDataProvider |
| 18 | + */ |
| 19 | + public function testMessageFormatting(string $message, array $values, string $expected): void |
| 20 | + { |
| 21 | + $client = ClientBuilder::create([ |
| 22 | + 'enable_logs' => true, |
| 23 | + ])->getClient(); |
| 24 | + |
| 25 | + $hub = new Hub($client); |
| 26 | + SentrySdk::setCurrentHub($hub); |
| 27 | + |
| 28 | + $aggregator = new LogsAggregator(); |
| 29 | + |
| 30 | + $aggregator->add(LogLevel::info(), $message, $values); |
| 31 | + |
| 32 | + $logs = $aggregator->all(); |
| 33 | + |
| 34 | + $this->assertCount(1, $logs); |
| 35 | + |
| 36 | + $log = $logs[0]; |
| 37 | + |
| 38 | + $this->assertEquals($expected, $log->getBody()); |
| 39 | + } |
| 40 | + |
| 41 | + public static function messageFormattingDataProvider(): \Generator |
| 42 | + { |
| 43 | + yield [ |
| 44 | + 'Simple message without values', |
| 45 | + [], |
| 46 | + 'Simple message without values', |
| 47 | + ]; |
| 48 | + |
| 49 | + yield [ |
| 50 | + 'Message with a value: %s', |
| 51 | + ['value'], |
| 52 | + 'Message with a value: value', |
| 53 | + ]; |
| 54 | + |
| 55 | + yield [ |
| 56 | + 'Message with placeholders but no values: %s', |
| 57 | + [], |
| 58 | + 'Message with placeholders but no values: %s', |
| 59 | + ]; |
| 60 | + |
| 61 | + yield [ |
| 62 | + 'Message with placeholders but incorrect number of values: %s, %s', |
| 63 | + ['value'], |
| 64 | + 'Message with placeholders but incorrect number of values: %s, %s', |
| 65 | + ]; |
| 66 | + |
| 67 | + yield [ |
| 68 | + 'Message with a percentage: 42%', |
| 69 | + [], |
| 70 | + 'Message with a percentage: 42%', |
| 71 | + ]; |
| 72 | + |
| 73 | + // This test case is a bit of an odd one, you would not expect this to happen in practice unless the user intended |
| 74 | + // to format the message but did not add the proper placeholder. On PHP 8+ this will return the message as is, but |
| 75 | + // on PHP 7 it will return the message without the percentage sign because some processing is done by `vsprintf`. |
| 76 | + // You would however more likely expect the previous test case where no values are provided when no placeholders are present |
| 77 | + yield [ |
| 78 | + 'Message with a percentage: 42%', |
| 79 | + ['value'], |
| 80 | + \PHP_VERSION_ID >= 80000 |
| 81 | + ? 'Message with a percentage: 42%' |
| 82 | + : 'Message with a percentage: 42', |
| 83 | + ]; |
| 84 | + } |
| 85 | +} |
0 commit comments