ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How do I test a service caller in python?

asked 2015-10-15 16:39:48 -0600

dustingooding gravatar image

updated 2015-10-15 16:41:49 -0600

I have a python class that has a method that calls a ROS service. I'd like to test that class's method. My going in approach is to create a mock service, call it, and validate the calls are working.

# my_package/src/my_package/
class Foo(object):
    def bar(self, req):
            send_request = rospy.ServiceProxy('service_name', MyService)
            resp = send_request(req)
            return resp
        except rospy.ServiceException, e:
            logging.error('[service_name] service call failed: %s' % e)

I've set up a test file that creates a Foo object in a unittest fixture, starts creates a node and service in the main and calls the unit testing framework.

# my_package/test/
class FooTest(unittest.TestCase):

    def setUp(self):

    def tearDown(self):

    def test_bar(self):
        f = Foo()
        req = MyServiceRequest()

def mock_baz_callback(req):
    res = MyServiceResponse()
    res.ok = True
    return res

if __name__ == "__main__":
    s = rospy.Service('my_service', MyService, mock_baz_callback)

    # unittest.main() doesn't start roscore
    import rostest
    rostest.rosrun('my_package', 'my_test', FooTest)

Using unittest.main() doesn't work, because roscore isn't started automatically. I assumed rostest would work better, but I'm unable to get it working. It appears to hang waiting for wait_for_service() to complete, which tells me either the Service in the main isn't starting or the test roscore isn't starting.

  <test test-name="my_test" pkg="my_package" type="" />

Do I need to make the mock service a stand-alone node that the launch file starts? I'd rather not have to...

Edit: If I manually start roscore and rosrun the test file directly, the test passes.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2015-10-15 19:15:29 -0600

dustingooding gravatar image

I ended up just moving the service to a separate ROS node, spinning it up in the .test file, and moving on with life. If someone has a better option for a single file test, I'd love to hear it.

edit flag offensive delete link more

Question Tools



Asked: 2015-10-15 16:39:48 -0600

Seen: 1,820 times

Last updated: Oct 15 '15