Exemplo n.º 1
0
class TestSystemWSCommsServerAndClient(TestSystemWSCommsServerOnly):
    socket = 8882

    def setUp(self):
        super(TestSystemWSCommsServerAndClient, self).setUp()
        self.process2 = Process("proc2", self.sf)
        self.block2 = Block()
        ClientController(self.process2, self.block2, 'hello')
        self.cc = WSClientComms("cc", self.process2,
                                "ws://localhost:%s/ws" % self.socket)
        self.process2.start()
        self.cc.start()

    def tearDown(self):
        super(TestSystemWSCommsServerAndClient, self).tearDown()
        self.cc.stop()
        self.cc.wait()
        self.process2.stop()

    def test_server_with_malcolm_client(self):
        # Normally we would wait for it to be connected here, but it isn't
        # attached to a process so just sleep for a bit
        time.sleep(0.5)
        ret = self.block2.say_hello("me2")
        self.assertEqual(ret, dict(greeting="Hello me2"))
Exemplo n.º 2
0
class TestSystemWSCommsServerAndClient(TestSystemWSCommsServerOnly):
    socket = 8882

    def setUp(self):
        super(TestSystemWSCommsServerAndClient, self).setUp()
        self.process2 = Process("proc2", self.sf)
        self.block2 = Block()
        ClientController(self.process2, self.block2, 'hello')
        self.cc = WSClientComms("cc", self.process2, "ws://localhost:%s/ws" %
                                self.socket)
        self.process2.start()
        self.cc.start()

    def tearDown(self):
        super(TestSystemWSCommsServerAndClient, self).tearDown()
        self.cc.stop()
        self.cc.wait()
        self.process2.stop()

    def test_server_with_malcolm_client(self):
        # Normally we would wait for it to be connected here, but it isn't
        # attached to a process so just sleep for a bit
        time.sleep(0.5)
        ret = self.block2.say_hello("me2")
        self.assertEqual(ret, dict(greeting="Hello me2"))
Exemplo n.º 3
0
 def test_report_changes(self):
     change = [["path"], "value"]
     s = MagicMock()
     p = Process("proc", s)
     s.reset_mock()
     p.report_changes(change)
     p.q.put.assert_called_once_with(BlockChanges(changes=[change]))
Exemplo n.º 4
0
 def test_spawned_adds_to_other_spawned(self):
     s = MagicMock()
     p = Process("proc", s)
     spawned = p.spawn(callable, "fred", a=4)
     self.assertEqual(spawned, s.spawn.return_value)
     self.assertEqual(p._other_spawned, [spawned])
     s.spawn.assert_called_once_with(callable, "fred", a=4)
Exemplo n.º 5
0
 def test_add_block(self):
     p = Process("proc", MagicMock())
     b = MagicMock()
     p.add_block("myblock", b)
     b.set_parent.assert_called_once_with(p, "myblock")
     req = p.q.put.call_args[0][0]
     self.assertEqual(req.block, b)
Exemplo n.º 6
0
 def test_on_changed(self):
     change = [["path"], "value"]
     s = MagicMock()
     p = Process("proc", s)
     s.reset_mock()
     p.on_changed(change, notify=False)
     p.q.put.assert_called_once_with(BlockChanged(change=change))
Exemplo n.º 7
0
class TestSystemWSCommsServerOnly(unittest.TestCase):
    socket = 8881

    def setUp(self):
        self.sf = SyncFactory("sync")
        self.process = Process("proc", self.sf)
        block = Block()
        HelloController(self.process, block, 'hello')
        self.sc = WSServerComms("sc", self.process, self.socket)
        self.process.start()
        self.sc.start()

    def tearDown(self):
        self.sc.stop()
        self.sc.wait()
        self.process.stop()

    @gen.coroutine
    def send_message(self):
        conn = yield websocket_connect("ws://localhost:%s/ws" % self.socket)
        req = dict(type="Post",
                   id=0,
                   endpoint=["hello", "say_hello"],
                   parameters=dict(name="me"))
        conn.write_message(json.dumps(req))
        resp = yield conn.read_message()
        resp = json.loads(resp)
        self.assertEqual(
            resp, dict(id=0, type="Return", value=dict(greeting="Hello me")))
        conn.close()

    def test_server_and_simple_client(self):
        self.send_message()
Exemplo n.º 8
0
 def setUp(self):
     self.process = Process("proc")
     self.part = MyPart("test_part")
     self.part2 = MyPart("test_part2")
     self.o = MyController(self.process, "mri", [self.part, self.part2])
     self.context = Context(self.process)
     self.process.start()
Exemplo n.º 9
0
 def test_report_changes(self):
     change = [["path"], "value"]
     s = MagicMock()
     p = Process("proc", s)
     s.reset_mock()
     p.report_changes(change)
     p.q.put.assert_called_once_with(BlockChanges(changes=[change]))
Exemplo n.º 10
0
 def setUp(self):
     self.sf = SyncFactory("sync")
     self.process = Process("proc", self.sf)
     block = Block()
     HelloController(self.process, block, 'hello')
     self.sc = WSServerComms("sc", self.process, self.socket)
     self.process.start()
     self.sc.start()
Exemplo n.º 11
0
 def test_add_block(self):
     p = Process("proc", MagicMock())
     b = Block()
     b.set_process_path(p, ("name", ))
     c = MagicMock()
     p.add_block(b, c)
     self.assertEqual(p._blocks["name"], b)
     self.assertEqual(p._controllers["name"], c)
Exemplo n.º 12
0
 def test_add_block(self):
     p = Process("proc", MagicMock())
     b = Block()
     b.set_process_path(p, ("name",))
     c = MagicMock()
     p.add_block(b, c)
     self.assertEqual(p._blocks["name"], b)
     self.assertEqual(p._controllers["name"], c)
Exemplo n.º 13
0
 def setUp(self):
     self.process = Process("proc")
     self.part = MyPart("test_part")
     self.controller = MyController(self.process, "mri", [self.part])
     self.process.add_controller("mri", self.controller)
     self.context = Context(self.process)
     self.block = self.controller.make_view(self.context)
     self.process.start()
     self.process.my_method_executed = False
Exemplo n.º 14
0
 def test_on_changed_with_notify(self):
     change = [["path"], "value"]
     s = MagicMock()
     p = Process("proc", s)
     s.reset_mock()
     p.on_changed(change)
     p.q.put.assert_has_calls([
         call(BlockChanged(change=change)),
         call(BlockNotify(name="path"))])
Exemplo n.º 15
0
 def setUp(self):
     super(TestSystemWSCommsServerAndClient, self).setUp()
     self.process2 = Process("proc2", self.sf)
     self.block2 = Block()
     ClientController(self.process2, self.block2, 'hello')
     self.cc = WSClientComms("cc", self.process2,
                             "ws://localhost:%s/ws" % self.socket)
     self.process2.start()
     self.cc.start()
Exemplo n.º 16
0
 def test_block_respond(self):
     p = Process("proc", MagicMock())
     p.q.put = MagicMock()
     response = MagicMock()
     response_queue = MagicMock()
     p.block_respond(response, response_queue)
     block_response = p.q.put.call_args[0][0]
     self.assertEquals(block_response.response, response)
     self.assertEquals(block_response.response_queue, response_queue)
Exemplo n.º 17
0
 def setUp(self):
     sync_factory = SyncFactory("sync")
     self.process = Process("proc", sync_factory)
     block = Block("hello")
     self.process.add_block(block)
     HelloController(block)
     self.sc = WSServerComms("sc", self.process, 8888)
     self.process.start()
     self.sc.start()
Exemplo n.º 18
0
    def test_block_respond_triggers_response(self):
        p = Process("proc", MagicMock())
        response = MagicMock()
        response_queue = MagicMock()
        p.q.get = MagicMock(
            side_effect=[BlockRespond(response, response_queue), PROCESS_STOP])

        p.recv_loop()

        response_queue.put.assert_called_once_with(response)
Exemplo n.º 19
0
    def test_unsubscribe_error(self):
        p = Process("proc", MagicMock())
        unsub = Unsubscribe(MagicMock(), MagicMock())
        unsub.set_id(1234)
        unsub.response_queue.qsize.return_value = 0
        p.q.get = MagicMock(side_effect=[unsub, PROCESS_STOP])

        p.recv_loop()

        responses = unsub.response_queue.put.call_args_list
        self.assertEquals(1, len(responses))
        response = responses[0][0][0]
        self.assertEquals(Error, type(response))
Exemplo n.º 20
0
    def test_unsubscribe_error(self):
        p = Process("proc", MagicMock())
        unsub = Unsubscribe(MagicMock(), MagicMock())
        unsub.set_id(1234)
        unsub.response_queue.qsize.return_value = 0
        p.q.get = MagicMock(side_effect=[unsub, PROCESS_STOP])

        p.recv_loop()

        responses = unsub.response_queue.put.call_args_list
        self.assertEquals(1, len(responses))
        response = responses[0][0][0]
        self.assertEquals(Error, type(response))
Exemplo n.º 21
0
    def test_unsubscribe_error(self):
        p = Process("proc", MagicMock())
        unsub = Unsubscribe(MagicMock(), MagicMock())
        unsub.set_id(1234)
        p.q.get = MagicMock(side_effect=[unsub, PROCESS_STOP])

        p.recv_loop()

        responses = unsub.response_queue.put.call_args_list
        self.assertEquals(1, len(responses))
        response = responses[0][0][0]
        self.assertEquals(Error, type(response))
        self.assertEquals("No subscription found for id 1234",
                          response.message)
Exemplo n.º 22
0
    def test_multiple_notifies_single_change(self):
        block_1 = MagicMock(
            to_dict=MagicMock(return_value={"attr": "initial_value"}))
        block_1.name = "block_1"
        block_2 = MagicMock(
            to_dict=MagicMock(return_value={"attr2": "initial_value"}))
        block_2.name = "block_2"
        sub_1 = MagicMock()
        sub_1.endpoint = ["block_1"]
        sub_1.delta = False
        sub_2 = MagicMock()
        sub_2.endpoint = ["block_1"]
        sub_2.delta = True
        sub_3 = MagicMock()
        sub_3.endpoint = ["block_2"]
        sub_3.delta = False
        sub_4 = MagicMock()
        sub_4.endpoint = ["block_2"]
        sub_4.delta = True
        change_1 = [["block_1", "attr"], "final_value"]
        change_2 = [["block_2", "attr2"], "final_value"]
        request_1 = BlockNotify("block_1")
        request_2 = BlockChanged(change_1)
        request_3 = BlockChanged(change_2)
        request_4 = BlockNotify("block_1")
        request_5 = BlockNotify("block_1")
        request_6 = BlockNotify("block_2")
        p = Process("proc", MagicMock())
        p.q.get = MagicMock(side_effect=[request_1, request_2, request_3,
                                         request_4, request_5, request_6,
                                         PROCESS_STOP])
        p.q.put = MagicMock(side_effect=p.q.put)
        p._subscriptions["block_1"] = [sub_1, sub_2]
        p._subscriptions["block_2"] = [sub_3, sub_4]
        p._handle_block_add(BlockAdd(block_1))
        p._handle_block_add(BlockAdd(block_2))

        p.recv_loop()

        call_list = sub_1.response_queue.put.call_args_list
        self.assertEquals(1, len(call_list))
        self.assertIsInstance(call_list[0][0][0], Update)
        self.assertEquals({"attr": "final_value"}, call_list[0][0][0].value)

        call_list = sub_2.response_queue.put.call_args_list
        self.assertEquals(1, len(call_list))
        self.assertIsInstance(call_list[0][0][0], Delta)
        self.assertEquals([[["attr"], "final_value"]],
                          call_list[0][0][0].changes)

        call_list = sub_3.response_queue.put.call_args_list
        self.assertEquals(1, len(call_list))
        self.assertIsInstance(call_list[0][0][0], Update)
        self.assertEquals({"attr2": "final_value"}, call_list[0][0][0].value)

        call_list = sub_4.response_queue.put.call_args_list
        self.assertEquals(1, len(call_list))
        self.assertIsInstance(call_list[0][0][0], Delta)
        self.assertEquals([[["attr2"], "final_value"]],
                          call_list[0][0][0].changes)
Exemplo n.º 23
0
    def test_get(self):
        p = Process("proc", MagicMock())
        block = MagicMock()
        block.name = "myblock"
        block.to_dict = MagicMock(
            return_value={"path_1": {"path_2": {"attr": "value"}}})
        request = Get(MagicMock(), MagicMock(), ["myblock", "path_1", "path_2"])
        p._handle_block_add(BlockAdd(block))
        p.q.get = MagicMock(side_effect=[request, PROCESS_STOP])

        p.recv_loop()

        response = request.response_queue.put.call_args[0][0]
        self.assertIsInstance(response, Return)
        self.assertEquals({"attr": "value"}, response.value)
Exemplo n.º 24
0
 def setUp(self):
     self.sync = SyncFactory("threads")
     self.process = Process("proc", self.sync)
     self.block = Block("block")
     self.host = socket.gethostname().split('.')[0]
     self.prefix = "%s-AD-SIM-01" % self.host
     pass
Exemplo n.º 25
0
    def setUp(self):
        s = SyncFactory("sync")
        self.p = Process("process", s)
        self.b = Block("blockname")
        self.comms = MagicMock()
        serialized = dict(say_hello=dict(
            description="Says hello",
            takes=dict(
                elements=dict(name=dict(
                    description="A name",
                    metaOf="malcolm:core/String:1.0",
                ), ),
                required=["name"],
            ),
            defaults={},
            returns=dict(
                elements=dict(greeting=dict(
                    description="A greeting",
                    metaOf="malcolm:core/String:1.0",
                ), ),
                required=["response"],
            ),
        ), )

        def f(request):
            request.respond_with_return(serialized)

        self.comms.q.put.side_effect = f
        self.cc = ClientController(self.p, self.b, self.comms)
Exemplo n.º 26
0
 def setUp(self):
     self.sf = SyncFactory("sync")
     self.process = Process("proc", self.sf)
     block = Block()
     HelloController(self.process, block,'hello')
     self.sc = WSServerComms("sc", self.process, self.socket)
     self.process.start()
     self.sc.start()
Exemplo n.º 27
0
 def test_add_block_calls_handle(self):
     s = SyncFactory("sched")
     p = Process("proc", s)
     b = Block()
     b.set_parent(p, "myblock")
     p.add_block(b)
     p.start()
     p.stop()
     self.assertEqual(len(p._blocks), 2)
     self.assertEqual(p._blocks, dict(myblock=b, proc=p.process_block))
Exemplo n.º 28
0
    def test_overlapped_changes(self):
        block = MagicMock(
            to_dict=MagicMock(return_value={"attr": "value", "attr2": "other"}))
        block.name = "block"
        sub_1 = MagicMock()
        sub_1.endpoint = ["block"]
        sub_1.delta = False
        sub_2 = MagicMock()
        sub_2.endpoint = ["block"]
        sub_2.delta = True
        changes_1 = [["block", "attr"], "changing_value"]
        changes_2 = [["block", "attr"], "final_value"]
        request_1 = BlockChanged(changes_1)
        request_2 = BlockChanged(changes_2)
        request_3 = BlockNotify(block.name)
        s = MagicMock()
        p = Process("proc", s)
        p._subscriptions["block"] = [sub_1, sub_2]
        p.q.get = MagicMock(
            side_effect=[request_1, request_2, request_3, PROCESS_STOP])

        p._handle_block_add(BlockAdd(block))
        p.recv_loop()

        self.assertEqual(sub_1.response_queue.put.call_count, 1)
        self.assertEqual(sub_2.response_queue.put.call_count, 1)
        response_1 = sub_1.response_queue.put.call_args[0][0]
        response_2 = sub_2.response_queue.put.call_args[0][0]
        self.assertEquals({"attr": "final_value", "attr2": "other"},
                          response_1.value)
        self.assertEquals(
            [[["attr"], "changing_value"], [["attr"], "final_value"]],
            response_2.changes)
Exemplo n.º 29
0
    def test_partial_structure_subscriptions(self):
        block_1 = MagicMock(to_dict=MagicMock(return_value={
            "attr": "value",
            "inner": {
                "attr2": "value"
            }
        }))
        block_2 = MagicMock(to_dict=MagicMock(return_value={"attr": "value"}))

        sub_1 = MagicMock()
        sub_1.endpoint = ["block_1", "inner"]
        sub_1.delta = False
        sub_2 = MagicMock()
        sub_2.endpoint = ["block_1", "inner"]
        sub_2.delta = True

        changes_1 = [[["block_1", "inner", "attr2"], "new_value"],
                     [["block_1", "attr"], "new_value"]]
        changes_2 = [[["block_2", "attr"], "block_2_value"]]
        request_1 = BlockChanges(changes_1)
        request_2 = BlockChanges(changes_2)
        p = Process("proc", MagicMock())
        p.q.get = MagicMock(side_effect=[request_1, request_2, PROCESS_STOP])
        p._subscriptions = [sub_1, sub_2]

        p._handle_block_add(BlockAdd(block_1, "block_1"))
        p._handle_block_add(BlockAdd(block_2, "block_2"))
        p.recv_loop()

        response_1 = sub_1.respond_with_update.call_args[0][0]
        response_2 = sub_2.respond_with_delta.call_args[0][0]
        self.assertEquals({"attr2": "new_value"}, response_1)
        self.assertEquals([[["attr2"], "new_value"]], response_2)
Exemplo n.º 30
0
 def test_hello_controller_with_process(self):
     sync_factory = SyncFactory("sched")
     process = Process("proc", sync_factory)
     block = Block("hello")
     HelloController(block)
     process.add_block(block)
     process.start()
     q = sync_factory.create_queue()
     req = Request.Post(response_queue=q, context="ClientConnection",
                        endpoint=["hello", "say_hello"],
                        parameters=dict(name="thing"))
     req.set_id(44)
     process.q.put(req)
     resp = q.get(timeout=1)
     self.assertEqual(resp.id_, 44)
     self.assertEqual(resp.context, "ClientConnection")
     self.assertEqual(resp.type_, "Return")
     self.assertEqual(resp.value, dict(greeting="Hello thing"))
Exemplo n.º 31
0
 def setUp(self):
     super(TestSystemWSCommsServerAndClient, self).setUp()
     self.process2 = Process("proc2", self.sf)
     self.block2 = Block()
     ClientController(self.process2, self.block2, 'hello')
     self.cc = WSClientComms("cc", self.process2, "ws://localhost:%s/ws" %
                             self.socket)
     self.process2.start()
     self.cc.start()
Exemplo n.º 32
0
 def test_make_process_block(self):
     p = Process("proc", MagicMock())
     p_block = p.process_block
     self.assertEquals(p_block.process_path, ["proc"])
     self.assertEquals(NTScalarArray, type(p_block["blocks"]))
     self.assertEquals(StringArrayMeta, type(p_block["blocks"].meta))
     self.assertEquals(("proc", ), p_block.blocks)
     self.assertEquals("Blocks hosted by this Process",
                       p_block["blocks"].meta.description)
Exemplo n.º 33
0
 def setUp(self):
     sync_factory = SyncFactory("sync")
     self.process = Process("proc", sync_factory)
     block = Block("hello")
     self.process.add_block(block)
     HelloController(block)
     self.sc = WSServerComms("sc", self.process, 8888)
     self.process.start()
     self.sc.start()
Exemplo n.º 34
0
 def setUp(self):
     # Spawn ds under cothread
     self.ds = DirectoryService(["zmq://ipc:///tmp/sock.ipc"])
     self.ds.run(block=False)
     self.lp = Process(
         [], "Local Process", ds_string="zmq://ipc:///tmp/sock.ipc")
     self.lp.run(block=False)
     self.lp.ds.createCounter(name="The Counter")
     self.c = self.lp.get_device("The Counter")
Exemplo n.º 35
0
 def test_add_block_calls_handle(self):
     s = SyncFactory("sched")
     p = Process("proc", s)
     b = MagicMock()
     b.name = "myblock"
     p.add_block("myblock", b)
     p.start()
     p.stop()
     b.set_parent.assert_called_once_with(p, "myblock")
     self.assertEqual(len(p._blocks), 2)
     self.assertEqual(p._blocks, dict(myblock=b, proc=p.process_block))
Exemplo n.º 36
0
class TestSystemWSCommsServerOnly(unittest.TestCase):
    socket = 8881

    def setUp(self):
        self.sf = SyncFactory("sync")
        self.process = Process("proc", self.sf)
        block = Block()
        HelloController(self.process, block,'hello')
        self.sc = WSServerComms("sc", self.process, self.socket)
        self.process.start()
        self.sc.start()

    def tearDown(self):
        self.sc.stop()
        self.sc.wait()
        self.process.stop()


    @gen.coroutine
    def send_message(self):
        conn = yield websocket_connect("ws://localhost:%s/ws" % self.socket)
        req = dict(
            type="Post",
            id=0,
            endpoint=["hello", "say_hello"],
            parameters=dict(
                name="me"
            )
        )
        conn.write_message(json.dumps(req))
        resp = yield conn.read_message()
        resp = json.loads(resp)
        self.assertEqual(resp, dict(
            id=0,
            type="Return",
            value=dict(
                greeting="Hello me"
            )
        ))
        conn.close()

    def test_server_and_simple_client(self):
        self.send_message()
Exemplo n.º 37
0
 def test_get_block(self):
     p = Process("proc", MagicMock())
     p.process_block["remoteBlocks"].set_value(['name1'])
     b1 = p.get_block("name1")
     self.assertEqual(b1.status, "Waiting for connection...")
     self.assertEqual(p.get_block("name1"), b1)
     b2 = Block()
     b2.set_process_path(p, ("name2", ))
     c = MagicMock()
     p.add_block(b2, c)
     self.assertEqual(p.get_block("name2"), b2)
     self.assertEqual(p.get_controller("name2"), c)
Exemplo n.º 38
0
    def test_partial_structure_subscriptions(self):
        block_1 = MagicMock(
            to_dict=MagicMock(
                return_value={"attr": "value", "inner": {"attr2": "value"}}))
        block_2 = MagicMock(
            to_dict=MagicMock(return_value={"attr": "value"}))

        sub_1 = Subscribe(None, MagicMock(), ["block_1", "inner"], delta=False)
        sub_1.set_id(1)
        sub_1.response_queue.qsize.return_value = 0

        sub_2 = Subscribe(None, MagicMock(), ["block_1"], delta=True)
        sub_2.set_id(2)
        sub_2.response_queue.qsize.return_value = 0

        sub_3 = Subscribe(None, MagicMock(), ["block_1", "inner", "attr2"],
                          delta=False)
        sub_3.set_id(3)
        sub_3.response_queue.qsize.return_value = 0

        changes_1 = [[["block_1", "inner", "attr2"], "new_value"],
                     [["block_1", "attr"], "new_value"]]
        changes_2 = [[["block_2", "attr"], "block_2_value"]]
        request_1 = BlockChanges(changes_1)
        request_2 = BlockChanges(changes_2)
        p = Process("proc", MagicMock())
        p.q.get = MagicMock(side_effect=[
            sub_1, sub_2, sub_3, request_1, request_2,
            PROCESS_STOP])

        p._handle_block_add(BlockAdd(block_1, "block_1", None))
        p._handle_block_add(BlockAdd(block_2, "block_2", None))
        p.recv_loop()

        response_1 = sub_1.response_queue.put.call_args_list[1][0][0]["value"]
        self.assertEquals({"attr2": "new_value"}, response_1)

        response_2 = sub_2.response_queue.put.call_args_list[1][0][0]["changes"]
        self.assertEquals([[["inner", "attr2"], "new_value"],
                           [["attr"], "new_value"]], response_2)

        response_3 = sub_3.response_queue.put.call_args_list[1][0][0]["value"]
        self.assertEquals("new_value", response_3)
Exemplo n.º 39
0
 def test_starting_process(self):
     s = SyncFactory("sched")
     p = Process("proc", s)
     b = MagicMock()
     p._handle_block_add(BlockAdd(b, "myblock", None))
     self.assertEqual(p._blocks, dict(myblock=b, proc=ANY))
     p.start()
     request = Post(MagicMock(), MagicMock(), ["myblock", "foo"])
     p.q.put(request)
     # wait for spawns to have done their job
     p.stop()
     b.handle_request.assert_called_once_with(request)
Exemplo n.º 40
0
 def test_make_process_block(self):
     p = Process("proc", MagicMock())
     p_block = p.process_block
     self.assertEquals(p.name, p_block.name)
     self.assertEquals(Attribute, type(p_block.blocks))
     self.assertEquals(StringArrayMeta, type(p_block.blocks.meta))
     self.assertEquals("blocks", p_block.blocks.name)
     self.assertEquals("meta", p_block.blocks.meta.name)
     self.assertEquals("Blocks hosted by this Process",
                       p_block.blocks.meta.description)
Exemplo n.º 41
0
 def test_hello_with_process(self):
     sync_factory = SyncFactory("sched")
     process = Process("proc", sync_factory)
     b = Hello(process, dict(mri="hello"))[0]
     process.start()
     # wait until block is Ready
     task = Task("hello_ready_task", process)
     task.when_matches(b["state"], "Ready", timeout=1)
     q = sync_factory.create_queue()
     req = Post(response_queue=q, context="ClientConnection",
                endpoint=["hello", "greet"],
                parameters=dict(name="thing"))
     req.set_id(44)
     process.q.put(req)
     resp = q.get(timeout=1)
     self.assertEqual(resp.id, 44)
     self.assertEqual(resp.context, "ClientConnection")
     self.assertEqual(resp.typeid, "malcolm:core/Return:1.0")
     self.assertEqual(resp.value["greeting"], "Hello thing")
     process.stop()
Exemplo n.º 42
0
    def test_subscribe(self):
        block = MagicMock(to_dict=MagicMock(return_value={
            "attr": "value",
            "inner": {
                "attr2": "other"
            }
        }))
        p = Process("proc", MagicMock())
        sub_1 = Subscribe(MagicMock(), MagicMock(), ["block"], False)
        sub_1.response_queue.qsize.return_value = 0
        sub_2 = Subscribe(MagicMock(), MagicMock(), ["block", "inner"], True)
        sub_2.response_queue.qsize.return_value = 0
        p.q.get = MagicMock(side_effect=[sub_1, sub_2, PROCESS_STOP])

        p._handle_block_add(BlockAdd(block, "block", None))
        p.recv_loop()

        self.assertEquals([sub_1, sub_2], list(p._subscriptions.values()))
        response_1 = sub_1.response_queue.put.call_args[0][0]
        response_2 = sub_2.response_queue.put.call_args[0][0]
        self.assertEquals({
            "attr": "value",
            "inner": {
                "attr2": "other"
            }
        }, response_1.value)
        self.assertEquals([[[], {"attr2": "other"}]], response_2.changes)
Exemplo n.º 43
0
    def test_counter_subscribe(self):
        sync_factory = SyncFactory("sched")
        process = Process("proc", sync_factory)
        b = Counter(process, dict(mri="counting"))[0]
        process.start()
        # wait until block is Ready
        task = Task("counter_ready_task", process)
        task.when_matches(b["state"], "Ready", timeout=1)
        q = sync_factory.create_queue()

        sub = Subscribe(response_queue=q, context="ClientConnection",
                        endpoint=["counting", "counter"],
                        delta=False)
        process.q.put(sub)
        resp = q.get(timeout=1)
        self.assertIsInstance(resp, Update)
        attr = NTScalar.from_dict(resp.value)
        self.assertEqual(0, attr.value)

        post = Post(response_queue=q, context="ClientConnection",
                    endpoint=["counting", "increment"])
        process.q.put(post)

        resp = q.get(timeout=1)
        self.assertIsInstance(resp, Update)
        self.assertEqual(resp.value["value"], 1)
        resp = q.get(timeout=1)
        self.assertIsInstance(resp, Return)

        process.stop()
Exemplo n.º 44
0
def make_client():
    parser = argparse.ArgumentParser(
        description="Interactive client shell for malcolm")
    parser.add_argument('server',
                        help="Server string for connection to malcolm "
                        "directory server like 172.23.243.13:5600")
    parser.add_argument('--log', default="INFO",
                        help="Lowest level of logs to see. One of: "
                        "ERROR, WARNING, INFO, DEBUG. "
                        "Default is INFO")
    args = parser.parse_args()
    # assuming loglevel is bound to the string value obtained from the
    # command line argument. Convert to upper case to allow the user to
    # specify --log=DEBUG or --log=debug
    numeric_level = getattr(logging, args.log.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % args.log)
    logging.basicConfig(level=numeric_level)
    ds_string = "zmq://tcp://{}".format(args.server)
    client = Process([], "iMalcolmClient", ds_string=ds_string)
    client.DeviceClient = IDeviceClient
    return client
Exemplo n.º 45
0
    def test_subscribe(self):
        block = MagicMock(
            to_dict=MagicMock(
                return_value={"attr": "value", "inner": {"attr2": "other"}}))
        block.name = "block"
        p = Process("proc", MagicMock())
        sub_1 = Subscribe(
            MagicMock(), MagicMock(), ["block"], False)
        sub_2 = Subscribe(
            MagicMock(), MagicMock(), ["block", "inner"], True)
        p.q.get = MagicMock(side_effect=[sub_1, sub_2, PROCESS_STOP])

        p._handle_block_add(BlockAdd(block))
        p.recv_loop()

        self.assertEquals(OrderedDict(block=[sub_1, sub_2]),
                          p._subscriptions)
        response_1 = sub_1.response_queue.put.call_args[0][0]
        response_2 = sub_2.response_queue.put.call_args[0][0]
        self.assertEquals({"attr": "value", "inner": {"attr2": "other"}},
                          response_1.value)
        self.assertEquals([[[], {"attr2": "other"}]], response_2.changes)
Exemplo n.º 46
0
class ZmqSystemTest(unittest.TestCase):
    # class ZmqSystemTest(object):

    def setUp(self):
        # Spawn ds under cothread
        self.ds = DirectoryService(["zmq://ipc:///tmp/sock.ipc"])
        self.ds.run(block=False)
        self.lp = Process(
            [], "Local Process", ds_string="zmq://ipc:///tmp/sock.ipc")
        self.lp.run(block=False)
        self.lp.ds.createCounter(name="The Counter")
        self.c = self.lp.get_device("The Counter")

    def test_simple_function(self):
        import cothread
        cothread.Sleep(0.2)
        start = self.c.getCount()
        self.assertEqual(self.c.hello(), "world")
        # Hello world takes about 10 ticks
        self.assertAlmostEqual(self.c.getCount(), start + 10, delta=3)
        # Do a long running call
        s = cothread.Spawn(self.c.longHello)
        # Check it returns immediately
        self.assertAlmostEqual(self.c.getCount(), start + 10, delta=3)
        self.assertEqual(self.c.hello(), "world")
        # Hello world takes 10 ticks
        self.assertAlmostEqual(self.c.getCount(), start + 20, delta=3)
        self.assertEqual(s.Wait(), "long world")
        # Long hello takes about 50 ticks from send
        self.assertAlmostEqual(self.c.getCount(), start + 60, delta=8)
        s.Wait()

    def tearDown(self):
        self.c = None
        self.lp.ds.exit()
        self.lp.exit()
        self.lp = None
        self.ds.loop_wait()
        self.ds = None
Exemplo n.º 47
0
 def test_add_block_calls_handle(self):
     s = SyncFactory("sched")
     p = Process("proc", s)
     b = Block()
     c = MagicMock()
     b.set_process_path(p, ("myblock",))
     p.add_block(b, c)
     p.start()
     p.stop()
     self.assertEqual(len(p._blocks), 2)
     self.assertEqual(p._blocks, dict(myblock=b, proc=p.process_block))
Exemplo n.º 48
0
 def test_starting_process(self):
     s = SyncFactory("sched")
     p = Process("proc", s)
     b = MagicMock()
     p._handle_block_add(BlockAdd(b, "myblock", None))
     self.assertEqual(p._blocks, dict(myblock=b, proc=ANY))
     p.start()
     request = Post(MagicMock(), MagicMock(), ["myblock", "foo"])
     p.q.put(request)
     # wait for spawns to have done their job
     p.stop()
     b.handle_request.assert_called_once_with(request)
Exemplo n.º 49
0
 def test_get_block(self):
     p = Process("proc", MagicMock())
     p.process_block["remoteBlocks"].set_value(['name1'])
     b1 = p.get_block("name1")
     self.assertEqual(b1.status, "Waiting for connection...")
     self.assertEqual(p.get_block("name1"), b1)
     b2 = Block()
     b2.set_process_path(p, ("name2",))
     c = MagicMock()
     p.add_block(b2, c)
     self.assertEqual(p.get_block("name2"), b2)
     self.assertEqual(p.get_controller("name2"), c)
Exemplo n.º 50
0
    def test_unsubscribe(self):
        # Test that we remove the relevant subscription only and that
        # updates are no longer sent
        block = MagicMock(
            to_dict=MagicMock(
                return_value={"attr": "0", "inner": {"attr2": "other"}}))
        p = Process("proc", MagicMock())
        sub_1 = Subscribe(
            MagicMock(), MagicMock(), ["block"], False)
        sub_1.response_queue.qsize.return_value = 0
        sub_2 = Subscribe(
            MagicMock(), MagicMock(), ["block"], False)
        sub_2.response_queue.qsize.return_value = 0
        sub_1.set_id(1234)
        sub_2.set_id(1234)
        change_1 = BlockChanges([[["block", "attr"], "1"]])
        change_2 = BlockChanges([[["block", "attr"], "2"]])
        unsub_1 = Unsubscribe(sub_1.context, sub_1.response_queue)
        unsub_1.set_id(sub_1.id)

        p.q.get = MagicMock(side_effect=[sub_1, sub_2, change_1,
                                         unsub_1, change_2, PROCESS_STOP])
        p._handle_block_add(BlockAdd(block, "block", None))
        p.recv_loop()

        self.assertEqual([sub_2], list(p._subscriptions.values()))

        sub_1_responses = sub_1.response_queue.put.call_args_list
        sub_2_responses = sub_2.response_queue.put.call_args_list
        self.assertEquals(3, len(sub_1_responses))
        self.assertEquals(sub_1_responses[0][0][0].value["attr"], "0")
        self.assertEquals(sub_1_responses[1][0][0].value["attr"], "1")
        self.assertIsInstance(sub_1_responses[2][0][0], Return)
        self.assertEquals(3, len(sub_2_responses))
        self.assertEquals(sub_2_responses[0][0][0].value["attr"], "0")
        self.assertEquals(sub_2_responses[1][0][0].value["attr"], "1")
        self.assertEquals(sub_2_responses[2][0][0].value["attr"], "2")