def iterate_finish(self): information = self.finished_store.get(timeout=self.timeout) if information is not None: reservation_id, obj, initial_time, end_time = information if not self.commands_store.empty( ) or not self.completed_store.empty(): # They have higher priority self.finished_store.put(reservation_id, obj, initial_time, end_time) return initial_timestamp = time.mktime( initial_time.timetuple()) + initial_time.microsecond / 1e6 end_timestamp = time.mktime( end_time.timetuple()) + end_time.microsecond / 1e6 command = CommandSent(Command.Command("@@@finish@@@"), initial_timestamp, Command.Command(str(obj)), end_timestamp) if not self.db_manager.finish_experiment_usage( reservation_id, initial_timestamp, command): # If it could not be added because the experiment id # did not exist, put it again in the queue self.finished_store.put(reservation_id, obj, initial_time, end_time) time.sleep(0.01)
def test_send_command(self): port = 15130 self.configurationManager._set_value(self.rfs.FACADE_JSON_PORT, port) self.rfs.start() try: client = WebLabDeustoClient("http://localhost:%s/weblab/" % port) expected_sess_id = SessionId.SessionId("whatever") expected_request_command = Command.Command('my request command') expected_response_command = Command.Command('my response command') self.mock_server.return_values['send_command'] = expected_response_command obtained_response_command = client.send_command(expected_sess_id, expected_request_command) self.assertEquals( expected_sess_id.id, self.mock_server.arguments['send_command'][0] ) self.assertEquals( expected_request_command.get_command_string(), self.mock_server.arguments['send_command'][1].get_command_string() ) self.assertEquals( expected_response_command.get_command_string(), obtained_response_command.get_command_string() ) finally: self.rfs.stop()
def _single_async_use(self, logout=True): session_id, reservation_id = self._get_reserved() # send the program again, but asynchronously. Though this should work, it is not really very customary # to send_file more than once in the same session. In fact, it is a feature which might get removed in # the future. When/if that happens, this will need to be modified. CONTENT = "content of the program FPGA" reqid = self.client.send_async_file(reservation_id, ExperimentUtil.serialize(CONTENT), 'program') # Wait until send_async_file query is actually finished. #self._get_async_response(session_id, reqid) self._wait_async_done(reservation_id, (reqid, )) # We need to wait for the programming to finish, while at the same # time making sure that the tests don't dead-lock. reqid = self.client.send_async_command(reservation_id, Command.Command("STATE")) respcmd = self._get_async_response(reservation_id, reqid) response = respcmd.get_command_string() # Check that the current state is "Ready" self.assertEquals("STATE", response) reqid = self.client.send_async_command( reservation_id, Command.Command("ChangeSwitch on 0")) self._wait_async_done(reservation_id, (reqid, )) reqid = self.client.send_async_command( reservation_id, Command.Command("ClockActivation on 250")) self._wait_async_done(reservation_id, (reqid, )) if logout: self.client.logout(session_id)
def test_send_command_ok(self): self._return_reserved() command = Command.Command("Your command") lab_response = Command.Command("LAB RESPONSE") self.lab_mock.send_command(SessionId.SessionId('my_lab_session_id'), command) self.mocker.result(lab_response) self.mocker.replay() self.create_reservation_processor() self.coordinator.confirmer._confirm_handler.join(10) self.assertFalse(self.coordinator.confirmer._confirm_handler.isAlive()) self.reservation_processor.get_status() self.assertFalse(self.reservation_processor.is_expired()) response = self.reservation_processor.send_command(command) self.assertEquals(lab_response, response) self.assertFalse(self.reservation_processor.is_expired()) self.reservation_processor.finish() self.assertEquals(self.reservation_processor.get_status().status, Reservation.Reservation.POST_RESERVATION)
def send_async_file(self, file_content, file_info): """ Sends a file asynchronously. Status of the request may be checked through check_async_command_status. @param file_content: Content of the file being sent @param file_info: File information of the file being sent @see check_async_command_status """ lab_session_id = self._reservation_session.get('lab_session_id') lab_coordaddr = self._reservation_session.get('lab_coordaddr') if lab_session_id is None or lab_coordaddr is None: raise core_exc.NoCurrentReservationError( "send_async_file called but no current reservation") laboratory_server = self._locator.get_server_from_coordaddr( lab_coordaddr, ServerType.Laboratory) usage_file_sent = self._store_file(file_content, file_info) command_id_pack = self._append_file(usage_file_sent) try: response = laboratory_server.send_async_file( lab_session_id, file_content, file_info) # TODO: how do we store async files? whenever somebody ask for the status? what if they don't ask for it? return response except LaboratoryErrors.SessionNotFoundInLaboratoryServerError: self._update_command_or_file( command_id_pack, Command.Command("ERROR: SessionNotFound: None")) try: self.finish() except core_exc.FailedToFreeReservationError: pass raise core_exc.NoCurrentReservationError( 'Experiment reservation expired') except LaboratoryErrors.FailedToInteractError as ftspe: self._update_command_or_file( command_id_pack, Command.Command("ERROR: " + str(ftspe))) try: self.finish() except core_exc.FailedToFreeReservationError: pass raise core_exc.FailedToInteractError("Failed to send file: %s" % ftspe)
def run_user(self): self.bot.raise_exceptions = True self.bot.do_login(self.username, self.password) self.bot.do_get_user_information() experiments = self.bot.do_list_experiments() if experiments is not None: experiments_found = [ exp for exp in experiments if exp.name == self.experiment_name and exp.category.name == self.experiment_category_name ] if len(experiments_found) > 0: reservation = self.bot.do_reserve_experiment(experiments_found[0].to_experiment_id(), "{}", "{}") else: raise Exceptions.ExperimentDoesNotExistError("Desired experiment doesn't exist: %s." % self.experiment_name) while isinstance(reservation, Reservation.WaitingReservation) or isinstance(reservation, Reservation.WaitingConfirmationReservation): if isinstance(reservation, Reservation.WaitingReservation): time.sleep(self._get_waiting_reservation_poll_time(reservation.position)) elif isinstance(reservation, Reservation.WaitingConfirmationReservation): time.sleep(self._get_waiting_confirmation_poll_time()) reservation = self.bot.do_get_reservation_status() sys.stdout.flush() if not isinstance(reservation, Reservation.ConfirmedReservation): exc = self.bot.calls[-1].exception raise Exceptions.UserAssertionError("At this point, it should be a ConfirmedReservation. Found: <%s>; <%s>" % (reservation, exc) ) self.bot.do_send_file(self.program,"program") #for _ in xrange(10): self.bot.do_send_command(Command.Command("ChangeSwitch on 0")) self.bot.do_finished_experiment() self.bot.do_logout()
def run(self): """ run() @return HTML defined above, with the success or failure response. """ try: session_id = self._check_arguments() sid = SessionId(session_id) result = self.server.send_command(sid, Command.Command("get_html")) except LabViewError as lve: message = lve.args[0] return HTML_TEMPLATE % { 'MESSAGE': "Failed to load LabVIEW experiment. Reason: %s." % message } except Exception as e: message = e.args[0] return HTML_TEMPLATE % { 'MESSAGE': "Failed to load LabVIEW experiment. Reason: %s. Call the administrator to fix it." % message } else: resultstr = result.commandstring print "[DBG] Returning result from labview: " + resultstr return HTML_TEMPLATE % {'MESSAGE': resultstr}
def test_send_async_command_session_not_found_in_lab(self): self._return_reserved() command = Command.Command("Your command") self.lab_mock.send_async_command( SessionId.SessionId('my_lab_session_id'), command) self.mocker.throw( LaboratoryErrors.SessionNotFoundInLaboratoryServerError( "problem@laboratory")) self.mocker.replay() self.create_reservation_processor() self.coordinator.confirmer._confirm_handler.join(10) self.assertFalse(self.coordinator.confirmer._confirm_handler.isAlive()) self.reservation_processor.get_status() self.assertFalse(self.reservation_processor.is_expired()) self.assertRaises(coreExc.NoCurrentReservationError, self.reservation_processor.send_async_command, command) self.assertEquals(self.reservation_processor.get_status().status, Reservation.Reservation.POST_RESERVATION)
def _get_async_response(self, reservation_id, reqid): """ _get_async_response(reqids) Helper method that synchronously gets the response for the specified async request, asserting that it was successful. @param reqid The request identifier for the async request whose response we want @return Response to the request, if successful. None, otherwise. """ # Wait until send_async_file query is actually finished. max_counter = 15 while True: max_counter -= 1 if max_counter == 0: raise Exception("Maximum times running get_async_response") time.sleep(0.1) requests = self.client.check_async_command_status( reservation_id, (reqid, )) self.assertEquals(1, len(requests)) self.assertTrue(reqid in requests) req = requests[reqid] status = req[0] self.assertTrue(status in ("running", "ok", "error")) if status != "running": self.assertEquals("ok", status, "Contents: " + req[1]) return Command.Command(req[1])
def _send_async_command_t(self, session, command): """ This method is used for asynchronously calling the experiment server's send_command_to_device, and for that purpose runs on its own thread. This implies that its response will arrive asynchronously to the client. """ lab_session_id = session['session_id'] experiment_instance_id = session['experiment_instance_id'] api = self._assigned_experiments.get_api(experiment_instance_id) experiment_coord_address = session['experiment_coord_address'] experiment_server = self._locator[experiment_coord_address] try: if api.endswith("concurrent"): response = experiment_server.send_command_to_device( lab_session_id, command.get_command_string()) else: response = experiment_server.send_command_to_device( command.get_command_string()) except Exception as e: log.log(LaboratoryServer, log.level.Warning, "Exception sending async command to experiment: %s" % e) log.log_exc(LaboratoryServer, log.level.Info) raise LaboratoryErrors.FailedToSendCommandError( "Couldn't send async command: %s" % str(e)) return Command.Command(str(response))
def test_send_file(self): self.configurationManager._set_value(self.rfs.FACADE_ZSI_PORT, 14129) self.rfs.start() try: wds = UserProcessingWebLabDeustoSOAP("http://localhost:14129/weblab/soap/") expected_sess_id = SessionId.SessionId("whatever") expected_content = 'my file' expected_result = 'hello there' file_info = 'program' self.mock_server.return_values['send_file' ] = Command.Command(expected_result) result = wds.send_file(expected_sess_id, expected_content, file_info) self.assertEquals( expected_sess_id.id, self.mock_server.arguments['send_file'][0] ) self.assertEquals( expected_content, self.mock_server.arguments['send_file'][1] ) self.assertEquals( expected_result, result.commandstring ) finally: self.rfs.stop()
def test_send_file_ok(self): file_content = "SAMPLE CONTENT" lab_response = Command.Command("LAB RESPONSE") file_info = 'program' self._return_reserved() self.lab_mock.send_file(SessionId.SessionId('my_lab_session_id'), file_content, file_info) self.mocker.result(lab_response) self.mocker.replay() self.create_reservation_processor() self.coordinator.confirmer._confirm_handler.join(10) self.assertFalse(self.coordinator.confirmer._confirm_handler.isAlive()) self.reservation_processor.get_status() self.assertFalse(self.reservation_processor.is_expired()) response = self.reservation_processor.send_file( file_content, file_info) self.assertEquals(lab_response, response) self.assertFalse(self.reservation_processor.is_expired()) self.reservation_processor.finish() self.assertEquals(self.reservation_processor.get_status().status, Reservation.Reservation.POST_RESERVATION)
def do_send_command(self, session, command): lab_session_id = session['session_id'] experiment_instance_id = session['experiment_instance_id'] api = self._assigned_experiments.get_api(experiment_instance_id) experiment_coord_address = session['experiment_coord_address'] experiment_server = self._locator.get_server_from_coordaddr( experiment_coord_address, ServerType.Experiment) try: if api.endswith("concurrent"): response = experiment_server.send_command_to_device( lab_session_id, command.get_command_string()) else: response = experiment_server.send_command_to_device( command.get_command_string()) except Exception as e: log.log(LaboratoryServer, log.level.Warning, "Exception sending command to experiment: %s" % e) log.log_exc(LaboratoryServer, log.level.Info) raise LaboratoryErrors.FailedToSendCommandError( "Couldn't send command: %s" % str(e)) return Command.Command(str(response))
def test_send_async_command_fail(self): lab_session_id, experiment_server_result, exp_coord_str = self.lab.do_reserve_experiment( self.experiment_instance_id, {}, {}) self.fake_client.fail = True reqid = self.lab.do_send_async_command(lab_session_id, Command.Command("foo")) # We don't know how much time it will take so we have to keep checking # until we are done, for a maximum of 3 seconds. time_start = time.time() while (True): time_now = time.time() if (time_now - time_start > 3000): self.assertTrue(False, "Timeout while trying to run async commands") result = self.lab.do_check_async_command_status( lab_session_id, (reqid, )) tup = result[reqid] self.assertTrue(tup[0] in ("running", "ok", "error")) self.assertNotEquals("ok", tup[0], "Expected an error") if (tup[0] != "running"): self.assertTrue("error", tup[0]) self.assertTrue(tup[1] is not None) break return
def send_command(self, command): # # Check the that the experiment is enabled # lab_session_id = self._reservation_session.get('lab_session_id') lab_coordaddr = self._reservation_session.get('lab_coordaddr') if lab_session_id is None or lab_coordaddr is None: raise core_exc.NoCurrentReservationError( "send_command called but the reservation is not enabled") laboratory_server = self._locator.get_server_from_coordaddr( lab_coordaddr, ServerType.Laboratory) command_id_pack = self._append_command(command) try: # We call the laboratory server's send_command, which will finally # get the command to be handled by the experiment. response = laboratory_server.send_command(lab_session_id, command) # The previous call was executed synchronously and we have # received the response. Before returning it, we will store it # locally so that we can log it. self._update_command_or_file(command_id_pack, response) return response except LaboratoryErrors.SessionNotFoundInLaboratoryServerError: self._update_command_or_file( command_id_pack, Command.Command("ERROR: SessionNotFound: None")) try: self.finish() except core_exc.FailedToFreeReservationError: pass raise core_exc.NoCurrentReservationError( 'Experiment reservation expired') except LaboratoryErrors.FailedToInteractError as ftspe: self._update_command_or_file( command_id_pack, Command.Command("ERROR: " + str(ftspe))) try: self.finish() except core_exc.FailedToFreeReservationError: pass raise core_exc.FailedToInteractError("Failed to send command: %s" % ftspe)
def iterate_initial(self): initial_information = self.initial_store.get(timeout=self.timeout) if initial_information is not None: initial_timestamp = time.mktime( initial_information.initial_time.timetuple( )) + initial_information.initial_time.microsecond / 1e6 end_timestamp = time.mktime(initial_information.end_time.timetuple( )) + initial_information.end_time.microsecond / 1e6 request_info = initial_information.request_info from_ip = request_info.pop('from_ip', '<address not found>') try: username = request_info.pop('username') except: log.log( TemporalInformationRetriever, log.level.Critical, "Provided information did not contain some required fields (such as username or role). This usually means that the reservation has previously been expired. Provided request_info: %r; provided data: %r" % (request_info, initial_information), max_size=10000) log.log_exc(TemporalInformationRetriever, log.level.Critical) return usage = ExperimentUsage() usage.start_date = initial_timestamp usage.from_ip = from_ip usage.experiment_id = initial_information.experiment_id usage.reservation_id = initial_information.reservation_id usage.coord_address = initial_information.exp_coordaddr usage.request_info = initial_information.request_info command_request = CommandSent( Command.Command("@@@initial::request@@@"), initial_timestamp, Command.Command(str(initial_information.client_initial_data)), end_timestamp) command_response = CommandSent( Command.Command("@@@initial::response@@@"), initial_timestamp, Command.Command(str( initial_information.initial_configuration)), end_timestamp) usage.append_command(command_request) usage.append_command(command_response) self.db_manager.store_experiment_usage(username, usage)
def test_update_command(self): student1 = self.gateway._get_user(self.session, 'student1') RESERVATION_ID1 = 'my_reservation_id1' usage1 = ExperimentUsage() usage1.start_date = time.time() usage1.end_date = time.time() usage1.from_ip = "130.206.138.16" usage1.experiment_id = ExperimentId("ud-dummy", "Dummy experiments") usage1.coord_address = CoordAddress("machine1", "instance1", "server1") usage1.reservation_id = RESERVATION_ID1 usage1.request_info = { 'facebook': False, 'permission_scope': 'user', 'permission_id': student1.id } self.gateway.store_experiment_usage(student1.login, usage1) usages = self.gateway.list_usages_per_user(student1.login) self.assertEquals(1, len(usages)) full_usage = self.gateway.retrieve_usage(usages[0].experiment_use_id) self.assertEquals(0, len(full_usage.commands)) command1 = CommandSent(Command.Command("your command"), time.time()) command_id = self.gateway.append_command(RESERVATION_ID1, command1) full_usage = self.gateway.retrieve_usage(usages[0].experiment_use_id) self.assertEquals("your command", full_usage.commands[0].command.commandstring) self.assertEquals(Command.NullCommand(), full_usage.commands[0].response) self.gateway.update_command(command_id, Command.Command("the response"), time.time()) full_usage = self.gateway.retrieve_usage(usages[0].experiment_use_id) self.assertEquals("your command", full_usage.commands[0].command.commandstring) self.assertEquals("the response", full_usage.commands[0].response.commandstring)
def create_usage(gateway, reservation_id = 'my_reservation_id'): session = gateway.Session() student1 = gateway._get_user(session, 'student1') initial_usage = ExperimentUsage() initial_usage.start_date = time.time() initial_usage.end_date = time.time() initial_usage.from_ip = "130.206.138.16" initial_usage.experiment_id = ExperimentId("ud-dummy","Dummy experiments") initial_usage.coord_address = CoordAddress.CoordAddress("machine1","instance1","server1") #.translate_address("server1:instance1@machine1") initial_usage.reservation_id = reservation_id file1 = FileSent( 'path/to/file1', '{sha}12345', time.time() ) file2 = FileSent( 'path/to/file2', '{sha}123456', time.time(), Command.Command('response'), time.time(), file_info = 'program' ) command1 = CommandSent( Command.Command("your command1"), time.time() ) command2 = CommandSent( Command.Command("your command2"), time.time(), Command.Command("your response2"), time.time() ) initial_usage.append_command(command1) initial_usage.append_command(command2) initial_usage.append_file(file1) initial_usage.append_file(file2) initial_usage.request_info = {'facebook' : False} gateway.store_experiment_usage(student1.login, initial_usage) return student1, initial_usage, command1, command2, file1, file2
def test_send_command_fail(self): lab_session_id, experiment_server_result, exp_coord_str = self.lab.do_reserve_experiment( self.experiment_instance_id, {}, {}) self.fake_client.fail = True self.assertRaises(LaboratoryErrors.FailedToSendCommandError, self.lab.do_send_command, lab_session_id, Command.Command("foo"))
def _single_sync_use(self, logout=True): session_id, reservation_id = self._get_reserved() CONTENT = "content of the program FPGA" response = self.client.send_file(reservation_id, ExperimentUtil.serialize(CONTENT), 'program') self.assertEquals(response.commandstring, 'ack') response = self.client.send_command(reservation_id, Command.Command("STATE")) self.assertEquals(response.commandstring, 'STATE') response = self.client.send_command( reservation_id, Command.Command("ChangeSwitch on 0")) self.assertEquals(response.commandstring, "ChangeSwitch on 0") if logout: self.client.logout(session_id)
def send_file(self, file_content, file_info): # # Check that the reservation is enabled # lab_session_id = self._reservation_session.get('lab_session_id') lab_coordaddr = self._reservation_session.get('lab_coordaddr') if lab_session_id is None or lab_coordaddr is None: raise core_exc.NoCurrentReservationError( "send_file called but the reservation was not enabled") # # Retrieve the laboratory server # laboratory_server = self._locator.get_server_from_coordaddr( lab_coordaddr, ServerType.Laboratory) usage_file_sent = self._store_file(file_content, file_info) command_id_pack = self._append_file(usage_file_sent) try: response = laboratory_server.send_file(lab_session_id, file_content, file_info) self._update_command_or_file(command_id_pack, response) return response except LaboratoryErrors.SessionNotFoundInLaboratoryServerError: self._update_command_or_file( command_id_pack, Command.Command("ERROR: SessionNotFound")) try: self.finish() except core_exc.FailedToFreeReservationError: pass raise core_exc.NoCurrentReservationError( 'Experiment reservation expired') except LaboratoryErrors.FailedToInteractError as ftie: self._update_command_or_file( command_id_pack, Command.Command("ERROR: " + str(ftie))) try: self.finish() except core_exc.FailedToFreeReservationError: pass raise core_exc.FailedToInteractError("Failed to send: %s" % ftie)
def test_return_send_command(self): expected_sess_id = {'id': "whatever"} expected_command = Command.Command("ChangeSwitch on 9") self.mock_ups.return_values['send_command'] = None self.rfm.send_command(expected_sess_id, expected_command.to_dict()) self.assertEquals(expected_sess_id['id'], self.mock_ups.arguments['send_command'][0].id) self.assertEquals( expected_command.get_command_string(), self.mock_ups.arguments['send_command'][1].get_command_string())
def test_get_experiment_uses_by_id(self): port = 15131 self.configurationManager._set_value(self.rfs.FACADE_JSON_PORT, port) self.rfs.start() try: client = WebLabDeustoClient("http://localhost:%s/weblab/" % port) expected_sess_id = SessionId.SessionId("whatever") expected_usage = ExperimentUsage(10, time.time(), time.time(), '127.0.0.1', ExperimentId("exp","cat"), 'reser1', CoordAddress('machine','instance','server')) command_sent = CommandSent(Command.Command("request"), time.time(), Command.Command("response"), time.time()) expected_usage.append_command(command_sent) loaded_file_sent = LoadedFileSent('content-of-the-file', time.time(), Command.Command("response"), time.time(), 'program') expected_usage.append_file(loaded_file_sent) expected_finished_result = FinishedReservationResult(expected_usage) expected_alive_result = RunningReservationResult() expected_cancelled_result = CancelledReservationResult() self.mock_server.return_values['get_experiment_uses_by_id'] = (expected_finished_result, expected_alive_result, expected_cancelled_result) expected_reservations = (SessionId.SessionId('reservation'), SessionId.SessionId('reservation2'), SessionId.SessionId('reservation3') ) results = client.get_experiment_uses_by_id(expected_sess_id, expected_reservations) self.assertEquals( expected_sess_id.id, self.mock_server.arguments['get_experiment_uses_by_id'][0]) self.assertEquals( expected_reservations, tuple(self.mock_server.arguments['get_experiment_uses_by_id'][1])) self.assertEquals(3, len(results)) self.assertEquals(expected_finished_result.status, results[0].status) self.assertEquals(expected_alive_result.status, results[1].status) self.assertEquals(expected_cancelled_result.status, results[2].status) self.assertEquals(expected_usage, results[0].experiment_use) finally: self.rfs.stop()
def test_simple_use_zsi(self): response_command = Command.Command(RESPONSE_COMMAND) rfm_obj = self.mocker.mock() rfm_obj.send_command(mocker.ARGS) self.mocker.result(response_command) WrappedRemoteFacadeServer.rfm_mock = rfm_obj self.rfs = WrappedRemoteFacadeServer(None, self.configurationManager) self.mocker.replay() self.rfs.start() try: zsi_client = Client.BotZSI( "http://localhost:10223/weblab/soap/", "http://localhost:10223/weblab/login/soap/") zsi_client.reservation_id = SessionId.SessionId(REAL_ID) response_command = zsi_client.do_send_command( Command.Command(COMMAND)) self.assertEquals(response_command.commandstring, RESPONSE_COMMAND) finally: self.rfs.stop()
def test_return_send_command(self): expected_sess_id = SessionId.SessionId("whatever") expected_command = Command.Command("ChangeSwitch on 9") self.mock_ups.return_values['send_command'] = None self.rfm.send_command(expected_sess_id, expected_command) self.assertEquals(expected_sess_id.id, self.mock_ups.arguments['send_command'][0].id) self.assertEquals( expected_command.get_command_string(), self.mock_ups.arguments['send_command'][1].get_command_string())
def test_send_command_ok(self): lab_session_id, experiment_server_result, exp_coord_str = self.lab.do_reserve_experiment( self.experiment_instance_id, {}, {}) commands_sent = ["foo", "bar"] responses = ["result1", "result2"] self.fake_client.responses = responses[:] for command in commands_sent: result = self.lab.do_send_command(lab_session_id, Command.Command(command)) cur_response = responses.pop(0) self.assertEquals(cur_response, result.get_command_string()) self.assertTrue(self.fake_client.verify_commands(commands_sent))
def test_return_get_experiment_uses_by_id(self): expected_sess_id = SessionId.SessionId("whatever") expected_usage = ExperimentUsage(10, time.time(), time.time(), '127.0.0.1', ExperimentId("exp", "cat")) command_sent = CommandSent(Command.Command("request"), time.time(), Command.Command("response"), time.time()) expected_usage.append_command(command_sent) loaded_file_sent = LoadedFileSent('content-of-the-file', time.time(), Command.Command("response"), time.time(), 'program') expected_usage.append_file(loaded_file_sent) expected_finished_result = FinishedReservationResult(expected_usage) expected_alive_result = WaitingReservationResult() expected_cancelled_result = CancelledReservationResult() self.mock_ups.return_values['get_experiment_uses_by_id'] = ( expected_finished_result, expected_alive_result, expected_cancelled_result) results = self.rfm.get_experiment_uses_by_id( expected_sess_id, (SessionId.SessionId('reservation'), SessionId.SessionId('reservation2'), SessionId.SessionId('reservation3'))) self.assertEquals(3, len(results)) self.assertEquals(expected_finished_result.status, results[0].status) self.assertEquals(expected_alive_result.status, results[1].status) self.assertEquals(expected_cancelled_result.status, results[2].status) self.assertEquals(expected_usage, expected_finished_result.experiment_use)
def test_send_async_command_ok(self): lab_session_id, experiment_server_result, exp_coord_str = self.lab.do_reserve_experiment( self.experiment_instance_id, {}, {}) commands_sent = ["foo", "bar"] responses = ["result1", "result2"] request_ids = [] self.fake_client.responses = responses[:] # We will send the commands asynchronously. for command in commands_sent: reqid = self.lab.do_send_async_command(lab_session_id, Command.Command(command)) request_ids.append(reqid) # Build a dictionary relating the ids to the expected responses expected = dict(zip(request_ids, responses)) is_first_time = True # We don't know how much time it will take so we have to keep checking # until we are done, for a maximum of 3 seconds. time_start = time.time() while (len(expected) > 0): result = self.lab.do_check_async_command_status( lab_session_id, request_ids) if is_first_time: self.assertEquals(2, len(result)) is_first_time = False time_now = time.time() if (time_now - time_start > 3000): self.assertTrue(False, "Timeout while trying to run async commands") # Check every remaining command for id in expected.keys(): tup = result[id] self.assertTrue(tup[0] in ("running", "ok", "error")) if (tup[0] == "ok"): self.assertTrue(tup[1] in responses) del expected[id] elif (tup[0] == "error"): self.assertTrue( False, "Async command reported an error: " + tup[1]) del expected[id]
def _get_async_response(self, session_id, reqid): """ _get_async_response(reqids) Helper method that synchronously gets the response for the specified async request, asserting that it was successful. @param reqid The request identifier for the async request whose response we want @return Response to the request, if successful. None, otherwise. """ # Wait until send_async_file query is actually finished. while True: requests = self.real_ups.check_async_command_status(session_id, (reqid,)) self.assertEquals(1, len(requests)) self.assertTrue(reqid in requests) req = requests[reqid] status = req[0] self.assertTrue(status in ("running", "ok", "error")) if status != "running": self.assertEquals("ok", status, "Contents: " + req[1]) return Command.Command(req[1])
def labview(): try: reservation_id = get_argument(SESSION_ID) if reservation_id is None: return HTML_TEMPLATE % { 'MESSAGE' : "Failed to load LabVIEW experiment. Reason: %s argument not provided!." % SESSION_ID } weblab_api.ctx.reservation_id = reservation_id result = weblab_api.api.send_command(Command.Command("get_html")) except Exception as e: message = e.args[0] return HTML_TEMPLATE % { 'MESSAGE' : "Failed to load LabVIEW experiment. Reason: %s. Call the administrator to fix it." % message } else: resultstr = result.commandstring print("[DBG] Returning result from labview: " + resultstr) return HTML_TEMPLATE % { 'MESSAGE' : resultstr }