Beispiel #1
0
def main():    
    global tp, reconfig_client
    regression_test = rospy.get_param('~regression_test', False)
    tp = TriggerChecker(plot = not regression_test, silent = regression_test)
    head_trig = Trigger(tp, '/head_camera_trigger')
    l_forearm_trig = Trigger(tp, 'l_forearm_cam_trigger')
    r_forearm_trig = Trigger(tp, 'r_forearm_cam_trigger')
    Camera(tp, '/narrow_stereo_both', head_trig)
    tp.set_projector(Trigger(tp, '/projector_trigger'))
    Camera(tp, '/wide_stereo_both', head_trig)
    Camera(tp, '/l_forearm_cam', l_forearm_trig)
    Camera(tp, '/r_forearm_cam', r_forearm_trig)
    if regression_test:
         import rostest
         rospy.loginfo("Running in unit test mode")
         reconfig_client = dynamic_reconfigure.client.Client('synchronizer')
         rostest.rosrun(PKG, 'test_bare_bones', Test)
    else:
        rospy.loginfo("Running in plotting mode")
        while not rospy.is_shutdown():
            time.sleep(0.1)
Beispiel #2
0
import unittest

from cob_camera_calibration import CalibrationData

TEST_FILE = "test/data/calibration_data.yaml"
TEST_OUT = "/tmp/calibration_data.yaml"


class TestCalibrationData(unittest.TestCase):
    def test_read(self):
        data = CalibrationData("camera", "frame", "image_width",
                               "image_height")
        data.read_camera_yaml_file(TEST_FILE)

    def test_read_write(self):
        data = CalibrationData("camera", "frame", "image_width",
                               "image_height")
        data.read_camera_yaml_file(TEST_FILE)
        data.save_camera_yaml_file(TEST_OUT)

        # compare with correct results
        self.assertTrue(self._cmp_files(TEST_FILE, TEST_OUT))

    def _cmp_files(self, f1, f2):
        return open(f1).read() == open(f2).read()


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'TestCalibrationData', TestCalibrationData)
Beispiel #3
0
import roslib; roslib.load_manifest(PKG)

import sys
import unittest


## A simple unit test to make sure python module structure and files aren't broken
class TestImports(unittest.TestCase):

    ## import everything
    def test_imports(self):

        from actionlib import simple_action_client
        from actionlib import action_client

        from actionlib import goal_id_generator
        from actionlib import handle_tracker_deleter
        from actionlib import server_goal_handle
        from actionlib import status_tracker

        from actionlib import action_server
        from actionlib import simple_action_server

        self.assertEquals(1, 1, "1!=1")

if __name__ == '__main__':
    import rostest
    print sys.path
    rostest.rosrun(PKG, 'test_imports', TestImports)

        self.assertEqual(vs.sum_forward, lf+rf, "different value: sum_forward")

    def test_node_exist(self):
        nodes = rosnode.get_node_names()
        self.assertIn('/lightsensors',nodes, "node does not exist")

    def test_get_value(self):
        rospy.set_param('/lightsensors/frequency',10)    #センサの値取得の周期を10Hzに
        time.sleep(2)                              #パラメータの反映を待つ
        with open("/dev/rtlightsensor0","w") as f: #ダミーの値をダミーのファイルに
            f.write("-1 0 123 4321\n")

        time.sleep(3)
        ###コールバック関数が最低1回は呼ばれ、値が取得できているかを確認###
        self.assertFalse(self.count == 0,"cannot subscribe the topic") 
        self.check_values(4321,123,0,-1) 

    def test_change_parameter(self):
        rospy.set_param('/lightsensors/frequency',1)    #センサの値取得の周期を1Hzに
        time.sleep(2)                             #反映を待つ
        c_prev = self.count                       #callbackが呼ばれた回数を記録
        time.sleep(3) 
        ###コールバック関数が3秒間で最低1回、最高でも4回しか呼ばれてないことを確認###
        self.assertTrue(self.count < c_prev + 4,"freq does not change")
        self.assertFalse(self.count == c_prev,"subscriber is stopped")

if __name__ == '__main__':
    time.sleep(3)
    rospy.init_node('travis_test_lightsensors')
    rostest.rosrun('raspimouse_ros_2','travis_test_lightsensors',LightsensorTest)
                    400,
                    False,
                    # arm
                    1,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                )

                armed = True

            if (
                self.local_position.pose.position.x > 5
                and self.local_position.pose.position.z > 5
                and self.local_position.pose.position.y < -5
            ):
                break
            count = count + 1

        self.assertTrue(count < timeout, "took too long to cross boundaries")


if __name__ == "__main__":
    import rostest

    rostest.rosrun(PKG, "mavros_offboard_attctl_test", MavrosOffboardAttctlTest)
    # unittest.main()
        self.relay.start()
        # grace delay
        time.sleep(1.0)

    def tearDown(self):
        self.relay.stop()
        self.server.shutdown()
        self.server_thread.join()

    def test_relay(self):
        """Test bi-directional communication over the relay."""
        remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        remote_sock.settimeout(1.0)
        remote_sock.connect(('127.0.0.1', self.remote_port))

        remote_sock.sendall(MAGIC)
        response = remote_sock.recv(1024)

        self.assertEqual(MAGIC, response)
        self.assertEqual(1, len(self.server.messages))
        self.assertEqual(MAGIC, self.server.messages[0])

        remote_sock.close()


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, NAME, TestTCPRelay)

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
PKG = 'test_uniboard_service'

class TestUniboardService(unittest.TestCase):
    def test_motor_left(self):
        rospy.wait_for_service('uniboard_service')
        self.uniboard_service = rospy.ServiceProxy('uniboard_service', communication)
        left = self.uniboard_service('motor_left', 1, str('0.1'), rospy.Time(secs=500))
        self.assertEquals(left.status, True)
        self.assertEquals(left.response, 'Success')
        self.assertEquals(left.data, '')


    def test_addToQueue(self):
        controller = UniboardCommunication()
        req = Bunch()
        req.priority = 1
        req.function = 'motor_left'
        req.data = "0.12"
        req.timestamp = rospy.Time(secs=500)
        t = threading.Thread(target=controller.addToQueue, args=(req,))
        t.daemon = True
        t.start()
        item = controller.get()
        self.assertEquals(item[1],controller.motor_left)
        self.assertEquals(item[2], req.data)
        self.assertEquals(item[3], req.timestamp)
        self.assertEquals(item[4], [])

if __name__ == '__main__':
    rostest.rosrun(PKG, 'test_uniboard_service', TestUniboardService)
        cmd = "%s pkg-config openhrp3.1 --variable=idl_dir"%(self.PKG_CONFIG_PATH)
        fname = "../sample/model/PA10/pa10.main.wrl"
        # check if model file exists
        print "`"+cmd+"`"+fname+" = "+os.path.join(check_output(cmd, shell=True).rstrip(), fname)
        self.assertTrue(os.path.exists(os.path.join(check_output(cmd, shell=True).rstrip(), fname)))

    def test_sample_samplerobot(self):
        cmd = "%s pkg-config openhrp3.1 --variable=idl_dir"%(self.PKG_CONFIG_PATH)
        fname = "../sample/model/sample1.wrl"
        # check if model file exists
        print "`"+cmd+"`"+fname+" = "+os.path.join(check_output(cmd, shell=True).rstrip(), fname)
        self.assertTrue(os.path.exists(os.path.join(check_output(cmd, shell=True).rstrip(), fname)), "cmd = %r, fname = %r"%(cmd, fname))
        #
        # check if walk data file exists
        fname = "../sample/controller/SampleController/etc/Sample.pos"
        print "`"+cmd+"`"+fname+" = "+os.path.join(check_output(cmd, shell=True).rstrip(), fname)
        self.assertTrue(os.path.exists(os.path.join(check_output(cmd, shell=True).rstrip(), fname)), "cmd = %r, fname = %r"%(cmd, fname))

#unittest.main()
if __name__ == '__main__':
    import rostest
    global PID
    PID = os.getpid()
    f = open("/tmp/%d-openhrp3-sample.cpp"%(PID),'w')
    f.write(code)
    f.close()
    rostest.rosrun(PKG, 'test_openhrp3', TestCompile) 



                    'D-5': 'p'
                },
                '7': {
                    'D-1': 'x'
                }
            },
            'cleaning_methods': {
                '1': DRY_TASK,
                '10': BOTH_TASKS,
                '7': DRY_TASK
            }
        }]
        expected_outputs = [{
            '1': {TRASH_TASK, DRY_TASK},
            '10': {TRASH_TASK},
            '7': {DRY_TASK, TRASH_TASK}
        }]

        self.applyScenarios(scenarios=scenarios,
                            expected_outputs=expected_outputs,
                            evaluator=self.overdueRoomsEvaluator)

    def testComputeAllRooms(self):
        # test both due and overdue rooms
        pass


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, NAME, TestDatabaseHandler)
import rostest
import rospy

from pandora_testing_tools.testing_interface import alert_delivery
from test_base import distance
from test_base import direction
import test_base

DIR = os.path.dirname(os.path.realpath(__file__))


class SubscriberTest(test_base.TestBase):

    def test_new_subscriber(self):

        self.deliveryBoy.deliverHoleOrder(0, 0, 1)
        self.deliveryBoy.deliverHoleOrder(0, 0, 1)
        outs = []
        self.fillInfo(outs)

        # Benchmark new subscriber style...
        self.assertEqual(len(outs[0].holes), 1)

if __name__ == '__main__':

    rospy.sleep(2)
    rospy.init_node(NAME, anonymous=True, log_level=rospy.DEBUG)
    SubscriberTest.connect()
    rostest.rosrun(PKG, NAME, SubscriberTest, sys.argv)
    SubscriberTest.disconnect()
import time

class WallStopTest(unittest.TestCase):
	def set_and_get(self,lf,ls,rs,rf):
		with open("/dev/rtlightsensor0","w") as f:
			f.write("%d %d %d %d\n" % (rf,rs,ls,lf))

		time.sleep(0.3)

		with open("/dev/rtmotor_raw_l0","r") as lf,\
		     open("/dev/rtmotor_raw_r0","r") as rf:
			left = int(lf.readline().rstrip())
			right = int(rf.readline().rstrip())

		return left, right

	def test_io(self):
		left, right = self.set_and_get(400,100,100,0) #total: 600
		self.assertTrue(left == 0 and right == 0, "can't stop")
		
		left, right = self.set_and_get(400,0,0,99) #total: 499
		self.assertTrue(left != 0 and right != 0, "can't move again")

		left, right = self.set_and_get(150,0,200,150) #total; 500
		self.assertTrue(left == 0 and right == 0, "can't stop")

if __name__ == '__main__':
	time.sleep(3)
	rospy.init_node('travis_test_wall_stop')
	rostest.rosrun('pimouse_run_corridor','travis_test_wall_stop',WallStopTest)
Beispiel #12
0
        first_level_network.add_precondition(pre_con)

        goal_with_same_cond = OfflineGoal('CentralGoal2', planner_prefix=planner_prefix)
        goal_with_same_cond.add_condition(condition)
        first_level_network.add_goal(goal_with_same_cond)

        increaser_behavior = IncreaserBehavior(effect_name=sensor.name, topic_name=topic_name,
                                               name=method_prefix + "TopicIncreaser",
                                               planner_prefix=first_level_network.get_manager_prefix())

        increaser_behavior.add_precondition(pre_con)

        # activate the first_level_network increaser_Behavior
        for x in range(0, 3, 1):
            self.assertFalse(first_level_network._isExecuting)
            m.step()
            pre_con_sensor.update(True)
            rospy.sleep(0.1)

        self.assertTrue(first_level_network._isExecuting)

        for x in range(0, 4, 1):
            m.step()
            rospy.sleep(0.1)

        self.assertTrue(increaser_behavior._isExecuting)


if __name__ == '__main__':
    rostest.rosrun(PKG, 'NetworkBehaviourTestNode', TestNetworkBehaviour)
                         "Should be active")
        self.assertEqual(g2.get_goal_status(), GoalStatus.ACTIVE,
                         "Should be active")
        self.assertEqual(g3.get_goal_status(), GoalStatus.ACTIVE,
                         "Shoule be active")
        self.assertEqual(g4.get_goal_status(), GoalStatus.ACTIVE,
                         "Should be active")

        g5 = client.send_goal(goal_result)
        rospy.sleep(0.5)
        self.assertEqual(g5.get_goal_status(), GoalStatus.SUCCEEDED,
                         "Should be done")

        self.assertEqual(g1.get_goal_status(), GoalStatus.SUCCEEDED)
        self.assertEqual(g1.get_result().result, 4)
        self.assertEqual(g2.get_goal_status(), GoalStatus.ABORTED)
        self.assertEqual(g2.get_result().result, 3)
        self.assertEqual(g3.get_goal_status(), GoalStatus.SUCCEEDED)
        self.assertEqual(g3.get_result().result, 2)
        self.assertEqual(g4.get_goal_status(), GoalStatus.ABORTED)
        self.assertEqual(g4.get_result().result, 1)
        g6 = client.send_goal(goal_abort)
        rospy.sleep(0.5)


if __name__ == '__main__':
    import rostest
    rospy.init_node('test_ref_simple_action_server')
    rostest.rosrun('actionlib', 'test_simple_action_client_python',
                   TestRefSimpleActionServer)
        dummy0 = Dummy()
        dummy0.value = 354
        dummy1 = Dummy()
        dummy1.value = 5649

        id_from_setter0 = set_srv(dummy0)
        # id_from_setter cannot be passed to get_srv because of
        # type incompatibility, "transform" it to a Get...Request()
        id_to_getter0 = GetDummyDescriptorRequest()
        id_to_getter0.id = id_from_setter0.id
        response0 = get_srv(id_to_getter0)

        id_from_setter1 = set_srv(dummy1)
        # id_from_setter cannot be passed to get_srv because of
        # type incompatibility, "transform" it to a Get...Request()
        id_to_getter1 = GetDummyDescriptorRequest()
        id_to_getter1.id = id_from_setter1.id
        response1 = get_srv(id_to_getter1)

        self.assertIsNot(dummy0, response0.descriptor)
        self.assertIsNot(dummy0.value, response0.descriptor.value)
        self.assertIsNot(dummy1, response1.descriptor)
        self.assertEqual(dummy0.value, response0.descriptor.value)
        self.assertEqual(dummy1.value, response1.descriptor.value)


if __name__ == '__main__':
    import rostest
    rostest.rosrun('nlj_dummy', 'test_db_message_passing',
                   TestDbMessagePassing)
Beispiel #15
0
#! /usr/bin/env python

import rospy
import rosunit
import unittest
import rostest
import time
PKG = 'pointcloud_merger'
NAME = 'pointcloud_merger_test'

class TestPCM(unittest.TestCase):

    def setUp(self):
        rospy.init_node('test_node')

    def test_merge(self):
        self.assertTrue((True), "Integration error")

if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestPCM)
        number = 0
        path = "./se306Project1/src/"
        files = []
        for i in os.listdir(path):
            if os.path.isfile(os.path.join(path, i)) and re.match('Visitor\d.py',i):
                number += 1
        config_number = int(self.config.get('visitor.number').rstrip())
        if config_number > 4:
            config_number = 4
        self.assertEqual(number, config_number, "Testing visitor files generated")

    def test_WorkerGenerated(self):
        number = 0
        path = "./se306Project1/src/"
        files = []
        for i in os.listdir(path):
            if os.path.isfile(os.path.join(path, i)) and re.match('Visitor\d.py',i):
                number += 1
        config_number = int(self.config.get('worker.number').rstrip())
        if config_number > 4:
            config_number = 4
        self.assertEqual(number, config_number, "Testing worker files generated")

    def tearDown(self):
        generateEntity.exit_process(self.list)

if __name__ == '__main__':
    # unittest.main()
    import rostest
    rostest.rosrun('se306Project1', 'test_bare_bones', Test_Generate_Files)
Beispiel #17
0
from robots import Animal, PickerRobot
from speedkiwi_msgs.msg import robot_status

PKG = 'speedkiwi_test'


class TestAnimal(unittest.TestCase):
    def setUp(self):
        rospy.init_node('test_animal')
        self.animal = Animal('robot_0', 2, 0.5, 0, 0, 0)

    def test_init(self):
        """Checks if animal attributes are set correctly after init."""
        animal = self.animal
        self.assertFalse(animal.currently_targeting)
        self.assertEqual(animal.dict_index, -1)
        self.assertEqual(animal.counter, 0)
        self.assertFalse(animal.retreat, False)

    def test_dog_stops_retreating(self):
        """Check the dog stops retreating when it reaches the kennel"""
        animal = self.animal
        animal.retreat = True
        animal.execute_callback()
        self.assertFalse(animal.retreat)

if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'test_animal', TestAnimal, sys.argv)
Beispiel #18
0
        F = ghmm.Float()

        Abig = [[0.0, 1.0], [1.0, 0.0]]
        Bbig = [[[1.0, 1.0, 1.0],
                 [0.9, 0.4, 0.2, 0.4, 2.2, 0.5, 0.2, 0.5, 1.0]],
                [[10.0, 10.0, 10.0],
                 [1.0, 0.2, 0.8, 0.2, 2.0, 0.6, 0.8, 0.6, 0.9]]]
        piBig = [0.5, 0.5]
        modelBig = ghmm.HMMFromMatrices(
            F, ghmm.MultivariateGaussianDistribution(F), Abig, Bbig, piBig)
        modelBig.sample(10, 100, seed=3586662)

        e = modelBig.sampleSingle(1)
        print[x for x in e]

        # get log P(seq | model)
        logp = model.loglikelihood(seq)
        print logp

        # cacluate viterbi path
        path = model.viterbi(seq)
        print path

        # train model parameters
        model.baumWelch(seq_set, 500, 0.0001)


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'TestHMM', TestCustomHMMGestureModel)
                      "windows":[
                        {
                        "activity":"streetview",
                        "assets":["%s", "foo", "bar"],
                        "height":600,
                        "presentation_viewport":"center",
                        "width":800,
                        "x_coord":100,
                        "y_coord":100
                        }
                        ]
                    }
        """ % panoid

        # get existing asset
        asset = get_first_asset_from_activity(
            load_director_message(director_msg), "streetview")
        self.assertEqual(asset, panoid, 'Invalid asset returned')
        # get non existing asset
        asset = get_first_asset_from_activity(
            load_director_message(director_msg), "panoview")
        self.assertEqual(asset, None, 'No asset should have been returned')

        self.check_soft_relaunch()


if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestSVServer, sys.argv)

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
        self.assertTrue(
            time_since_last_execution < 2 * Constants.max_action_duration,
            "Too long since last goal was executed; likely due to a deadlock")

    def execute_callback(self, goal):
        # Note down last_execution time
        self.last_execution_time = rospy.Time.now()

        # Determine duration of this action
        action_duration = random.uniform(0, Constants.max_action_duration)

        with self.condition:
            if not self.action_server.is_preempt_requested():
                self.condition.wait(action_duration)

        if self.action_server.is_preempt_requested():
            self.action_server.set_preempted()
        else:
            self.action_server.set_succeeded()

    def preempt_callback(self):
        with self.condition:
            self.condition.notify()


if __name__ == '__main__':
    import rostest
    rospy.init_node(Constants.node)
    rostest.rosrun(Constants.pkg, Constants.node, DeadlockTest)
            (2, 2, -2),
            (2, -2, -2),
            (-2, -2, -2),
            (2, 2, -2))

        # flight path assertion
        self.fpa = FlightPathAssertion(positions, 1, 0)
        self.fpa.start()

        for i in range(0, len(positions)):
            self.reach_position(positions[i][0], positions[i][1], positions[i][2], 120)
            self.assertFalse(self.fpa.failed, "breached flight path tunnel (%d)" % i)
        
        # does it hold the position for Y seconds?
        count = 0
        timeout = 50
        while count < timeout:
            if not self.is_at_position(2, 2, -2, 0.5):
                break
            count = count + 1
            self.rate.sleep()

        self.assertTrue(count == timeout, "position could not be held")
        self.fpa.stop()
    

if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'direct_offboard_posctl_test', DirectOffboardPosctlTest)
    #unittest.main()
        pub = rospy.Publisher(TOPIC, String, queue_size=1)

        def publish_timer():
            rospy.sleep(WARMUP_DELAY)
            pub.publish(String(STRING))
            rospy.sleep(TIME_LIMIT)
            reactor.stop()

        reactor.callInThread(publish_timer)
        reactor.run()

        self.assertEqual(len(test_client_received), 1)
        websocket_message = decode_cbor(test_client_received[0])
        self.assertEqual(websocket_message['topic'], TOPIC)
        buff = io.BytesIO()
        String(STRING).serialize(buff)
        self.assertEqual(websocket_message['msg']['bytes'], buff.getvalue())


PKG = 'rosbridge_server'
NAME = 'test_websocket_cbor_raw'

if __name__ == '__main__':
    rospy.init_node(NAME)

    while not rospy.is_shutdown() and not rospy.has_param(
            '/rosbridge_websocket/actual_port'):
        rospy.sleep(1.0)

    rostest.rosrun(PKG, NAME, TestWebsocketCborRaw)
Beispiel #23
0
        self.assertEqual(res, self.correct_loglikelihoods["qtcc"])

    def test_qtcbc_create(self):
        res = self._create_hmm(self.QTCBC_QSR, 'qtcbc')
        self.assertEqual(hashlib.md5(res).hexdigest(), self.correct_hashsum["qtcbc"])

    def test_qtcbc_sample(self):
        res = self._create_sample(self.QTCBC_SAMPLE_TEST_HMM, 'qtcbc')
        self.assertEqual(res, self.correct_samples["qtcbc"])

    def test_qtcbc_loglikelihood(self):
        res = self._calculate_loglikelihood(self.QTCBC_PASSBY_LEFT_HMM, self.QTCBC_QSR, 'qtcbc')
        self.assertEqual(res, self.correct_loglikelihoods["qtcbc"])

    def test_rcc3_create(self):
        res = self._create_hmm(self.RCC3_QSR, 'rcc3')
        self.assertEqual(hashlib.md5(res).hexdigest(), self.correct_hashsum["rcc3"])

    def test_rcc3_sample(self):
        res = self._create_sample(self.RCC3_TEST_HMM, 'rcc3')
        self.assertTrue(type(res) == list and len(res) > 0)

    def test_rcc3_loglikelihood(self):
        res = self._calculate_loglikelihood(self.RCC3_TEST_HMM, self.RCC3_QSR, 'rcc3')
        self.assertEqual(res, self.correct_loglikelihoods["rcc3"])


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, NAME, TestHMM, sys.argv)
Beispiel #24
0
import time
from src.Animal import Animal
import math
import logging
from TestModule import TestModule
import inspect
"""
@class

This is a test for the correct construction of the Animal object.

"""


class Test_Animal_Setup(unittest.TestCase, TestModule):

    animal = Animal("Node", 2, -10, -28, math.pi / 2)

    def test_robot_carrier_setup(self):

        self.assertEqual(self.animal.linearX, 3, "Setting linearX")
        self.assertEqual(self.animal.dict_of_visitors, {},
                         "Setting dict_of_visitors")
        self.assertEqual(self.animal.animal_state, "", "Setting animal_state")


if __name__ == '__main__':
    # unittest.main()
    import rostest
    rostest.rosrun('se306Project1', 'test_bare_bones', Test_Animal_Setup)
Beispiel #25
0
        self.tractor._action_queue[:] = [] #clear the list
        self.tractor.execute_callback()
        self.assertEqual(len(self.tractor._action_queue),4)

    def test_execute_callback_was_blocked_true(self):
        """test was_blocked is true and action queue is old 
        queue when was_blocked is true"""
        self.tractor.was_blocked = True
        self.tractor.old_queue = []
        self.tractor.execute_callback()
        self.assertFalse(self.tractor.was_blocked)
        self.assertEqual(self.tractor._action_queue,self.tractor.old_queue)

    def test_orchard_get_coordinates(self):
        """Test the boundary values obtained from file are floats
        NOTE: This is based on default world file. If configured world is run last this will fail"""
        boundaries = locations.get_wall_boundaries()
        self.tractor.min_x = boundaries["min_x"]
        self.tractor.max_x = boundaries["max_x"]
        self.tractor.min_y = boundaries["min_y"]
        self.tractor.max_y = boundaries["max_y"]
        self.assertEqual(self.tractor.min_x, -35)
        self.assertEqual(self.tractor.min_y, -60)
        self.assertEqual(self.tractor.max_x, 35)
        self.assertEqual(self.tractor.max_y, 60)


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'test_tractor', TestTractor, sys.argv)
Beispiel #26
0
                         sensor_msgs.msg.Imu,
                         self.incoming_imu,
                         queue_size=1000)

    def incoming_imu(self, imu_data):
        with self.openzen_imu_access:
            self.openzen_imu.append(imu_data)

    def test_imu_data_incoming(self):
        # wait for some data to arrive
        rospy.sleep(0.5)

        with self.openzen_imu_access:
            self.assertTrue(len(self.openzen_imu) > 0)

            # some sanity check on content
            last_imu = self.openzen_imu.pop()

            self.assertAlmostEqual(0.0, last_imu.linear_acceleration.x, 2)
            self.assertAlmostEqual(0.0, last_imu.linear_acceleration.y, 2)
            self.assertAlmostEqual(9.81, last_imu.linear_acceleration.z, 2)

            # the test sensor will output some arbitrary gyro values
            self.assertLess(0.0, last_imu.angular_velocity.x)
            self.assertLess(0.0, last_imu.angular_velocity.y, 2)
            self.assertLess(0.0, last_imu.angular_velocity.z, 2)


if __name__ == '__main__':
    rostest.rosrun('openzen_driver', 'test_openzen_readout', TestOpenZen)
    def test_run(self):
        self.pose.orientation.x = 0.0
        self.pose.orientation.y = 0.0
        self.pose.orientation.z = 0.0
        self.pose.orientation.w = 1.0
        self.pose.position.x = 5.0
        self.pose.position.y = 4.0
        self.pose.position.z = 3.0

        self.transform.translation.x = 2.0
        self.transform.translation.y = 2.0
        self.transform.translation.z = 2.0
        self.transform.rotation.x = 0.0
        self.transform.rotation.y = 0.0
        self.transform.rotation.z = 0.0
        self.transform.rotation.w = 1.0

        self.expected.orientation   = self.pose.orientation
        self.expected.position.x = 7.0
        self.expected.position.y = 6.0
        self.expected.position.z = 5.0

        self.execute()

if __name__ == '__main__':
    import rostest
    rostest.rosrun('estirabot_apps', 'testHomogeneoustranformOnlyrotation', 
                                      TestHomogeneousTranformOnlyRotation)
    rostest.rosrun('estirabot_apps', 'testHomogeneoustranformonlytranslation', 
                                      TestHomogeneousTranformOnlyTranslation)
Beispiel #28
0
                                          u'arm')

    def test_cartpole_dynamics_solver(self):
        check_dynamics_solver_derivatives('exotica/CartpoleDynamicsSolver')

    def test_pendulum_dynamics_solver(self):
        check_dynamics_solver_derivatives('exotica/PendulumDynamicsSolver')

    # def test_quadrotor_dynamics_solver(self):
    #     check_dynamics_solver_derivatives('exotica/QuadrotorDynamicsSolver',
    #                                       u'{exotica_examples}/resources/robots/quadrotor.urdf',
    #                                       u'{exotica_examples}/resources/robots/quadrotor.srdf',
    #                                       u'base')

    def test_pinocchio_dynamics_solver(self):
        check_dynamics_solver_derivatives('exotica/PinocchioDynamicsSolver',
                                          u'{exotica_examples}/resources/robots/lwr_simplified.urdf',
                                          u'{exotica_examples}/resources/robots/lwr_simplified.srdf',
                                          u'arm')

    def test_pinocchio_gravity_compensation_dynamics_solver(self):
        check_dynamics_solver_derivatives('exotica/PinocchioDynamicsSolverWithGravityCompensation',
                                          u'{exotica_examples}/resources/robots/lwr_simplified.urdf',
                                          u'{exotica_examples}/resources/robots/lwr_simplified.srdf',
                                          u'arm')


if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'TestDynamicsSolver', TestDynamicsSolver)
        self.subs += [sub]
        self.subs += subs

        self.assertTrue(self.wait(), "Wait for throttled topic")
        self.assertAlmostEqual(self.count, 5, delta=1)
        self.assertEqual(self.max_diff, 0.0)

    def test_async_delay(self):
        sub = rospy.Subscriber("/foo", PoseStamped, self.delay_baz_cb)
        subs = [
            MF.Subscriber("/foo/async", PoseStamped, queue_size=1),
            MF.Subscriber("/bar/async", PoseStamped, queue_size=1),
            MF.Subscriber("/baz/async", PoseStamped, queue_size=1),
        ]
        sync = MF.ApproximateTimeSynchronizer(subs, queue_size=10, slop=0.01)
        sync.registerCallback(self.throttle_cb)

        self.subs += [sub]
        self.subs += subs

        self.assertTrue(self.wait(), "Wait for throttled topic")
        self.assertAlmostEqual(self.count, 5, delta=1)
        self.assertLess(self.max_diff, 0.002)


if __name__ == '__main__':
    import rostest
    rospy.init_node("test_synchronized_throttle")
    rostest.rosrun("jsk_topic_tools", "test_synchronized_throttle", TestSynchronizedThrottle)
Beispiel #30
0
#!/usr/bin/env python
import sys
import unittest
import rospy
from actions import NavigateAction, MoveAction, RotateAction
from world_locations import locations
from robots import Robot, CarrierRobot
from math import pi

PKG = 'speedkiwi_test'


class TestCarrier(unittest.TestCase):

    def setUp(self):
        rospy.init_node('test_picker')
        self.carrier = CarrierRobot('robot_0', 2, 0.9, -20, 43, 0)

    def test_execute_callback_speed(self):
        """Checks carrier sets speed to top speed in execute_callback"""
        self.carrier.current_speed = 0
        self.carrier.execute_callback()
        self.assertEqual(self.carrier.current_speed, self.carrier.top_speed)

if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'test_carrier', TestCarrier, sys.argv)
PKG = 'smart_home_core'
NAME = 'command_server_test'

import unittest
import sys
import rospy, rostest
from smart_home_core.srv import *

class TestCommandServer(unittest.TestCase):

    def test_empty_call(self):
        rospy.wait_for_service('command')
        command = rospy.ServiceProxy('command', Command)
        resp = command('').response.decode('utf-8')
        self.assertTrue(resp.startswith(u'неизвестная команда'))

    def test_wrong_call(self):
        rospy.wait_for_service('command')
        command = rospy.ServiceProxy('command', Command)
        resp = command('unknown').response.decode('utf-8')
        self.assertTrue(resp.startswith(u'неизвестная команда unknown'))

    def test_ok_call(self):
        rospy.wait_for_service('command')
        command = rospy.ServiceProxy('command', Command)
        resp = command('test param').response.decode('utf-8')
        self.assertTrue(resp.startswith('test ok, param:param'))

if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestCommandServer, sys.argv)
Beispiel #32
0
        start_pose.pose.position.z = 3.0
        start_pose.pose.orientation.x = 0.0
        start_pose.pose.orientation.y = 0.0
        start_pose.pose.orientation.z = 1.0
        start_pose.pose.orientation.w = 0.0

        goal_pose.pose.position.x = 1.0
        start_pose.pose.position.y = 2.0
        goal_pose.pose.position.z = 3.0
        # 180 degrees rotation around the X axis
        goal_pose.pose.orientation.x = 1.0
        goal_pose.pose.orientation.y = 0.0
        goal_pose.pose.orientation.z = 0.0
        goal_pose.pose.orientation.w = 0.0

        while not self.wait_for_result:
            self.event_out.publish('e_start')
            self.start_pose.publish(start_pose)
            self.goal_pose.publish(goal_pose)

        assert type(self.result) is geometry_msgs.msg.PoseArray

    def result_callback(self, msg):
        self.result = msg
        self.wait_for_result = True


if __name__ == '__main__':
    rospy.init_node('dmp_based_task_space_test')
    rostest.rosrun(PKG, 'dmp_based_task_space_test', TestDmpBasedTaskSpace)
import sys 
import time
import unittest

import rospy
import rostest
from std_msgs.msg import String


class TestOnShutdown(unittest.TestCase):
    def __init__(self, *args):
        super(TestOnShutdown, self).__init__(*args)
        self.success = False
        
    def callback(self, data):
        print rospy.get_caller_id(), "I heard %s"%data.data
        #greetings is only sent over peer_publish callback, so hearing it is a success condition
        if "I'm dead" in data.data:
            self.success = True

    def test_notify(self):
        rospy.Subscriber("chatter", String, self.callback)
        rospy.init_node(NAME, anonymous=True)
        timeout_t = time.time() + 10.0*1000 #10 seconds
        while not rospy.is_shutdown() and not self.success and time.time() < timeout_t:
            time.sleep(0.1)
        self.assert_(self.success, str(self.success))
        
if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestOnShutdown, sys.argv)
Beispiel #34
0
    from std_msgs.msg import Float32


def eps_equal(a, b, err=0.001):
    return abs(a - b) < err


hz_msg = None


def topic_cb(msg):
    global hz_msg
    hz_msg = msg


class TestHzMeasure(unittest.TestCase):
    def test_hz(self):
        global hz_msg
        while hz_msg == None:
            if not rospy.is_shutdown():
                rospy.sleep(1.0)  #wait 1 sec
        # should be 30Hz
        self.assertTrue(eps_equal(hz_msg.data, 30, 1))


if __name__ == "__main__":
    import rostest
    rospy.init_node("test_hz_measure")
    s = rospy.Subscriber("/hz/output", Float32, topic_cb)
    rostest.rosrun("jsk_topic_tools", "test_hz_measure", TestHzMeasure)
    def step2(self):
        rospy.loginfo('Step 2')
        self.verify([self.rq1, self.rq2])

        # send another request, which should wait
        self.rq3 = self.request_turtlebot()
        self.verify([self.rq1, self.rq2, self.rq3])

        self.rqr.send_requests()
        self.next_step = self.step3

    def step3(self):
        rospy.loginfo('Step 3')
        self.verify([self.rq1, self.rq2, self.rq3])
        self.rqr.rset[self.rq2].cancel()
        self.rq4 = self.request_turtlebot()
        self.verify([self.rq1, self.rq2, self.rq3, self.rq4])
        self.rqr.send_requests()
        self.next_step = self.step4

    def step4(self):
        rospy.loginfo('Step 4')
        self.verify([self.rq1, self.rq3, self.rq4])
        self.next_step = None

if __name__ == '__main__':
    import rostest
    rostest.rosrun('concert_scheduler_requests',
                   'timeout_requester', TestTimeoutRequester)
Beispiel #36
0
        self.assertEquals(len(task_events), 2)
        # task must start
        self.assertEquals(task_events[0].event, TaskEvent.TASK_STARTED)
        # might be preempted or failed, but not succeeeded
        self.assertIn(task_events[1].event,
                      [TaskEvent.TASK_FAILED, TaskEvent.TASK_PREEMPTED])

    def test_execution(self):
        te = TestEntry('execution_test')
        test = rospy.get_param('~test', 0)
        if test == 0:
            te.run_test(self.list_empty)
        elif test == 1:
            te.run_test(self.list_empty, test_tasks=5, pause_count=3)
        elif test == 2:
            te.run_test(self.list_empty,
                        test_tasks=10,
                        time_critical_tasks=3,
                        time_diffs_fn=self.check_time_diffs)
        elif test == 3:
            te.run_test(self.list_empty,
                        time_critical_tasks=5,
                        demanded_tasks=3,
                        test_tasks=5)
        elif test == 4:
            te.bad_timings(self.check_task_events)


if __name__ == '__main__':
    rostest.rosrun('task_executor', 'executor_tests', TestWrapper, sys.argv)
import rospy
import rostest
import roslib.scriptutil as scriptutil
from std_msgs.msg import String


class TestListenerConnectionHeader(unittest.TestCase):
    def __init__(self, *args):
        super(TestListenerConnectionHeader, self).__init__(*args)
        self.success = False
        
    def callback(self, data):
        chatter = data.data
        if 'callerid' in data._connection_header:
            who = data._connection_header['callerid']
            self.success = True
        else:
            who = 'unknown'
        print "I just heard %s from %s"%(chatter, who)

    def test_notify(self):
        rospy.Subscriber("chatter", String, self.callback)
        rospy.init_node(NAME, anonymous=True)
        timeout_t = time.time() + 10.0*1000 #10 seconds
        while not rospy.is_shutdown() and not self.success and time.time() < timeout_t:
            time.sleep(0.1)
        self.assert_(self.success, str(self.success))
        
if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestListenerConnectionHeader, sys.argv)
        self.safety.timing()
        self.proxy_pass = False
        msg = self.create_msg(m, self.safety.get_abs_pos('motor2','min',0.95))
        self.pub['motor2'].publish(msg)
        time.sleep(self._TIMEOUT)
        # Check if same limit applies
        self.assertMessageVal(expected,m)
        # After time is passed limit is gradually increased with timing call
        mock_time.return_value = start + 5.1
        self.safety.timing()
        msg = self.create_msg(m, self.safety.get_abs_pos('motor2','min',0.95))
        self.pub['motor2'].publish(msg)
        time.sleep(self._TIMEOUT)
        self.assertMessageVal(expected, m, equal=False)
        # Limit is beack to extreme position after multiple timing calls
        # Should be similar number of calls as for decreasing the limit
        self.safety.timing()
        self.safety.timing()
        self.safety.timing()
        # Check if extreme messages are not modified after returniong back to normal value
        self.proxy_pass = False
        msg = self.create_msg(m, self.safety.get_abs_pos('motor2','min',0.99))
        self.pub['motor2'].publish(msg)
        time.sleep(self._TIMEOUT)
        self.assertMessageVal(m['default'] + (m['min']-m['default'])*0.99,m)


if __name__ == "__main__":
    import rostest
    rostest.rosrun('motors_safety', 'test', MotorSafetyTest)
        self.elapsed_time = rospy.rostime.get_time() - self.start_time

        self.log[self.PKG]["simulation"]["elapsed_time"] = self.elapsed_time
        self.log[self.PKG]["simulation"]["number_collisions"] = self.collisions_ctr
        self.log[self.PKG]["simulation"]["direction_changes"] = self.dir_chg

        yaml.dump(self.log, self.log_file, default_flow_style=False)

        self.log_file.close()

    def navigationGoal(self, GX, GY, GTh):

        goal = PoseStamped()
        goal.header.frame_id = "/map"
        goal.header.stamp = rospy.get_rostime()
        goal.pose.position.x = GX
        goal.pose.position.y = GY

        quat = quaternion_from_euler(0, 0, GTh)

        goal.pose.orientation.w = quat[3]

        return goal


if __name__ == "__main__":

    rospy.init_node("test", anonymous=True)
    rostest.rosrun("cob_navigation_global", "NavigationDiagnostics", TestNavigation, sys.argv)
#!/usr/bin/env python
#encoding: utf8

import rospy, unittest, rostest
import rosnode
import time

class HelloWorldTest(unittest.TestCase):
    def test_node_exist(self):
        nodes = rosnode.get_node_names()
        self.assertIn('/hello_world', nodes, 'node does not exist')


if __name__ == '__main__':
    time.sleep(3) # テスト対象のノードが立ち上がるのを待つ
    rospy.init_node('test_hello_world.')
    rostest.rosrun('frootspi_hello_world', 'test_hello_world', HelloWorldTest)
## Talker/listener demo validation 

PKG = 'rospy_tutorials'
NAME = 'talker_listener_test'

import sys, unittest, time

import rospy, rostest
from std_msgs.msg import *

class TestTalkerListener(unittest.TestCase):
    def __init__(self, *args):
        super(TestTalkerListener, self).__init__(*args)
        self.success = False
        
    def callback(self, data):
        print(rospy.get_caller_id(), "I heard %s"%data.data)
        self.success = data.data and data.data.startswith('hello world')

    def test_talker_listener(self):
        rospy.init_node(NAME, anonymous=True)
        rospy.Subscriber("chatter", String, self.callback)
        timeout_t = time.time() + 10.0 #10 seconds
        while not rospy.is_shutdown() and not self.success and time.time() < timeout_t:
            time.sleep(0.1)
        self.assert_(self.success)
        
if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestTalkerListener, sys.argv)
            if lhz == prev_lhz and rhz == prev_rhz:
                continue

            if lhz > rhz: r_turn_count += 1
            if lhz < rhz: l_turn_count += 1

            prev_lhz, prev_rhz = lhz, rhz

            count += 1
            rate.sleep()

        r_turn_rate = 1.0*r_turn_count / count
        l_turn_rate = 1.0*l_turn_count / count

        turn = None
        if r_turn_rate > 0.6 and l_turn_rate < 0.2: turn = "right"
        if l_turn_rate > 0.6 and r_turn_rate < 0.2: turn = "left"

        self.assertFalse(turn is None,
                "direction is not fixed. l:" + str(l_turn_rate) + " r:" + str(r_turn_rate))
        self.assertEqual(sys.argv[1], turn,
                "wrong direction. l: " + str(l_turn_rate) + " r:" + str(r_turn_rate))

if __name__ == '__main__':
    rospy.init_node('test_face_to_face')
    rostest.rosrun('cpimouse_vision_control','test_face_to_face', VisionTest)

# Copyright 2016 Ryuichi Ueda
# Released under the MIT License.
# To make line numbers be identical with the book, this statement is written here. Don't move it to the header.
Beispiel #43
0
                    # There was no error...check that this was okay.
                    self.assertTrue(rows_dim_is_dynamic or R == ii, testType)
                    self.assertTrue(cols_dim_is_dynamic or C == jj, testType)
                    
                    # Check that the matrices are the same.
                    self.assertMatrixClose(numpyM,eigenM, testType)
                except TypeError as inst:
                    # There was a type error. Check that this was expected.
                    self.assertFalse( (rows_dim_is_dynamic or R == ii) and (cols_dim_is_dynamic or C == jj), testType)
                    
                    
    def vectorTests(self,t,i,j):
        x = 1
        # um...
        
    def test_eigen(self):
        T = ['double']
        N = ('01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','D')
        #N = (1,2,3,4,'dynamic')
        for t in T:
            for i in N:
                for j in N:
                    self.matrixTests(t,i,j)
        



if __name__ == '__main__':
    import rostest
    rostest.rosrun('numpy_eigen', 'test_eigen', TestEigen)
Beispiel #44
0
            name = "Test{}".format(2 * i)
            self.assertStatus(self.save_workspace(name, robot_poses))
            ret_get_pos = self.get_workspace_poses(name)
            self.assertStatus(ret_get_pos[0])

            self.assertEqual(ret_get_pos[1], robot_poses)
            name2 = "Test{}".format(2 * i + 1)
            self.assertStatus(self.save_workspace_from_points(name2, points))

            list_names.append(name)
            list_names.append(name2)

            self.assertEqual(self.get_workspace_list(), list_names)
        for name in list_names:
            self.assertStatus(self.delete_workspace(name))
        self.assertEqual(self.get_workspace_list(), [])


if __name__ == '__main__':
    while not rospy.has_param('/niryo_robot_poses_handlers/initialized'):
        rospy.sleep(0.10)

    position_dir = os.path.expanduser(
        rospy.get_param('/niryo_robot_poses_handlers/poses_dir'))
    trajectory_dir = os.path.expanduser(
        rospy.get_param('/niryo_robot_poses_handlers/trajectories_dir'))
    workspace_dir = os.path.expanduser(
        rospy.get_param('/niryo_robot_poses_handlers/workspace_dir'))
    # Going to execute all unittest.TestCase subclasses in the file -> Import are also concerned
    rostest.rosrun("poses_handlers", "test_poses_handlers", __name__)
Beispiel #45
0
    def test_ros_to_ntp(self):
        r = rospy.Time(secs=self.secs,  nsecs=self.nsecs)
        ntp = ROStime_to_NTP64(r)
        self.assertEqual(ntp >> 32,  self.secs)
        # seems to be some rounding imprecision with the division,
        # it's irrelevent at this level so just account for it
        ntp32 = ntp & 0xffffffff
        diff = abs(ntp32 - self.frac32)
        self.assertTrue((diff < 4))

    def test_ntpsplit_to_ros(self):
        r = NTP64split_to_ROStime(self.secs,  self.frac32)
        self.assertEqual(r.secs,  self.secs)
        # seems to be some rounding imprecision with the division,
        # it's irrelevent at this level so just account for it
        diff = abs(r.nsecs - self.nsecs)
        self.assertTrue(diff < 2)

    def test_bitstring(self):
        self.assertEqual(bitString(6),  '00000110')
        self.assertEqual(bitString(0),  '00000000')
        self.assertEqual(bitString(0xa5),  '10100101')
        self.assertEqual(bitString(0xff),  '11111111')
        self.assertEqual(bitString(0xdeadbeef),  '11011110101011011011111011101111')
        self.assertEqual(bitString(0x1234),  '1001000110100')

if __name__ == '__main__':
    rospy.init_node('ldmrs_utils',  disable_rostime=True)
    rostest.rosrun(PKG, 'ldmrs_util', TestUtils)
Beispiel #46
0
        goal.durations = [2, 2, 2, 2]

        self.client.wait_for_server()
        self.client.send_goal(goal, feedback_cb=self.feedback_cb)
        self.client.wait_for_result()

        self.assertTrue(self.client.get_result(), "invalid result")
        self.assertEqual(
            goal.freqs, self.device_values, "invalid feedback:" +
            ",".join([str(e) for e in self.device_values]))

        ### preemption ###
        self.device_values = []
        self.client.send_goal(goal, feedback_cb=self.feedback_cb)
        self.client.wait_for_result(rospy.Duration.from_sec(0.5))

        self.assertFalse(self.client.get_result(),
                         "stop is requested but return true")
        self.assertFalse(goal.freqs == self.device_values, "not stopped")

    def feedback_cb(self, feedback):
        with open("/dev/rtbuzzer0", "r") as f:
            data = f.readline()
            self.device_values.append(int(data.rstrip()))


if __name__ == '__main__':
    time.sleep(3)
    rospy.init_node('travis_test_buzzer')
    rostest.rosrun('pimouse_ros', 'travis_test_buzzer', BuzzerTest)
Beispiel #47
0
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "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.

PKG = 'test_rosmaster'
NAME = 'test_ps_encapsulation'

import sys

import rospy
import rostest

from param_server_test_case import ParamServerTestCase

class PsEncapsulationTestCase(ParamServerTestCase):
    def testEncapsulation(self):
        return self._testEncapsulation()

if __name__ == '__main__':
    rospy.init_node(NAME)
    rostest.rosrun(PKG, NAME, PsEncapsulationTestCase, sys.argv)
#!/usr/bin/env python

PKG = 'openrtm_ros_bridge'
import roslib; roslib.load_manifest(PKG)
import rospy

import unittest
import openrtm_ros_bridge.srv
#from openrtm_ros_bridge.srv import *

class TestMyServiceRosBridge(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        rospy.init_node('test_myservice_rosbridge')

    def testEcho(self):
        rospy.wait_for_service("/bridge/echo")
        echo = rospy.ServiceProxy("/bridge/echo", openrtm_ros_bridge.srv.SimpleService_MyService_echo)
        req = openrtm_ros_bridge.srv.SimpleService_MyService_echo
        msg = "this is test data 123"
        rospy.loginfo("send request > " + msg)
        res = echo(msg)
        rospy.loginfo("check return < " + res.operation_return)
        self.assertTrue(res.operation_return == msg, "SimpleService.echo returns incorrect string")

if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'test_myservice_rosbridge', TestMyServiceRosBridge)
    # Test method
    #
    def test_posctl(self):
        """Test offboard position control"""

        # make sure the simulation is ready to start the mission
        self.wait_for_topics(60)
        self.wait_for_landed_state(mavutil.mavlink.MAV_LANDED_STATE_ON_GROUND,
                                   10, -1)

        self.log_topic_vars()
        self.set_mode("OFFBOARD", 5)
        self.set_arm(True, 5)

        rospy.loginfo("run mission")
        positions = ((0, 0, 0), (2, 2, 2), (2, -2, 2), (-2, -2, 2), (2, 2, 2))

        for i in xrange(len(positions)):
            self.reach_position(positions[i][0], positions[i][1],
                                positions[i][2], 18)

        self.set_arm(False, 5)


if __name__ == '__main__':
    import rostest
    rospy.init_node('test_node', anonymous=True)

    rostest.rosrun(PKG, 'mavros_offboard_posctl_test',
                   MavrosOffboardPosctlTest)
Beispiel #50
0
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Manual exection of ATF recording phase.', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('pkg', type=str,
                        help='test package name')
    parser.add_argument('-g', dest='test_generation_config_file',
                        default='atf/test_generation_config.yaml',
                        help='path to test_generation_config file, relative to package root')
    parser.add_argument('-t', dest='test',
                        default="ts*",
                        help='test identifier, e.g. \n'
                         + '* or ts*                  --> record all tests (default)\n'
                         + 'ts0_*                     --> record all tests with ts0\n'
                         + 'ts0_*_r0_*                --> record all tests with ts0 and r0\n'
                         + 'ts0_c0_r0_e0_s0_0         --> record a single test ts0_c0_r0_e0_s0_0\n'
                         + 'ts0_c0_r0_e0_s0_*         --> record all iterations of test ts0_c0_r0_e0_s0_*\n'
                        )
    parser.add_argument('-e', dest='execute_as_test', action='count',
                        help='execute as rostest')
    parser.add_argument('-d', dest='dry_run', action='count',
                        help='execute dry run')

    args, unknown = parser.parse_known_args()
    if args.execute_as_test:
        rostest.rosrun("atf_core", 'recording', TestRecording)
    else:
        args = parser.parse_args() # strictly parse only known arguments again. will raise an error if unknown arguments are specified
        print("recording test in package '%s' with test generation file '%s'"%(args.pkg, args.test_generation_config_file))
        recorder = Recorder()
        recorder.record(args.pkg, args.test_generation_config_file, args.dry_run)
Beispiel #51
0
import sys
import unittest

import rospy
import rostest
from rbe_3002.srv import *

class TestAStar(unittest.TestCase):
    def test_correct_response(self):
        # When we setup access to the aStar service
        rospy.loginfo("Starting Unit Test")
        rospy.wait_for_service('a_star')
        s = rospy.ServiceProxy('a_star', AStar)
        startPoint = (4, 4)
        goalPoint = (7, 9)

        # When we make a request to this service
        req = AStarRequest(startPoint, goalPoint)
        pathResponse = s(req)
        path = zip(pathResponse.pathx, pathResponse.pathy)

        #Then the first and last values returned by the path should be the start and goal repspectively
        self.assertEquals(goalPoint, path[0], "The first elemet of the returned tuple was not the goal point")
        self.assertEquals(startPoint, path[-1], "The last elemet of the returned tuple was not the start point")



if __name__ == '__main__':
    rostest.rosrun(PKG, NAME, TestAStar, sys.argv)
Beispiel #52
0

class TestSimpleActionClient(unittest.TestCase):
    def testsimple(self):
        client = SimpleActionClient('reference_action', TestAction)
        self.assertTrue(client.wait_for_server(rospy.Duration(10.0)),
                        'Could not connect to the action server')

        goal = TestGoal(1)
        client.send_goal(goal)
        self.assertTrue(client.wait_for_result(rospy.Duration(10.0)),
                        "Goal didn't finish")
        self.assertEqual(GoalStatus.SUCCEEDED, client.get_state())
        self.assertEqual("The ref server has succeeded",
                         client.get_goal_status_text())

        goal = TestGoal(2)
        client.send_goal(goal)
        self.assertTrue(client.wait_for_result(rospy.Duration(10.0)),
                        "Goal didn't finish")
        self.assertEqual(GoalStatus.ABORTED, client.get_state())
        self.assertEqual("The ref server has aborted",
                         client.get_goal_status_text())


if __name__ == '__main__':
    import rostest
    rospy.init_node('simple_python_client_test')
    rostest.rosrun('actionlib', 'test_simple_action_client_python',
                   TestSimpleActionClient)
Beispiel #53
0
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "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.

PKG = 'test_rosmaster'
NAME = 'test_ps_values'

import sys

import rospy
import rostest

from param_server_test_case import ParamServerTestCase

class PsValuesTestCase(ParamServerTestCase):
    def testParamValues(self):
        return self._testParamValues()

if __name__ == '__main__':
    rospy.init_node(NAME)
    rostest.rosrun(PKG, NAME, PsValuesTestCase, sys.argv)
       self.assertEqual(vs.sum_forward, lf+rf, "different value: sum_forward")

   def test_node_exist(self):
       nodes = rosnode.get.node_names()
       self.assertIn('/lightsensors' ,nodes, "node does not exist")

   def test_get_value(self):
       rospy.set_param('lightsensors_freq' ,10)
       time.sleep(2)
       with open("/dev/rtlightsensor0","w") as f:
            f.write("-1 0 123 4567\n")

       time.sleep(3)

       self.assertFalse(self.count == 0 , "cannot subscribe the topic")
       self.check_values(4321,123,0,-1)

   def test_change_parameter(self):
       rospy.set_param('lightsensors_freq',1)
       time.sleep(2)
       c_prev = self.count
       time.sleep(3)
       self.assertTrue(self.count < c_prev + 4,"freq does not change")
       self.assertFalse(self.count == c_prev , "subscriver is stopped")

if __name__ == '__main__':
       time.sleep(3)
       rospy.init_node('travis_test_lightsensors')
       rostest.rosrun('pimouse_ros','travis_test_lightsensors',LightsensorTest)
 
        req = WeatherReporterCurrentSrvRequest()
        response = self._test_service(req)
        self.assertEqual(response.error,
            "'City provided is wrong or not supported'")

    #  @unittest.expectedFailure
    @unittest.skip('Skipping tests - Uncomment decorators to test manually')
    def test_actual_city(self):
        req = WeatherReporterCurrentSrvRequest()
        for city in self._cities:
            req.city = city
            response = self._test_service(req)
            self.assertEqual(response.error, "")
            self.assertNotEqual(response.temperature, "")

    #  @unittest.expectedFailure
    @unittest.skip('Skipping tests - Uncomment decorators to test manually')
    def test_random_city(self):
        req = WeatherReporterCurrentSrvRequest()
        req.city = \
            ''.join(random.choice(string.ascii_letters) for _ in range(20))
        response = self._test_service(req)
        self.assertEqual(response.error,
            "'City provided is wrong or not supported'")

if __name__ == '__main__':
    rostest.rosrun(
        'rapp_weather_reporter',
        'yweather_reporter_current_test',
        TestCurrentYWeatherReporter)
        time.sleep(0.3)

        with open("/dev/rtmotor_raw_l0","r") as lf,\
             open("/dev/rtmotor_raw_r0","r") as rf:
            left = int(lf.readline().rstrip())
            right = int(rf.readline().rstrip())

        return left, right

    def test_io(self):
        left, right = self.set_and_get(400, 100, 100, 0) #total:600
        self.assertTrue(left == 0 and right == 0, "can't stop")

        left, right = self.set_and_get(0, 5, 1000, 0) #side direction is not a trigger of stop
        self.assertTrue( left == right != 0, "stop wrongly by side sensors")

        left, right = self.set_and_get(0, 10, 0, 0) #curve to left
        self.assertTrue( left < right, "don't curve to left")

        left, right = self.set_and_get(0, 200, 0, 0) #curve to right
        self.assertTrue( left > right, "don't curve to right")

        left, right = self.set_and_get(0, 5, 0, 0) #don't control when far from a wall
        self.assertTrue( 0 < left == right, "curve wrongly")        

if __name__=='__main__':
    time.sleep(3)
    rospy.init_node('travis_test_wall_trace')
    rostest.rosrun('pimouse_run_corridor','travis_test_wall_trace',WallTraceTest)
Beispiel #57
0
            with capture_screen(video, timeout):
                pub.publish(msg_class(*targets[name]))
            add_text_to_video(video)
            videos.append(video)
        ofile = "%s/face.avi" % self.output_dir
        concatenate_videos(videos, ofile, True)
        pub.unregister()

    def test_long_viseme(self):
        filename = get_rosbag_file("long_viseme")
        # job = play_rosbag(filename)
        # job.join()
        pub, msg_class = rostopic.create_publisher("/blender_api/queue_viseme", "blender_api_msgs/Viseme", True)
        bag = rosbag.Bag(filename)
        duration = bag.get_end_time() - bag.get_start_time()
        fps = bag.get_message_count() / float(duration)
        wait = 1.0 / fps / 10  # 10 times faster than the speed of the msg recoreded
        for topic, msg, _ in rosbag_msg_generator(filename):
            pub.publish(msg)
            time.sleep(wait)
        # Test if blender is still alive
        self.assertIn("/blender_api", rosnode.get_node_names())
        self.assertTrue(any(["blender_api" in name for name in self.runner.pm.get_active_names()]))


if __name__ == "__main__":
    import rostest

    rostest.rosrun(PKG, "blender_api", BlenderAPITest)
    # unittest.main()
Beispiel #58
0
        self.as_server = actionlib.SimpleActionServer(as_name,
                                                      MoveBaseAction,
                                                      execute_cb=self.base_cb,
                                                      auto_start=False)
        self.as_server.start()

        client = actionlib.SimpleActionClient('/script_server', ScriptAction)

        self.cb_move_executed = False
        if not client.wait_for_server(rospy.Duration(10)):
            self.fail('Action server not ready')
        client.send_goal(goal)
        client.wait_for_result(rospy.Duration(10))
        #if not client.wait_for_result(rospy.Duration(10)):
        #	self.fail('Action didnt give a result before timeout')

        #if not self.cb_executed:
        #	self.fail('Action Server not called. script server error_code: ' + str(client.get_result().error_code))

    def base_cb(self, goal):
        self.cb_move_executed = True
        result = MoveBaseResult()
        self.as_server.set_succeeded(result)

    # test move trajectory commands
    #TODO

if __name__ == '__main__':
    import rostest
    rostest.rosrun(PKG, 'action_interface', TestActionInterface)
#!/usr/bin/env python
#-*- coding: utf-8 -*-

PKG = 'jenkins_test_repro'
#import roslib; roslib.load_manifest(PKG)  # This line is not needed with Catkin.

import os
import rostest
import unittest
from MetricTester import MetricTester

class TestMetricStarter(unittest.TestCase):

    def test_metrics(self):
        mt = MetricTester()
        #self.assertTrue(False, os.getcwd())
        #self.assertTrue(False, os.listdir(os.getcwd()))

        self.assertTrue(mt.load_yaml_config(), "loading yaml-config")
        self.assertTrue(mt.triggerFeedbackServer(), "feedback server response")
        self.assertTrue(mt.download_resources(), "downloading resources")
        self.assertTrue(mt.cleanup_resources(), "cleanup resources")

if __name__ == '__main__':
    rostest.rosrun(PKG, 'MetricStarter', TestMetricStarter)

        self.assertEqual(grasp.id, "super_amazing_grasp")

        self.assertEqual(grasp.grasp_pose.pose.position.x, 0.5)
        self.assertEqual(grasp.grasp_pose.pose.position.y, 0.5)
        self.assertEqual(grasp.grasp_pose.pose.position.z, 0.7)

        self.assertEqual(round_sig(grasp.grasp_pose.pose.orientation.x, 5),
                         round_sig(0.396609862374, 5))
        self.assertEqual(round_sig(grasp.grasp_pose.pose.orientation.y, 5),
                         round_sig(0.443462541797, 5))
        self.assertEqual(round_sig(grasp.grasp_pose.pose.orientation.z, 5),
                         round_sig(0.770688050305, 5))
        self.assertEqual(round_sig(grasp.grasp_pose.pose.orientation.w, 5),
                         round_sig(0.2282137599, 5))

        self.assertEqual(1, 1)


if __name__ == '__main__':
    import rostest

    rospy.sleep(20)

    # rostest.rosrun("test_service_running",
    #                "test_fast_grasp_planner",
    #                TestFastGraspPlanner)

    rostest.rosrun("test_grasp_selection",
                   'test_fast_grasp_planner',
                   TestFastGraspPlanner)