66
77use Exception ;
88use JsonSerializable ;
9+ use OpenTelemetry \API \Behavior \Internal \Logging ;
10+ use OpenTelemetry \API \Behavior \Internal \LogWriter \LogWriterInterface ;
911use OpenTelemetry \Contrib \Instrumentation \Psr3 \Formatter ;
12+ use PHPUnit \Framework \MockObject \MockObject ;
1013use PHPUnit \Framework \TestCase ;
1114use Stringable ;
1215
1316class FormatterTest extends TestCase
1417{
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+
1532 public function test_format (): void
1633 {
1734 $ context = [
@@ -30,6 +47,7 @@ public function __toString(): string
3047 return 'string_value ' ;
3148 }
3249 },
50+ 'b ' => true ,
3351 ];
3452 $ formatted = Formatter::format ($ context );
3553 $ this ->assertSame ('bar ' , $ formatted ['foo ' ]);
@@ -39,5 +57,21 @@ public function __toString(): string
3957 $ this ->assertSame ('bar ' , $ formatted ['exception ' ]['previous ' ]['message ' ]);
4058 $ this ->assertSame ('string_value ' , $ formatted ['s ' ]);
4159 $ 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 );
4276 }
4377}
0 commit comments