From 26f6087f347a413cbee050c1dc909122998475dd Mon Sep 17 00:00:00 2001 From: ben Date: Tue, 2 Aug 2016 15:31:19 +0200 Subject: [PATCH] add tests, and modify calls to api accordingly --- pokemongo_bot/__init__.py | 29 ++++----- .../cell_workers/collect_level_up_reward.py | 3 +- pokemongo_bot/cell_workers/evolve_all.py | 6 +- pokemongo_bot/cell_workers/handle_soft_ban.py | 1 - pokemongo_bot/cell_workers/incubate_eggs.py | 9 +-- .../cell_workers/nickname_pokemon.py | 13 ++-- .../cell_workers/pokemon_catch_worker.py | 62 ++++++++++++------- pokemongo_bot/cell_workers/recycle_items.py | 8 +-- pokemongo_bot/cell_workers/spin_fort.py | 13 ++-- .../cell_workers/transfer_pokemon.py | 9 +-- pokemongo_bot/cell_workers/utils.py | 6 +- pokemongo_bot/metrics.py | 7 ++- tests/__init__.py | 2 +- tests/api_wrapper_test.py | 7 +++ 14 files changed, 94 insertions(+), 81 deletions(-) diff --git a/pokemongo_bot/__init__.py b/pokemongo_bot/__init__.py index 983f30252e..2d9d4a6ad3 100644 --- a/pokemongo_bot/__init__.py +++ b/pokemongo_bot/__init__.py @@ -121,13 +121,12 @@ def update_web_location(self, cells=[], lat=None, lng=None, alt=None): if cells == []: cellid = get_cell_ids(lat, lng) timestamp = [0, ] * len(cellid) - self.api.get_map_objects( + response_dict = self.api.get_map_objects( latitude=f2i(lat), longitude=f2i(lng), since_timestamp_ms=timestamp, cell_id=cellid ) - response_dict = self.api.call() map_objects = response_dict.get( 'responses', {} ).get('GET_MAP_OBJECTS', {}) @@ -139,14 +138,13 @@ def update_web_location(self, cells=[], lat=None, lng=None, alt=None): if 'forts' in cell: for fort in cell['forts']: if fort.get('type') != 1: - self.api.get_gym_details( + response_gym_details = self.api.get_gym_details( gym_id=fort.get('id'), player_latitude=lng, player_longitude=lat, gym_latitude=fort.get('latitude'), gym_longitude=fort.get('longitude') ) - response_gym_details = self.api.call() fort['gym_details'] = response_gym_details.get( 'responses', {} ).get('GET_GYM_DETAILS', None) @@ -183,13 +181,12 @@ def find_close_cells(self, lat, lng): cellid = get_cell_ids(lat, lng) timestamp = [0, ] * len(cellid) - self.api.get_map_objects( + response_dict = self.api.get_map_objects( latitude=f2i(lat), longitude=f2i(lng), since_timestamp_ms=timestamp, cell_id=cellid ) - response_dict = self.api.call() map_objects = response_dict.get( 'responses', {} ).get('GET_MAP_OBJECTS', {}) @@ -275,7 +272,7 @@ def login(self): def _setup_api(self): # instantiate pgoapi - self.api = ApiWrapper(PGoApi()) + self.api = ApiWrapper() # provide player position on the earth self._set_starting_position() @@ -294,8 +291,7 @@ def _setup_api(self): def _print_character_info(self): # get player profile call # ---------------------- - self.api.get_player() - response_dict = self.api.call() + response_dict = self.api.get_player() # print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2))) currency_1 = "0" currency_2 = "0" @@ -376,15 +372,11 @@ def _print_character_info(self): logger.log('') def use_lucky_egg(self): - self.api.use_item_xp_boost(item_id=301) - inventory_req = self.api.call() - return inventory_req + return self.api.use_item_xp_boost(item_id=301) def get_inventory(self): if self.latest_inventory is None: - self.api.get_inventory() - response = self.api.call() - self.latest_inventory = response + self.latest_inventory = self.api.get_inventory() return self.latest_inventory def update_inventory(self): @@ -548,9 +540,10 @@ def heartbeat(self): self.fort_timeouts = {id: timeout for id, timeout in self.fort_timeouts.iteritems() if timeout >= time.time() * 1000} - self.api.get_player() - self.api.check_awarded_badges() - self.api.call() + request = self.api.create_request() + request.get_player() + request.check_awarded_badges() + request.call() self.update_web_location() # updates every tick def get_inventory_count(self, what): diff --git a/pokemongo_bot/cell_workers/collect_level_up_reward.py b/pokemongo_bot/cell_workers/collect_level_up_reward.py index 8398153386..912a97d197 100644 --- a/pokemongo_bot/cell_workers/collect_level_up_reward.py +++ b/pokemongo_bot/cell_workers/collect_level_up_reward.py @@ -25,8 +25,7 @@ def work(self): self.previous_level = self.current_level def _collect_level_reward(self): - self.bot.api.level_up_rewards(level=self.current_level) - response_dict = self.bot.api.call() + response_dict = self.bot.api.level_up_rewards(level=self.current_level) if 'status_code' in response_dict and response_dict['status_code'] == 1: data = (response_dict .get('responses', {}) diff --git a/pokemongo_bot/cell_workers/evolve_all.py b/pokemongo_bot/cell_workers/evolve_all.py index 7a7a19e020..be17c5e88a 100644 --- a/pokemongo_bot/cell_workers/evolve_all.py +++ b/pokemongo_bot/cell_workers/evolve_all.py @@ -156,8 +156,7 @@ def _execute_pokemon_evolve(self, pokemon, cache): if pokemon_name in cache: return - self.bot.api.evolve_pokemon(pokemon_id=pokemon_id) - response_dict = self.bot.api.call() + response_dict = self.bot.api.evolve_pokemon(pokemon_id=pokemon_id) status = response_dict['responses']['EVOLVE_POKEMON']['result'] if status == 1: logger.log('[#] Successfully evolved {} with {} CP and {} IV!'.format( @@ -173,8 +172,7 @@ def _execute_pokemon_evolve(self, pokemon, cache): # TODO: move to utils. These methods are shared with other workers. def transfer_pokemon(self, pid): - self.bot.api.release_pokemon(pokemon_id=pid) - response_dict = self.bot.api.call() + response_dict = self.bot.api.release_pokemon(pokemon_id=pid) def count_pokemon_inventory(self): response_dict = self.bot.get_inventory() diff --git a/pokemongo_bot/cell_workers/handle_soft_ban.py b/pokemongo_bot/cell_workers/handle_soft_ban.py index d13bd63eea..04e5178b50 100644 --- a/pokemongo_bot/cell_workers/handle_soft_ban.py +++ b/pokemongo_bot/cell_workers/handle_soft_ban.py @@ -50,7 +50,6 @@ def spin_fort(self, fort): player_latitude=f2i(self.bot.position[0]), player_longitude=f2i(self.bot.position[1]) ) - self.bot.api.call() def should_run(self): return self.bot.softban diff --git a/pokemongo_bot/cell_workers/incubate_eggs.py b/pokemongo_bot/cell_workers/incubate_eggs.py index 9ec65c41de..47f5f20c19 100644 --- a/pokemongo_bot/cell_workers/incubate_eggs.py +++ b/pokemongo_bot/cell_workers/incubate_eggs.py @@ -47,8 +47,10 @@ def _apply_incubators(self): continue if self.bot.config.debug: logger.log('[x] Attempting to apply incubator {} to egg {}'.format(incubator['id'], egg['id'])) - self.bot.api.use_item_egg_incubator(item_id=incubator["id"], pokemon_id=egg["id"]) - ret = self.bot.api.call() + ret = self.bot.api.use_item_egg_incubator( + item_id=incubator["id"], + pokemon_id=egg["id"] + ) if ret: code = ret.get("responses", {}).get("USE_ITEM_EGG_INCUBATOR", {}).get("result", 0) if code == 1: @@ -125,8 +127,7 @@ def _check_inventory(self, lookup_ids=[]): return matched_pokemon def _hatch_eggs(self): - self.bot.api.get_hatched_eggs() - response_dict = self.bot.api.call() + response_dict = self.bot.api.get_hatched_eggs() log_color = 'green' try: result = reduce(dict.__getitem__, ["responses", "GET_HATCHED_EGGS"], response_dict) diff --git a/pokemongo_bot/cell_workers/nickname_pokemon.py b/pokemongo_bot/cell_workers/nickname_pokemon.py index d626595d11..2c61d87a9f 100644 --- a/pokemongo_bot/cell_workers/nickname_pokemon.py +++ b/pokemongo_bot/cell_workers/nickname_pokemon.py @@ -7,7 +7,7 @@ def initialize(self): self.template = self.config.get('nickname_template','').lower().strip() if self.template == "{name}": self.template = "" - + def work(self): try: inventory = reduce(dict.__getitem__, ["responses", "GET_INVENTORY", "inventory_delta", "inventory_items"], self.bot.get_inventory()) @@ -16,8 +16,8 @@ def work(self): else: pokemon_data = self._get_inventory_pokemon(inventory) for pokemon in pokemon_data: - self._nickname_pokemon(pokemon) - + self._nickname_pokemon(pokemon) + def _get_inventory_pokemon(self,inventory_dict): pokemon_data = [] for inv_data in inventory_dict: @@ -29,7 +29,7 @@ def _get_inventory_pokemon(self,inventory_dict): if not pokemon.get('is_egg',False): pokemon_data.append(pokemon) return pokemon_data - + def _nickname_pokemon(self,pokemon): """This requies a pokemon object containing all the standard fields: id, ivs, cp, etc""" new_name = "" @@ -62,10 +62,9 @@ def _nickname_pokemon(self,pokemon): logger.log("Unable to nickname {} due to bad template ({})".format(name,bad_key),log_color) if pokemon.get('nickname', "") == new_name: return - self.bot.api.nickname_pokemon(pokemon_id=instance_id,nickname=new_name) - response = self.bot.api.call() + response = self.bot.api.nickname_pokemon(pokemon_id=instance_id,nickname=new_name) sleep(1.2) - try: + try: result = reduce(dict.__getitem__, ["responses", "NICKNAME_POKEMON"], response) except KeyError: logger.log("Attempt to nickname received bad response from server.",log_color) diff --git a/pokemongo_bot/cell_workers/pokemon_catch_worker.py b/pokemongo_bot/cell_workers/pokemon_catch_worker.py index 6e90472a0c..3bcb8a6268 100644 --- a/pokemongo_bot/cell_workers/pokemon_catch_worker.py +++ b/pokemongo_bot/cell_workers/pokemon_catch_worker.py @@ -93,8 +93,11 @@ def work(self): break # Use the berry to catch - self.api.use_item_capture(item_id = berry_id,encounter_id = encounter_id,spawn_point_id = self.spawn_point_guid) - response_dict = self.api.call() + response_dict = self.api.use_item_capture( + item_id=berry_id, + encounter_id=encounter_id, + spawn_point_id=self.spawn_point_guid + ) if response_dict and response_dict['status_code'] is 1 and 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']: for i in range(len(catch_rate)): if 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']: @@ -126,8 +129,10 @@ def work(self): success_percentage = '{0:.2f}'.format(catch_rate[pokeball-1]*100) logger.log('Catch Rate with normal Pokeball is low ({}%). Thinking to throw a {}... ({} left!)'.format(success_percentage,self.item_list[str(berry_id)],berries_count-1)) - self.api.use_item_capture(item_id = berry_id,encounter_id = encounter_id,spawn_point_id = self.spawn_point_guid) - response_dict = self.api.call() + response_dict = self.api.use_item_capture(item_id=berry_id, + encounter_id=encounter_id, + spawn_point_id=self.spawn_point_guid + ) if response_dict and response_dict['status_code'] is 1 and 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']: for i in range(len(catch_rate)): if 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']: @@ -159,8 +164,10 @@ def work(self): success_percentage = '{0:.2f}'.format(catch_rate[pokeball-1]*100) logger.log('Catch Rate with normal Pokeball is low ({}%). Thinking to throw a {}... ({} left!)'.format(success_percentage,self.item_list[str(berry_id)],berries_count-1)) - self.api.use_item_capture(item_id = berry_id,encounter_id = encounter_id,spawn_point_id = self.spawn_point_guid) - response_dict = self.api.call() + response_dict = self.api.use_item_capture(item_id=berry_id, + encounter_id=encounter_id, + spawn_point_id=self.spawn_point_guid + ) if response_dict and response_dict['status_code'] is 1 and 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']: for i in range(len(catch_rate)): if 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']: @@ -205,14 +212,15 @@ def work(self): reticle_size_parameter = normalized_reticle_size(self.config.catch_randomize_reticle_factor) spin_modifier_parameter = spin_modifier(self.config.catch_randomize_spin_factor) - self.api.catch_pokemon(encounter_id=encounter_id, - pokeball=pokeball, - normalized_reticle_size=reticle_size_parameter, - spawn_point_id=self.spawn_point_guid, - hit_pokemon=1, - spin_modifier=spin_modifier_parameter, - normalized_hit_position=1) - response_dict = self.api.call() + response_dict = self.api.catch_pokemon( + encounter_id=encounter_id, + pokeball=pokeball, + normalized_reticle_size=reticle_size_parameter, + spawn_point_id=self.spawn_point_guid, + hit_pokemon=1, + spin_modifier=spin_modifier_parameter, + normalized_hit_position=1 + ) if response_dict and \ 'responses' in response_dict and \ @@ -254,8 +262,7 @@ def work(self): if len(pokemon_to_transfer) == 0: raise RuntimeError( 'Trying to evolve 0 pokemons!') - self.api.evolve_pokemon(pokemon_id=pokemon_to_transfer[0]) - response_dict = self.api.call() + response_dict = self.api.evolve_pokemon(pokemon_id=pokemon_to_transfer[0]) status = response_dict['responses']['EVOLVE_POKEMON']['result'] if status == 1: logger.log( @@ -269,8 +276,7 @@ def work(self): def count_pokemon_inventory(self): # don't use cached bot.get_inventory() here # because we need to have actual information in capture logic - self.api.get_inventory() - response_dict = self.api.call() + response_dict = self.api.get_inventory() id_list = [] callback = lambda pokemon: id_list.append(pokemon['id']) @@ -360,22 +366,30 @@ def create_encounter_api_call(self): player_latitude = self.pokemon['latitude'] player_longitude = self.pokemon['longitude'] + request = self.api.create_request() if 'spawn_point_id' in self.pokemon: spawn_point_id = self.pokemon['spawn_point_id'] self.spawn_point_guid = spawn_point_id self.response_key = 'ENCOUNTER' self.response_status_key = 'status' - self.api.encounter(encounter_id=encounter_id, spawn_point_id=spawn_point_id, - player_latitude=player_latitude, player_longitude=player_longitude) + request.encounter( + encounter_id=encounter_id, + spawn_point_id=spawn_point_id, + player_latitude=player_latitude, + player_longitude=player_longitude + ) else: fort_id = self.pokemon['fort_id'] self.spawn_point_guid = fort_id self.response_key = 'DISK_ENCOUNTER' self.response_status_key = 'result' - self.api.disk_encounter(encounter_id=encounter_id, fort_id=fort_id, - player_latitude=player_latitude, player_longitude=player_longitude) - - return self.api.call() + request.disk_encounter( + encounter_id=encounter_id, + fort_id=fort_id, + player_latitude=player_latitude, + player_longitude=player_longitude + ) + return request.call() def check_vip_pokemon(self,pokemon, cp, iv): diff --git a/pokemongo_bot/cell_workers/recycle_items.py b/pokemongo_bot/cell_workers/recycle_items.py index 2ece62f95b..022a711f1a 100644 --- a/pokemongo_bot/cell_workers/recycle_items.py +++ b/pokemongo_bot/cell_workers/recycle_items.py @@ -44,9 +44,9 @@ def work(self): logger.log("-- Failed to discard " + item_name, 'red') def send_recycle_item_request(self, item_id, count): - self.bot.api.recycle_inventory_item(item_id=item_id, count=count) - inventory_req = self.bot.api.call() - # Example of good request response #{'responses': {'RECYCLE_INVENTORY_ITEM': {'result': 1, 'new_count': 46}}, 'status_code': 1, 'auth_ticket': {'expire_timestamp_ms': 1469306228058L, 'start': '/HycFyfrT4t2yB2Ij+yoi+on778aymMgxY6RQgvrGAfQlNzRuIjpcnDd5dAxmfoTqDQrbz1m2dGqAIhJ+eFapg==', 'end': 'f5NOZ95a843tgzprJo4W7Q=='}, 'request_id': 8145806132888207460L} - return inventory_req + return self.bot.api.recycle_inventory_item( + item_id=item_id, + count=count + ) diff --git a/pokemongo_bot/cell_workers/spin_fort.py b/pokemongo_bot/cell_workers/spin_fort.py index 6534731a86..f34fc2b8ef 100644 --- a/pokemongo_bot/cell_workers/spin_fort.py +++ b/pokemongo_bot/cell_workers/spin_fort.py @@ -33,12 +33,13 @@ def work(self): logger.log('Now at Pokestop: {0}'.format(fort_name), 'cyan') logger.log('Spinning ...', 'cyan') - self.bot.api.fort_search(fort_id=fort['id'], - fort_latitude=lat, - fort_longitude=lng, - player_latitude=f2i(self.bot.position[0]), - player_longitude=f2i(self.bot.position[1])) - response_dict = self.bot.api.call() + response_dict = self.bot.api.fort_search( + fort_id=fort['id'], + fort_latitude=lat, + fort_longitude=lng, + player_latitude=f2i(self.bot.position[0]), + player_longitude=f2i(self.bot.position[1]) + ) if 'responses' in response_dict and \ 'FORT_SEARCH' in response_dict['responses']: diff --git a/pokemongo_bot/cell_workers/transfer_pokemon.py b/pokemongo_bot/cell_workers/transfer_pokemon.py index 101e0b92f4..9f7698920a 100644 --- a/pokemongo_bot/cell_workers/transfer_pokemon.py +++ b/pokemongo_bot/cell_workers/transfer_pokemon.py @@ -70,8 +70,10 @@ def work(self): def _release_pokemon_get_groups(self): pokemon_groups = {} - self.bot.api.get_player().get_inventory() - inventory_req = self.bot.api.call() + request = self.bot.api.create_request() + request.get_player() + request.get_inventory() + inventory_req = request.call() if inventory_req.get('responses', False) is False: return pokemon_groups @@ -173,8 +175,7 @@ def release_pokemon(self, pokemon_name, cp, iv, pokemon_id): logger.log('Exchanging {} [CP {}] [Potential {}] for candy!'.format(pokemon_name, cp, iv), 'green') - self.bot.api.release_pokemon(pokemon_id=pokemon_id) - response_dict = self.bot.api.call() + response_dict = self.bot.api.release_pokemon(pokemon_id=pokemon_id) action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max) def _get_release_config_for(self, pokemon): diff --git a/pokemongo_bot/cell_workers/utils.py b/pokemongo_bot/cell_workers/utils.py index 253083bc0b..946c757b16 100644 --- a/pokemongo_bot/cell_workers/utils.py +++ b/pokemongo_bot/cell_workers/utils.py @@ -28,10 +28,10 @@ def fort_details(bot, fort_id, latitude, longitude): """ Lookup the fort details and cache the response for future use. """ - bot.api.fort_details(fort_id=fort_id, latitude=latitude, longitude=longitude) - + request = bot.api.create_request() + request.fort_details(fort_id=fort_id, latitude=latitude, longitude=longitude) try: - response_dict = bot.api.call() + response_dict = request.call() FORT_CACHE[fort_id] = response_dict['responses']['FORT_DETAILS'] except Exception: pass diff --git a/pokemongo_bot/metrics.py b/pokemongo_bot/metrics.py index 0ab7cb14dd..0ffeb39a6c 100644 --- a/pokemongo_bot/metrics.py +++ b/pokemongo_bot/metrics.py @@ -70,9 +70,10 @@ def released_pokemon(self, count=1): self.releases += count def capture_stats(self): - self.bot.api.get_inventory() - self.bot.api.get_player() - response_dict = self.bot.api.call() + request = self.bot.api.create_request() + request.get_inventory() + request.get_player() + response_dict = request.call() try: self.dust['latest'] = response_dict['responses']['GET_PLAYER']['player_data']['currencies'][1]['amount'] if self.dust['start'] is None: self.dust['start'] = self.dust['latest'] diff --git a/tests/__init__.py b/tests/__init__.py index 24f6e5957f..5318e2d482 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -5,7 +5,7 @@ from pokemongo_bot import PokemonGoBot class FakeApi(ApiWrapper): - def create_request(self, return_value=None): + def create_request(self, return_value='mock return'): request = ApiWrapper.create_request(self) request.can_call = MagicMock(return_value=True) request._call = MagicMock(return_value=return_value) diff --git a/tests/api_wrapper_test.py b/tests/api_wrapper_test.py index 166a26d9f7..335f04cbf2 100644 --- a/tests/api_wrapper_test.py +++ b/tests/api_wrapper_test.py @@ -114,3 +114,10 @@ def test_api_call_throttle_should_fail(self): with self.assertRaises(TimeoutError): for i in range(request.requests_per_seconds * 2): request.call() + + @patch('pokemongo_bot.api_wrapper.ApiRequest.is_response_valid') + def test_api_direct_call(self, mock_method): + mock_method.return_value = True + + result = FakeApi().get_inventory() + self.assertEqual(result, 'mock return')