|
4 | 4 |
|
5 | 5 | namespace OpenTelemetry\Contrib\Psr3\tests\Unit; |
6 | 6 |
|
| 7 | +use Exception; |
| 8 | +use JsonSerializable; |
| 9 | +use OpenTelemetry\API\Behavior\Internal\Logging; |
| 10 | +use OpenTelemetry\API\Behavior\Internal\LogWriter\LogWriterInterface; |
7 | 11 | use OpenTelemetry\Contrib\Instrumentation\Psr3\Formatter; |
| 12 | +use PHPUnit\Framework\MockObject\MockObject; |
8 | 13 | use PHPUnit\Framework\TestCase; |
| 14 | +use Stringable; |
9 | 15 |
|
10 | 16 | class FormatterTest extends TestCase |
11 | 17 | { |
| 18 | + /** @var LogWriterInterface&MockObject */ |
| 19 | + private LogWriterInterface $logWriter; |
| 20 | + |
| 21 | + public function setUp(): void |
| 22 | + { |
| 23 | + $this->logWriter = $this->createMock(LogWriterInterface::class); |
| 24 | + Logging::setLogWriter($this->logWriter); |
| 25 | + } |
| 26 | + |
| 27 | + public function tearDown(): void |
| 28 | + { |
| 29 | + Logging::reset(); |
| 30 | + } |
| 31 | + |
12 | 32 | public function test_format(): void |
13 | 33 | { |
14 | 34 | $context = [ |
15 | 35 | 0 => 'zero', |
16 | 36 | 'foo' => 'bar', |
17 | | - 'exception' => new \Exception('foo', 500, new \RuntimeException('bar')), |
| 37 | + 'exception' => new Exception('foo', 500, new \RuntimeException('bar')), |
| 38 | + 'j' => new class() implements JsonSerializable { |
| 39 | + public function jsonSerialize(): array |
| 40 | + { |
| 41 | + return ['foo' => 'bar']; |
| 42 | + } |
| 43 | + }, |
| 44 | + 's' => new class() implements Stringable { |
| 45 | + public function __toString(): string |
| 46 | + { |
| 47 | + return 'string_value'; |
| 48 | + } |
| 49 | + }, |
| 50 | + 'b' => true, |
18 | 51 | ]; |
19 | 52 | $formatted = Formatter::format($context); |
20 | 53 | $this->assertSame('bar', $formatted['foo']); |
21 | 54 | $this->assertArrayHasKey('exception', $formatted); |
22 | 55 | $this->assertSame('foo', $formatted['exception']['message']); |
23 | 56 | $this->assertSame(500, $formatted['exception']['code']); |
24 | 57 | $this->assertSame('bar', $formatted['exception']['previous']['message']); |
| 58 | + $this->assertSame('string_value', $formatted['s']); |
| 59 | + $this->assertSame(['foo' => 'bar'], $formatted['j']); |
| 60 | + $this->assertTrue($formatted['b']); |
| 61 | + } |
| 62 | + |
| 63 | + public function test_invalid_input_logs_warning(): void |
| 64 | + { |
| 65 | + $this->logWriter->expects($this->once())->method('write')->with( |
| 66 | + $this->equalTo('warning'), |
| 67 | + $this->stringContains('Failed to encode value'), |
| 68 | + ); |
| 69 | + $context = [ |
| 70 | + 'good' => 'foo', |
| 71 | + 'bad' => [fopen('php://memory', 'r+')], //resource cannot be encoded |
| 72 | + ]; |
| 73 | + $formatted = Formatter::format($context); |
| 74 | + $this->assertSame('foo', $formatted['good']); |
| 75 | + $this->assertArrayNotHasKey('bad', $formatted); |
25 | 76 | } |
26 | 77 | } |
0 commit comments