class TestCancellationToken(unittest.TestCase): def setUp(self): self.ct = CancellationToken() self.sleep_time = 0.2 self.count = 15 def test_token(self): self.assertFalse(self.ct.is_cancellation_requested()) self.ct.request_cancellation() self.assertTrue(self.ct.is_cancellation_requested()) self.assertRaises(SystemExit, lambda: self.ct.raise_if_cancelled()) def test_cancelling_threads(self): # Create a bunch of threads and start a timer threads = [ threading.Thread(target=sleeper, args=(self.sleep_time, self.ct)) for _ in range(self.count) ] start = timer() for t in threads: t.start() # Request cancellation and wait for threads to end self.ct.request_cancellation() for t in threads: t.join() # Assert that threads finished faster than 1.5x the sleep time stop = timer() self.assertLess(stop - start, 1.5 * self.sleep_time)
def test_process_is_not_killed_before_timeout(self): ct = CancellationToken() with subprocess.Popen(["sleep", "1"]) as proc: res = mcerd.MCERD.timeout_check(proc, 0.1, ct) obs = MockObserver() res.subscribe(obs) self.assertIsNone(proc.poll(), msg=FAILURE_MSG) self.assertEqual([], obs.nexts, msg=FAILURE_MSG) self.assertFalse(ct.is_cancellation_requested(), msg=FAILURE_MSG)
def test_process_is_killed_after_timeout(self): ct = CancellationToken() with subprocess.Popen(["sleep", "1"]) as proc: res = mcerd.MCERD.timeout_check(proc, 0.01, ct) obs = MockObserver() res.subscribe(obs) time.sleep(DEFAULT_SLEEP_TIME) self.assertNotEqual(0, int(proc.poll()), msg=FAILURE_MSG) self.assertEqual([{ "is_running": False, "msg": "Simulation timed out" }], obs.nexts, msg=FAILURE_MSG) self.assertTrue(ct.is_cancellation_requested(), msg=FAILURE_MSG)
def test_process_ending_before_timeout_does_not_change_outcome(self): ct = CancellationToken() with subprocess.Popen(["echo", "hello"], stdout=subprocess.DEVNULL) as proc: res = mcerd.MCERD.timeout_check(proc, 0.01, ct) obs = MockObserver() res.subscribe(obs) time.sleep(DEFAULT_SLEEP_TIME) self.assertEqual(0, proc.poll(), msg=FAILURE_MSG) self.assertEqual([{ "is_running": False, "msg": "Simulation timed out" }], obs.nexts, msg=FAILURE_MSG) self.assertTrue(ct.is_cancellation_requested(), msg=FAILURE_MSG)