• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import asyncio
2import decimal
3import unittest
4
5
6def tearDownModule():
7    asyncio.set_event_loop_policy(None)
8
9
10@unittest.skipUnless(decimal.HAVE_CONTEXTVAR, "decimal is built with a thread-local context")
11class DecimalContextTest(unittest.TestCase):
12
13    def test_asyncio_task_decimal_context(self):
14        async def fractions(t, precision, x, y):
15            with decimal.localcontext() as ctx:
16                ctx.prec = precision
17                a = decimal.Decimal(x) / decimal.Decimal(y)
18                await asyncio.sleep(t)
19                b = decimal.Decimal(x) / decimal.Decimal(y ** 2)
20                return a, b
21
22        async def main():
23            r1, r2 = await asyncio.gather(
24                fractions(0.1, 3, 1, 3), fractions(0.2, 6, 1, 3))
25
26            return r1, r2
27
28        r1, r2 = asyncio.run(main())
29
30        self.assertEqual(str(r1[0]), '0.333')
31        self.assertEqual(str(r1[1]), '0.111')
32
33        self.assertEqual(str(r2[0]), '0.333333')
34        self.assertEqual(str(r2[1]), '0.111111')
35