|
15 | 15 | import threading
|
16 | 16 | from concurrent.futures import ThreadPoolExecutor
|
17 | 17 | from typing import List
|
| 18 | +from unittest.mock import MagicMock, patch |
18 | 19 |
|
19 |
| -from opentelemetry import trace |
| 20 | +from opentelemetry import context, trace |
20 | 21 | from opentelemetry.instrumentation.threading import ThreadingInstrumentor
|
21 | 22 | from opentelemetry.test.test_base import TestBase
|
22 | 23 |
|
23 | 24 |
|
| 25 | +# pylint: disable=too-many-public-methods |
24 | 26 | class TestThreading(TestBase):
|
25 | 27 | def setUp(self):
|
26 | 28 | super().setUp()
|
@@ -224,3 +226,46 @@ def test_uninstrumented(self):
|
224 | 226 | self.assertEqual(len(spans), 1)
|
225 | 227 |
|
226 | 228 | ThreadingInstrumentor().instrument()
|
| 229 | + |
| 230 | + def test_threading_with_none_context_token(self): |
| 231 | + with self.get_root_span(), patch( |
| 232 | + "opentelemetry.context.attach", return_value=None |
| 233 | + ), patch("opentelemetry.context.detach") as mock_detach: |
| 234 | + thread = threading.Thread(target=self.fake_func) |
| 235 | + thread.start() |
| 236 | + thread.join() |
| 237 | + mock_detach.assert_not_called() |
| 238 | + |
| 239 | + def test_threading_with_valid_context_token(self): |
| 240 | + mock_token = MagicMock(spec=context.Token) |
| 241 | + with patch( |
| 242 | + "opentelemetry.context.attach", return_value=mock_token |
| 243 | + ), self.get_root_span(), patch( |
| 244 | + "opentelemetry.context.detach", autospec=True |
| 245 | + ) as mock_detach: |
| 246 | + thread = threading.Thread(target=self.fake_func) |
| 247 | + thread.start() |
| 248 | + thread.join() |
| 249 | + mock_detach.assert_called_once() |
| 250 | + |
| 251 | + def test_thread_pool_with_none_context_token(self): |
| 252 | + with self.get_root_span(), patch( |
| 253 | + "opentelemetry.context.attach", return_value=None |
| 254 | + ), patch( |
| 255 | + "opentelemetry.context.detach" |
| 256 | + ) as mock_detach, ThreadPoolExecutor(max_workers=1) as executor: |
| 257 | + future = executor.submit(self.get_current_span_context_for_test) |
| 258 | + future.result() |
| 259 | + |
| 260 | + mock_detach.assert_not_called() |
| 261 | + |
| 262 | + def test_threadpool_with_valid_context_token(self): |
| 263 | + mock_token = MagicMock(spec=context.Token) |
| 264 | + with self.get_root_span(), patch( |
| 265 | + "opentelemetry.context.attach", return_value=mock_token |
| 266 | + ), patch( |
| 267 | + "opentelemetry.context.detach", autospec=True |
| 268 | + ) as mock_detach, ThreadPoolExecutor(max_workers=1) as executor: |
| 269 | + future = executor.submit(self.get_current_span_context_for_test) |
| 270 | + future.result() |
| 271 | + mock_detach.assert_called_once() |
0 commit comments