MCPcopy Create free account
hub / github.com/Distributive-Network/PythonMonkey / test_set_clear_timeout

Function test_set_clear_timeout

tests/python/test_event_loop.py:60–146  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

58
59
60def test_set_clear_timeout():
61 # throw RuntimeError outside a coroutine
62 with pytest.raises(RuntimeError,
63 match="PythonMonkey cannot find a running Python event-loop to make asynchronous calls."):
64 pm.eval("setTimeout")(print)
65
66 async def async_fn():
67 # standalone `setTimeout`
68 loop = asyncio.get_running_loop()
69 f0 = loop.create_future()
70
71 def add(a, b, c):
72 f0.set_result(a + b + c)
73 pm.eval("setTimeout")(add, 0, 1, 2, 3)
74 assert 6.0 == await f0
75
76 # test `clearTimeout`
77 f1 = loop.create_future()
78
79 def to_raise(msg):
80 f1.set_exception(TypeError(msg))
81 timeout_id0 = pm.eval("setTimeout")(to_raise, 100, "going to be there")
82 # `setTimeout` should return a `Timeout` instance wrapping a positive integer value
83 assert pm.eval("(t) => t instanceof setTimeout.Timeout")(timeout_id0)
84 assert pm.eval("(t) => Number(t) > 0")(timeout_id0)
85 assert pm.eval("(t) => Number.isInteger(Number(t))")(timeout_id0)
86 with pytest.raises(TypeError, match="going to be there"):
87 await f1 # `clearTimeout` not called
88 f1 = loop.create_future()
89 timeout_id1 = pm.eval("setTimeout")(to_raise, 100, "shouldn't be here")
90 pm.eval("clearTimeout")(timeout_id1)
91 with pytest.raises(asyncio.exceptions.TimeoutError):
92 await asyncio.wait_for(f1, timeout=0.5) # `clearTimeout` is called
93
94 # `this` value in `setTimeout` callback should be the global object, as spec-ed
95 assert await pm.eval("new Promise(function (resolve) { setTimeout(function(){ resolve(this == globalThis) }) })")
96 # `setTimeout` should allow passing additional arguments to the callback, as spec-ed
97 assert 3.0 == await pm.eval("""
98 new Promise((resolve) => setTimeout(function(){
99 resolve(arguments.length);
100 },
101 100, 90, 91, 92))
102 """)
103 assert 92.0 == await pm.eval("""
104 new Promise((resolve) => setTimeout((...args) => {
105 resolve(args[2]);
106 },
107 100, 90, 91, 92))
108 """)
109 # test `setTimeout` setting delay to 0 if < 0
110 await asyncio.wait_for(pm.eval("new Promise((resolve) => setTimeout(resolve, 0))"), timeout=0.05)
111 # won't be precisely 0s
112 await asyncio.wait_for(pm.eval("new Promise((resolve) => setTimeout(resolve, -10000))"), timeout=0.05)
113 # test `setTimeout` accepting string as the delay, coercing to a number.
114 # Number('100') -> 100, pass if the actual delay is > 90ms and < 150ms
115 # won't be precisely 100ms
116 await asyncio.wait_for(pm.eval("new Promise((resolve) => setTimeout(resolve, '100'))"), timeout=0.15)
117 with pytest.raises(asyncio.exceptions.TimeoutError):

Callers

nothing calls this directly

Calls 1

async_fnFunction · 0.70

Tested by

no test coverage detected