def run_tests():
    # run the tests in this thread
    import rosunit
    try:
        rosunit.unitrun(PKG, 'test_camera_info_manager',
                        TestCameraInfoManager)
    finally:
        rospy.signal_shutdown('test complete') # terminate the test node
def run_tests():
    # run the tests in this thread
    import rosunit
    try:
        rosunit.unitrun('rocon_scheduler_requests',
                        'test_rocon_scheduler_requests_py',
                        TestSchedulerRequestManager)
    finally:
        rospy.signal_shutdown('test complete') # terminate the test node
Ejemplo n.º 3
0
def unitrun(package, test_name, test, sysargs=None, coverage_packages=None):
    """
    Wrapper routine from running python unitttests with
    JUnit-compatible XML output.  This is meant for unittests that do
    not not need a running ROS graph (i.e. offline tests only).
    
    This enables JUnit-compatible test reporting so that
    test results can be reported to higher-level tools. 
    
    @param package: name of ROS package that is running the test
    @type  package: str
    @param coverage_packages: list of Python package to compute coverage results for. Defaults to package
    @type  coverage_packages: [str]
    """
    rosunit.unitrun(package, test_name, test, sysargs=sysargs, coverage_packages=coverage_packages)
                    idx_stamps = i
                i += 1

            i = 0
            for point in pc2.read_points(cloud_out):
                ri = scan.ranges[i]
                ai = scan.angle_min + i * scan.angle_increment

                self.assertAlmostEqual(point[idx_x], ri * np.cos(ai),
                        tolerance, "x not equal")
                self.assertAlmostEqual(point[idx_y], ri * np.sin(ai),
                        tolerance, "y not equal")
                self.assertAlmostEqual(point[idx_z], 0,
                        tolerance, "z not equal")
                self.assertAlmostEqual(point[idx_intensity],
                        scan.intensities[i],
                        tolerance, "Intensity not equal")
                self.assertAlmostEqual(point[idx_index], i,
                        tolerance, "Index not equal")
                self.assertAlmostEqual(point[idx_distance], ri,
                        tolerance, "Distance not equal")
                self.assertAlmostEqual(point[idx_stamps],
                        i * scan.time_increment,
                        tolerance, "Timestamp not equal")
                i += 1


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'projection_test', ProjectionTest)
from ecto_image_pipeline.io.source.ros import BagReader
from ecto_image_pipeline.io.source.camera_base import _assert_source_interface
import unittest

class TestSourceBagReader(unittest.TestCase):

    def test_interface(self):
        br = BagReader()

        print br.__doc__
        assert 'image_message' in br.__doc__
        assert 'depth' in br.__doc__
        assert 'image' in br.__doc__
        assert 'K' in br.__doc__

        #verify some types.
        assert 'boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const>' == br.outputs.at('image_message').type_name

        #this should pass our interface check
        _assert_source_interface(br)

        #test the bag file name parameter
        br = BagReader(bag='testy.bag')
        assert br.params.bag == 'testy.bag'
        assert br.source.params.bag == 'testy.bag'
        _assert_source_interface(br)

if __name__ == '__main__':
    import rosunit
    rosunit.unitrun('ecto_image_pipeline', 'test_source_bag_reader', TestSourceBagReader)
Ejemplo n.º 6
0
## A sample python unit test
class TestUrdf(unittest.TestCase):

	def test_correct_format(self):
		print sys.argv
		print len(sys.argv)
	
		if len(sys.argv) < 2:
			self.fail("no urdf file given, usage: " + os.path.basename(sys.argv[0]) + " file.urdf.xacro. \ninput parameters are: " + str(sys.argv))
	
		file_to_test = sys.argv[1]
		print "testing " + file_to_test
		
		# check if file exists
		if not os.path.exists(file_to_test):
			self.fail('file "' + file_to_test + '" not found')

		# check if xacro can be converted
		if os.system("`rospack find xacro`/xacro.py " + file_to_test + " > /tmp/test.urdf") != 0:
			self.fail("cannot convert xacro. file: " + file_to_test)

		# check if urdf is correct
		if os.system("check_urdf /tmp/test.urdf") != 0:
			self.fail("urdf not correct. file: " + file_to_test)
 
if __name__ == '__main__':
	import rosunit
	rosunit.unitrun(PKG, 'test_urdf', TestUrdf) 

########NEW FILE########
    def test_json_with_invalid_message_fields(self):
        self.assertRaises(ValueError,
                          json_message_converter.convert_json_to_ros_message,
                          'std_msgs/String',
                          '{"not_data": "Hello"}')


def serialize_deserialize(message):
    """
    Serialize and then deserialize a message. This simulates sending a message
    between ROS nodes and makes sure that the ROS messages being tested are
    actually serializable, and are in the same format as they would be received
    over the network. In rospy, it is possible to assign an illegal data type
    to a message field (for example, `message = String(data=42)`), but trying
    to publish this message will throw `SerializationError: field data must be
    of type str`. This method will expose such bugs.
    """
    from StringIO import StringIO
    buff = StringIO()
    message.serialize(buff)
    result = message.__class__()   # create new instance of same class as message
    result.deserialize(buff.getvalue())
    return result


PKG = 'rospy_message_converter'
NAME = 'test_json_message_converter'
if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, NAME, TestJsonMessageConverter)
Ejemplo n.º 8
0
        rr = os.path.abspath('test2')
        retcode, retval = self._rospack_langs(rr, None, None)
        self.assertEquals(0, retcode)
        self.failIf(retval, "rospack langs on empty directory returned value %s"%retval)

    # Test auto-inclusion of msg_gen include directories, #3018
    def test_msg_gen(self):
        test_path = os.path.abspath('test')
        pkgs = ['msg_gen_no_export', 'msg_gen_no_cpp', 'msg_gen_no_cflags']
        for p in pkgs:
          self.rospack_succeed(p, "cflags-only-I")
          self.assertEquals(os.path.join(test_path, p, "msg_gen/cpp/include"), self.strip_opt_ros(self.run_rospack(p, "cflags-only-I")))

    # Test that -q option suppresses errors, #3177.
    def test_quiet_option(self):
        ros_root = os.path.abspath('test')
        # With -q: look for non-existent package, make sure that it fails, yet
        # produces nothing on stderr.
        status_code, stdout, stderr = self._run_rospack(ros_root, None, 'nonexistentpackage', 'find -q')
        self.assertNotEquals(0, status_code)
        self.assertEquals(0, len(stderr))
        # Without -q: look for non-existent package, make sure that it fails, 
        # and produces somthing on stderr.
        status_code, stdout, stderr = self._run_rospack(ros_root, None, 'nonexistentpackage', 'find')
        self.assertNotEquals(0, status_code)
        self.assertNotEquals(0, len(stderr))

if __name__ == "__main__":
    import rosunit
    rosunit.unitrun(PKG, 'rospack_exe_process', RospackTestCase)
    def test_update_baseline_zero(self):
        # do update
        updater = camera_yaml_updater.CameraYamlUpdater(FILE_IN, FILE_OUT)
        updater.update_baseline(0.0)
        
        # compare with correct results
        self.assertTrue(self._cmp_yaml_files(FILE_OUT, FILE_IN))
        
    def test_update_baseline_positive(self):
        # do update
        updater = camera_yaml_updater.CameraYamlUpdater(FILE_IN, FILE_OUT)
        updater.update_baseline(10.0)
        
        # compare with correct results
        self.assertTrue(self._cmp_yaml_files(FILE_OUT, FILE_OUT_RES_POS))

    def test_update_baseline_negative(self):
        # do update
        updater = camera_yaml_updater.CameraYamlUpdater(FILE_IN, FILE_OUT)
        updater.update_baseline(-10.0)
        
        # compare with correct results
        self.assertTrue(self._cmp_yaml_files(FILE_OUT, FILE_OUT_RES_NEG))

    def _cmp_yaml_files(self, f1, f2):
        return yaml.load(file(f1)) == yaml.load(file(f2))

if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'TestCameraYamlUpdater', TestCameraYamlUpdater)
Ejemplo n.º 10
0
        self.assertEqual(out.vel.z(), 2)
        self.assertEqual(out.rot.x(), 4)
        self.assertEqual(out.rot.y(), -5)
        self.assertEqual(out.rot.z(), -6)

        w = PyKDL.Wrench(PyKDL.Vector(1,2,3), PyKDL.Vector(4,5,6))
        out = b.transform(tf2_ros.Stamped(w, rospy.Time(2), 'a'), 'b')
        self.assertEqual(out.force.x(), 1)
        self.assertEqual(out.force.y(), -2)
        self.assertEqual(out.force.z(), -3)
        self.assertEqual(out.torque.x(), 4)
        self.assertEqual(out.torque.y(), -8)
        self.assertEqual(out.torque.z(), -4)

    def test_convert(self):
        v = PyKDL.Vector(1,2,3)
        vs = tf2_ros.Stamped(v, rospy.Time(2), 'a')
        vs2 = tf2_ros.convert(vs, PyKDL.Vector)
        self.assertEqual(vs.x(), 1)
        self.assertEqual(vs.y(), 2)
        self.assertEqual(vs.z(), 3)
        self.assertEqual(vs2.x(), 1)
        self.assertEqual(vs2.y(), 2)
        self.assertEqual(vs2.z(), 3)


if __name__ == '__main__':
    import rosunit
    rospy.init_node('test_tf2_kdl_python')
    rosunit.unitrun("test_tf2_kdl", "test_tf2_kdl_python", KDLConversions)
Ejemplo n.º 11
0
        # Check number of alternatives
        self.assertEqual(len(response.alternatives), 0)

    def test_notExistentFile(self):
        rospack = rospkg.RosPack()
        google_service = rospy.get_param(\
                "rapp_speech_detection_google_detect_speech_topic")
        rospy.wait_for_service(google_service)
        stt_service = rospy.ServiceProxy(google_service, SpeechToTextSrv)
        req = SpeechToTextSrvRequest()
        req.filename = rospack.get_path('rapp_testing_tools') + \
                '/test_data/something.flac'
        req.audio_type = 'nao_wav_1_ch'
        req.user = '******'
        req.language = 'en'
        response = stt_service(req)
        words_basic = len(response.words)

        # self.assertEqual(response.words, 1)

        # Check number of words
        self.assertEqual(words_basic, 0)

        # Check number of alternatives
        self.assertEqual(len(response.alternatives), 0)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'SpeechToTextFunc', SpeechToTextFunc)
        rospy.wait_for_service(service)

        test_service = rospy.ServiceProxy(\
                service, ontologyLoadDumpSrv)

        req = ontologyLoadDumpSrvRequest()
        req.file_url = "testDump.owl"
        response = test_service(req)
        self.assertEqual(response.success, True)

## Test dump ontology with invalid path

    def test_dump_invalid_path(self):
        service = rospy.get_param(\
                "rapp_knowrob_wrapper_dump_ontology_topic")
        rospy.wait_for_service(service)

        test_service = rospy.ServiceProxy(\
                service, ontologyLoadDumpSrv)

        req = ontologyLoadDumpSrvRequest()
        req.file_url = "/someInvalidPath/testDump.owl"
        response = test_service(req)
        self.assertEqual(response.success, False)


## The main function. Initializes the Cognitive Exercise System functional tests
if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'OntologyFunc', OntologyFunc)

class TestBagSystemIO(unittest.TestCase):
    def test_init(self):
        self.assertTrue(BagSystemIO())

    def test_input(self):
        bag_system_io = BagSystemIO()
        input = [(0.1, (1, 2, 2, 2, 2, 2)), (0.1, (1, 2, 2, 2, 2, 2)),
                 (0.1, (1, 2, 2, 2, 2, 2))]
        output = [(0.1, (1, 2)), (0.1, (1, 2)), (0.1, (1, 2))]
        self.assertEqual(bag_system_io.get_input(input), output)

    def test_output(self):
        bag_system_io = BagSystemIO()
        input = [(0.1, (1, 2, 2, 2, 2, 2)), (0.1, (1, 2, 2, 2, 2, 2)),
                 (0.1, (1, 2, 2, 2, 2, 2))]
        output = [(0.1, (1, 2)), (0.1, (1, 2)), (0.1, (1, 2))]
        self.assertEqual(bag_system_io.get_output(input), output)

    def test_states(self):
        bag_system_io = BagSystemIO()
        input = [(0.1, (1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1)),
                 (0.1, (1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1))]
        output = [(0.1, (1, 1, 1, 1, 1, 1)), (0.1, (1, 1, 1, 1, 1, 1))]
        self.assertEqual(bag_system_io.get_states(input), output)


if __name__ == '__main__':
    rosunit.unitrun("adapt_kalman", 'test_bag_system_io', TestBagSystemIO)
Ejemplo n.º 14
0
        param(logm='errorf', rosm='logerr'),
        param(logm='fatalf', rosm='logfatal'),
    ])
    @patch('fiware_ros_bridge.logging.rospy')
    def test_log_w_params(self, mocked_rospy, logm, rosm):
        name = 'foo'
        message = 'test message'
        arg0 = 'arg0'
        arg1 = 'arg1'
        kwargs0 = 'kwargs0'
        kwargs1 = 'kwargs1'
        log_message = '[{name}:{caller}] {message}, {arg1}, {kwargs0}, {arg0}, {kwargs1}'.format(
            name=name,
            caller=self.__class__.__name__ + '.' + sys._getframe().f_code.co_name,
            message=message,
            arg0=arg0,
            arg1=arg1,
            kwargs0=kwargs0,
            kwargs1=kwargs1,
        )

        logger = getLogger(name)
        assert logger.name == name

        getattr(logger, logm)(message + ', {1}, {kwargs0}, {0}, {kwargs1}', arg0, arg1, kwargs1=kwargs1, kwargs0=kwargs0)
        getattr(mocked_rospy, rosm).assert_called_once_with(log_message)


if __name__ == '__main__':
    rosunit.unitrun('fiware_ros_bridge', 'test_logging', TestGetLogger)
Ejemplo n.º 15
0
        param(mcmd='circle', rcmd='circle'),
        param(mcmd='square', rcmd='square'),
        param(mcmd='triangle', rcmd='triangle'),
        param(mcmd='cross', rcmd='stop'),
        param(mcmd='up', rcmd='up'),
        param(mcmd='down', rcmd='down'),
        param(mcmd='left', rcmd='left'),
        param(mcmd='right', rcmd='right'),
        param(mcmd='invalid', rcmd=None),
    ])
    @patch('fiware_ros_bridge.cmd_bridge.rospy')
    def test__on_message(self, mocked_rospy, mcmd, rcmd):
        mocked_rospy.get_param.return_value = utils.get_cmd_params()
        mocked_client = MagicMock()

        msg = type('msg', (object,), {'payload': 'deviceid@move|{}'.format(mcmd)})
        CmdBridge()._on_message(mocked_client, None, msg)

        if mcmd in ('circle', 'square', 'triangle', 'cross', 'up', 'down', 'left', 'right'):
            mocked_rospy.Publisher.return_value.publish.assert_called_once_with(String(data=rcmd))
            mocked_client.publish.assert_called_once_with('/robot/turtlebot3/cmdexe',
                                                          'deviceid@move|cmd {} executed successfully'.format(mcmd))
        else:
            mocked_rospy.Publisher.return_value.publish.assert_not_called()
            mocked_client.publish.assert_called_once_with('/robot/turtlebot3/cmdexe',
                                                          'deviceid@move|unknown cmd {} did not executed'.format(mcmd))


if __name__ == '__main__':
    rosunit.unitrun('fiware_ros_bridge', 'test_cmd_bridge', TestCmdBridge)
Ejemplo n.º 16
0
        self.assertIsInstance(
            Constraint.create('LogBarrierMethod', 'test_log',
                              'x'), LogBarrierMethod,
            'Log barrier constraint object could not be created')
        self.assertIsInstance(
            Constraint.create('InverseBarrierMethod', 'test_inverse',
                              'x'), InverseBarrierMethod,
            'Inverse barrier constraint object could not be created')
        self.assertIsInstance(
            Constraint.create('PenaltyFunction', 'test_penalty', 'x'),
            PenaltyFunction, 'Penalty constraint object could not be created')

    def test_penalty(self):
        p_fcn = Constraint.create('PenaltyFunction', 'test_penalty', 'x')
        p_fcn.from_dict(self.penalty_params_valid)

        self.assertEquals(p_fcn.compute(0), 0,
                          'Invalid output for value in the feasible set')
        self.assertGreater(
            p_fcn.compute(self.penalty_params_valid['offset'] + 1), 0,
            'Invalid output for value outside of the feasible set')

    def test_barrier(self):
        pass


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, NAME, TestConstraint)
Ejemplo n.º 17
0
            for pt2 in g.points:
                path = pl.planner(makeRequest(g.id.uuid,
                                              pt1.id.uuid,
                                              pt2.id.uuid))

    def test_3x3_grid(self):
        # generate a fully-connected 3x3 grid
        g = grid_graph(-0.003, -0.003, 0.0, 0.0)
        pl = Planner(g)
        # all pairs of points should have a valid path
        for pt1 in g.points:
            for pt2 in g.points:
                path = pl.planner(makeRequest(g.id.uuid,
                                              pt1.id.uuid,
                                              pt2.id.uuid))

    def test_10x10_grid(self):
        # generate a fully-connected 10x10 grid
        g = grid_graph(0.0, 0.0, 0.01, 0.01)
        pl = Planner(g)
        # all pairs of points should have a valid path
        for pt1 in g.points:
            for pt2 in g.points:
                path = pl.planner(makeRequest(g.id.uuid,
                                              pt1.id.uuid,
                                              pt2.id.uuid))

if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'test_planner_py', TestPlanner) 
        capping of input values between 0 and 1."""
        # Preparing mocks within the widget
        self.psi.barSpeed = MagicMock()
        self.psi.barSpeed.setValue = MagicMock()

        # 0 speed should be displayed as 0%
        self.psi.set_speed(0)
        self.psi.barSpeed.setValue.assert_called_with(0)

        # 0.5 speed should be displayed as 50%
        self.psi.set_speed(.5)
        self.psi.barSpeed.setValue.assert_called_with(50)

        # 1 speed should be displayed as 100%
        self.psi.set_speed(1)
        self.psi.barSpeed.setValue.assert_called_with(100)

        # speed values below 0 should be displayed as 0%
        self.psi.set_speed(-1)
        self.psi.barSpeed.setValue.assert_called_with(0)

        # speed values above 1 should be displayed as 100%
        self.psi.set_speed(2)
        self.psi.barSpeed.setValue.assert_called_with(100)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun('pilz_status_indicator_rqt',
                    'test_status_indicator_widget', TestStatusIndicatorWidget)
        r = resolve_args('$(anon foo)/bar')
        self.assert_('/bar' in r)
        self.failIf('$(anon foo)' in r)        
        
            
        # test against strings that should not match
        noop_tests = [
            '$(find roslib', '$find roslib', '', ' ', 'noop', 'find roslib', 'env ROS_ROOT', '$$', ')', '(', '()',
            None, 
            ]
        for t in noop_tests:
            self.assertEquals(t, resolve_args(t))
        failures = [
            '$((find roslib))',  '$(find $roslib)',
            '$(find)', '$(find roslib roslib)', '$(export roslib)',
            '$(env)', '$(env ROS_ROOT alternate)',
            '$(env NOT_SET)',
            '$(optenv)',
            '$(anon)',
            '$(anon foo bar)',            
            ]
        for f in failures:
            try:
                resolve_args(f)
                self.fail("resolve_args(%s) should have failed"%f)
            except SubstitutionException: pass

if __name__ == '__main__':
  rosunit.unitrun('test_roslib', 'test_substitution_args', SubArgsTest, coverage_packages=['roslib.substitution_args'])

Ejemplo n.º 20
0
import roslib
roslib.load_manifest('test_roslib_comm')

import unittest
import rosunit
from test_roslib_comm.msg import *


class TestMd5sums(unittest.TestCase):
    def test_field_name_change(self):
        self.assertNotEquals(FieldNameChange1._md5sum,
                             FieldNameChange2._md5sum)

    def test_type_name_change(self):
        self.assertEquals(TypeNameChange1._md5sum, TypeNameChange2._md5sum)

    def test_type_name_change_array(self):
        self.assertEquals(TypeNameChangeArray1._md5sum,
                          TypeNameChangeArray2._md5sum)

    def test_type_name_change_complex(self):
        self.assertEquals(TypeNameChangeComplex1._md5sum,
                          TypeNameChangeComplex2._md5sum)


if __name__ == '__main__':
    rosunit.unitrun('test_roslib_comm',
                    'test_md5sums',
                    TestMd5sums,
                    coverage_packages=[])
Ejemplo n.º 21
0
            self.client.login()

            # Test unsuccessful delete of image from server.
            # Set an image on the server, then try to delete the image from
            # the server.
            self.object.set_image(generate_image())
            server.set_post_object_image_response(1)
            self.object.sync()

            # Delete the image.
            self.object.delete_image()

            # Try to delete the image from the server.
            codes = [400, 404, 500]
            for code in codes:
                server.set_delete_object_image_response(1, code=code)
                self.object.sync()

                self.assertFalse(self.object._needs_adding)
                self.assertFalse(self.object._needs_updating)
                self.assertFalse(self.object._needs_deleting)
                self.assertFalse(self.object._image_needs_setting)
                self.assertTrue(self.object._image_needs_deleting)

                self.assertTrue(self.object.image_is_on_server)


if __name__ == "__main__":
    rospy.init_node("test_local_objects")
    rosunit.unitrun("test_local_objects", "test_object", TestObject)
from __future__ import absolute_import, print_function

import uuid
import unittest

# module being tested:
import rocon_scheduler_requests.common as common

TEST_UUID_HEX = '0123456789abcdef0123456789abcdef'
TEST_UUID = uuid.UUID(hex=TEST_UUID_HEX)


class TestCommonModule(unittest.TestCase):
    """Unit tests for scheduler request manager common module.

    These tests do not require a running ROS core.
    """
    def test_feedback_default_topic(self):
        self.assertEqual(common.feedback_topic(TEST_UUID),
                         common.SCHEDULER_TOPIC + '_' + TEST_UUID_HEX)

    def test_feedback_topic(self):
        topic = common.feedback_topic(TEST_UUID, scheduler_topic='xxx')
        self.assertEqual(topic, 'xxx_' + TEST_UUID_HEX)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun('rocon_scheduler_requests_common', 'test_common_module',
                    TestCommonModule)
Ejemplo n.º 23
0
            self.assertLess(
                difference, 
                max_error,
                msg="Failed on request {}, with error {}, producing {}".format(
                    (fx, fy, moment), 
                    difference,
                    net
                )
            )
            return success

        tests = [
            (0, 0, 0),
            (20, 70, -3),
            (100, 0, 0),
            (0, 0, 5),
            (180, 0, 0),
            (200, 0, 0),
            (100, 20, -3),
            (120, 15, 12),
        ]
        results = {}
        for test in tests:
            result = run_test(*test)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'test_azi_drive', Test_Azi_Drive)
Ejemplo n.º 24
0
    def test_calculate_sync_velocity_angular(self):
        """
        Tests that the 'calculate_sync_velocity' function returns the correct value,
        given linear and angular velocities (i.e. a six-dimensional list).

        """
        max_time = 2.0

        error_1 = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
        velocity_1 = [1.0, -2.0, 3.0, -4.0, -5.0, 6.0]
        desired_1 = [0.5, -1.0, 1.5, -2.0, -2.5, 3.0]

        error_2 = [1.0, 2.0, 0.0, 0.0, 0.0, 6.0]
        velocity_2 = [1.0, -2.0, 3.0, -4.0, -5.0, 6.0]
        desired_2 = [0.5, -1.0, 0.0, 0.0, 0.0, 3.0]

        actual_1 = twist_synchronizer_utils.calculate_sync_velocity(
            error_1, velocity_1, max_time, angular_synchronization=True
        )
        actual_2 = twist_synchronizer_utils.calculate_sync_velocity(
            error_2, velocity_2, max_time, angular_synchronization=True
        )

        testing.assert_almost_equal(actual_1, desired_1, decimal=4)
        testing.assert_almost_equal(actual_2, desired_2, decimal=4)


if __name__ == '__main__':
    rosunit.unitrun(PKG, 'test_twist_synchronizer', TestTwistSynchronizer)
Ejemplo n.º 25
0
    def test_Servo_ExceedsVelocityLimitThrows(self):
        velocity_limits = self._robot.GetDOFVelocityLimits(self._indices)
        velocity_limits_small = -velocity_limits - 0.1 * numpy.ones(self._num_dofs)
        velocity_limits_large =  velocity_limits + 0.1 * numpy.ones(self._num_dofs)
        self.assertRaises(Exception, self._wam.Servo, (velocity_limits_small, 0.3))
        self.assertRaises(Exception, self._wam.Servo, (velocity_limits_large, 0.3))

    def test_Servo_InvalidAccelTimeThrows(self):
        velocity_limits = 0.1 * numpy.ones(self._num_dofs)
        self.assertRaises(Exception, self._wam.Servo, (velocity_limits, -0.1))
        self.assertRaises(Exception, self._wam.Servo, (velocity_limits,  0.0))

    def test_SetVelocityLimits_SetsLimits(self):
        velocity_limits = 0.1 * numpy.ones(self._num_dofs)
        self._wam.SetVelocityLimits(velocity_limits, 0.3)
        numpy.testing.assert_array_almost_equal(self._robot.GetDOFVelocityLimits(self._indices), velocity_limits)

    def test_MoveUntilTouch_ZeroDirectionThrows(self):
        self.assertRaises(Exception, self._wam.MoveUntilTouch, (numpy.zeros(3), 0.1))

    def test_MoveUntilTouch_ZeroDistanceThrows(self):
        self.assertRaises(Exception, self._wam.MoveUntilTouch, (numpy.array([ 1., 0., 0. ]), 0.0))

    def test_MoveUntilTouch_NonPositiveForceThrows(self):
        self.assertRaises(Exception, self._wam.MoveUntilTouch, (numpy.array([ 1., 0., 0. ]), 0.1, 0.))

if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'test_wam', WamTest)
Ejemplo n.º 26
0
 def perform_rostest(self, test_pkg):
     TestCase = type(test_pkg + '_test_class', (unittest.TestCase, ),
                     self._evaluation_tests)
     rosunit.unitrun(test_pkg, test_pkg + '_flexbe_tests', TestCase)
Ejemplo n.º 27
0
        l = len(cache.getInterval(rospy.Time(0), rospy.Time(4)))
        self.assertEquals(l, 5, "invalid number of messages" + " returned in getInterval 3")

        s = cache.getElemAfterTime(rospy.Time(0)).header.stamp
        self.assertEqual(s, rospy.Time(0), "invalid msg return by getElemAfterTime")

        s = cache.getElemBeforeTime(rospy.Time(3.5)).header.stamp
        self.assertEqual(s, rospy.Time(3), "invalid msg return by getElemBeforeTime")

        s = cache.getLastestTime()
        self.assertEqual(s, rospy.Time(4), "invalid stamp return by getLastestTime")

        s = cache.getOldestTime()
        self.assertEqual(s, rospy.Time(0), "invalid stamp return by getOldestTime")

        # Add another msg to fill the buffer
        msg = AnonymMsg()
        msg.header.stamp = rospy.Time(5)
        cache.add(msg)

        # Test that it discarded the right one
        s = cache.getOldestTime()
        self.assertEqual(s, rospy.Time(1), "wrong message discarded")


if __name__ == "__main__":
    import rosunit

    rosunit.unitrun(PKG, "test_message_filters_cache", TestCache)
Ejemplo n.º 28
0
    def recv_job_status(self, msg):
        if msg.data == "finished":
            self.job_finish_event.set()

    def test_pick_and_place(self):
        rospy.Subscriber('/state_machine/state', String, self.recv_state)
        rospy.Subscriber('/job_status', String, self.recv_job_status)
        self._start_pick_place = rospy.Publisher('/start_pick_place',
                                                 Empty,
                                                 queue_size=10)

        rospy.sleep(1)

        # Wait until the system is initialized, if it is still uninitialized
        if not self.robot_state == 'standby':
            rospy.loginfo("Waiting until system is ready")
            self.robot_state_event.clear()
            self.robot_state_event.wait()
            rospy.sleep(1)

        rospy.loginfo("Sending command to start the job")
        self.job_finish_event.clear()
        self._start_pick_place.publish()
        self.job_finish_event.wait()


if __name__ == '__main__':
    # unittest.main()
    import rosunit
    rosunit.unitrun(PKG, 'test_pick_place', TestPickPlace)
Ejemplo n.º 29
0
class TPCC_Test(Abstractclass_Unittest_Triadic):
    def __init__(self, *args):
        super(TPCC_Test, self).__init__(*args)
        self._unique_id = "tpcc"

    # data1 contains data for only 2 objects so the default tests has to be with data2
    # would be same as test_without_bounding_boxes in other QSRs tests
    def test_defaults(self):
        self.assertItemsEqual(*self.defaults("data3", "data3_tpcc_defaults.txt"))

    def test_qsrs_for_global_namespace(self):
        self.assertItemsEqual(*self.qsrs_for_global_namespace("data3", "data3_tpcc_qsrs_for_global_namespace.txt"))

    def test_qsrs_for_qsr_namespace(self):
        self.assertItemsEqual(*self.qsrs_for_qsr_namespace("data3", "data3_tpcc_qsrs_for_qsr_namespace.txt"))
        # precedes "for_all_qsrs" namespace
        self.assertItemsEqual(*self.qsrs_for_qsr_namespace_over_global_namespace("data3",
                                                                                 "data3_tpcc_qsrs_for_qsr_namespace.txt"))

    def test_with_bounding_boxes(self):
        self.assertItemsEqual(*self.defaults("data2", "data2_tpcc_defaults.txt"))

    def test_floats(self):
        self.assertItemsEqual(*self.defaults("data4", "data4_tpcc_defaults.txt"))


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun("qsr_lib", "tpcc_test", TPCC_Test, sys.argv)
        cs_params.P[3].y = 100
        cs_params.T[0].x = 0
        cs_params.T[0].y = 0
        cs_params.resolution = 1000

        try:
            self.projector_manager.connect_and_setup()
            status = self.projector_manager.get_connection_status()
            if status:
                # create coordinate system
                self.projector_manager.define_coordinate_system(
                    cs_params, False)
                cs_read = self.projector_manager.get_coordinate_system_params(
                    name)
                self.assertEquals(cs_read.distance, cs_params.distance)
                # create axes and frame
                self.projector_manager.cs_axes_create(cs_params)
                self.projector_manager.cs_frame_create(cs_params)
                pass
            else:
                self.fail("connection error")

        except Exception as e:
            self.fail("Exception raised: {}".format(e))


if __name__ == '__main__':
    rosunit.unitrun('z_laser_zlp1',
                    'test_manager_coordinate_system',
                    TestProjectorManager,
                    sysargs=None)
Ejemplo n.º 31
0
import roslib
roslib.load_manifest(PKG)


def call_xacro(xml_file):
    assert os.path.isfile(xml_file), 'Invalid XML xacro file'
    return subprocess.check_output(['xacro', '--inorder', xml_file])


class TestRexROVURDFFiles(unittest.TestCase):
    def test_xacro(self):
        # Retrieve the root folder for the tests
        test_dir = os.path.abspath(os.path.dirname(__file__))
        robots_dir = os.path.join(test_dir, '..', 'robots')

        for item in os.listdir(robots_dir):
            if 'oberon' in item:
                continue
            if not os.path.isfile(os.path.join(robots_dir, item)):
                continue
            output = call_xacro(os.path.join(robots_dir, item))
            self.assertNotIn(output, 'XML parsing error',
                             'Parsing error found for file {}'.format(item))
            self.assertNotIn(output, 'No such file or directory',
                             'Some file not found in {}'.format(item))


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, NAME, TestRexROVURDFFiles)
Ejemplo n.º 32
0
        req.file_size = len(file_bytes)
        response = up_prox(req)

        status = response.status

        self.assertEqual( status, True )
if __name__ == '__main__':
    import rosunit
    home = expanduser("~")
    if os.path.isdir(home+"/rapp_platform_files/maps/functional_test"):
        shutil.rmtree(home+"/rapp_platform_files/maps/functional_test")
    rospack = rospkg.RosPack()
    map_server_path = rospack.get_path("rapp_map_server")

    shutil.copytree(map_server_path+"/maps/", home+"/rapp_platform_files/maps/functional_test/")
    rosunit.unitrun(PKG, 'PathPlanFunc', PathPlanFunc)
    shutil.rmtree(home+"/rapp_platform_files/maps/functional_test")













# 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.
#
# Author: Brian Gerkey

PKG = 'rosrt'
import roslib; roslib.load_manifest(PKG)

import unittest
import os
from subprocess import Popen, PIPE

class TestPublisherNoInitializeTestCase(unittest.TestCase):
  
    # Check that test_publisher_no_initialize exits cleanly, as opposed to,
    # for example, seg-faulting, #3569.
    def test_no_initialize(self):
        cmd = os.path.join(roslib.packages.get_pkg_dir(PKG), 'bin', 'test_publisher_no_initialize')
        p = Popen([cmd], stdout=PIPE, stderr=PIPE)
        p.communicate()
        self.assertEquals(p.returncode, 0)

if __name__ == "__main__":
    import rosunit
    rosunit.unitrun(PKG, 'test_publisher_no_initialize', TestPublisherNoInitializeTestCase)
            self.fail("error test3")

    # test start projection without active coordinate system defined should return error
    def test4_start_proj(self):

        license_path = (os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/lic/1900027652.lic')
        projector_manager = ZLPProjectorManager(projector_IP = "192.168.10.10", 
                                                server_IP = "192.168.10.11", 
                                                connection_port = 9090, 
                                                lic_path=license_path)

        try:
            projector_manager.connect_and_setup()
            status = projector_manager.get_connection_status()
            if status:
                projector_manager.start_projection()
                projector_manager.deactivate()
                projector_manager.client_server_disconnect()
                pass
            else:
                self.fail("error test4")

        except Exception:
            projector_manager.deactivate()
            projector_manager.client_server_disconnect()
            pass


if __name__ == '__main__':
    rosunit.unitrun('z_laser_zlp1', 'test_manager_connection', TestProjectorManager,  sysargs=None)
Ejemplo n.º 35
0
    # *** abstractmethods
    def qsrs_for_global_namespace(self, world_name, gt_filename):
        dynamic_args = deepcopy(self.__dynamic_args)
        dynamic_args["for_all_qsrs"] = {"qsrs_for": [("o2", "o1"), "o2"]}
        return self.custom(world_name, gt_filename, dynamic_args)

    def qsrs_for_qsr_namespace(self, world_name, gt_filename):
        dynamic_args = deepcopy(self.__dynamic_args)
        # cherry pick some of the qsrs
        dynamic_args["rcc2"] = {"qsrs_for": [("o1", "o2")]}
        dynamic_args["qtcbs"]["qsrs_for"] = [("o1", "o2")]
        dynamic_args["mwe"] = {"qsrs_for": [("o1", "o2")]}
        dynamic_args["mos"] = {"qsrs_for": ["o1"]}
        return self.custom(world_name, gt_filename, dynamic_args)

    def qsrs_for_qsr_namespace_over_global_namespace(self, world_name, gt_filename):
        dynamic_args = deepcopy(self.__dynamic_args)
        dynamic_args["for_all_qsrs"] = {"qsrs_for": [("o2", "o1"), "o2"]}
        # cherry pick some of the qsrs
        dynamic_args["rcc2"] = {"qsrs_for": [("o1", "o2")]}
        dynamic_args["qtcbs"]["qsrs_for"] = [("o1", "o2")]
        dynamic_args["mwe"] = {"qsrs_for": [("o1", "o2")]}
        dynamic_args["mos"] = {"qsrs_for": ["o1"]}
        return self.custom(world_name, gt_filename, dynamic_args)
    # *** eof abstractmethods


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun("qsr_lib", "multiple_test", Multiple_Test, sys.argv)
Ejemplo n.º 36
0
    @patch("sensehat_ros.host.SenseHat")
    def test_get_environmental(self, sense):
        # Configure mocked hardware
        senseObj = sense.return_value   # to track instance methods we need to target the instance mock, not the class
        senseObj.get_humidity.return_value = 1.0
        senseObj.get_temperature_from_humidity.return_value = 2.0
        senseObj.get_temperature_from_pressure.return_value = 3.0
        senseObj.get_pressure.return_value = 4.0

        # Create a patched Host without requiring the SenseHat hardware
        host = self.get_host(smoothing=0)

        # Read sensor values
        environmental = host._get_environmental(datetime.now())
        senseObj.get_humidity.assert_called_once()
        senseObj.get_temperature_from_humidity.assert_called_once()
        senseObj.get_temperature_from_pressure.assert_called_once()
        senseObj.get_pressure.assert_called_once()

        # Assert
        self.assertEqual(environmental.humidity, self.calibration['humidity'] + 1)
        self.assertEqual(environmental.temperature_from_humidity, self.calibration['temperature_from_humidity'] + 2)
        self.assertEqual(environmental.temperature_from_pressure, self.calibration['temperature_from_pressure'] + 3)
        self.assertEqual(environmental.pressure, self.calibration['pressure'] + 4)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'TestHost', TestHost)
Ejemplo n.º 37
0
        self.assertRaises(TypeError, SEUID, ("hello", "world"))

    def test_msg_hostmsg(self):
        s = SEUID(hs)
        self.assertEqual(s.host, "127.0.0.1")

    def test_get_seuid(self):
        s = SEUID(hs)
        self.assertEqual("h!127.0.0.1", s.get_seuid("host"))

    def test_get_seuid_invalid(self):
        s = SEUID()
        self.assertRaises(AttributeError, s.get_seuid, "host")
        s = SEUID(hs)
        self.assertRaises(KeyError, s.get_seuid, "node")


if __name__ == '__main__':
    import rosunit

    data = rospy.get_param('/arni/test/mockdata')
    hs = HostStatistics()
    for k in data.keys():
        try:
            setattr(hs, k, data[k])
        except Exception:
            pass

    rosunit.unitrun(PKG, 'test_seuid', TestSeuid)

Ejemplo n.º 38
0
        error = [1.0 for _ in range(10)]
        max_error = 20.0
        error[2] = max_error

        # Not using a ROS bag to calculate the KPIs
        kpi = KPI.get_kpi('max_error', 'test', False)
        self.assertIsNotNone(kpi, 'The KPI instance was not created properly')
        self.assertEqual(kpi.compute(error), max_error,
                         'Max. error was not calculated properly')

    def test_mean_error_without_bag(self):
        error = np.random.rand(10) + 2
        # Not using a ROS bag to calculate the KPIs
        kpi = KPI.get_kpi('mean_error', 'test', False)
        self.assertIsNotNone(kpi, 'The KPI instance was not created properly')
        self.assertIsNotNone(kpi.compute(error),
                             'Mean error was not calculated properly')

    def test_rms_error_without_bag(self):
        error = np.random.rand(10) + 2
        # Not using a ROS bag to calculate the KPIs
        kpi = KPI.get_kpi('rmse', 'test', False)
        self.assertIsNotNone(kpi, 'The KPI instance was not created properly')
        self.assertIsNotNone(kpi.compute(error),
                             'RMS error was not calculated properly')


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, NAME, TestKPIS)
Ejemplo n.º 39
0
      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__':
  rosunit.unitrun('test_roslib', 'test_network', NetworkTest, coverage_packages=['roslib.network'])

Ejemplo n.º 40
0
        """
        r in 'rxyz' is 'r'otating frames indicating rotations are applied consecutively with respect to current
        frames' axes, "relative-rotation". Order of rotations are first X, second Y and third Z. Rotation matrix
        composition rule for relative rotations: Rx * Ry * Rz.

        s in 'sxyz' is 's'tationary frames indicating rotations are applied with respect to the coordinate frame
        of the INITIAL frame, "fixed-axis rotation". Rotation matrix composition rule for fixed-axis rotations:
        Rz * Ry * Rx.
        """

        Rx_90 = tr.rotation_matrix(
            math.pi / 4, [1, 0, 0])  # first, rotate 90 degrees around x axis
        Ry_90 = tr.rotation_matrix(
            math.pi / 5,
            [0, 1, 0])  # second, 45 degrees around y axis of the current frame
        Rz_90 = tr.rotation_matrix(
            math.pi / 6,
            [0, 0, 1])  # third, 30 degrees around z axis of the current frame

        R1 = np.matmul(Rz_90, Ry_90)
        R = np.matmul(R1, Rx_90)

        euler_angles = tr.euler_from_matrix(R, 'sxyz')
        euler_angles_expected = [math.pi / 4, math.pi / 5, math.pi / 6]

        np.testing.assert_almost_equal(euler_angles, euler_angles_expected)


if __name__ == '__main__':
    rosunit.unitrun('apriltags2_ros', 'test_rotation_utils', RotationUtils)
Ejemplo n.º 41
0
#!/usr/bin/env python
PKG='wet6'
import roslib; roslib.load_manifest(PKG)

import sys
import os
import unittest

class TestSample(unittest.TestCase):

	def test_sample(self):
		# nothing to report
		pass
 
if __name__ == '__main__':
	import rosunit
	rosunit.unitrun(PKG, 'test_urdf', TestSample) 
class TestFaceDetector(unittest.TestCase):
    def set_up(self):
        

        # Harr cascade classifiers
        
        self.c1 = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
        self.c2 = cv2.CascadeClassifier("haarcascade_frontalface_alt")
        self.c3 = cv2.CascadeClassifier("haarcascade_profileface.xml")

        self.test_image_face = self.convert_cv_to_img(cv2.imread('test_face.jpg',0))
        self.test_image_no_face = self.convert_cv_to_img(cv2.imread('test_no_face.jpg',0))
        self.no_image = np.zeros((0,0), np.uint8)
        self.test_images_good = self.import_test_images
        self.test_images_bad = self.generate_bad_images

        def import_test_images(self):
            test_images = []
            prefix = "i"
            filetype = ".jpg"
            for suffix in range(0,12):
                im_name = prefix+str(suffix)+filetype
                im = self.convert_cv_to_img(cv2.imread(im_name,0))
                test_images.append
            return test_images

        def generate_bad_images(self):
            good images = self.import_test_images()
            bad_images = good_images[0:6]
            bad_images.append(self.no_image)
            bad_images = good_images[7:11]
            bad_images.append(self.no_image)
            return bad_images

        def test_face_detector_face(self):
            fd.set_classifiers(c1, c2, c3)
            face_box = fd.detect_face(self.test_image_face)
            if face_box is not None:
            x1 = face_box.x
            y1 = face_box.y
            x2 = face_box.width + x1
            y2 = face_box.height + y1
            self.assertTrue(face_box is not None, "Image contains a face between (%d,%d) and (%d,%d)"%(x1,y1,x2,y2))

        def test_face_detector_no_face(self):
            fd.set_classifiers(c1, c2, c3)
            face_box = fd.detect_face(self.test_image_face)
            x1 = face_box.x
            y1 = face_box.y
            x2 = face_box.width + x1
            y2 = face_box.height + y1
            self.assertTrue(face_box is None, "Image does not contain a face!")

        def test_multiple_faces(self, faces):
            fd.set_classifiers(c1, c2, c3)
            for image in faces:
                index = 0
                face_box = fd.detect_face(image)
                if face_box is not None:
                    x1 = face_box.x
                    y1 = face_box.y
                    x2 = face_box.width + x1
                    y2 = face_box.height + y1

                    self.assertTrue(face_box is not None, "Image %d contains a face between (%d,%d) and (%d,%d)"%(index,x1,y1,x2,y2))
                else:
                    self.assertTrue(face_box is None, "Image %d contains no face!"%s(index))
                index+=1

        def test_face_detector_multiple_good_faces(self):
            self.test_multiple_faces(self.test_images_good)

        def test_face_detector_multiple_bad_faces(self):
            self.test_multiple_faces(self.test_images_bad)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'unit_test_face_detector', TestFaceDetector)
Ejemplo n.º 43
0
import unittest

import rosunit
import rosdep.core
import rosdep.installers

class RosdepSourceTest(unittest.TestCase):
    
    def test_aptinstaller_installed(self):
        args = {}
        args["packages"] = "libc6 gcc"
        ai = rosdep.installers.AptInstaller(args)
        self.assertTrue(ai.check_presence())
        ## Requires sudo self.assertTrue(ai.generate_package_install_command())
        
    def test_aptinstaller_not_installed(self):
        args = {}
        args["packages"] = "not-a-package"
        ai = rosdep.installers.AptInstaller(args)
        self.assertFalse(ai.check_presence())
        ## Requres sudo self.assertFalse(ai.generate_package_install_command())



        

if __name__ == '__main__':
  os.environ["ROSDEP_TEST_OS"] = "rosdep_test_os"
  rosunit.unitrun('test_rosdep', 'test_source', RosdepSourceTest, coverage_packages=['rosdep.core'])  

Ejemplo n.º 44
0
from rqt_dep.dotcode_pack import RosPackageGraphDotcodeGenerator

PKG = 'rqt_deps'


class DotcodeGeneratorTest(unittest.TestCase):
    def test_packages_only(self):
        with patch('rospkg.RosPack') as rospack:
            with patch('rospkg.RosStack') as rosstack:
                factoryMock = Mock()
                graphMock = Mock()
                rospack.list.return_value = []
                rosstack.list.return_value = []
                factoryMock.get_graph.return_value = graphMock
                gen = RosPackageGraphDotcodeGenerator(rospack, rosstack)
                graph = gen.generate_dotcode(factoryMock)

                rospack.list.assert_called()
                rosstack.list.assert_called()
                factoryMock.get_graph.assert_called_with(simplify=True,
                                                         rank='same',
                                                         ranksep=0.2,
                                                         rankdir='TB')
                factoryMock.create_dot.assert_called_with(graphMock)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'test_packages_only', DotcodeGeneratorTest)
Ejemplo n.º 45
0
        # Points
        points = []
        normals = []
        for item in docking:
            points.append(item['point'])
            normals.append(item['normal'])

        # Expected
        expected_points = [[3, 5], [4, 4], [6, 4]]
        expected_normals = [[1, 0], [0, 1], [0, 1]]

        outcome = True
        for p in expected_points:
            if not p in points:
                outcome = False
                break
        if not np.allclose(normals, expected_normals):
            outcome = False

        err_msg = 'wrong result is: '
        for i in range(3):
            err_msg += '[' + `points[i][0]` + ', ' + `points[i][1]` + ']'
        for i in range(3):
            err_msg += '[' + `normals[i][0]` + ', ' + `normals[i][1]` + ']'

        self.assertTrue(outcome, err_msg)

if __name__ == '__main__':
    rosunit.unitrun(PKG, 'docking_test', TestDocking)
Ejemplo n.º 46
0
            board.n_rows = setup.rows
            board.dim = self.board_width_dim

            mc = MonoCalibrator([board],
                                flags=cv2.CALIB_FIX_K3,
                                pattern=setup.pattern)

            if 0:
                # display the patterns viewed by the camera
                for pattern_warped in self.limages[i]:
                    cv2.imshow("toto", pattern_warped)
                    cv2.waitKey(0)

            mc.cal(self.limages[i])
            self.assert_good_mono(mc, self.limages[i], setup.lin_err)

            # Make sure the intrinsics are similar
            err_intrinsics = numpy.linalg.norm(mc.intrinsics - self.K,
                                               ord=numpy.inf)
            self.assert_(
                err_intrinsics < setup.K_err,
                'intrinsics error is %f for resolution i = %d' %
                (err_intrinsics, i))
            print('intrinsics error is %f' %
                  numpy.linalg.norm(mc.intrinsics - self.K, ord=numpy.inf))


if __name__ == '__main__':
    #rosunit.unitrun('camera_calibration', 'directed', TestDirected)
    rosunit.unitrun('camera_calibration', 'artificial', TestArtificial)
        
        #remove user        
        ros_service = rospy.get_param("rapp_mysql_wrapper_remove_platform_user_service_topic")
        rospy.wait_for_service(ros_service)    
        test_service = rospy.ServiceProxy(ros_service, removePlatformUserSrv)
        req = removePlatformUserSrvRequest()
        req.username="******"             
        response = test_service(req)     
        self.assertTrue(response.success) 
        
        
        
## The main function. Initializes the Cognitive Exercise System functional tests
if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'CognitiveExerciseFunc', CognitiveExerciseFunc)














Ejemplo n.º 48
0
        self.assertEqual(expected, result)

    def test_add(self):
        expected = 3
        result = self._calculator.add(1, 2)
        self.assertEqual(expected, result)

        expected = 2.5
        result = self._calculator.add(1.7, 0.8)
        self.assertAlmostEqual(expected, result)

    def test_set_value(self):
        value = 4
        self._calculator.set_value(value)

        result = self._calculator.get_value()
        self.assertEqual(value, result)

    def test_delete_value(self):
        self._calculator.set_value(2.4)
        self._calculator.delete_value()

        expected = None
        result = self._calculator.get_value()
        self.assertEqual(expected, result)


if __name__ == "__main__":
    import rosunit
    rosunit.unitrun('frootspi_hello_world', 'test_hello', TestHello)
Ejemplo n.º 49
0
                        "Launch file not copied.")
        self.assertTrue(os.path.exists(self.pjoin("etc/ros", os.getenv("ROS_DISTRO"), "baz.d/b.launch")),
                        "Launch file not copied.")

    def test_uninstall(self):
        j = segway_upstart.Job(name="boo")
        j.add('segway_upstart', glob='test/launch/*.launch')
        j.install(sudo=None, root=self.root_dir)
        j.uninstall(sudo=None, root=self.root_dir)

        self.assertFalse(os.path.exists(self.pjoin("etc/ros", os.getenv("ROS_DISTRO"), "boo.d")),
                         "Job dir not removed.")
        self.assertFalse(os.path.exists(self.pjoin("etc/ros", os.getenv("ROS_DISTRO"), "usr/sbin/foo-start")),
                         "Start script not removed.")

    def test_uninstall_user_file(self):
        j = segway_upstart.Job(name="goo")
        j.add('segway_upstart', glob='test/launch/*.launch')
        j.install(sudo=None, root=self.root_dir)
        with open(self.pjoin("etc/ros", os.getenv("ROS_DISTRO"), "goo.d/c.launch"), "w") as f:
            f.write("<launch></launch>")
        j.uninstall(sudo=None, root=self.root_dir)

        self.assertTrue(os.path.exists(self.pjoin("etc/ros", os.getenv("ROS_DISTRO"), "goo.d/c.launch")),
                        "User launch file wrongly removed.")


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun('segway_upstart', 'test_basics', TestBasics)
Ejemplo n.º 50
0
        }

        r = Robot.from_urdf_file(donbot_urdf)
        self.assertSetEqual(set(r.get_joint_names_controllable()), expected)

    def test_get_joint_names_boxy(self):
        expected = {
            u'left_arm_2_joint', u'neck_joint_end', u'neck_wrist_1_joint',
            u'right_arm_2_joint', u'right_arm_4_joint', u'neck_wrist_3_joint',
            u'right_arm_3_joint', u'right_gripper_base_gripper_right_joint',
            u'left_gripper_base_gripper_right_joint', u'left_arm_0_joint',
            u'right_gripper_base_gripper_left_joint', u'left_arm_4_joint',
            u'left_arm_6_joint', u'right_arm_1_joint', u'left_arm_1_joint',
            u'neck_wrist_2_joint', u'triangle_base_joint', u'neck_elbow_joint',
            u'right_arm_5_joint', u'left_arm_3_joint',
            u'neck_shoulder_pan_joint', u'right_arm_0_joint',
            u'neck_shoulder_lift_joint', u'left_arm_5_joint',
            u'left_gripper_base_gripper_left_joint', u'right_arm_6_joint'
        }

        r = Robot.from_urdf_file(body_urdf)
        self.assertSetEqual(set(r.get_joint_names_controllable()), expected)


if __name__ == '__main__':
    import rosunit

    rosunit.unitrun(package=PKG,
                    test_name='TestSymengineController',
                    test=TestSymengineController)
Ejemplo n.º 51
0
    def _Timer_callback(self, event):
        self.timer_callbacks += 1
        self.timer_event = event

    def callback(event):
        print('last_expected:        ', event.last_expected)
        print('last_real:            ', event.last_real)
        print('current_expected:     ', event.current_expected)
        print('current_real:         ', event.current_real)
        print('current_error:        ', (event.current_real - event.current_expected).to_sec())
        print('profile.last_duration:', event.last_duration)
        if event.last_real:
            print('last_error:           ', (event.last_real - event.last_expected).to_sec(), 'secs')

    def test_Timer(self):
        import rospy
        timer = rospy.Timer(rospy.Duration(1), self._Timer_callback)
        time.sleep(10)
        timer.shutdown()
        
        # make sure we got an approximately correct number of callbacks
        self.assert_(abs(self.timer_callbacks - 10) < 2)
        # make sure error is approximately correct.  the Timer
        # implementation tracks error in accumulated real time.
        ev = self.timer_event
        self.assert_(ev is not None)
        self.assert_(abs((ev.current_real - ev.current_expected).to_sec()) < 2.)
        
if __name__ == '__main__':
    rosunit.unitrun('test_rospy', sys.argv[0], TestRospyTimerOnline, coverage_packages=['rospy.timer'])
Ejemplo n.º 52
0
        timeout_t = time.time() + 5.
        t2 = TestTask(task2)
        t2.start()
        while not t2.done and time.time() < timeout_t:
            time.sleep(0.5)
        self.assert_(t2.success)
        self.assert_('hello' in t2.value.data)

        # test wait for message with timeout FAILURE
        def task3():
            # #2842 raising bounds from .1 to .3 for amazon VM
            return rospy.wait_for_message('fake_topic',
                                          std_msgs.msg.String,
                                          timeout=.3)

        timeout_t = time.time() + 2.
        t3 = TestTask(task3)
        t3.start()
        while not t3.done and time.time() < timeout_t:
            time.sleep(0.5)
        self.failIf(t3.success)
        self.assert_(t3.done)
        self.assert_(t3.value is None)


if __name__ == '__main__':
    rosunit.unitrun('test_rospy',
                    sys.argv[0],
                    TestRospyClientOnline,
                    coverage_packages=['rospy.client', 'rospy.msproxy'])
        test_service = rospy.ServiceProxy(conf_service, AudioProcessingSetNoiseProfileSrv)

        req = AudioProcessingSetNoiseProfileSrvRequest()
        req.audio_file_type = 'nao_wav_6_ch'
        req.noise_audio_file = aux + '/silence_wav_d05_a1.wav'
        req.user = '******'
        response = test_service(req)
        self.assertNotEqual( response.error, '' )
        self.assertEqual( response.success, 'false' )

    def test_setNoiseProfileService_no_silence_file(self):
        rospack = rospkg.RosPack()
        aux = rospack.get_path('rapp_testing_tools') + '/test_data'

        conf_service = rospy.get_param("rapp_audio_processing_set_noise_profile_topic")
        rospy.wait_for_service(conf_service)
        test_service = rospy.ServiceProxy(conf_service, AudioProcessingSetNoiseProfileSrv)

        req = AudioProcessingSetNoiseProfileSrvRequest()
        req.audio_file_type = 'nao_wav_4_ch'
        req.noise_audio_file = aux + '/silence_wav_d05_a1_nope.wav'
        req.user = '******'
        response = test_service(req)
        self.assertNotEqual( response.error, '' )
        self.assertEqual( response.success, 'false' )

if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'AudioProcessingSetNoiseProfileFunc', AudioProcessingSetNoiseProfileFunc)

Ejemplo n.º 54
0
        plasm.connect(inc, "out", printer, "in")
        #
        #    o = open('graph.dot', 'w')
        #    print >>o, plasm.viz()
        #    o.close()
        #    print "\n", plasm.viz(), "\n"
        sched = Sched(plasm)
        sched.execute(niter)

        print("RESULT:", inc.outputs.out)
        shouldbe = float(n_nodes + niter - 1)
        print("expected:", shouldbe)
        assert inc.outputs.out == shouldbe

    def test_plasm1(self):
        self.execute_plasm(ecto.Scheduler, 1, 1, 1, 50)

    def test_plasm2(self):
        self.execute_plasm(ecto.Scheduler, 1, 5, 5, 50)

    def test_plasm3(self):
        self.execute_plasm(ecto.Scheduler, 10, 10, 10, 50)

    def test_plasm4(self):
        self.execute_plasm(ecto.Scheduler, 15, 25, 35, 50)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun('ecto', 'test_lineplasm', TestActionlib)
Ejemplo n.º 55
0
go here</author>
  <license>Public Domain
with other stuff</license>
  <url>http://ros.org/stack/</url>
  <logo>http://www.willowgarage.com/files/willowgarage/robot10.jpg</logo>
  <depend stack="stackname" />
  <depend stack="common"/>
</stack>"""

STACK_INVALID1 = """<stack>
  <description brief="a brief description">Line 1</description>
  <author>The authors</author>
  <license>Public Domain</license>
  <rosdep name="python" />
</stack>"""

STACK_INVALID2 = """<stack>
  <description brief="a brief description">Line 1</description>
  <author>The authors</author>
  <license>Public Domain</license>
  <export>
    <cpp cflags="-I${prefix}/include" lflags="-L${prefix}/lib -lros"/>
    <cpp os="osx" cflags="-I${prefix}/include" lflags="-L${prefix}/lib -lrosthread -framework CoreServices"/>
  </export>
</stack>"""

    
if __name__ == '__main__':
  rosunit.unitrun('test_roslib', 'test_stack_manifest', RoslibStackManifestTest, coverage_packages=['roslib.stack_manifest'])  

Ejemplo n.º 56
0
    def test_single_merge(self):
        msg1 = Request(id=unique_id.toMsg(TEST_UUID),
                       resources=[TEST_WILDCARD],
                       status=Request.NEW)
        rset = RequestSet([msg1], RQR_UUID)
        self.assertEqual(rset[TEST_UUID].msg.status, Request.NEW)
        self.assertEqual(rset[TEST_UUID].msg.resources, [TEST_WILDCARD])
        self.assertEqual(rset[TEST_UUID].msg.id, unique_id.toMsg(TEST_UUID))

        # merge an updated request set: resource list should change
        msg2 = Request(id=unique_id.toMsg(TEST_UUID),
                       resources=[TEST_RESOURCE],
                       status=Request.GRANTED)
        rset.merge(RequestSet([msg2], RQR_UUID, contents=ActiveRequest))
        self.assertEqual(len(rset), 1)
        self.assertIn(TEST_UUID, rset)
        self.assertEqual(rset[TEST_UUID].msg.status, Request.GRANTED)
        self.assertEqual(rset[TEST_UUID].msg.resources, [TEST_RESOURCE])
        sch_msg = SchedulerRequests(requester=unique_id.toMsg(RQR_UUID),
                                    requests=[msg2])
        self.assertEqual(rset.to_msg(stamp=rospy.Time()), sch_msg)


if __name__ == '__main__':
    import rosunit
    rosunit.unitrun('concert_scheduler_requests', 'test_transitions',
                    TestTransitions)
    rosunit.unitrun('concert_scheduler_requests', 'test_request_sets',
                    TestRequestSets)
Ejemplo n.º 57
0
        self.assertEqual(data["autonomous"], object_.autonomous)

    def test_object_image_serializer(self):
        """Tests object image serializer can be deserialized."""
        # Create random 40 x 30 RGB image.
        width = 40
        height = 30
        nparr = np.random.randint(0, 256, (width, height, 3)).astype(np.uint8)

        # Convert to ROS Image.
        bridge = CvBridge()
        msg = bridge.cv2_to_imgmsg(nparr)

        # Serialize.
        png = serializers.ObjectImageSerializer.from_msg(msg)

        # Deserialize.
        converted_msg = serializers.ObjectImageSerializer.from_raw(png)

        # Convert to array.
        converted_img = bridge.imgmsg_to_cv2(converted_msg)
        converted_arr = np.asarray(converted_img)

        # Test if we get the original image.
        self.assertTrue((converted_arr == nparr).all())


if __name__ == "__main__":
    rospy.init_node("test_serializers")
    rosunit.unitrun("test_serializers", "test_serializers", TestSerializers)
Ejemplo n.º 58
0
        self.assertEqual(data["autonomous"], object_.autonomous)

    def test_object_image_serializer(self):
        """Tests object image serializer can be deserialized."""
        # Create random 40 x 30 RGB image.
        width = 40
        height = 30
        nparr = np.random.randint(0, 256, (width, height, 3)).astype(np.uint8)

        # Convert to ROS Image.
        bridge = CvBridge()
        msg = bridge.cv2_to_imgmsg(nparr)

        # Serialize.
        png = serializers.ObjectImageSerializer.from_msg(msg)

        # Deserialize.
        converted_msg = serializers.ObjectImageSerializer.from_raw(png)

        # Convert to array.
        converted_img = bridge.imgmsg_to_cv2(converted_msg)
        converted_arr = np.asarray(converted_img)

        # Test if we get the original image.
        self.assertTrue((converted_arr == nparr).all())


if __name__ == "__main__":
    rospy.init_node("test_serializers")
    rosunit.unitrun("test_serializers", "test_serializers", TestSerializers)
                service_name, ontologyIsSubSuperClassOfSrv)

        req = ontologyIsSubSuperClassOfSrvRequest()
        req.parent_class = 'Aoua'
        req.child_class = 'Aoua2'
        req.recursive = True

        response = test_service(req)
        self.assertEqual(response.result, False)
        self.assertEqual(response.success, False)
        self.assertEqual(response.error, "Class: Aoua does not exist")

## The main function. Initializes the Cognitive Exercise System functional tests
if __name__ == '__main__':
    import rosunit
    rosunit.unitrun(PKG, 'OntologyFunc', OntologyFunc)














Ejemplo n.º 60
0
#!/usr/bin/env python
import rosunit

from .entry_model_test import EntryModelTest
from .entry_test import EntryTest
from .filter_map_test import FilterMapTest

PKG = "march_rqt_note_taker"

if __name__ == "__main__":
    rosunit.unitrun(PKG, "entry_mode_test", EntryModelTest)
    rosunit.unitrun(PKG, "entry_test", EntryTest)
    rosunit.unitrun(PKG, "filter_test", FilterMapTest)