Skip to content
File

Blob: src/workerd/server/tests/python/random/worker.py

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