|
| 1 | +import threading |
| 2 | +import unittest |
| 3 | + |
| 4 | +import mock |
| 5 | + |
| 6 | +from .. import worker |
| 7 | + |
| 8 | + |
| 9 | +class WorkerTest(unittest.TestCase): |
| 10 | + def test_worker_resilency(self): |
| 11 | + canary = mock.Mock() |
| 12 | + |
| 13 | + collection_one = ["one", KeyError("random internal error"), "three"] |
| 14 | + collection_two = ["one", "two", SystemExit()] |
| 15 | + |
| 16 | + def send(collection, collection_target, now, interval, pid): |
| 17 | + obj = collection.pop(0) |
| 18 | + if isinstance(obj, BaseException): |
| 19 | + raise obj |
| 20 | + else: |
| 21 | + canary.send(collection_target, obj) |
| 22 | + |
| 23 | + the_time = [100] |
| 24 | + |
| 25 | + mutex = threading.Lock() |
| 26 | + |
| 27 | + # worker thread will call this at the top of its main loop. |
| 28 | + def start_loop(): |
| 29 | + # still supporting Python 2, in Py3k only can instead use |
| 30 | + # nonlocal for "the_time" |
| 31 | + mutex.acquire() |
| 32 | + try: |
| 33 | + return the_time[0] |
| 34 | + finally: |
| 35 | + the_time[0] += 5 |
| 36 | + mutex.release() |
| 37 | + |
| 38 | + with mock.patch.object( |
| 39 | + worker, "log" |
| 40 | + ) as mock_logger, mock.patch.object( |
| 41 | + worker.time, "time", mock.Mock(side_effect=start_loop) |
| 42 | + ), mock.patch.object( |
| 43 | + worker.time, "sleep" |
| 44 | + ): |
| 45 | + mutex.acquire() |
| 46 | + try: |
| 47 | + # this adds the target and also starts the worker thread. |
| 48 | + # however we have it blocked from doing anything via the |
| 49 | + # mutex above... |
| 50 | + worker.add_target( |
| 51 | + collection_one, "target one", mock.Mock(send=send) |
| 52 | + ) |
| 53 | + |
| 54 | + # ...so that we can also add this target and get deterministic |
| 55 | + # results |
| 56 | + worker.add_target( |
| 57 | + collection_two, "target two", mock.Mock(send=send) |
| 58 | + ) |
| 59 | + finally: |
| 60 | + # worker thread is unblocked |
| 61 | + mutex.release() |
| 62 | + |
| 63 | + # now wait, it will hit the SystemExit and exit. |
| 64 | + # if it times out, we failed. |
| 65 | + worker._WORKER_THREAD.join(1) |
| 66 | + |
| 67 | + # see that it did what we asked. |
| 68 | + self.assertEqual( |
| 69 | + [ |
| 70 | + mock.call.send("target one", "one"), |
| 71 | + mock.call.send("target two", "one"), |
| 72 | + mock.call.send("target two", "two"), |
| 73 | + mock.call.send("target one", "three"), |
| 74 | + ], |
| 75 | + canary.mock_calls, |
| 76 | + ) |
| 77 | + |
| 78 | + self.assertEqual( |
| 79 | + [ |
| 80 | + mock.call.info("Starting process thread in pid %s", mock.ANY), |
| 81 | + mock.call.error("error sending stats", exc_info=True), |
| 82 | + mock.call.info( |
| 83 | + "message sender thread caught SystemExit " |
| 84 | + "exception, exiting" |
| 85 | + ), |
| 86 | + ], |
| 87 | + mock_logger.mock_calls, |
| 88 | + ) |
0 commit comments