Path: blob/master/tests/multimechanize/test_scripts/interact_session.py
447 views
#! /usr/bin/env python12import client3import time4import random56computation = """@interact7def f(x=(1, 100, 1)):8print(x^2)"""910class Transaction(object):11"""12A transaction that simulates loading the page13and manipulating an interact14"""1516def __init__(self):17self.custom_timers = {}1819def run(self):20t = time.time()21client.load_root()22self.custom_timers["root load"] = time.time() - t23time.sleep(5)24t = time.time()25with client.SageCellSession() as s:26self.custom_timers["initial connection"] = time.time() - t27t = time.time()28s.execute(computation)29output = ""30while True:31msg = s.iopub_recv()32if msg["header"]["msg_type"] == "status" and msg["content"]["execution_state"] == "idle":33break34elif msg["header"]["msg_type"] == "display_data" and "application/sage-interact" in msg["content"]["data"]:35interact_id = msg["content"]["data"]["application/sage-interact"]["new_interact_id"]36elif msg["header"]["msg_type"] == "stream" and msg["content"]["name"] == "stdout" and msg["metadata"]["interact_id"] == interact_id:37output += msg["content"]["data"]38assert output == "1\n", "Incorrect output: %r" % (output,)39times = []40self.custom_timers["initial computation"] = time.time() - t41for i in range(10):42time.sleep(1)43num = random.randint(1, 100)44t = time.time()45s.update_interact(interact_id, {"x": num})46output = ""47while True:48msg = s.iopub_recv()49if msg["header"]["msg_type"] == "status" and msg["content"]["execution_state"] == "idle":50break51elif msg["header"]["msg_type"] == "stream" and msg["content"]["name"] == "stdout" and msg["metadata"]["interact_id"] == interact_id:52output += msg["content"]["data"]53assert int(output.strip()) == num * num, "Incorrect output: %r" % (output,)54times.append(time.time() - t)55self.custom_timers["interact update (average of 10)"] = sum(times) / len(times)5657if __name__ == "__main__":58t = Transaction()59t.run()60print(t.custom_timers)616263