import unittest from main import Box, TaskState, start, open_cancel_scope, sleep_forever class TestBoxFunctionality(unittest.TestCase): def test_get_then_put(self): TS = TaskState b = Box() t1 = start(b.get()) t2 = start(b.get()) self.assertIs(t1.state, TS.STARTED) self.assertIs(t2.state, TS.STARTED) b.put(7, crow='raven') self.assertEqual(t1.result, ((7,), {'crow': 'raven'})) self.assertEqual(t2.result, ((7,), {'crow': 'raven'})) def test_put_then_get(self): TS = TaskState b = Box() b.put(7, crow='raven') t1 = start(b.get()) t2 = start(b.get()) self.assertIs(t1.state, TS.FINISHED) self.assertIs(t2.state, TS.FINISHED) self.assertEqual(t1.result, ((7,), {'crow': 'raven'})) self.assertEqual(t2.result, ((7,), {'crow': 'raven'})) def test_clear(self): b1 = Box() b2 = Box() async def async_fn(): self.assertEqual(await b1.get(), ((7,), {'crow': 'raven'})) self.assertEqual(await b2.get(), ((6,), {'crocodile': 'alligator'})) self.assertEqual(await b1.get(), ((5,), {'toad': 'frog'})) task = start(async_fn()) b1.put(7, crow='raven') b1.clear() b2.put(6, crocodile='alligator') b1.put(5, toad='frog') self.assertTrue(task.finished) def test_cancel(self): TS = TaskState async def async_fn(ctx, b): async with open_cancel_scope() as scope: ctx['scope'] = scope await b.get() self.fail() # This should not be reached if cancel works await sleep_forever() ctx = {} b = Box() task = start(async_fn(ctx, b)) self.assertIs(task.state, TS.STARTED) ctx['scope'].cancel() self.assertIs(task.state, TS.STARTED) # Still running until we get a value b.put() # This will finish the task self.assertIs(task.state, TS.STARTED) task._step() # Process the task self.assertIs(task.state, TS.FINISHED) def test_complicated_cancel(self): TS = TaskState async def async_fn_1(ctx, b): await b.get() ctx['scope'].cancel() async def async_fn_2(ctx, b): async with open_cancel_scope() as scope: ctx['scope'] = scope await b.get() self.fail() # This should not be reached if cancel works await sleep_forever() ctx = {} b = Box() t1 = start(async_fn_1(ctx, b)) t2 = start(async_fn_2(ctx, b)) self.assertEqual(b._waiting_tasks, [t1, t2]) self.assertIs(t2.state, TS.STARTED) b.put() self.assertIs(t1.state, TS.FINISHED) self.assertIs(t2.state, TS.STARTED) self.assertEqual(b._waiting_tasks, []) t2._step() # Process t2 self.assertIs(t2.state, TS.FINISHED) if __name__ == '__main__': unittest.main()