File
Blob: src/workerd/server/tests/python/random/worker.py
| 1 | """ |
| 2 | Verify that calling `random` at the top-level throws. |
| 3 | |
| 4 | Calls to random should only work inside a request context. |
| 5 | """ |
| 6 | |
| 7 | # Disable do not `assert False` lint |
| 8 | # ruff: noqa: B011 |
| 9 | |
| 10 | from random import choice, randbytes, random |
| 11 | |
| 12 | try: |
| 13 | random() |
| 14 | except RuntimeError as e: |
| 15 | assert ( |
| 16 | repr(e) |
| 17 | == "RuntimeError('Cannot use random.random() outside of request context')" |
| 18 | ) |
| 19 | else: |
| 20 | assert False |
| 21 | |
| 22 | try: |
| 23 | randbytes(5) |
| 24 | except RuntimeError as e: |
| 25 | assert ( |
| 26 | repr(e) |
| 27 | == "RuntimeError('Cannot use random.randbytes() outside of request context')" |
| 28 | ) |
| 29 | else: |
| 30 | assert False |
| 31 | |
| 32 | try: |
| 33 | choice([1, 2, 3]) |
| 34 | except RuntimeError as e: |
| 35 | assert ( |
| 36 | repr(e) |
| 37 | == "RuntimeError('Cannot use random.choice() outside of request context')" |
| 38 | ) |
| 39 | else: |
| 40 | assert False |
| 41 | |
| 42 | |
| 43 | def t1(): |
| 44 | from random import randbytes, random |
| 45 | |
| 46 | random() |
| 47 | randbytes(5) |
| 48 | choice([1, 2, 3]) |
| 49 | |
| 50 | |
| 51 | def t2(): |
| 52 | random() |
| 53 | randbytes(5) |
| 54 | choice([1, 2, 3]) |
| 55 | |
| 56 | t1() |
| 57 | |
| 58 | |
| 59 | def test(): |
| 60 | t2() |