|
17 | 17 | from opentelemetry.semconv._incubating.attributes.user_agent_attributes import ( |
18 | 18 | UserAgentSyntheticTypeValues, |
19 | 19 | ) |
20 | | -from opentelemetry.util.http import detect_synthetic_user_agent |
| 20 | +from opentelemetry.util.http import ( |
| 21 | + detect_synthetic_user_agent, |
| 22 | + normalize_user_agent, |
| 23 | +) |
21 | 24 |
|
22 | 25 |
|
23 | 26 | class TestDetectSyntheticUserAgent(unittest.TestCase): |
@@ -86,3 +89,44 @@ def test_priority_test_over_bot(self): |
86 | 89 | result = detect_synthetic_user_agent(user_agent) |
87 | 90 | # alwayson should be checked first and return 'test' |
88 | 91 | self.assertEqual(result, UserAgentSyntheticTypeValues.TEST.value) |
| 92 | + |
| 93 | + def test_bytes_like_user_agent(self): |
| 94 | + """Test that bytes-like user agents are decoded and detected.""" |
| 95 | + |
| 96 | + test_cases = [ |
| 97 | + (b"alwayson-monitor/1.0", UserAgentSyntheticTypeValues.TEST.value), |
| 98 | + ( |
| 99 | + bytearray(b"googlebot/2.1"), |
| 100 | + UserAgentSyntheticTypeValues.BOT.value, |
| 101 | + ), |
| 102 | + (memoryview(b"MyApp/1.0"), None), |
| 103 | + ] |
| 104 | + |
| 105 | + for user_agent_raw, expected in test_cases: |
| 106 | + with self.subTest(user_agent=user_agent_raw): |
| 107 | + normalized = normalize_user_agent(user_agent_raw) |
| 108 | + result = detect_synthetic_user_agent(normalized) |
| 109 | + self.assertEqual(result, expected) |
| 110 | + |
| 111 | + |
| 112 | +class TestNormalizeUserAgent(unittest.TestCase): |
| 113 | + def test_preserves_string(self): |
| 114 | + self.assertEqual(normalize_user_agent("Mozilla"), "Mozilla") |
| 115 | + |
| 116 | + def test_decodes_bytes(self): |
| 117 | + self.assertEqual( |
| 118 | + normalize_user_agent(b"Custom-Client/1.0"), "Custom-Client/1.0" |
| 119 | + ) |
| 120 | + |
| 121 | + def test_decodes_bytearray(self): |
| 122 | + self.assertEqual( |
| 123 | + normalize_user_agent(bytearray(b"Bot/2.0")), "Bot/2.0" |
| 124 | + ) |
| 125 | + |
| 126 | + def test_decodes_memoryview(self): |
| 127 | + self.assertEqual( |
| 128 | + normalize_user_agent(memoryview(b"Monitor/3.0")), "Monitor/3.0" |
| 129 | + ) |
| 130 | + |
| 131 | + def test_none(self): |
| 132 | + self.assertIsNone(normalize_user_agent(None)) |
0 commit comments