55namespace Tests \Unit \Middleware ;
66
77use Hyperf \Contract \ConfigInterface ;
8+ use Hyperf \HttpMessage \Exception \HttpException ;
89use Hyperf \OpenTelemetry \Instrumentation ;
910use Hyperf \OpenTelemetry \Middleware \TraceMiddleware ;
1011use Hyperf \OpenTelemetry \Support \SpanScope ;
@@ -258,6 +259,12 @@ public function testProcessWithException(): void
258259 ->method ('recordException ' )
259260 ->with ($ exception );
260261
262+ $ spanScope ->expects ($ this ->once ())
263+ ->method ('setAttributes ' )
264+ ->with ([
265+ HttpAttributes::HTTP_RESPONSE_STATUS_CODE => 500 ,
266+ ]);
267+
261268 $ spanScope ->expects ($ this ->once ())
262269 ->method ('end ' );
263270
@@ -279,6 +286,48 @@ public function testProcessWithException(): void
279286 $ middleware ->process ($ this ->request , $ handler );
280287 }
281288
289+ public function testProcessWithHttpException (): void
290+ {
291+ $ this ->configureRequestMock ('POST ' , 'https://api.example.com:443/api/not-found ' );
292+
293+ $ exception = new HttpException (404 , 'Not Found ' );
294+
295+ $ spanScope = $ this ->createMock (SpanScope::class);
296+ $ this ->instrumentation ->expects ($ this ->once ())
297+ ->method ('startSpan ' )
298+ ->willReturn ($ spanScope );
299+
300+ $ spanScope ->expects ($ this ->once ())
301+ ->method ('recordException ' )
302+ ->with ($ exception );
303+
304+ $ spanScope ->expects ($ this ->once ())
305+ ->method ('setAttributes ' )
306+ ->with ([
307+ HttpAttributes::HTTP_RESPONSE_STATUS_CODE => 404 ,
308+ ]);
309+
310+ $ spanScope ->expects ($ this ->once ())
311+ ->method ('end ' );
312+
313+ $ handler = $ this ->createMock (RequestHandlerInterface::class);
314+ $ handler ->expects ($ this ->once ())
315+ ->method ('handle ' )
316+ ->with ($ this ->request )
317+ ->willThrowException ($ exception );
318+
319+ $ this ->expectException (HttpException::class);
320+ $ this ->expectExceptionMessage ('Not Found ' );
321+
322+ $ middleware = new TraceMiddleware (
323+ $ this ->config ,
324+ $ this ->instrumentation ,
325+ $ this ->switcher
326+ );
327+
328+ $ middleware ->process ($ this ->request , $ handler );
329+ }
330+
282331 private function configureRequestMock (string $ method , string $ url , array $ headers = []): void
283332 {
284333 $ parts = parse_url ($ url );
0 commit comments