def test_responder_hands_what_it_got_from_receive_to_handler(self): self.transmitter.receive = mock.MagicMock(return_value="for the handler") handler = ResponseHandler(MoveGenerator()) handler.response = mock.Mock() responder = Responder(self.transmitter,handler) responder.respond() handler.response.assert_called_with("for the handler")
def get_msg(): t = Torrent('../torrent/flagfromserver.torrent') t.make_request() # make request, get response, handle response r = requests.get(t.request) rh = ResponseHandler(r) rh.get_peer_ip() # get handshake h = Handshake(t) #pick ip and port from peers ip = rh.ips[-1][0] port = rh.ips[-1][1] # socket connection and send data s = socket.socket() s.connect((ip, port)) s.sendall(str(h)) # receive data back and pretty print recv = s.recv(100) print 'Handshake received: %s' % (recv.__repr__(), ) s.sendall(send_interested()) recv = s.recv(10000) prefix, message = message_decode(recv) return recv
def testComplete(self): try: fibDataDB = self.initializeFibDataDB(self.testName) fibData = FibDataRequest(None, { "worker_id": "abcd", "fib_id": 3, "fib_value": 2 }) testFD = fibDataDB.addRequest(fibData) fibDataDB.updateRequest(testFD) fibData = FibDataRequest(None, { "worker_id": "efgh", "fib_id": 3, "fib_value": 2 }) testFD = fibDataDB.addRequest(fibData) fibDataDB.updateRequest(testFD) fibData = FibDataRequest(None, { "worker_id": "efgh", "fib_id": 4, "fib_value": 3 }) testFD = fibDataDB.addRequest(fibData) responseHandler = ResponseHandler(uuid.uuid1(), fibDataDB) response = responseHandler.getComplete() self.assertTrue(response != None) parsedResponses = json.loads(response) self.assertTrue(len(parsedResponses) == 2) parsedResponse = parsedResponses[0] self.assertTrue( parsedResponse.has_key('formattedFinishDate') == True) self.assertTrue(parsedResponse['fibData']['fibId'] == 3) self.assertTrue(parsedResponse['fibData']['fibValue'] == 2) self.assertTrue(parsedResponse['fibData']['workerId'] == 'abcd') parsedResponse = parsedResponses[1] self.assertTrue( parsedResponse.has_key('formattedFinishDate') == True) self.assertTrue(parsedResponse['fibData']['fibId'] == 3) self.assertTrue(parsedResponse['fibData']['fibValue'] == 2) self.assertTrue(parsedResponse['fibData']['workerId'] == 'efgh') except MySQLdb.Error, e: self.log.error("error creating table fibdata") self.log.error(e) self.handleMySQLException(e, True) return None
def test_responder_hands_what_it_got_from_receive_to_handler(self): self.transmitter.receive = mock.MagicMock( return_value="for the handler") handler = ResponseHandler(MoveGenerator()) handler.response = mock.Mock() responder = Responder(self.transmitter, handler) responder.respond() handler.response.assert_called_with("for the handler")
def test_empty_keys(self): handler = ResponseHandler() handler.country_info = CountryInfoPlaceHolder({ "name": "Egypt", "capital": "Cairo" }) response = handler.get('egypt', '') self.assertEqual(response, handler.invalid_info)
def test_get_true_info(self): handler = ResponseHandler() handler.country_info = CountryInfoPlaceHolder({ "name": "Egypt", "capital": "Cairo" }) response = handler.get('egypt', 'name') self.assertEqual(response['name'], 'Egypt')
def test_get_any_info(self): handler = ResponseHandler() handler.country_info = CountryInfoPlaceHolder({ "name": "Egypt", "capital": "Cairo" }) response = handler.get_all_info('egypt') self.assertTrue(len(response) > 0)
def test_get_valid_data(self): handler = ResponseHandler() handler.country_info = CountryInfoPlaceHolder({ "capital": "Cairo", "demonym": "Egyptian" }) response = handler.get('egypt', 'capital,demonym') expected = {"capital": "Cairo", "demonym": "Egyptian"} self.assertEqual(expected, response)
def processResponse(self, resp_obj): resp_code = resp_obj["response_code"] # Setting up PDUData object to be used in response handling obj = pdu_data.PDUData() obj.payload = resp_obj["payload"] resh_obj = ResponseHandler(obj) # Calls the associated function for the received response code return resh_obj.runResponseCodeAction(resp_code)
def test_filter_with_invalid_keys(self): handler = ResponseHandler() handler.country_info = CountryInfoPlaceHolder({ "capital": "Cairo", "demonym": "Egyptian" }) with open('offline_country_info.json') as file: info = json.load(file) response = handler.filter('capital,invalid_key', info) self.assertEqual(handler.invalid_info, response)
def test_public_api_error(self): self.handler = ResponseHandler() url = '/country/name/invalid_country/keys/name' testClient = app.test_client() testClient.testing = True response = testClient.get(url) self.assertEqual(response.json, self.handler.public_api_error)
def test_invalid_request_wrong_info(self): self.handler = ResponseHandler() url = '/country/name/egypt/keys/invalid_key' testClient = app.test_client() testClient.testing = True response = testClient.get(url) self.assertEqual(response.json, self.handler.invalid_info)
def test_handler_returns_winner_on_board_key(self): data = {"board":"stuff"} generator = mock.Mock() generator.winner_of = mock.MagicMock(return_value="x") response = ResponseHandler(generator).response(data) generator.winner_of.assert_any_call("stuff") self.assertEqual("x",response["winner_on_board"])
def test_response_contains_updated_game_information(self): data = {"board": {1:"o", 2:"o",5:"x"}, "depth": 20} response = ResponseHandler(MoveGenerator()).response(data) self.assertEqual(3,response["ai_move"]) self.assertEqual("o",response["winner_after_ai_move"]) self.assertEqual(None,response["winner_on_board"])
def testComplete(self): try: fibDataDB = self.initializeFibDataDB(self.testName) fibData = FibDataRequest(None,{"worker_id":"abcd","fib_id":3, "fib_value":2}) testFD = fibDataDB.addRequest(fibData) fibDataDB.updateRequest(testFD) fibData = FibDataRequest(None,{"worker_id":"efgh","fib_id":3, "fib_value":2}) testFD = fibDataDB.addRequest(fibData) fibDataDB.updateRequest(testFD) fibData = FibDataRequest(None,{"worker_id":"efgh","fib_id":4, "fib_value":3}) testFD = fibDataDB.addRequest(fibData) responseHandler = ResponseHandler(uuid.uuid1(),fibDataDB) response = responseHandler.getComplete() self.assertTrue(response != None) parsedResponses = json.loads(response) self.assertTrue(len(parsedResponses) == 2) parsedResponse = parsedResponses[0] self.assertTrue(parsedResponse.has_key('formattedFinishDate') == True) self.assertTrue(parsedResponse['fibData']['fibId'] == 3) self.assertTrue(parsedResponse['fibData']['fibValue'] == 2) self.assertTrue(parsedResponse['fibData']['workerId'] == 'abcd') parsedResponse = parsedResponses[1] self.assertTrue(parsedResponse.has_key('formattedFinishDate') == True) self.assertTrue(parsedResponse['fibData']['fibId'] == 3) self.assertTrue(parsedResponse['fibData']['fibValue'] == 2) self.assertTrue(parsedResponse['fibData']['workerId'] == 'efgh') except MySQLdb.Error, e: self.log.error("error creating table fibdata") self.log.error(e) self.handleMySQLException(e,True) return None
def test_returns_board_with_obvious_move(self): transmitter = mock.Mock() transmitter.receive = mock.MagicMock( return_value=self.easy_win_possible) generator = MoveGenerator() handler = ResponseHandler(generator) responder = Responder(transmitter, handler) responder.respond() transmitter.send.called_with({ "winner_after_ai_move": "o", "ai_move": 3 })
def __init__(self, user_profile): self.prepared_data = dict() self.url = None self.method = 'GET' self.headers = {} self.profile = UserProfile(**user_profile) self.logger = logging.getLogger(__name__) self.response = ResponseHandler({ "success": False, "ok": False, "content": '' })
def test_it_hooks_into_socket_sends_and_receives(self): transmitter = JsonTransmitter(self.connection_socket) handler = ResponseHandler(MoveGenerator()) responder = Responder(transmitter, handler) game_info = json.dumps({"board": {1: "o", 3: "o"}, "depth": 20}) self.sock.send(game_info) responder.respond() data_received = self.sock.recv(1024) updated_game = json.loads(data_received) WIN_MOVE = 2 self.assertEqual(WIN_MOVE, updated_game["ai_move"]) self.assertEqual("o", updated_game["winner_after_ai_move"]) self.assertEqual(None, updated_game["winner_on_board"])
def send_request(self): """ Used to send the final SOAP request and to be called by subclass. It internally override the _send_request of subclass. :return: None """ try: response = self._send_request() self.response = ResponseHandler(response) except Fault as fault: raise ParamValidationError(message=fault.message, code=fault.code) except Exception as exc: pass return self.response
def main(): handler = ResponseHandler() bot = DodgyBot(handler) print "Hello I am a Dodgy Bot" os.system("say 'Hello I am a Dodgy Bot'") while True: bot.listen() print bot.recogniseAudio() # user_input = bot.recogniseAudio().lower().strip() # if (user_input in ["goodbye", "bye", "exit"]): # os.system("say 'Bye'") # exit() intent = bot.getIntent() print bot.loadResponse(intent)
def check_config_and_launch(self): self.load_json() response = requests.get( "https://api.github.com/notifications", auth=(self.current_config['github_username'], self.current_config['github_bearer_token'])).json() if isinstance(response, dict) and 'Bad credentials' in response.values(): print("Wrong credentials, starting config.") sleep(1) ConfigGenerator() else: show_security_updates = self.current_config[ 'max_nb_notifications'] == "Y" max_nb = int(self.current_config['max_nb_notifications']) ResponseHandler(api_response=response, max_nb=max_nb, show_security_updates=show_security_updates)
def __init__(self, user_profile): """Initialization method for Delhivery base class, which sets credentials for using Delhivery API Args: user_profile - This will be the dictionary containing client name and api token. """ self.prepared_data = None self.url = None self.method = 'GET' self.headers = {} self.profile = UserProfile(**user_profile) self.logger = logging.getLogger(__name__) self.response = ResponseHandler({ "success": False, "ok": False, "content": '' })
def test_integration_of_parts(self): DUMB_AI_DEPTH = 1 data_from_transmitter_receive = { "board": { 1: "x", 2: "x" }, "depth": DUMB_AI_DEPTH } SMART_MOVE = 3 transmitter = mock.Mock() transmitter.receive = mock.MagicMock( return_value=data_from_transmitter_receive) handler = ResponseHandler(MoveGenerator()) responder = Responder(transmitter, handler) responder.respond() self.assertNotEqual(SMART_MOVE, transmitter.send.call_args[0][0]["ai_move"]) self.assertEqual( None, transmitter.send.call_args[0][0]["winner_after_ai_move"])
resultsMessageQueue.createQueue(resultsQueueName) # worker ID is unique to this instance of worker log.debug("generating worker ID") workerId = uuid.uuid1() # need to receive work requests async in order to also handle web requests workerT = Thread(name='daemon', target=doWork, args=(jobMessageQueue, resultsMessageQueue, workerDataDB, workerId)) workerT.setDaemon(True) workerT.start() responseHandler = ResponseHandler(workerId, workerDataDB) log.debug("starting web server") application = bottle.app() application.catchall = False # NOTE that these will default to rational values if not set for local run. assignedHost = os.getenv('VCAP_APP_HOST', '127.0.0.1') assignedPort = os.getenv('VCAP_APP_PORT', 8081) log.debug('launching application at %s:%s' % (assignedHost, assignedPort)) bottle.run(application, host=assignedHost, port=assignedPort) # this is the last line
def test_responder_sends_what_it_got_from_handler(self): handler = ResponseHandler(mock.Mock()) handler.response = mock.MagicMock(return_value="some stuff") responder = Responder(self.transmitter, handler) responder.respond() self.transmitter.send.assert_called_with("some stuff")
def test_handler_returns_winner_after_ai_move_key(self): data = {"board":""} generator = mock.Mock() generator.winner = mock.MagicMock(return_value="winner!") response = ResponseHandler(generator).response(data) self.assertEqual("winner!",response["winner_after_ai_move"])
from move_generator import MoveGenerator from response_handler import ResponseHandler from response_thread import ResponseThread command_line_parser = OptionParser() command_line_parser.add_option("-p", "--port", type="int", dest="port", help="Port for the server to run on") command_line_parser.set_defaults(port=5000) (options, args) = command_line_parser.parse_args() server = ServerSocket("localhost", options.port) print "Server starting on port %d..." % options.port server.initialize_and_listen_for_connections() while True: try: connection_socket = server.accept_connection_and_return_socket() transmitter = JsonTransmitter(connection_socket) move_generator = MoveGenerator() handler = ResponseHandler(move_generator) responder = Responder(transmitter, handler) ResponseThread(responder).start() except KeyboardInterrupt: print "\nShutting down server..." break
def test_public_api_error_get(self): handler = ResponseHandler() handler.country_info = CountryInfoPlaceHolder(None) response = handler.get('egypt', 'capital') self.assertEqual(response, handler.public_api_error)
def test_handler_defaults_difficulty_if_depth_not_set(self): data = {"board": {1:"x",2:"x",5:"o"}} handler = ResponseHandler(MoveGenerator()) response = handler.response(data) self.assertEqual(3,response["ai_move"])
def test_handler_returns_with_move_key(self): data = {"board":""} generator = mock.Mock() generator.next_move = mock.MagicMock(return_value="ai_move") response = ResponseHandler(generator).response(data) self.assertEqual("ai_move",response["ai_move"])
def route_scenario_1(name): handler = ResponseHandler() response = handler.get_all_info(name) return response
def route_scenario_2(name, keys): handler = ResponseHandler() response = handler.get(name, keys) return response
async def main(args): backend_parser = BurpRequestParser rp = RequestParser(args.frequest, backend_parser) request = rp.parse_text() request.url = args.protocol + "://" + request.url key_request, subkey_request = find_world_in_request(request) if args.fproxies: ph = ProxiesHandler(args.fproxies) else: ph = None response_handler = ResponseHandler( stop_status=args.stop_status, output_type=args.output_type, print_request=args.print_request, ) range_step = args.range_step or 1 async with aiohttp.ClientSession() as session: for value in get_values_from_range(args.range_start, args.range_end, range_step, args.min_len): replica_request = Request(request.get_data().copy()) replica_request.url = request.url replace_world_in_request(replica_request, key_request, subkey_request, value) no_answer = True attempt_request_limit = 10 request_count = 0 response = None while no_answer: proxy = None if ph: if not ph.proxies: print("List of working proxies is empty") sys.exit() proxy = ph.get_random_proxy() try: response = await do_request(session, replica_request, proxy=proxy) except (aiohttp.client_exceptions.ClientProxyConnectionError, asyncio.TimeoutError): print( f"There was failed request attempt with the proxy {proxy}" ) if ph: ph.exclude_not_working_proxy(proxy) else: no_answer = False finally: request_count += 1 if no_answer and request_count > attempt_request_limit: print("you have exceeded maximum request limit") break await response_handler.handle(replica_request, response)