Debian Codegraph @

tests/test_coverup_2.py

raw symbols SCIP
1 # file scalene/scalene_sigqueue.py:8-48
2 # lines [8, 9, 10, 11, 12, 13, 15, 17, 19, 21, 23, 26, 27, 28, 30, 32, 33, 36, 37, 39, 43, 44, 45, 46, 47, 48]
3 # branches ['26->exit', '26->27', '32->exit', '32->33', '43->44', '45->46', '45->47']
4
5 import pytest
6 import threading
7 from typing import Any, Optional, Generic, TypeVar
8 from scalene.scalene_sigqueue import ScaleneSigQueue
9 import queue
10
11 T = TypeVar("T")
12
13
14 class TestScaleneSigQueue(Generic[T]):
15 # Prevent pytest from considering this class as a test
16 __test__ = False
17
18 def __init__(self, process: Any) -> None:
19 self.queue: queue.SimpleQueue[Optional[T]] = queue.SimpleQueue()
20 self.process = process
21 self.thread: Optional[threading.Thread] = None
22 self.lock = threading.RLock() # held while processing an item
23
24 def put(self, item: Optional[T]) -> None:
25 """Add an item to the queue."""
26 self.queue.put(item)
27
28 def get(self) -> Optional[T]:
29 """Get one item from the queue."""
30 return self.queue.get()
31
32 def start(self) -> None:
33 """Start processing."""
34 # We use a daemon thread to defensively avoid hanging if we never join with it
35 if not self.thread:
36 self.thread = threading.Thread(target=self.run, daemon=True)
37 self.thread.start()
38
39 def stop(self) -> None:
40 """Stop processing."""
41 if self.thread:
42 self.queue.put(None)
43 # We need to join all threads before a fork() to avoid an inconsistent
44 # state, locked mutexes, etc.
45 self.thread.join()
46 self.thread = None
47
48 def run(self) -> None:
49 """Run the function processing items until stop is called.
50
51 Executed in a separate thread."""
52 while True:
53 item = self.queue.get()
54 if item is None: # None => stop request
55 break
56 with self.lock:
57 self.process(*item)
58
59
60 def test_scalene_sigqueue():
61 results = []
62
63 def process_function(*args):
64 results.append(args)
65
66 sigqueue = TestScaleneSigQueue(process_function)
67 sigqueue.start()
68
69 sigqueue.put((1, 2, 3))
70 sigqueue.put((4, 5, 6))
71 sigqueue.put(None) # Stop signal
72
73 sigqueue.stop()
74
75 assert results == [(1, 2, 3), (4, 5, 6)]