Example #1
0
    def test_args_kwds_to_message(self):
        import rospy
        from rospy.msg import args_kwds_to_message
        from test_rospy.msg import Val, Empty

        v = Val('hello world-1')
        d = args_kwds_to_message(Val, (v, ), None)
        self.assert_(d == v)
        d = args_kwds_to_message(Val, ('hello world-2', ), None)
        self.assertEquals(d.val, 'hello world-2')
        d = args_kwds_to_message(Val, (), {'val': 'hello world-3'})
        self.assertEquals(d.val, 'hello world-3')

        # error cases
        try:
            args_kwds_to_message(Val, 'hi', val='hello world-3')
            self.fail("should not allow args and kwds")
        except TypeError:
            pass
        try:
            args_kwds_to_message(Empty, (Val('hola'), ), None)
            self.fail(
                "should raise TypeError when publishing Val msg to Empty topic"
            )
        except TypeError:
            pass
Example #2
0
    def test_String_String(self):
        from std_msgs.msg import String
        from test_rospy.srv import StringString, StringStringRequest
        from test_rospy.msg import Val
        Cls = StringString
        Req = StringStringRequest

        for name in [STRING_CAT_SERVICE_NAKED, STRING_CAT_SERVICE_WRAPPED]:
            resp_req = self._test(name, Cls, Req(String('FOO'), Val('bar')))
            resp_req_naked = self._test_req_naked(name, Cls, (String('FOO'), Val('bar'),))
            resp_req_kwds = self._test_req_kwds(name, Cls, {'str': String('FOO'), 'str2': Val('bar')})
            for resp in [resp_req, resp_req_naked, resp_req_kwds]:
                self.assertEquals('FOObar', resp.str.data)
Example #3
0
    def test_String_String_unicode(self):
        from std_msgs.msg import String
        from test_rospy.srv import StringString, StringStringRequest
        from test_rospy.msg import Val
        Cls = StringString
        Req = StringStringRequest

        for name in [STRING_CAT_SERVICE_NAKED, STRING_CAT_SERVICE_WRAPPED]:
            resp_req = self._test(name, Cls, Req(String(u'ロボット'), Val(u'机器人')))
            resp_req_naked = self._test_req_naked(name, Cls, (
                String(u'ロボット'),
                Val(u'机器人'),
            ))
            resp_req_kwds = self._test_req_kwds(name, Cls, {
                'str': String(u'ロボット'),
                'str2': Val(u'机器人')
            })
            for resp in [resp_req, resp_req_naked, resp_req_kwds]:
                self.assertEquals(
                    'ロボット机器人', resp.str.data
                )  # if you send in unicode, you'll receive in str
Example #4
0
    def test_args_kwds_to_message(self):
        import rospy
        from rospy.msg import args_kwds_to_message
        from test_rospy.msg import Val

        v = Val('hello world-1')
        d = args_kwds_to_message(Val, (v, ), None)
        self.assert_(d == v)
        d = args_kwds_to_message(Val, ('hello world-2', ), None)
        self.assertEquals(d.val, 'hello world-2')
        d = args_kwds_to_message(Val, (), {'val': 'hello world-3'})
        self.assertEquals(d.val, 'hello world-3')

        # error cases
        try:
            args_kwds_to_message(Val, 'hi', val='hello world-3')
            self.fail("should not allow args and kwds")
        except TypeError:
            pass
Example #5
0
    def test_serialize_message(self):
        import rospy.msg
        import rospy.rostime
        # have to fake-init rostime so that Header can be stamped
        rospy.rostime.set_rostime_initialized(True)

        buff = StringIO()
        seq = random.randint(1, 1000)

        #serialize_message(seq, msg)
        from test_rospy.msg import Val

        #serialize a simple 'Val' with a string in it
        teststr = 'foostr-%s' % time.time()
        val = Val(teststr)

        fmt = "<II%ss" % len(teststr)
        size = struct.calcsize(fmt) - 4
        valid = struct.pack(fmt, size, len(teststr), teststr)

        rospy.msg.serialize_message(buff, seq, val)

        self.assertEquals(valid, buff.getvalue())

        #test repeated serialization
        rospy.msg.serialize_message(buff, seq, val)
        rospy.msg.serialize_message(buff, seq, val)
        self.assertEquals(valid * 3, buff.getvalue())

        # - once more just to make sure that the buffer position is
        # being preserved properly
        buff.seek(0)
        rospy.msg.serialize_message(buff, seq, val)
        self.assertEquals(valid * 3, buff.getvalue())
        rospy.msg.serialize_message(buff, seq, val)
        self.assertEquals(valid * 3, buff.getvalue())
        rospy.msg.serialize_message(buff, seq, val)
        self.assertEquals(valid * 3, buff.getvalue())

        #test sequence parameter
        buff.truncate(0)

        from test_rospy.msg import HeaderVal
        t = rospy.Time.now()
        t.secs = t.secs - 1  # move it back in time
        h = rospy.Header(None, rospy.Time.now(), teststr)
        h.stamp = t
        val = HeaderVal(h, teststr)
        seq += 1

        rospy.msg.serialize_message(buff, seq, val)
        self.assertEquals(val.header, h)
        self.assertEquals(seq, h.seq)
        #should not have been changed
        self.assertEquals(t, h.stamp)
        self.assertEquals(teststr, h.frame_id)

        #test frame_id setting
        h.frame_id = None
        rospy.msg.serialize_message(buff, seq, val)
        self.assertEquals(val.header, h)
        self.assertEquals('0', h.frame_id)
Example #6
0
    def test_embed_msg(self):
        self.assert_(self.callback_data is None, "invalid test fixture")

        # wait at most 5 seconds for listenerpublisher to be registered
        timeout_t = time.time() + 5.0
        while not rostest.is_subscriber(
                rospy.resolve_name(PUBTOPIC),
                rospy.resolve_name(LPNODE)) and time.time() < timeout_t:
            time.sleep(0.1)

        self.assert_(
            rostest.is_subscriber(rospy.resolve_name(PUBTOPIC),
                                  rospy.resolve_name(LPNODE)),
            "%s is not up" % LPNODE)

        print("Publishing to ", PUBTOPIC)
        pub = rospy.Publisher(PUBTOPIC, MSG, queue_size=0)
        rospy.Subscriber(LPTOPIC, MSG, self._test_embed_msg_callback)

        # publish about 10 messages for fun
        import random
        val = random.randint(0, 109812312)
        msg = "hi [%s]" % val
        for i in range(0, 10):
            # The test message could be better in terms of the values
            # it assigns to leaf fields, but the main focus is trying
            # to dig up edge conditions in the embeds, especially with
            # respect to arrays and embeds.
            pub.publish(
                MSG(
                    String(msg),
                    Int32(val),
                    [Int32(val + 1),
                     Int32(val + 2),
                     Int32(val + 3)],
                    Val(msg + msg),
                    [Val(msg), Val("two")],
                    [
                        ArrayVal([Val("av1"), Val("av2")
                                  ]),  #[Val("%s"%i) for i in range(0, 10)]),
                        ArrayVal([])  #,[Val("%s"%i) for i in range(0, 10)]),
                    ]))
            time.sleep(0.1)

        # listenerpublisher is supposed to repeat our messages back onto /listenerpublisher,
        # make sure we got it
        self.assert_(self.callback_data is not None,
                     "no callback data from listenerpublisher")
        print("Got ", self.callback_data.str1.data,
              self.callback_data.int1.data)
        errorstr = "callback msg field [%s] from listenerpublisher does not match"
        self.assertEquals(msg, self.callback_data.str1.data,
                          errorstr % "str1.data")
        self.assertEquals(val, self.callback_data.int1.data,
                          errorstr % "int1.data")
        for i in range(1, 4):
            self.assertEquals(val + i, self.callback_data.ints[i - 1].data,
                              errorstr % "ints[i-1].data")
        self.assertEquals(msg + msg, self.callback_data.val.val,
                          errorstr % "val.val")
        self.assertEquals(msg, self.callback_data.vals[0].val,
                          errorstr % "vals[0].val")
        self.assertEquals("two", self.callback_data.vals[1].val,
                          errorstr % "vals[1].val")
        # #435: test array of arrays
        self.assertEquals(2, len(self.callback_data.arrayval),
                          errorstr % "len arrayval")
        self.assertEquals(2, len(self.callback_data.arrayval[0].vals),
                          errorstr % "len arrayval[0].vals")
        self.assertEquals("av1", self.callback_data.arrayval[0].vals[0].val,
                          errorstr % "arrayval[0].vals[0].val")
        self.assertEquals("av2", self.callback_data.arrayval[0].vals[1].val,
                          errorstr % "arrayval[0].vals[1].val")
        self.assertEquals(0, len(self.callback_data.arrayval[1].vals),
                          errorstr % "len arrayval[1].vals")
Example #7
0
    def test_Publisher(self):
        import rospy
        from rospy.impl.registration import get_topic_manager, Registration
        from rospy.topics import Publisher, DEFAULT_BUFF_SIZE
        # Publisher(self, name, data_class, subscriber_listener=None, tcp_nodelay=False, latch=False, headers=None)

        name = 'foo'
        rname = rospy.resolve_name('foo')
        data_class = test_rospy.msg.Val

        # test invalid params
        for n in [None, '', 1]:
            try:
                Publisher(n, data_class)
                self.fail("should not allow invalid name")
            except ValueError:
                pass
        for d in [None, 1, TestRospyTopics]:
            try:
                Publisher(name, d)
                self.fail("should now allow invalid data_class")
            except ValueError:
                pass
        try:
            Publisher(name, None)
            self.fail("None should not be allowed for data_class")
        except ValueError:
            pass

        # round 1: test basic params
        pub = Publisher(name, data_class)
        self.assertEquals(rname, pub.resolved_name)
        # - pub.name is left in for backwards compatiblity, but resolved_name is preferred
        self.assertEquals(rname, pub.name)
        self.assertEquals(data_class, pub.data_class)
        self.assertEquals('test_rospy/Val', pub.type)
        self.assertEquals(data_class._md5sum, pub.md5sum)
        self.assertEquals(Registration.PUB, pub.reg_type)

        # verify impl as well
        impl = get_topic_manager().get_impl(Registration.PUB, rname)
        self.assert_(impl == pub.impl)
        self.assertEquals(rname, impl.resolved_name)
        self.assertEquals(data_class, impl.data_class)
        self.failIf(impl.is_latch)
        self.assertEquals(None, impl.latch)
        self.assertEquals(0, impl.seq)
        self.assertEquals(1, impl.ref_count)
        self.assertEquals('', impl.buff.getvalue())
        self.failIf(impl.closed)
        self.failIf(impl.has_connections())
        # check publish() fall-through
        from test_rospy.msg import Val
        impl.publish(Val('hello world-1'))

        # check stats
        self.assertEquals(0, impl.message_data_sent)
        # check acquire/release don't bomb
        impl.acquire()
        impl.release()

        # do a single publish with connection override. The connection
        # override is a major cheat as the object isn't even an actual
        # connection. I will need to add more integrated tests later
        co1 = ConnectionOverride('co1')
        self.failIf(impl.has_connection('co1'))
        impl.add_connection(co1)
        self.assert_(impl.has_connection('co1'))
        self.assert_(impl.has_connections())
        impl.publish(Val('hello world-1'), connection_override=co1)

        import cStringIO
        buff = cStringIO.StringIO()
        Val('hello world-1').serialize(buff)
        # - check equals, but strip length field first
        self.assertEquals(co1.data[4:], buff.getvalue())
        self.assertEquals(None, impl.latch)

        # Now enable latch
        pub = Publisher(name, data_class, latch=True)
        impl = get_topic_manager().get_impl(Registration.PUB, rname)
        # have to verify latching in pub impl
        self.assert_(impl == pub.impl)
        self.assertEquals(True, impl.is_latch)
        self.assertEquals(None, impl.latch)
        self.assertEquals(2, impl.ref_count)

        co2 = ConnectionOverride('co2')
        self.failIf(impl.has_connection('co2'))
        impl.add_connection(co2)
        for n in ['co1', 'co2']:
            self.assert_(impl.has_connection(n))
        self.assert_(impl.has_connections())
        v = Val('hello world-2')
        impl.publish(v, connection_override=co2)
        self.assert_(v == impl.latch)

        buff = cStringIO.StringIO()
        Val('hello world-2').serialize(buff)
        # - strip length and check value
        self.assertEquals(co2.data[4:], buff.getvalue())

        # test that latched value is sent to connections on connect
        co3 = ConnectionOverride('co3')
        self.failIf(impl.has_connection('co3'))
        impl.add_connection(co3)
        for n in ['co1', 'co2', 'co3']:
            self.assert_(impl.has_connection(n))
        self.assert_(impl.has_connections())
        self.assertEquals(co3.data[4:], buff.getvalue())

        # TODO: tcp_nodelay
        # TODO: suscribe listener
        self.assert_(impl.has_connection('co1'))
        impl.remove_connection(co1)
        self.failIf(impl.has_connection('co1'))
        self.assert_(impl.has_connections())
        # TODO: need to validate DeadTransport better
        self.assert_(
            [d for d in impl.dead_connections if d.endpoint_id == 'co1'])

        self.assert_(impl.has_connection('co3'))
        impl.remove_connection(co3)
        self.failIf(impl.has_connection('co3'))
        self.assert_(impl.has_connections())
        for id in ['co1', 'co3']:
            self.assert_(
                [d for d in impl.dead_connections if d.endpoint_id == id])

        self.assert_(impl.has_connection('co2'))
        impl.remove_connection(co2)
        self.failIf(impl.has_connection('co2'))
        self.failIf(impl.has_connections())
        for id in ['co1', 'co2', 'co3']:
            self.assert_(
                [d for d in impl.dead_connections if d.endpoint_id == id])

        # test publish() latch on a new Publisher object (this was encountered in testing, so I want a test case for it)
        pub = Publisher('bar', data_class, latch=True)
        v = Val('no connection test')
        pub.impl.publish(v)
        self.assert_(v == pub.impl.latch)

        # test connection header
        h = {'foo': 'bar', 'fuga': 'hoge'}
        pub = Publisher('header_test', data_class, headers=h)
        self.assertEquals(h, pub.impl.headers)