def test_spin(self): failed = True try: rospy.spin() except rospy.ROSInitException: failed = False self.failIf(failed, "spin() should failed if not initialized") def test_myargv(self): orig_argv = sys.argv try: from rospy.client import myargv args = myargv() self.assertEquals(args, sys.argv) self.assertEquals(['foo', 'bar', 'baz'], myargv(['foo', 'bar', 'baz'])) self.assertEquals(['-foo', 'bar', '-baz'], myargv(['-foo', 'bar', '-baz'])) self.assertEquals(['foo'], myargv(['foo', 'bar:=baz'])) self.assertEquals(['foo'], myargv(['foo', '-bar:=baz'])) finally: sys.argv = orig_argv if __name__ == '__main__': rostest.unitrun('test_rospy', sys.argv[0], TestRospyClient, coverage_packages=['rospy.client'])
self.failIf("Subscribed topics:" in v) # test with multiple topic names try: rostopic.rostopicmain([cmd, 'list', 'rosout', 'rosout_agg']) self.fail("should have caused parser error") except SystemExit: pass # test with resolved names for n in topics: with fakestdout() as b: rostopic.rostopicmain([cmd, 'list', n]) self.assertEquals(n, b.getvalue().strip()) # test with relative names with fakestdout() as b: rostopic.rostopicmain([cmd, 'list', 'rosout']) self.assertEquals('/rosout', b.getvalue().strip()) # test with namespaces with fakestdout() as b: rostopic.rostopicmain([cmd, 'list', '/foo']) self.assertEquals('/foo/chatter', b.getvalue().strip()) with fakestdout() as b: rostopic.rostopicmain([cmd, 'list', 'bar']) self.assertEquals('/bar/chatter', b.getvalue().strip()) if __name__ == '__main__': rostest.unitrun('test_rostopic', NAME, TestRostopic, sys.argv, coverage_packages=['rostopic'])
def test_deflate(self): cb = Checkerboard() param_vec = matrix([10,20], float).T cb.inflate( param_vec ) result = cb.deflate() print "" print result self.assertAlmostEqual(numpy.linalg.norm(result - param_vec), 0.0, 6) def test_generate_points(self): cb = Checkerboard({"corners_x": 2, "corners_y": 3, "spacing_x": 10, "spacing_y": 20 }) result = cb.generate_points() expected = matrix( [ [ 0, 10, 0, 10, 0, 10], [ 0, 0, 20, 20, 40, 40], [ 0, 0, 0, 0, 0, 0], [ 1, 1, 1, 1, 1, 1] ], float) print "" print result self.assertAlmostEqual(numpy.linalg.norm(result - expected), 0.0, 6) def test_get_length(self): cb = Checkerboard() self.assertEqual(cb.get_length(), 2) if __name__ == '__main__': import rostest rostest.unitrun('cob_robot_calibration_est', 'test_Checkerboard', TestCheckerboard, coverage_packages=['cob_robot_calibration_est.checkerboard'])
ret = p() proto = Protocol("test_call_service_works") s = CallService(proto) msg = loads( dumps({ "op": "call_service", "service": "/rosout/get_loggers" })) received = {"msg": None} def cb(msg, cid=None): received["msg"] = msg proto.send = cb s.call_service(msg) time.sleep(0.5) for x, y in zip(ret.loggers, received["msg"]["values"]["loggers"]): self.assertEqual(x.name, y["name"]) self.assertEqual(x.level, y["level"]) PKG = 'rosbridge_library' NAME = 'test_call_service' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestCallService)
import sys import unittest import tf2_py as tf2 import tf2_ros import tf2_geometry_msgs from geometry_msgs.msg import PointStamped import rospy import tf2_kdl import PyKDL class TestConvert(unittest.TestCase): def test_convert(self): p = tf2_ros.Stamped(PyKDL.Vector(1, 2, 3), rospy.Time(), 'my_frame') print(p) msg = tf2_ros.convert(p, PointStamped) print(msg) p2 = tf2_ros.convert(msg, PyKDL.Vector) print(p2) p2[0] = 100 print(p) print(p2) print(p2.header) if __name__ == '__main__': import rostest rostest.unitrun(PKG, 'test_buffer_client', TestConvert)
#!/usr/bin/env python from __future__ import print_function import unittest import rostest from capabilities.client import CapabilitiesClient from capabilities.client import CapabilityNotRunningException TEST_NAME = 'test_client_module' class Test(unittest.TestCase): def test_client_module(self): c = CapabilitiesClient() c.wait_for_services(3) c.use_capability('minimal_pkg/Minimal', 'minimal_pkg/minimal') c.use_capability('minimal_pkg/Minimal', 'minimal_pkg/minimal') c.free_capability('minimal_pkg/Minimal') with self.assertRaises(CapabilityNotRunningException): c.free_capability('not_a_pkg/NotACap') c.shutdown() if __name__ == '__main__': import rospy rospy.init_node(TEST_NAME, anonymous=True) rostest.unitrun('capabilities', TEST_NAME, Test)
self.assert_("%s %s"%(cmd, c) in output[0], "%s: %s"%(c, output[0])) # test no args on commands that require args for c in ['ping', 'info']: output = Popen([cmd, c], stdout=PIPE, stderr=PIPE).communicate() self.assert_("Usage:" in output[0] or "Usage:" in output[1], "[%s]: %s"%(c, output)) def test_offline(self): cmd = 'rosnode' # point at a different 'master' env = os.environ.copy() env['ROS_MASTER_URI'] = 'http://localhost:11312' kwds = { 'env': env, 'stdout': PIPE, 'stderr': PIPE} msg = "ERROR: Unable to communicate with master!\n" output = Popen([cmd, 'list',], **kwds).communicate() self.assert_(msg in output[1]) output = Popen([cmd, 'ping', 'talker'], **kwds).communicate() self.assertEquals(msg, output[1]) output = Popen([cmd, 'info', 'talker'], **kwds).communicate() self.assert_(msg in output[1]) output = Popen([cmd, 'kill', 'talker'], **kwds).communicate() self.assert_(msg in output[1]) if __name__ == '__main__': rostest.unitrun('test_rosnode', NAME, TestRosnodeOffline, sys.argv, coverage_packages=[])
sys.argv = real_argv def test_create_local_xmlrpc_uri(self): from roslib.network import parse_http_host_and_port, create_local_xmlrpc_uri self.assertEquals(type(create_local_xmlrpc_uri(1234)), str) os.environ['ROS_HOSTNAME'] = 'localhost' self.assertEquals(('localhost', 1234), parse_http_host_and_port(create_local_xmlrpc_uri(1234))) def setUp(self): self._ros_hostname = self._ros_ip = None if 'ROS_HOSTNAME' in os.environ: self._ros_hostname = os.environ['ROS_HOSTNAME'] del os.environ['ROS_HOSTNAME'] if 'ROS_IP' in os.environ: self._ros_ip = os.environ['ROS_IP'] del os.environ['ROS_IP'] def tearDown(self): if 'ROS_HOSTNAME' in os.environ: del os.environ['ROS_HOSTNAME'] if 'ROS_IP' in os.environ: del os.environ['ROS_IP'] if self._ros_hostname: os.environ['ROS_HOSTNAME'] = self._ros_hostname if self._ros_ip: os.environ['ROS_IP'] = self._ros_ip if __name__ == '__main__': rostest.unitrun('test_roslib', 'test_network', NetworkTest, coverage_packages=['roslib.network'])
pinged, unpinged = rosnode.rosnode_ping_all(verbose=False) self.assert_('/rosout' in pinged) with fakestdout() as b: pinged, unpinged = rosnode.rosnode_ping_all(verbose=True) self.assert_('xmlrpc reply' in b.getvalue()) self.assert_('/rosout' in pinged) def test_rosnode_kill(self): from ros import rosnode cmd = 'rosnode' for n in ['to_kill/kill1', '/to_kill/kill2']: self.assert_(rosnode.rosnode_ping(n, max_count=1)) rosnode._rosnode_cmd_kill([cmd, 'kill', n]) self.failIf(rosnode.rosnode_ping(n, max_count=1)) def test_fullusage(self): from ros import rosnode try: rosnode._fullusage() except SystemExit: pass try: rosnode.rosnodemain(['rosnode']) except SystemExit: pass try: rosnode.rosnodemain(['rosnode', 'invalid']) except SystemExit: pass if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestRosnode, sys.argv, coverage_packages=['rosnode'])
disappears and there is an event source.""" e = Event() t = e.trigger l = [] e.set_close_cb(l.append, 'closed') h = e.subscribe_repeating(lambda : None) del e self.assertEqual(l, []) h.unsubscribe() self.assertEqual(l, ['closed']) def test_liveness_sensor_with_dropping_source(self): """Tests when the liveness sensor gets set off when the event disappears and there is an event source.""" e = Event() t = e.trigger l = [] e.set_close_cb(l.append, 'closed') h = e.subscribe_repeating(lambda : None) del e self.assertEqual(l, []) del t self.assertEqual(l, ['closed']) if len(sys.argv) > 1 and sys.argv[1].startswith("--gtest_output="): import roslib; roslib.load_manifest('multi_interface_roam') import rostest rostest.unitrun('multi_interface_roam', 'event_basic', BasicTest) else: unittest.main()
PKG = 'life_test' import roslib; roslib.load_manifest(PKG) from life_test.config_loader import * import rostest, unittest import sys class TestManagerConfigCheck(unittest.TestCase): def test_rooms_config(self): rooms = load_rooms_from_file() self.assert_(len(rooms.items()) > 0, "No rooms loaded. This is probably a problem loading the file") def test_tests_config(self): tests = load_tests_from_file() self.assert_(len(tests.items()) > 0, "Tests file didn't load.") for lst in tests.values(): for tst in lst: self.assert_(tst.validate(), "Test %s failed to validated. Launch file may be invalid." % tst.name) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == '-v': suite = unittest.TestSuite() suite.addTest(TestManagerConfigCheck('test_rooms_config')) suite.addTest(TestManagerConfigCheck('test_tests_config')) unittest.TextTestRunner(verbosity = 2).run(suite) else: rostest.unitrun(PKG, 'check_config_files', TestManagerConfigCheck)
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import sys import unittest import rospy import rostest import subprocess class VersionTest(unittest.TestCase): def test_distro_version(self): val = (subprocess.Popen(['rosversion', '-d'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] or '').strip() param = rospy.get_param('rosdistro').strip() self.assertEquals(val, param, "rosversion -d [%s] and roscore [%s] do not match"%(val, param)) if __name__ == '__main__': rostest.unitrun('test_rostest', 'test_distro_version', VersionTest, coverage_packages=[])
h = block.compute_expected(target) z = block.get_measurement() r = block.compute_residual(target) self.assertAlmostEqual(numpy.linalg.norm(target-h), 0.0, 6) print "z=\n",z print "target=\n",target self.assertAlmostEqual(numpy.linalg.norm(target-z), 0.0, 6) self.assertAlmostEqual(numpy.linalg.norm(r - numpy.zeros([12])), 0.0, 6) def test_sparsity(self): config, robot_params = self.load() block = ChainSensor(config, ChainMeasurement(chain_id="chainA", chain_state=JointState(position=[numpy.pi / 2.0]) ), "boardA") block.update_config(robot_params) sparsity = block.build_sparsity_dict() self.assertEqual(sparsity['transforms']['transformA'], [1,1,1,1,1,1]) self.assertEqual(sparsity['transforms']['transformB'], [1,1,1,1,1,1]) self.assertEqual(sparsity['dh_chains']['chainA'], {'dh':[[1,1,1,1]], 'gearing':[1]}) if __name__ == '__main__': import rostest rostest.unitrun('cob_robot_calibration_est', 'test_ChainBundler', TestChainBundler) #rostest.unitrun('cob_robot_calibration_est', 'test_CameraChainRobotParamsBlock', TestCameraChainRobotParamsBlock, coverage_packages=['cob_robot_calibration_est.blocks.camera_chain']) rostest.unitrun('cob_robot_calibration_est', 'test_ChainSensor', TestChainSensor)
h = sensor.compute_expected(target_pts) z = sensor.get_measurement() r = sensor.compute_residual(target_pts) self.assertAlmostEqual(numpy.linalg.norm(h - target_pts), 0.0, 6) self.assertAlmostEqual(numpy.linalg.norm(z - target_pts), 0.0, 6) self.assertAlmostEqual(numpy.linalg.norm(r), 0.0, 6) # Test Sparsity sparsity = sensor.build_sparsity_dict() self.assertEqual(sparsity['transforms']['j0'], [1, 1, 1, 1, 1, 1]) self.assertEqual(sparsity['transforms']['j1'], [1, 1, 1, 1, 1, 1]) self.assertEqual(sparsity['transforms']['j2'], [1, 1, 1, 1, 1, 1]) self.assertEqual(sparsity['tilting_lasers']['laserA']['gearing'], 1) if __name__ == '__main__': import rostest rostest.unitrun('calibration_estimation', 'test_TiltingLaserBundler', TestTiltingLaserBundler, coverage_packages=[ 'calibration_estimation.sensors.tilting_laser_sensor' ]) rostest.unitrun('calibration_estimation', 'test_TiltingLaser', TestTiltingLaser, coverage_packages=[ 'calibration_estimation.sensors.tilting_laser_sensor' ])
# test remap_args n = Test('test6', 'pkg6', 'type6', remap_args=[('from6a', 'to6a'), ('from6b', 'to6b')]) self.assertEquals("""<test pkg="pkg6" type="type6" ns="/" args="" output="log" required="False" test-name="test6"> <remap from="from6a" to="to6a" /> <remap from="from6b" to="to6b" /> </test>""", n.to_remote_xml()) # test env args n = Test('test7', 'pkg7', 'type7', env_args=[('key7a', 'val7a'), ('key7b', 'val7b')]) self.assertEquals("""<test pkg="pkg7" type="type7" ns="/" args="" output="log" required="False" test-name="test7"> <env name="key7a" value="val7a" /> <env name="key7b" value="val7b" /> </test>""", n.to_remote_xml()) # test cwd n = Test('test8', 'pkg8', 'type8', cwd='ros-root') self.assertEquals('<test pkg="pkg8" type="type8" ns="/" args="" output="log" cwd="ros-root" required="False" test-name="test8">\n</test>', n.to_remote_xml()) n = Test('test9', 'pkg9', 'type9', cwd='node') self.assertEquals('<test pkg="pkg9" type="type9" ns="/" args="" output="log" cwd="node" required="False" test-name="test9">\n</test>', n.to_remote_xml()) #test everything n = Test('test20', 'pkg20', 'type20', namespace="/ns20/", machine_name="foo", remap_args=[('from20a', 'to20a'), ('from20b', 'to20b')], env_args=[('key20a', 'val20a'), ('key20b', 'val20b')], cwd="ros-root", args="arg20a arg20b") self.assertEquals("""<test pkg="pkg20" type="type20" ns="/ns20/" args="arg20a arg20b" output="log" cwd="ros-root" required="False" test-name="test20"> <remap from="from20a" to="to20a" /> <remap from="from20b" to="to20b" /> <env name="key20a" value="val20a" /> <env name="key20b" value="val20b" /> </test>""", n.to_remote_xml()) if __name__ == '__main__': rostest.unitrun('test_roslaunch', sys.argv[0], TestRoslaunchRemote, coverage_packages=['roslaunch.remote'])
def test_sync(self): self._rmb.sync_time() class TestRoombaSensor(unittest.TestCase): def setUp(self): self._rmb = RoombaIf() self._rmb.setup() import time time.sleep(1) def teardown(self): self._rmb.close() def test_sensors(self): print 'dist = ',self._rmb.get_distance() print 'angle =',self._rmb.get_angle() print 'voltage =',self._rmb.get_voltage() print 'current =',self._rmb.get_current() print 'temperature =',self._rmb.get_temperature() print 'battery_charge =',self._rmb.get_battery_charge() if __name__ == '__main__': import rostest # test_support.run_unittest(TestRoombaOpen, TestRoombaCommand) rostest.unitrun('test_roombaif', 'test_roomba_not_open', TestRoombaNotOpenCommand) rostest.unitrun('test_roombaif', 'test_roomba_command', TestRoombaCommand) rostest.unitrun('test_roombaif', 'test_roomba_sensor', TestRoombaSensor) rostest.unitrun('test_roombaif', 'test_roomba_open', TestRoombaOpen)
# Scramble sequences of length N of headerless and header-having messages. # Make sure that TimeSequencer recombines them. rospy.rostime.set_rostime_initialized(True) random.seed(0) for N in range(1, 10): m0 = MockFilter() m1 = MockFilter() seq0 = [MockMessage(rospy.Time(t), random.random()) for t in range(N)] seq1 = [MockHeaderlessMessage(random.random()) for t in range(N)] # random.shuffle(seq0) ts = ApproximateTimeSynchronizer([m0, m1], N, 0.1, allow_headerless=True) ts.registerCallback(self.cb_collector_2msg) self.collector = [] for msg in random.sample(seq0, N): m0.signalMessage(msg) self.assertEqual(self.collector, []) for i in random.sample(range(N), N): msg = seq1[i] rospy.rostime._set_rostime(rospy.Time(i+0.05)) m1.signalMessage(msg) self.assertEqual(set(self.collector), set(zip(seq0, seq1))) if __name__ == '__main__': if 1: rostest.unitrun('camera_calibration', 'testapproxsync', TestApproxSync) else: suite = unittest.TestSuite() suite.addTest(TestApproxSync('test_approx')) unittest.TextTestRunner(verbosity=2).run(suite)
def test_launch_manager_no_launch_file_provider(self): with redirected_stdio(): workspaces = [os.path.join(THIS_DIR, 'no_launch_file')] package_index = package_index_from_package_path(workspaces) spec_file_index = spec_file_index_from_package_index(package_index) spec_index, errors = spec_index_from_spec_file_index(spec_file_index) assert not errors, errors provider = 'minimal_pkg/minimal' assert provider in spec_index.providers lm = launch_manager.LaunchManager() lm._LaunchManager__quiet = True lm.run_capability_provider(spec_index.providers[provider], spec_index.provider_paths[provider]) time.sleep(1) # Allow time for output to be produced lm.stop() def test_process_monitoring(self): lm = launch_manager.LaunchManager() try: with assert_raises_regex(RuntimeError, 'Unknown process id'): proc = Mock() proc.pid = -1 lm._LaunchManager__monitor_process(proc) finally: lm.stop() if __name__ == '__main__': import rospy rospy.init_node(TEST_NAME, anonymous=True) rostest.unitrun('capabilities', TEST_NAME, Test)
for d in range(1, 10): pt3d = cam.projectPixelTo3d((x, y), d) ((lx, ly), (rx, ry)) = cam.project3dToPixel(pt3d) self.assertAlmostEqual(y, ly, 3) self.assertAlmostEqual(y, ry, 3) self.assertAlmostEqual(x, lx, 3) self.assertAlmostEqual(x, rx + d, 3) u = 100.0 v = 200.0 du = 17.0 dv = 23.0 Z = 2.0 xyz0 = cam.left.projectPixelTo3dRay((u, v)) xyz0 = (xyz0[0] * (Z / xyz0[2]), xyz0[1] * (Z / xyz0[2]), Z) xyz1 = cam.left.projectPixelTo3dRay((u + du, v + dv)) xyz1 = (xyz1[0] * (Z / xyz1[2]), xyz1[1] * (Z / xyz1[2]), Z) self.assertAlmostEqual(cam.left.getDeltaU(xyz1[0] - xyz0[0], Z), du, 3) self.assertAlmostEqual(cam.left.getDeltaV(xyz1[1] - xyz0[1], Z), dv, 3) self.assertAlmostEqual(cam.left.getDeltaX(du, Z), xyz1[0] - xyz0[0], 3) self.assertAlmostEqual(cam.left.getDeltaY(dv, Z), xyz1[1] - xyz0[1], 3) if __name__ == '__main__': if 1: rostest.unitrun('image_geometry', 'directed', TestDirected) else: suite = unittest.TestSuite() suite.addTest(TestDirected('test_stereo')) unittest.TextTestRunner(verbosity=2).run(suite)
for n in sample_nums ] transform_filenames = [ "test/data/single_transform_data/transform_%02u.txt" % n for n in sample_nums ] for params_filename, transform_filename in zip(params_filenames, transform_filenames): f_params = open(params_filename) f_transforms = open(transform_filename) param_elems = [float(x) for x in f_params.read().split()] transform_elems = [float(x) for x in f_transforms.read().split()] st = SingleTransform(param_elems) expected_result = numpy.matrix(transform_elems) expected_result.shape = 4, 4 self.assertAlmostEqual( numpy.linalg.norm(st.transform - expected_result), 0.0, 4, "Failed on %s" % params_filename) if __name__ == '__main__': import rostest rostest.unitrun( 'cob_robot_calibration_est', 'test_SingleTransform', TestSingleTransform, coverage_packages=['cob_robot_calibration_est.single_transform'])
self.assertEquals(set(['genmsg_cpp', 'rospack']), set(rospack_depends_1('roslib'))) self.assertEquals(set(['roslib', 'roslang']), set(rospack_depends_1('rospy'))) self.assertEquals(set(['rospack', 'roslib', 'roslang', 'genmsg_cpp']), set(rospack_depends('rospy'))) val = rospack_depends_on('roslang') self.assert_('rospy' in val, val) self.assert_('roscpp' in val) val = rospack_depends_on_1('roslang') self.assert_('rospy' in val) self.assert_('roscpp' in val) def test_rosstack(self): from roslib.rospack import rosstackexec, rosstack_depends, rosstack_depends_1,\ rosstack_depends_on, rosstack_depends_on_1 self.assertEquals(set([]), set(rosstack_depends('ros'))) self.assertEquals(set([]), set(rosstack_depends_1('ros'))) # can't actually test these w/o setting up stack environment, so just make sure they don't throw self.assert_(rosstack_depends_on('ros') is not None) self.assert_(rosstack_depends_on_1('ros') is not None) if __name__ == '__main__': rostest.unitrun('test_roslib', 'test_rospack', RoslibRospackTest, coverage_packages=['roslib.rospack'])
self.assertTrue(received["msg"]["result"]) for x, y in zip(ret.loggers, received["msg"]["values"]["loggers"]): self.assertEqual(x.name, y["name"]) self.assertEqual(x.level, y["level"]) def test_call_service_fail(self): proto = Protocol("test_call_service_fail") s = CallService(proto) send_msg = loads(dumps({"op": "call_service", "service": "/rosout/set_logger_level", "args": '["ros", "invalid"]'})) received = {"msg": None} def cb(msg, cid=None): received["msg"] = msg proto.send = cb s.call_service(send_msg) time.sleep(0.5) self.assertFalse(received["msg"]["result"]) PKG = 'rosbridge_library' NAME = 'test_call_service' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestCallService)
except ValueError: failed = False self.failIf(failed, "init_node allowed '/' in name") def test_spin(self): failed = True try: rospy.spin() except rospy.ROSInitException: failed = False self.failIf(failed, "spin() should failed if not initialized") def test_myargv(self): orig_argv = sys.argv try: from rospy.client import myargv args = myargv() self.assertEquals(args, sys.argv) self.assertEquals(["foo", "bar", "baz"], myargv(["foo", "bar", "baz"])) self.assertEquals(["-foo", "bar", "-baz"], myargv(["-foo", "bar", "-baz"])) self.assertEquals(["foo"], myargv(["foo", "bar:=baz"])) self.assertEquals(["foo"], myargv(["foo", "-bar:=baz"])) finally: sys.argv = orig_argv if __name__ == "__main__": rostest.unitrun("test_rospy", sys.argv[0], TestRospyClient, coverage_packages=["rospy.client"])
def test_deflate(self): cb = Checkerboard() param_vec = matrix([10,20], float).T cb.inflate( param_vec ) result = cb.deflate() print "" print result self.assertAlmostEqual(numpy.linalg.norm(result - param_vec), 0.0, 6) def test_generate_points(self): cb = Checkerboard({"corners_x": 2, "corners_y": 3, "spacing_x": 10, "spacing_y": 20 }) result = cb.generate_points() expected = matrix( [ [ 0, 10, 0, 10, 0, 10], [ 0, 0, 20, 20, 40, 40], [ 0, 0, 0, 0, 0, 0], [ 1, 1, 1, 1, 1, 1] ], float) print "" print result self.assertAlmostEqual(numpy.linalg.norm(result - expected), 0.0, 6) def test_get_length(self): cb = Checkerboard() self.assertEqual(cb.get_length(), 2) if __name__ == '__main__': import rostest rostest.unitrun('calibration_estimation', 'test_Checkerboard', TestCheckerboard, coverage_packages=['calibration_estimation.checkerboard'])
from rosbridge_library.internal.outgoing_message import OutgoingMessage from std_msgs.msg import String class TestOutgoingMessage(unittest.TestCase): def test_json_values(self): msg = String(data="foo") outgoing = OutgoingMessage(msg) result = outgoing.get_json_values() self.assertEqual(result['data'], msg.data) again = outgoing.get_json_values() self.assertTrue(result is again) def test_cbor_values(self): msg = String(data="foo") outgoing = OutgoingMessage(msg) result = outgoing.get_cbor_values() self.assertEqual(result['data'], msg.data) again = outgoing.get_cbor_values() self.assertTrue(result is again) PKG = 'rosbridge_library' NAME = 'test_outgoing_message' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestOutgoingMessage)
proto = Protocol("hello") adv = Advertise(proto) for valid_type in assortedmsgs: msg = { "op": "advertise", "topic": "/" + valid_type, "type": valid_type } adv.advertise(loads(dumps(msg))) adv.unadvertise(loads(dumps(msg))) def test_do_advertise(self): proto = Protocol("hello") adv = Advertise(proto) topic = "/test_do_advertise" type = "std_msgs/String" msg = {"op": "advertise", "topic": topic, "type": type} adv.advertise(loads(dumps(msg))) self.assertTrue(self.is_topic_published(topic)) adv.unadvertise(loads(dumps(msg))) self.assertFalse(self.is_topic_published(topic)) PKG = 'rosbridge_library' NAME = 'test_advertise' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestAdvertise)
import subprocess class TopicCount(unittest.TestCase): def test_topic_count(self): # Wait while the recorder creates a bag for us to examine time.sleep(10.0) # Check the topic count returned by `rosbag info` # We could probably do this through the rosbag Python API... cmd = [ 'rosbag', 'info', '/tmp/test_rosbag_record_one_publisher_two_topics.bag', '-y', '-k', 'topics' ] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() topic_count = 0 for l in out.split('\n'): f = l.strip().split(': ') if len(f) == 2 and f[0] == '- topic': topic_count += 1 self.assertEqual(topic_count, 2) if __name__ == '__main__': rostest.unitrun('test_rosbag', 'topic_count', TopicCount, sys.argv)
class TestFullChainCalcBlock(unittest.TestCase): def test_fk_1(self): print "" calc_block = loadSystem1() chain_state = JointState(position=[0]) result = calc_block.fk(chain_state) expected = numpy.matrix( [[ 1, 0, 0,11], [ 0, 1, 0, 0], [ 0, 0, 1,20], [ 0, 0, 0, 1]], float ) print result self.assertAlmostEqual(numpy.linalg.norm(result-expected), 0.0, 6) def test_fk_2(self): print "" calc_block = loadSystem1() chain_state = JointState(position=[pi/2]) result = calc_block.fk(chain_state) expected = numpy.matrix( [[ 0,-1, 0,10], [ 1, 0, 0, 1], [ 0, 0, 1,20], [ 0, 0, 0, 1]], float ) print result self.assertAlmostEqual(numpy.linalg.norm(result-expected), 0.0, 6) if __name__ == '__main__': import rostest rostest.unitrun('cob_robot_calibration_est', 'test_FullChainCalcBlock', TestFullChainCalcBlock, coverage_packages=['cob_robot_calibration_est.full_chain'])
self.assertEqual(cv.GetSize(img), cv.GetSize(flat)) flat = sc.r.remap(img) self.assertEqual(cv.GetSize(img), cv.GetSize(flat)) sc2 = StereoCalibrator([board]) sc2.from_message(sc.as_message()) # sc2.set_alpha(1.0) #sc2.report() self.assert_(len(sc2.ost()) > 0) def test_nochecker(self): # Run with same images, but looking for an incorrect chessboard size (8, 7). # Should raise an exception because of lack of input points. new_board = copy.deepcopy(board) new_board.n_cols = 8 new_board.n_rows = 7 sc = StereoCalibrator([new_board]) self.assertRaises(CalibrationException, lambda: sc.cal(self.limages, self.rimages)) mc = MonoCalibrator([new_board]) self.assertRaises(CalibrationException, lambda: mc.cal(self.limages)) if __name__ == '__main__': if 1: rostest.unitrun('camera_calibration', 'directed', TestDirected) else: suite = unittest.TestSuite() suite.addTest(TestDirected('test_stereo')) unittest.TextTestRunner(verbosity=2).run(suite)
% (diag_stat.level, diag_stat.message)) def test_empty_parse(self): gpu_stat = pr2_computer_monitor.parse_smi_output('') self.assert_( gpu_stat.temperature == 0, "Invalid temperature reading. Should be 0. Reading: %d" % gpu_stat.temperature) diag_stat = pr2_computer_monitor.gpu_status_to_diag(gpu_stat) self.assert_( diag_stat.level == 2, "Diagnostics didn't reports an error for empty input. Level: %d, Message: %s" % (diag_stat.level, diag_stat.message)) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == '-v': # Use to run tests verbosly suite = unittest.TestSuite() suite.addTest(TestNominalParser('test_parse')) suite.addTest(TestNominalParser('test_empty_parse')) suite.addTest(TestNominalParser('test_high_temp_parse')) unittest.TextTestRunner(verbosity=2).run(suite) else: import rostest rostest.unitrun(PKG, 'parse_nominal', TestNominalParser)
coll.object2 = coll.COLLISION_SET_OBJECTS coll.operation = coll.ENABLE goal.motion_plan_request.ordered_collision_operations.collision_operations.append(coll) goal.motion_plan_request.goal_constraints.joint_constraints[0].position = 0.0 goal.motion_plan_request.goal_constraints.joint_constraints[3].position = -0.2 goal.motion_plan_request.goal_constraints.joint_constraints[5].position = -0.2 self.move_arm_action_client.send_goal(goal) r = rospy.Rate(10) while True: cur_state = self.move_arm_action_client.get_state() if(cur_state != actionlib_msgs.msg.GoalStatus.ACTIVE and cur_state != actionlib_msgs.msg.GoalStatus.PENDING): break #should still have succeedeed final_state = self.move_arm_action_client.get_state() self.failIf(final_state == actionlib_msgs.msg.GoalStatus.SUCCEEDED) if __name__ == '__main__': import rostest rostest.unitrun('test_motion_execution_buffer', 'test_motion_execution_buffer', TestMotionExecutionBuffer)
set([ 'test_rosmsg/RossrvA', 'test_rosmsg/RossrvB', ]), set(l)) def test_get_srv_text(self): d = roslib.packages.get_pkg_dir('test_rosmsg') srv_d = os.path.join(d, 'srv') with open(os.path.join(srv_d, 'RossrvA.srv'), 'r') as f: text = f.read() self.assertEquals( text, rosmsg.get_srv_text('test_rosmsg/RossrvA', raw=False)) self.assertEquals(text, rosmsg.get_srv_text('test_rosmsg/RossrvA', raw=True)) # std_msgs/empty / std_msgs/empty with open(os.path.join(srv_d, 'RossrvB.srv'), 'r') as f: text = f.read() self.assertEquals( text, rosmsg.get_srv_text('test_rosmsg/RossrvB', raw=False)) self.assertEquals(text, rosmsg.get_srv_text('test_rosmsg/RossrvB', raw=True)) if __name__ == '__main__': rostest.unitrun('test_rosmsg', NAME, TestRosmsg, sys.argv, coverage_packages=['rosmsg'])
diag_stat = pr2_computer_monitor.gpu_status_to_diag(gpu_stat) self.assert_(diag_stat.level == 1, "Diagnostics didn't report warning for high temp input. Level %d, Message: %s" % (diag_stat.level, diag_stat.message)) def test_empty_parse(self): gpu_stat = pr2_computer_monitor.parse_smi_output('') self.assert_(gpu_stat.temperature == 0, "Invalid temperature reading. Should be 0. Reading: %d" % gpu_stat.temperature) diag_stat = pr2_computer_monitor.gpu_status_to_diag(gpu_stat) self.assert_(diag_stat.level == 2, "Diagnostics didn't reports an error for empty input. Level: %d, Message: %s" % (diag_stat.level, diag_stat.message)) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == '-v': # Use to run tests verbosly suite = unittest.TestSuite() suite.addTest(TestNominalParser('test_parse')) suite.addTest(TestNominalParser('test_empty_parse')) suite.addTest(TestNominalParser('test_high_temp_parse')) unittest.TextTestRunner(verbosity = 2).run(suite) else: import rostest rostest.unitrun(PKG, 'parse_nominal', TestNominalParser)
poseA = numpy.array([1, 0, 0, 0, 0, 0]) poseB = numpy.array([2, 0, 0, 0, 0, 0]) calc = ErrorCalc(robot_params, free_dict, [multisensorA, multisensorB]) expanded_param_vec = robot_params.deflate() free_list = robot_params.calc_free(free_dict) opt_param_mat = expanded_param_vec[numpy.where(free_list), 0].copy() opt_param = numpy.array(opt_param_mat)[0] opt_all_vec = concatenate([opt_param, poseA, poseB]) print "Calculating Sparse" J = calc.calculate_jacobian(opt_all_vec) numpy.savetxt("J_sparse.txt", J, fmt="% 4.3f") #import code; code.interact(local=locals()) print "Calculating Dense" from scipy.optimize.slsqp import approx_jacobian J_naive = approx_jacobian(opt_all_vec, calc.calculate_error, 1e-6) numpy.savetxt("J_naive.txt", J_naive, fmt="% 4.3f") self.assertAlmostEqual(numpy.linalg.norm(J-J_naive), 0.0, 6) if __name__ == '__main__': import rostest #rostest.unitrun('pr2_calibration_estimation', 'test_opt_runner', TestParamJacobian, coverage_packages=['pr2_calibration_estimation.opt_runner']) #rostest.unitrun('pr2_calibration_estimation', 'test_pose_J', TestPoseJacobian, coverage_packages=['pr2_calibration_estimation.opt_runner']) rostest.unitrun('pr2_calibration_estimation', 'test_full_J', TestFullJacobian, coverage_packages=['pr2_calibration_estimation.opt_runner'])
stereo_cal.ost() # Check error for big image archive = tarfile.open(my_archive_name) l1_big = image_from_archive(archive, "left-0000.png") r1_big = image_from_archive(archive, "right-0000.png") epi_big = stereo_cal.epipolar_error_from_images(l1_big, r1_big) self.assert_( epi_big < 1.0, "Epipolar error for large checkerboard > 1.0. Error: %.2f" % epi_big) # Small checkerboard has larger error threshold for now l1_sm = image_from_archive(archive, "left-0012-sm.png") r1_sm = image_from_archive(archive, "right-0012-sm.png") epi_sm = stereo_cal.epipolar_error_from_images(l1_sm, r1_sm) self.assert_( epi_sm < 2.0, "Epipolar error for small checkerboard > 2.0. Error: %.2f" % epi_sm) if __name__ == '__main__': if 1: rostest.unitrun('camera_calibration', 'test_multi_board_cal', TestMultipleBoards) else: suite = unittest.TestSuite() suite.addTest(TestMultipleBoards('test_multi_board_cal')) unittest.TextTestRunner(verbosity=2).run(suite)
except ValueError: pass self.assertEquals(([], []), expand_to_packages([])) self.assertEquals( (['rospy', 'test_roslib', 'roslib'], []), expand_to_packages(['rospy', 'test_roslib', 'roslib'])) self.assertEquals(([], ['bogus_one', 'bogus_two']), expand_to_packages(['bogus_one', 'bogus_two'])) self.assertEquals(([], ['bogus_one', 'bogus_two']), expand_to_packages(['bogus_one', 'bogus_two'])) # TODO: setup directory tree so that this can be more precisely calculated valid, invalid = expand_to_packages(['ros', 'bogus_one']) self.assertEquals(['bogus_one'], invalid) check = [ 'rospy', 'roscpp', 'rospack', 'rosmake', 'roslib', 'rostest', 'std_msgs' ] for c in check: self.assert_(c in valid, "expected [%s] to be in ros expansion" % c) if __name__ == '__main__': rostest.unitrun('test_roslib', 'test_stacks', RoslibStacksTest, coverage_packages=['roslib.stacks'])
def test_md5_equals(self): tests = self._load_md5_tests('same') for k, files in tests.iteritems(): print "running tests", k md5sum = self._compute_md5(files[0]) for f in files[1:]: self.assertEquals( md5sum, self._compute_md5(f), "failed on %s: \n[%s]\nvs.\n[%s]\n" % (k, self._compute_md5_text( files[0]), self._compute_md5_text(f))) def test_md5_not_equals(self): tests = self._load_md5_tests('different') for k, files in tests.iteritems(): print "running tests", k md5s = set() md6md5sum = self._compute_md5(files[0]) for f in files: md5s.add(self._compute_md5(f)) # each md5 should be unique self.assertEquals(len(md5s), len(files)) if __name__ == '__main__': rostest.unitrun('test_roslib', NAME, TestGentools, sys.argv, coverage_packages=['roslib.gentools'])
else: color = 255 circle(im, x, y, s, color) comp = Image.new("L", (im.size[0] * 2, im.size[1])) comp.paste(Image.open("face1.png").convert("L"), (0,0)) comp.paste(im, (im.size[0], 0)) comp.save("out.png") def perftest(self): print print for size in [ (512,384), (640,480) ]: im = self.im640.resize(size) sd = L.star_detector(im.size[0], im.size[1]) s = im.tostring() niter = 400 started = time.time() for i in range(niter): kp = sd.detect(s) took = time.time() - started print "%16s: %.1f ms/frame" % (str(size), 1e3 * took / niter) print print if __name__ == '__main__': rostest.unitrun('star_detector', 'directed', TestDirected) if 1: suite = unittest.TestSuite() suite.addTest(TestDirected('test_face')) unittest.TextTestRunner(verbosity=2).run(suite)
roslib.load_manifest('test_rospy') import os import sys import struct import unittest import time class TestRospyTcpros(unittest.TestCase): def test_init_tcpros(self): import rospy.impl.tcpros rospy.impl.tcpros.init_tcpros() # nothing to validate here other than make sure no exceptions def test_syms(self): import rospy.impl.tcpros import rospy.impl.transport self.assertEquals(int, type(rospy.impl.tcpros.DEFAULT_BUFF_SIZE)) self.assert_( isinstance(rospy.impl.tcpros.get_tcpros_handler(), rospy.impl.transport.ProtocolHandler)) if __name__ == '__main__': import rostest rostest.unitrun('test_rospy', sys.argv[0], TestRospyTcpros, coverage_packages=['rospy.impl.tcpros'])
import unittest import rostest import sys import time import subprocess class TopicCount(unittest.TestCase): def test_topic_count(self): # Wait while the recorder creates a bag for us to examine time.sleep(10.0) # Check the topic count returned by `rosbag info` # We could probably do this through the rosbag Python API... cmd = ['rosbag', 'info', '/tmp/test_rosbag_record_one_publisher_two_topics.bag', '-y', '-k', 'topics'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() topic_count = 0 for l in out.split('\n'): f = l.strip().split(': ') if len(f) == 2 and f[0] == '- topic': topic_count += 1 self.assertEqual(topic_count, 2) if __name__ == '__main__': rostest.unitrun('test_rosbag', 'topic_count', TopicCount, sys.argv)
#deserialize multiple values with max_msgs and queue_size queue_size = 5 max_msgs = 5 b.truncate(0) for v in valids: b.write(v) # fill queue with junk msg_queue = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11] rospy.msg.deserialize_messages(b, msg_queue, data_class, max_msgs=max_msgs, queue_size=queue_size) self.assertEquals(queue_size, len(msg_queue)) # - msg_queue should have the oldest messages validate_vals(msg_queue) # - buffer should be have remaining msgs b2 = StringIO() for v in valids[max_msgs:]: b2.write(v) self.assertEquals(b.getvalue(), b2.getvalue()) if __name__ == '__main__': import rostest rostest.unitrun('test_rospy', sys.argv[0], TestRospyMsg, coverage_packages=['rospy.msg'])
pass else: self.fail('service call should have thrown an exception') topics = list_srv().topics self.assertEquals(set(topics), set(['/input', '/new_input'])) # Select a topic, then try to delete it, make sure it fails, and # that nothing changes. select_srv('/input') try: delete_srv('/input') except rospy.ServiceException, e: pass else: self.fail('service call should have thrown an exception') topics = list_srv().topics self.assertEquals(set(topics), set(['/input', '/new_input'])) # Select nothing, to allow deletion select_srv('__none') # Delete topics delete_srv('/input') topics = list_srv().topics self.assertEquals(set(topics), set(['/new_input'])) delete_srv('/new_input') topics = list_srv().topics self.assertEquals(set(topics), set([])) if __name__ == "__main__": import rostest rostest.unitrun(PKG, 'mux_services', MuxServiceTestCase)
self.assertAlmostEqual(numpy.linalg.norm(target - h), 0.0, 6) print "z=\n", z print "target=\n", target self.assertAlmostEqual(numpy.linalg.norm(target - z), 0.0, 6) self.assertAlmostEqual(numpy.linalg.norm(r - numpy.zeros([12])), 0.0, 6) def test_sparsity(self): config, robot_params = loadSystem() block = ChainSensor( config["chainA"], ChainMeasurement(chain_id="chainA", chain_state=JointState(position=[numpy.pi / 2.0])), "boardA") block.update_config(robot_params) sparsity = block.build_sparsity_dict() self.assertEqual(sparsity['transforms']['j0'], [1, 1, 1, 1, 1, 1]) self.assertEqual(sparsity['transforms']['j1'], [1, 1, 1, 1, 1, 1]) self.assertEqual(sparsity['chains']['chainA'], {'gearing': [1]}) if __name__ == '__main__': import rostest rostest.unitrun('calibration_estimation', 'test_ChainBundler', TestChainBundler) rostest.unitrun('calibration_estimation', 'test_ChainSensor', TestChainSensor)
tr.waitForTransform("PARENT", "THISFRAME", rospy.Time().from_sec(4.0), rospy.Duration(3.0)) except tf.Exception, ex: self.assertFalse("This should not throw") def test_getTFPrefix(self): t = tf.Transformer() self.assertEqual(t.getTFPrefix(), "") def no_test_random(self): import networkx as nx for (r,h) in [ (2,2), (2,5), (3,5) ]: G = nx.balanced_tree(r, h) t = tf.Transformer(True, rospy.Duration(10.0)) for n in G.nodes(): if n != 0: # n has parent p p = min(G.neighbors(n)) setT(t, str(p), str(n), rospy.Time(0), 1) for n in G.nodes(): ((x,_,_), _) = t.lookupTransform("0", str(n), rospy.Time(0)) self.assert_(x == nx.shortest_path_length(G, 0, n)) for i in G.nodes(): for j in G.nodes(): ((x,_,_), _) = t.lookupTransform(str(i), str(j), rospy.Time()) self.assert_(abs(x) == abs(nx.shortest_path_length(G, 0, i) - nx.shortest_path_length(G, 0, j))) if __name__ == '__main__': rostest.unitrun('tf', 'directed', TestPython)
inbag = "%s/test/constants_gen%d.bag"%(self.pkg_binary_dir,N) outbag = "%s/test/constants_gen%d.fixed.bag"%(self.pkg_binary_dir,N) mm = rosbag.migration.MessageMigrator(rule_files, False) res = rosbag.migration.checkbag(mm, inbag) self.assertTrue(not False in [m[1] == [] for m in res], 'Bag not ready to be migrated') res = rosbag.migration.fixbag(mm, inbag, outbag) self.assertTrue(res, 'Bag not converted successfully') msgs = [msg for msg in rosbag.Bag(outbag).read_messages()] self.assertTrue(len(msgs) > 0) self.assertEqual(msgs[0][1]._type, 'test_rosbag/Constants', 'Type name is wrong') self.assertEqual(msgs[0][1].value, msgs[0][1].CONSTANT) def test_constants_no_rules_gen1(self): self.do_constants_no_rules(1) def test_constants_gen1(self): self.do_constants_rules(1) def test_constants_gen2(self): self.do_constants_rules(2) if __name__ == '__main__': rostest.unitrun('test_rosbag', 'migration_test', MigrationTest, sys.argv)
pub_handler = PublishingHandler(expected_pub_info) self.assertEqual(pub_handler.pub_info, expected_pub_info) #@TODO: a more advanced test should be conducted except rospy.ROSInterruptException: pass def test_publishing_handler_handle(self): try: pub_info = {} pub_info['HelloMessage'] = rospy.Publisher('Hello_Topic', HelloMessage, queue_size=10) pub_info['HeartbeatMessage'] = rospy.Publisher('Heartbeat_Topic', HeartbeatMessage, queue_size=10) pub_handler = PublishingHandler(pub_info) expected_msg = HeartbeatMessage() expected_msg.droneID = "UAV123" expected_msg.sessionID = "SE123" expected_msg.batteryLevel = 0.7 expected_msg.status = 0 expected_msg.latitude = 40 expected_msg.longitude = 40 expected_msg.altitude = 40 expected_msg.messageType = "HeartbeatMessage" self.assertEqual(pub_handler.handle(expected_msg),"HeartbeatMessage") except rospy.ROSInterruptException: pass PKG = 'rospy_message_transporter' NAME = 'rospy_message_transporter' if __name__ == '__main__': rospy.init_node('TestMessageHandler', anonymous=True) rostest.unitrun(PKG, NAME, TestMessageHandler)
padd = LinkPadding() padd.link_name = "r_end_effector" padd.padding = .03 state_req.link_padding = [] state_req.link_padding.append(padd) res = self.get_state_validity_server.call(state_req) #should be in collision self.failIf(res.error_code.val == res.error_code.SUCCESS) self.assertEqual(res.error_code.val, res.error_code.COLLISION_CONSTRAINTS_VIOLATED) #should be some contacts self.failIf(len(res.contacts) == 0) #check that revert works state_req.link_padding = [] res = self.get_state_validity_server.call(state_req) self.failIf(res.error_code.val != res.error_code.SUCCESS) if __name__ == '__main__': import rostest rostest.unitrun('test_alter_padding', 'test_alter_padding', TestAlterPadding)
flat = sc.r.remap(img) self.assertEqual(cv.GetSize(img), cv.GetSize(flat)) sc2 = StereoCalibrator([board]) sc2.from_message(sc.as_message()) # sc2.set_alpha(1.0) #sc2.report() self.assert_(len(sc2.ost()) > 0) def test_nochecker(self): # Run with same images, but looking for an incorrect chessboard size (8, 7). # Should raise an exception because of lack of input points. new_board = copy.deepcopy(board) new_board.n_cols = 8 new_board.n_rows = 7 sc = StereoCalibrator([new_board]) self.assertRaises(CalibrationException, lambda: sc.cal(self.limages, self.rimages)) mc = MonoCalibrator([new_board]) self.assertRaises(CalibrationException, lambda: mc.cal(self.limages)) if __name__ == '__main__': if 1: rostest.unitrun('camera_calibration', 'directed', TestDirected) else: suite = unittest.TestSuite() suite.addTest(TestDirected('test_stereo')) unittest.TextTestRunner(verbosity=2).run(suite)
6].position = 0.0 for x in range(3): self.move_arm_action_client.send_goal(goal) while True: cur_state = self.move_arm_action_client.get_state() if (cur_state != actionlib_msgs.msg.GoalStatus.ACTIVE and cur_state != actionlib_msgs.msg.GoalStatus.PENDING): break r.sleep() end_state = self.move_arm_action_client.get_state() if (end_state == actionlib_msgs.msg.GoalStatus.SUCCEEDED): break final_state = self.move_arm_action_client.get_state() self.assertEqual(final_state, actionlib_msgs.msg.GoalStatus.SUCCEEDED) if __name__ == '__main__': import rostest rostest.unitrun('test_motion_execution_buffer', 'test_motion_execution_buffer', TestMotionExecutionBuffer)
m = Machine('name1', ros_root, rpp, '1.2.3.4', ros_ip="4.5.6.7") d = create_local_process_env(n, m, master_uri) self.assertEquals(d['ROS_IP'], "4.5.6.7") # test node.env_args n = Node('nodepkg','nodetype', env_args=[('NENV1', 'val1'), ('NENV2', 'val2'), ('ROS_ROOT', '/new/root')]) d = create_local_process_env(n, m, master_uri) self.assertEquals(d['ROS_ROOT'], "/new/root") self.assertEquals(d['NENV1'], "val1") self.assertEquals(d['NENV2'], "val2") # test machine.env_args m = Machine('name1', ros_root, rpp, '1.2.3.4', ros_ip="4.5.6.7", env_args=[('MENV1', 'val1'), ('MENV2', 'val2'), ('ROS_ROOT', '/new/root2')]) n = Node('nodepkg','nodetype') d = create_local_process_env(n, m, master_uri) self.assertEquals(d['ROS_ROOT'], "/new/root2") self.assertEquals(d['MENV1'], "val1") self.assertEquals(d['MENV2'], "val2") # test node.env_args precedence m = Machine('name1', ros_root, rpp, '1.2.3.4', ros_ip="4.5.6.7", env_args=[('MENV1', 'val1'), ('MENV2', 'val2')]) n = Node('nodepkg','nodetype', env_args=[('MENV1', 'nodeval1')]) d = create_local_process_env(n, m, master_uri) self.assertEquals(d['MENV1'], "nodeval1") self.assertEquals(d['MENV2'], "val2") if __name__ == '__main__': import rostest rostest.unitrun('test_roslaunch', NAME, TestNodeArgs, coverage_packages=['roslaunch.node_args'])
data_offset = 1 ), data = [1.1, 2.2, 3.3] ) dictionary = { 'layout': { 'dim': [ { 'label' : expected_message.layout.dim[0].label, 'size' : expected_message.layout.dim[0].size, 'stride' : expected_message.layout.dim[0].stride }, { 'label' : expected_message.layout.dim[1].label, 'size' : expected_message.layout.dim[1].size, 'stride' : expected_message.layout.dim[1].stride } ], 'data_offset': expected_message.layout.data_offset }, 'data': expected_message.data } message = message_converter.convert_dictionary_to_ros_message('std_msgs/Float64MultiArray', dictionary) self.assertEqual(message, expected_message) PKG = 'rospy_message_converter' NAME = 'test_message_converter' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestMessageConverter)
rostype = "rosbridge_library/" + msgtype int8s = list(range(0, 256)) ret = test_int8_msg(rostype, int8s) self.assertEqual(ret, bytes(bytearray(int8s))) str_int8s = bytes(bytearray(int8s)) b64str_int8s = standard_b64encode(str_int8s).decode('ascii') ret = test_int8_msg(rostype, b64str_int8s) self.assertEqual(ret, str_int8s) for msgtype in ["TestUInt8FixedSizeArray16"]: rostype = "rosbridge_library/" + msgtype int8s = list(range(0, 16)) ret = test_int8_msg(rostype, int8s) self.assertEqual(ret, bytes(bytearray(int8s))) str_int8s = bytes(bytearray(int8s)) b64str_int8s = standard_b64encode(str_int8s).decode('ascii') ret = test_int8_msg(rostype, b64str_int8s) self.assertEqual(ret, str_int8s) PKG = 'rosbridge_library' NAME = 'test_message_conversion' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestMessageConversion)
# Pull the first message out of the bag msgs = [msg for msg in rosrecord.logplayer(newbag)] # Reserialize the new message so that floats get screwed up, etc. m = new_msg() buff = StringIO() m.serialize(buff) m.deserialize(buff.getvalue()) #Compare # print "old" # print roslib.message.strify_message(msgs[0][1]) # print "new" # print roslib.message.strify_message(m) # Strifying them helps make the comparison easier until I figure out why the equality operator is failing self.assertTrue(roslib.message.strify_message(msgs[0][1]) == roslib.message.strify_message(m)) # self.assertTrue(msgs[0][1] == m) #Cleanup os.remove(oldbag) os.remove(newbag) if __name__ == '__main__': rostest.unitrun('test_common_msgs', 'test_common_msgs_migration', TestCommonMsgsMigration, sys.argv)
msg.latitude = 40 msg.longitude = 40 msg.altitude = 40 json = message_formatter.format_from_ros_msg(msg) expected_json = '{"status": 0, "droneID": "UAV123", "altitude": 40, "longitude": 40, "sessionID": "SE123", "messageType": "", "latitude": 40, "batteryLevel": 0.7}' self.assertEqual(json, expected_json) def test_json_formatter_to_ros_msg(self): msg_typ_info = {} msg_typ_info['HelloMessage'] = 'rospy_message_transporter' msg_typ_info['HeartbeatMessage'] = 'rospy_message_transporter' message_formatter = JsonFormatter('messageType',msg_typ_info) json = '{"status": 0, "droneID": "UAV123", "altitude": 40, "longitude": 40, "sessionID": "SE123", "latitude": 40, "batteryLevel": 0.7, "messageType": "HeartbeatMessage"}' msg = message_formatter.format_to_ros_msg(json) expected_msg = HeartbeatMessage() expected_msg.droneID = "UAV123" expected_msg.sessionID = "SE123" expected_msg.batteryLevel = 0.7 expected_msg.status = 0 expected_msg.latitude = 40 expected_msg.longitude = 40 expected_msg.altitude = 40 expected_msg.messageType = "HeartbeatMessage" self.assertEqual(msg, expected_msg) self.assertTrue(isinstance(msg, HeartbeatMessage)) PKG = 'rospy_message_transporter' NAME = 'rospy_message_transporter' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestMessageFormatter)
env = os.environ.copy() env['ROS_MASTER_URI'] = 'http://localhost:11312' kwds = {'env': env, 'stdout': PIPE, 'stderr': PIPE} msg = "ERROR: Unable to communicate with master!\n" output = Popen([cmd, 'list'], **kwds).communicate() self.assertEquals(msg, output[1]) output = Popen([cmd, 'type', 'add_two_ints'], **kwds).communicate() self.assertEquals(msg, output[1]) output = Popen([cmd, 'uri', 'add_two_ints'], **kwds).communicate() self.assertEquals(msg, output[1]) output = Popen([cmd, 'call', 'add_two_ints', '1', '2'], **kwds).communicate() self.assertEquals(msg, output[1]) # - wait should still fail if master is offline output = Popen([cmd, 'call', '--wait', 'add_two_ints', '1', '2'], **kwds).communicate() self.assertEquals(msg, output[1]) output = Popen([cmd, 'find', 'test_ros/AddTwoInts'], **kwds).communicate() self.assertEquals(msg, output[1]) if __name__ == '__main__': rostest.unitrun('test_rosservice', NAME, TestRosserviceOffline, sys.argv, coverage_packages=[])
for y in (16, 240, m.height - 16): for d in range(1, 10): pt3d = cam.projectPixelTo3d((x, y), d) ((lx, ly), (rx, ry)) = cam.project3dToPixel(pt3d) self.assertAlmostEqual(y, ly, 3) self.assertAlmostEqual(y, ry, 3) self.assertAlmostEqual(x, lx, 3) self.assertAlmostEqual(x, rx + d, 3) u = 100.0 v = 200.0 du = 17.0 dv = 23.0 Z = 2.0 xyz0 = cam.left.projectPixelTo3dRay((u, v)) xyz0 = (xyz0[0] * (Z / xyz0[2]), xyz0[1] * (Z / xyz0[2]), Z) xyz1 = cam.left.projectPixelTo3dRay((u + du, v + dv)) xyz1 = (xyz1[0] * (Z / xyz1[2]), xyz1[1] * (Z / xyz1[2]), Z) self.assertAlmostEqual(cam.left.getDeltaU(xyz1[0] - xyz0[0], Z), du, 3) self.assertAlmostEqual(cam.left.getDeltaV(xyz1[1] - xyz0[1], Z), dv, 3) self.assertAlmostEqual(cam.left.getDeltaX(du, Z), xyz1[0] - xyz0[0], 3) self.assertAlmostEqual(cam.left.getDeltaY(dv, Z), xyz1[1] - xyz0[1], 3) if __name__ == '__main__': if 1: rostest.unitrun('image_geometry', 'directed', TestDirected) else: suite = unittest.TestSuite() suite.addTest(TestDirected('test_stereo')) unittest.TextTestRunner(verbosity=2).run(suite)
inbag = "%s/test/constants_gen%d.bag"%(self.pkg_dir,N) outbag = "%s/test/constants_gen%d.fixed.bag"%(self.pkg_dir,N) mm = rosbag.migration.MessageMigrator(rule_files, False) res = rosbag.migration.checkbag(mm, inbag) self.assertTrue(not False in [m[1] == [] for m in res], 'Bag not ready to be migrated') res = rosbag.migration.fixbag(mm, inbag, outbag) self.assertTrue(res, 'Bag not converted successfully') msgs = [msg for msg in rosbag.Bag(outbag).read_messages()] self.assertTrue(len(msgs) > 0) self.assertEqual(msgs[0][1]._type, 'test_rosbag/Constants', 'Type name is wrong') self.assertEqual(msgs[0][1].value, msgs[0][1].CONSTANT) def test_constants_no_rules_gen1(self): self.do_test_constants_no_rules(1) def test_constants_gen1(self): self.do_test_constants_rules(1) def test_constants_gen2(self): self.do_test_constants_rules(2) if __name__ == '__main__': rostest.unitrun('test_rosbag', 'migration_test', MigrationTest, sys.argv)