Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/tests/multimechanize/test_scripts/interact_session.py
447 views
1
#! /usr/bin/env python
2
3
import client
4
import time
5
import random
6
7
computation = """@interact
8
def f(x=(1, 100, 1)):
9
print(x^2)"""
10
11
class Transaction(object):
12
"""
13
A transaction that simulates loading the page
14
and manipulating an interact
15
"""
16
17
def __init__(self):
18
self.custom_timers = {}
19
20
def run(self):
21
t = time.time()
22
client.load_root()
23
self.custom_timers["root load"] = time.time() - t
24
time.sleep(5)
25
t = time.time()
26
with client.SageCellSession() as s:
27
self.custom_timers["initial connection"] = time.time() - t
28
t = time.time()
29
s.execute(computation)
30
output = ""
31
while True:
32
msg = s.iopub_recv()
33
if msg["header"]["msg_type"] == "status" and msg["content"]["execution_state"] == "idle":
34
break
35
elif msg["header"]["msg_type"] == "display_data" and "application/sage-interact" in msg["content"]["data"]:
36
interact_id = msg["content"]["data"]["application/sage-interact"]["new_interact_id"]
37
elif msg["header"]["msg_type"] == "stream" and msg["content"]["name"] == "stdout" and msg["metadata"]["interact_id"] == interact_id:
38
output += msg["content"]["data"]
39
assert output == "1\n", "Incorrect output: %r" % (output,)
40
times = []
41
self.custom_timers["initial computation"] = time.time() - t
42
for i in range(10):
43
time.sleep(1)
44
num = random.randint(1, 100)
45
t = time.time()
46
s.update_interact(interact_id, {"x": num})
47
output = ""
48
while True:
49
msg = s.iopub_recv()
50
if msg["header"]["msg_type"] == "status" and msg["content"]["execution_state"] == "idle":
51
break
52
elif msg["header"]["msg_type"] == "stream" and msg["content"]["name"] == "stdout" and msg["metadata"]["interact_id"] == interact_id:
53
output += msg["content"]["data"]
54
assert int(output.strip()) == num * num, "Incorrect output: %r" % (output,)
55
times.append(time.time() - t)
56
self.custom_timers["interact update (average of 10)"] = sum(times) / len(times)
57
58
if __name__ == "__main__":
59
t = Transaction()
60
t.run()
61
print(t.custom_timers)
62
63