Best Python code snippet using robotframework
mongo_client.py
Source:mongo_client.py  
1#!/usr/bin/python32import traceback3#check that the robot packages are present4print("Starting Client")5print("Using API level v3")6ev3_package_check = True7try:8    import ev3dev.ev3 as ev39    from robot_software.followLine import FollowLine10    print("ev3 modules imported")11except:12    traceback.print_exc()13    print("Unable to load robot control packages package!")14    ev3_package_check = False15import requests16print("request imported")17import socket18print("socket imported")19print("struct imported")20import time21print("time imported")22import sys23print("sys imported")24print("datetime imported")25import json26print("json imported")27from threading import Thread28print("threading imported")29from zeroconf import ServiceBrowser, Zeroconf30print("zeroconf imported")31from bobTranslation import extract32print("bobTranslation imported")33from followPath import FollowPath34print("followPath imported")35#remove me36last_json = {}37def polling(ip_addr, port, run_robot,username):38    running = True39    movement = False40    if run_robot:41        bob_bot = FollowLine()42    while running:43        try:44            headers = {'username':username}45            r = requests.get("http://{}:{}/api/robotjob".format(ip_addr,port),headers=headers)46            path = json.loads(r.text)47            if path["job"] == []:48                print("No order")49            else:50                print(path['job'])51                path_tuples = extract(path['job']['instruction_set'])52                print("Path tuples: ", path_tuples)53                robot_boy = FollowPath()54                robot_boy.start(path_tuples)55            56        except:57            58            traceback.print_exc()59        time.sleep(5)60class MyListener:61    def __init__(self,run_robot):62        self.run_robot = run_robot63    def remove_service(self, zeroconf, type, name):64        print("Service %s removed" % (name,))65    def add_service(self, zeroconf, type, name):66        info = zeroconf.get_service_info(type, name)67        ip_addr =(socket.inet_ntoa(info.address))68        port = info.port69        print(ip_addr,port,name)70        if (name == "assis10t._http._tcp.local."):71            #TODO: call get 3 times72            try:73                base_url = "http://{}:{}".format(ip_addr,port)74                75                r = requests.get("http://{}:{}/api/ping".format(ip_addr, port))76                # wait for response77                if (r.text == "pong"):78                    print("Server running on {}:{}".format(ip_addr,port))79                    username = "bob_test"80                    body = {'username':username,'type':'robot'}81                    r = requests.post('http://{}:{}/api/register'.format(ip_addr,port),json=body)82                    if (json.loads(r.text)["success"]):83                        print('Registered bob_test')84                    else:85                        print(r.text)86                    87                    r = requests.get('http://{}:{}/api/robot'.format(ip_addr,port),headers={'username':'bob_test'})88                    print(r.text)89                    if (self.run_robot):90                        ev3.Sound.tone([(1000, 250, 0),(1500, 250, 0),(2000, 250, 0)]).wait()91                        ev3.Sound.speak("i am bob. Beep. i collect your shopping").wait()92                        # TODO: add light to indicate status93                    poller = Thread(target=polling, name="poller",args=(ip_addr,port,self.run_robot,username))94                    poller.start()95                else:96                    print("Server did not respond!")97                    if (self.run_robot):98                        ev3.Sound.tone([(750, 250, 0),(750, 250, 0)]).wait()99                        # TODO: add light to indicate status100            except:101                print("Failed to connect to server!")102                traceback.print_exc()103                if (self.run_robot):104                    ev3.Sound.tone([(750, 250, 0),(750, 250, 0)]).wait()105                    # TODO: add light to indicate status106if __name__ == "__main__":107    run_robot = None108    if (len(sys.argv) > 1):109        mode_str = sys.argv[1]110        #TODO: clean this up111        if (mode_str == 'r' or mode_str == 'robot' and ev3_package_present == True):112            ev3.Sound().beep().wait()113            run_robot = True114        elif (mode_str == "t" or mode_str=="test"):115            print("Running client in test mode...")116            print(''.join(['-' for x in range(40)]) + '\n')117            run_robot = False118        else:119            print('Unable to determine mode! r/robot -> robot | t/test -> test')120            exit()121    else:122        if (ev3_package_check):123            #assume robot mode124            run_robot = True125        else:126            print("Unable to start client as ev3 package not present and test mode not indicated")127            exit()128    if (run_robot):129        ev3.Sound.beep().wait()130    zeroconf = Zeroconf()131    listener = MyListener(run_robot)132    browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)133    try:134        input("Press enter to exit...\n\n")135    finally:...test_run_robot.py
Source:test_run_robot.py  
1import sys2import os3import unittest4import time5import signal6from mock import Mock, patch7sys.path.append(os.path.abspath("."))8sys.path.append(os.path.abspath("rpirobot"))9from rpirobot.run_robot import RobotRunner, TimeoutError, create_robot10class timeout(object):11    """Timeout util."""12    def __init__(self, seconds=1, error_message='Timeout'):13        self.seconds = seconds14        self.error_message = error_message15    def handle_timeout(self, signum, frame):16        raise TimeoutError(self.error_message)17    def __enter__(self):18        signal.signal(signal.SIGALRM, self.handle_timeout)19        signal.alarm(self.seconds)20    def __exit__(self, type, value, traceback):21        signal.alarm(0)22class TestiRunRobot(unittest.TestCase):23    """Tests for Robot class."""24    @patch('rpirobot.run_robot.Led')25    @patch('rpirobot.run_robot.Button')26    @patch('rpirobot.run_robot.Robot')27    @patch('rpirobot.run_robot.Motor')28    def setUp(self, Led, Button, Robot, Motor):29        self.robot_runner = RobotRunner()30    def test_robot_runner(self):31        self.assertIsNotNone(self.robot_runner.robot)32    def test_robot_sets_led(self):33        self.assertTrue(self.robot_runner.robot.set_led.called)34    def test_robot_sets_button(self):35        self.assertTrue(self.robot_runner.robot.set_button.called)36    def test_robot_sets_motors(self):37        self.assertTrue(self.robot_runner.robot.set_motors.called)38    def test_run_forever(self):39        self.robot_runner.robot.button.is_hold = Mock(return_value=0)40        tm = time.time()41        with timeout(seconds=1):42            try:43                self.robot_runner.run_forever()44            except TimeoutError:45                pass46        self.assertEqual(int(time.time() - tm), 1)47    def test_toggle_status_on_button_press(self):48        self.robot_runner.robot.button.is_pressed = Mock(return_value=1)49        self.robot_runner.robot.button.is_hold = Mock(return_value=0)50        with timeout(seconds=1):51            try:52                self.robot_runner.run_forever()53            except TimeoutError:54                pass55        self.assertTrue(self.robot_runner.robot.toggle_status.called)56    def test_check_if_button_pressed(self):57        self.robot_runner.robot.button.reset_mock()58        self.robot_runner.robot.button.is_hold = Mock(return_value=0)59        with timeout(seconds=1):60            try:61                self.robot_runner.run_forever()62            except TimeoutError:63                pass64        self.assertTrue(self.robot_runner.robot.button.is_pressed.called)65    @patch('rpirobot.run_robot.subprocess')66    def test_system_halt_on_button_hold(self, subprocess):67        self.robot_runner.robot.button.is_hold = Mock(return_value=1)68        with timeout(seconds=4):69            try:70                self.robot_runner.run_forever()71            except TimeoutError:72                pass73        self.assertTrue(subprocess.call.called)74    @patch('rpirobot.run_robot.Led')75    @patch('rpirobot.run_robot.Button')76    @patch('rpirobot.run_robot.Robot')77    @patch('rpirobot.run_robot.Motor')78    def test_create_robot(self, Led, Button, Robot, Motor):79        robot = create_robot()80        #self.assertTrue(Robot.__init__.called)81        self.assertTrue(robot.set_led.called)82        self.assertTrue(robot.led.set_color.called)83        self.assertTrue(robot.led.on.called)84        self.assertTrue(robot.set_button.called)85        self.assertTrue(robot.set_motors.called)86if __name__ == '__main__':...run.py
Source:run.py  
1#!/usr/bin/python2"""3Example: python run.py COM14 70x70 test4arg1 --> Robot address COM145arg2 --> config file for the trial, 70x70.csv6arg3 --> output dir test7"""8run_robot = True9run_mocap = False10run_gyro_config = False11import sys, time12import dynaroach as dr13if run_mocap:14    import natnethelper as nt15    import NatNet16r = None17try:18    if len(sys.argv) != 4:19        print "Please input 3 arguments:"20        print "python run.py <robot_adress> <config file> <output_dir>"21        print "Example: python run.py COM14 70x70.csv test"22        sys.exit(1)23    #collect data and run the robot switch24    if run_mocap:25        nat_net_client = NatNet.NatNetClient(1);26        nat_net_client.Initialize("","");27    infile = sys.argv[2]28    29    if len(sys.argv) > 3:30        dir = sys.argv[3]31        save = True32    else:33        save = False34    ds = dr.datestring()35    if run_robot:36        r = dr.DynaRoach(sys.argv[1])37        38        if save:39            if run_gyro_config:40                r.run_gyro_calib()41                print("Running gyro calibration...")42                time.sleep(0.5)43                r.get_gyro_calib_param()44                time.sleep(0.5)45        while run_gyro_config and r.gyro_offsets == None:46            print "Waiting on gyro offset"47            time.sleep(2)48        if run_gyro_config:49            print ("got and waiting")50            raw_input()51            print "Received gyro offset"52        else:53            # fake some data54            r.gyro_offsets = [0, 0, 0]55        t = dr.Trial()56        if save:57            t.save_to_file('./' + dir + '/' + ds + '_cfg',58                gyro_offsets=r.gyro_offsets, rid=eval(open('rid.py').read()),59                cfg_file=infile, cfg_contents=open(infile, "r+").read())60        t.load_from_file(infile)61        r.configure_trial(t)62    print("Press any key to start the trial running.")63    raw_input()64    if run_mocap:65        print("Starting Motion Capture") 66        mocap_data = nt.start_collection(nat_net_client)67    if run_robot:68        r.run_trial()69    print("Press any key to request the mcu data from the robot.")70    raw_input()71    if run_mocap:72        print("Stopping mocap collection");73        nt.stop_collection(nat_net_client);74    75    if save:76        if run_robot:77            r.transmit_saved_data()78            print("Press any key when data is done transmitting.")79            input = raw_input()80            if input == 'q':81                r.__del__()82                pass83            r.save_trial_data('./' + dir + '/' + ds + '_mcu.csv')84            r.erase_mem_sector(0x100)85            time.sleep(1)86            r.erase_mem_sector(0x200)87            time.sleep(1)88            r.erase_mem_sector(0x300)89            time.sleep(1)90            r.reset(do_wait=False)91        if run_mocap:92            nt.csv_from_data(nat_net_client, mocap_data, './' + dir + '/' + ds + '_mocap.csv');93except Exception as e:94    print('Caught the following exception: ' + str(e))95finally:96    if r:97        r.__del__()...test_robot.py
Source:test_robot.py  
...4import random5from four_exercises import run_robot6class TestRobot(unittest.TestCase):7    @staticmethod8    def run_robot(user_input):9        with patch('builtins.input', side_effect=user_input):10            return run_robot()11    def test_one(self):12        user_input = [13            'UP 5',14            'DOWN 5',15            ''16        ]17        self.assertEqual(self.run_robot(user_input), 0)18    def test_two(self):19        user_input = [20            'UP 5',21            'DOWN 5',22            'LEFT 2',23            'RIGHT 3',24            'LEFT 1',25            ''26        ]27        self.assertEqual(self.run_robot(user_input), 0)28    def test_three(self):29        user_input = [30            'UP 5',31            'DOWN 5',32            'LEFT 2',33            'RIGHT 3',34            'LEFT 1',35            'RIGHT 2',36            'UP 1',37            ''38        ]39        self.assertEqual(self.run_robot(user_input), 2)40    def test_four(self):41        user_input = [42            'UP 22',43            'DOWN 5',44            'LEFT 8',45            'RIGHT 3',46            'LEFT 13',47            'RIGHT 2',48            'UP 1',49            ''50        ]51        self.assertEqual(self.run_robot(user_input), 24)52    def test_random(self):53        up = random.randint(0, 100)54        down = random.randint(0, 100)55        left = random.randint(0, 100)56        right = random.randint(0, 100)57        user_input = [58            f'UP {up}',59            f'DOWN {down}',60            f'LEFT {left}',61            f'RIGHT {right}',62        ]63        random.shuffle(user_input)64        user_input += ['']65        expected_result = int(66            round(math.sqrt((up - down) ** 2 + (left - right) ** 2))67        )68        self.assertEqual(69            self.run_robot(user_input), expected_result70        )71    def test_random_loop(self):72        for _ in range(100):73            self.test_random()74if __name__ == '__main__':75    random.seed(a=1)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
