def test_unavailable(monkeypatch): monkeypatch.setattr( requests, 'get', lambda *args, **kwargs: raise_(requests.ConnectTimeout)) with pytest.raises(errors.APIUnavailable): hero = Hero('someone') hero.sync()
def test_invalidtoken(mocked_get_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) hero = Hero('Mars', token='awuidhawudihaiwudh') health = hero.data.pop('health') with pytest.raises(errors.InvalidToken): hero.is_alive hero.data['health'] = health
def test_min_threshold(mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) with pytest.raises(errors.MinThresholdException): hero = Hero('Mars', threshold=1) hero = Hero('Mars') with pytest.raises(errors.MinThresholdException): hero.threshold = 1
def test_goldf(mocked_get_t, mocked_get_top_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) hero = Hero('Mars', token='adwadwad') assert hero.goldf == 0.3 with freezegun.freeze_time(datetime.now() + timedelta(hours=1)): monkeypatch.setattr(requests, 'get', mocked_get_top_t) hero.sync() assert hero.goldf == 1.0
def test_feezed(mocked_get, mocked_get_top, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) hero = Hero('Mars') assert hero.last_upd == FREEZED_NOW with freezegun.freeze_time(FREEZED_NOW_PLUS): monkeypatch.setattr(requests, 'get', mocked_get_top) hero.sync() assert hero.last_upd == FREEZED_NOW_PLUS
def cli(god, token, drop_cache, property_name): """CLI-интерфейс для доступа к API игры Годвилль. Аргументы: PROPERTY_NAME Имя свойства героя Полный список свойств и примеры использования данного CLI-интерфейса можно получить в документации.""" if not god: raise errors.GVAPIException('Не получено имя божества.') cache_dir = Path(Path.joinpath(Path.home(), '.cache', 'gvapi')) cache_dir.mkdir(parents=True, exist_ok=True) if token: cache_filename = md5('{}:{}'.format(god, token).encode()).hexdigest() else: cache_filename = md5(god.encode()).hexdigest() cache = Path(Path.joinpath(cache_dir, cache_filename)) if cache.is_file() and not drop_cache: with open(cache, 'rb') as dump: hero = pickle.loads(dump.read()) else: if token: hero = Hero(god, token) else: hero = Hero(god) try: value = getattr(hero, property_name) except AttributeError: click.echo("Получено некорректное свойство {}".format(property_name)) sys.exit(1) except errors.NeedToken: click.echo('Для доступа к данному свойству необходим токен') sys.exit(1) except errors.InvalidToken: click.echo("Токен невалиден или был сброшен") sys.exit(1) click.echo(value) with open(cache, 'wb') as dump: dump.write(pickle.dumps(hero))
def test_savings(mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) hero = Hero('Mars') with pytest.raises(errors.TheSavingsInUndone): hero.savings_completed_at with pytest.raises(errors.TheSavingsInUndone): hero.t_level with pytest.raises(errors.TheSavingsInUndone): hero.shop_name
def test_temple(mocked_get_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) hero = Hero('Mars', token='adwad') with pytest.raises(errors.TheTempleIsUndone): hero.temple_completed_at with pytest.raises(errors.TheTempleIsUndone): hero.savings with pytest.raises(errors.TheTempleIsUndone): hero.ark with pytest.raises(errors.TheTempleIsUndone): hero.wood_count
def test_pet_attributes(mocked_get_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) hero = Hero('Mars', token='awdpiawjdpajdwpoajdap') assert isinstance(hero.pet, Pet) assert hero.pet.name == 'Бублик «Обжора»' assert hero.pet.class_name == 'хохмяк' assert hero.pet.level == 5 assert not hero.pet.wounded assert hero.pet.__repr__() == '<Pet {}, class: {}>'.format( hero.pet.name, hero.pet.class_name) assert hero.pet.__str__() == 'Питомец {} "{}"'.format( hero.pet.class_name, hero.pet.name)
def test_basic(mocked_get_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) hero = Hero('Mars', token='aoiwdjawodijadw1234') assert hero.data == mocked_get_t().json() assert hero.__repr__() == '<Hero {}>'.format(hero.name) assert hero.__str__() == 'Герой {}'.format(hero.name) assert hero.__getattribute__('_Hero__get_data')() == mocked_get_t().json() assert hero.token.startswith('****') and hero.token.endswith('1234') assert hero.threshold == 300 hero.threshold = 200 assert hero.threshold == 200 hero.data['gender'] = 'female' assert hero.__str__() == 'Героиня {}'.format(hero.name)
def test_top_attributes(mocked_get_top, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_top) hero = Hero('Mars') data = mocked_get_top().json() def dparse(date_string: str) -> datetime: '''parse date string to datetime object''' time_zone = date_string[-6::] return datetime.strptime( date_string.replace(time_zone, time_zone.replace(':', '')), '%Y-%m-%dT%H:%M:%S%z') assert hero.savings == '30000 тысяч' assert hero.t_level == 18 assert hero.shop_name == 'Эволюция лайф' assert hero.boss_name == 'Обомлев' assert hero.boss_power == 211 assert hero.wood_count == 3456 assert hero.temple_completed_at == dparse(data['temple_completed_at']) assert hero.ark_completed_at == dparse(data['ark_completed_at']) assert hero.savings_completed_at == dparse(data['savings_completed_at'])
def test_nontokenized_attributes(mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) data = mocked_get().json() hero = Hero('Mars') assert hero.name == data['name'] assert hero.god == data['godname'] assert hero.gender == 'муж' assert hero.level == data['level'] assert hero.max_health == data['max_health'] assert hero.motto == data['motto'] assert hero.clan == data['clan'] assert hero.clan_pos == data['clan_position'] assert hero.max_godpower == 100 assert hero.inventory_max_num == data['inventory_max_num'] assert hero.words == 0 assert hero.ark == (100, 100) assert hero.arena == (data['arena_won'], data['arena_lost']) assert hero.alignment == data['alignment'] assert hero.bricks == data['bricks_cnt'] assert hero.bricks_percent == data['bricks_cnt'] / 1000 * 100
def test_tokenized_attributes(mocked_get_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) data = mocked_get_t().json() hero = Hero('Mars', token='aoiwdjaoiwjd') assert hero.is_alive assert hero.health == data['health'] assert hero.health_percent == data['health'] / data['max_health'] assert hero.gold == data['gold_approx'] assert hero.activatables == data['activatables'] assert hero.is_fighting == data['arena_fight'] assert hero.fight_type == '' assert hero.aura == '' assert hero.diary_last == data['diary_last'] assert hero.distance == data['distance'] assert hero.exp == data['exp_progress'] assert not hero.expired assert hero.godpower == data['godpower'] assert hero.godpower_percent == data['godpower'] / 100 assert hero.inventory_num == data['inventory_num'] assert hero.inventory == (data['inventory_num'], data['inventory_max_num'], data['activatables']) assert hero.quest_progress == data['quest_progress'] assert hero.quest == data['quest'] assert hero.town_name == data['town_name']
from gvapi import Hero hero = Hero('Mars', token='awudhawiudh') print('ЗЛ: ~{}k, КП: {:.1f}%'.format(hero.goldf, hero.bricks_percent))
def test_tokenized_exceptions(name, mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) hero = Hero('Mars') with pytest.raises(errors.NeedToken): hero.__getattribute__(name)
def test_unknown_god(monkeypatch): monkeypatch.setattr(requests, 'get', lambda *args, **kwargs: Response404()) with pytest.raises(errors.UnknownGod): hero = Hero('someone')
def test_create_with_token(mocked_get_t, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get_t) hero = Hero('Mars', token='aoidhaodwjaodwhaoidw') assert isinstance(hero, Hero) assert hero.is_alive
def test_unexpected_json(monkeypatch): monkeypatch.setattr(requests, 'get', lambda *args, **kwargs: UnexpectedResponseJson()) with pytest.raises(errors.UnexpectedAPIResponse): hero = Hero('someone') hero.sync()
def test_create_without_token(mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) hero = Hero('Mars') assert isinstance(hero, Hero) assert hero.god == 'Mars' assert hero.name == 'Gaius Iulius Caesar'
def test_ark(mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) hero = Hero('Mars') with pytest.raises(errors.TheArkIsUndone): hero.ark_completed_at
def test_need_token(mocked_get, monkeypatch): monkeypatch.setattr(requests, 'get', mocked_get) hero = Hero('Mars') with pytest.raises(errors.NeedToken): hero.health