1+ # Copyright The OpenTelemetry Authors
2+ #
3+ # Licensed under the Apache License, Version 2.0 (the "License");
4+ # you may not use this file except in compliance with the License.
5+ # You may obtain a copy of the License at
6+ #
7+ # http://www.apache.org/licenses/LICENSE-2.0
8+
9+ import unittest
10+ from unittest .mock import MagicMock
11+ from opentelemetry .trace .status import Status , StatusCode
12+ from opentelemetry .instrumentation ._semconv import (
13+ _set_status ,
14+ _StabilityMode ,
15+ )
16+
17+
18+ class TestSetStatus (unittest .TestCase ):
19+
20+ def _make_span (self , status_code , description = None ):
21+ span = MagicMock ()
22+ span .is_recording .return_value = True
23+ span .status = Status (status_code , description )
24+ return span
25+
26+ def test_does_not_downgrade_error_to_ok (self ):
27+ """ERROR status should not be overridden by a lower priority OK"""
28+ span = self ._make_span (StatusCode .ERROR , "original error" )
29+ _set_status (span , {}, 200 , "200" , server_span = True ,
30+ sem_conv_opt_in_mode = _StabilityMode .DEFAULT )
31+ # set_status should NOT have been called (no downgrade)
32+ for call in span .set_status .call_args_list :
33+ args = call [0 ]
34+ if args :
35+ self .assertNotEqual (args [0 ].status_code , StatusCode .OK )
36+
37+ def test_does_not_wipe_description_with_none (self ):
38+ """Same ERROR status should preserve existing description"""
39+ span = self ._make_span (StatusCode .ERROR , "keep this message" )
40+ _set_status (span , {}, 500 , "500" , server_span = True ,
41+ sem_conv_opt_in_mode = _StabilityMode .DEFAULT )
42+ last_call = span .set_status .call_args
43+ if last_call :
44+ status_arg = last_call [0 ][0 ]
45+ self .assertEqual (status_arg .description , "keep this message" )
46+
47+ def test_upgrades_unset_to_error (self ):
48+ """UNSET status should be upgraded to ERROR"""
49+ span = self ._make_span (StatusCode .UNSET )
50+ _set_status (span , {}, 500 , "500" , server_span = True ,
51+ sem_conv_opt_in_mode = _StabilityMode .DEFAULT )
52+ span .set_status .assert_called ()
53+ last_call = span .set_status .call_args [0 ][0 ]
54+ self .assertEqual (last_call .status_code , StatusCode .ERROR )
55+
56+ def test_unset_to_ok (self ):
57+ """UNSET status should be upgraded to OK for 2xx"""
58+ span = self ._make_span (StatusCode .UNSET )
59+ _set_status (span , {}, 200 , "200" , server_span = False ,
60+ sem_conv_opt_in_mode = _StabilityMode .DEFAULT )
61+ span .set_status .assert_called ()
62+
63+
64+ if __name__ == "__main__" :
65+ unittest .main ()
0 commit comments