class BuyRandomPremiumChestTask__EpicArtifact_Tests(base_buy_task._BaseBuyHeroMethodPosponedTaskTests):

    def setUp(self):
        super(BuyRandomPremiumChestTask__EpicArtifact_Tests, self).setUp()

        self.task = BuyRandomPremiumChest(account_id=self.account.id,
                                          transaction=self.transaction)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.cmd_update_with_account_data__call_count = 0
        self.accounts_manages_worker = False
        self.supervisor_worker = True

        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.assertEqual(self.hero.bag.occupation, 0)


    def _get_expected_arguments(self):
        return {}

    def _check_not_used(self):
        self.assertEqual(self.hero.bag.occupation, 0)
        self.assertEqual(RandomPremiumRequestPrototype._db_count(), 0)

    def _check_used(self):
        self.assertEqual(self.hero.bag.occupation, 1)
        self.assertTrue(self.hero.bag.values()[0].rarity.is_EPIC)
        self.assertEqual(RandomPremiumRequestPrototype._db_count(), 1)
class ResetPreferenceAllTests(CardsTestMixin, testcase.TestCase):
    CARD = effects.PreferencesCooldownsResetAll

    def setUp(self):
        super(ResetPreferenceAllTests, self).setUp()
        create_test_map()

        result, account_1_id, bundle_id = register_user("test_user", "*****@*****.**", "111111")

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        for preference in PREFERENCE_TYPE.records:
            self.hero.preferences._set(preference, self.hero.preferences._get(preference))

        self.card = self.CARD()

    def test_use(self):
        for preference in PREFERENCE_TYPE.records:
            self.assertFalse(self.hero.preferences.can_update(preference, datetime.datetime.now()))

        result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))

        self.assertEqual(
            (result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ())
        )

        for preference in PREFERENCE_TYPE.records:
            self.assertTrue(self.hero.preferences.can_update(preference, datetime.datetime.now()))
class BuyRandomPremiumChestTask__Energy_Tests(base_buy_task._BaseBuyHeroMethodPosponedTaskTests):

    def setUp(self):
        super(BuyRandomPremiumChestTask__Energy_Tests, self).setUp()

        self.task = BuyRandomPremiumChest(account_id=self.account.id,
                                          transaction=self.transaction)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.cmd_update_with_account_data__call_count = 0
        self.accounts_manages_worker = False
        self.supervisor_worker = True

        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.hero.energy_bonus = 0


    def _get_expected_arguments(self):
        return {}

    def _check_not_used(self):
        self.assertEqual(self.hero.energy_bonus, 0)
        self.assertEqual(RandomPremiumRequestPrototype._db_count(), 0)

    def _check_used(self):
        self.assertEqual(self.hero.energy_bonus, relations.RANDOM_PREMIUM_CHEST_REWARD.ENERGY.arguments['energy'])
        self.assertEqual(RandomPremiumRequestPrototype._db_count(), 1)
Exemple #4
0
class AddGoldTestMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(AddGoldTestMixin, self).setUp()
        create_test_map()

        result, account_1_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()


    def test_use(self):
        with self.check_delta(lambda: self.hero.money, self.CARD.GOLD):
            with self.check_delta(lambda: self.hero.statistics.money_earned_from_help, self.CARD.GOLD):
                with self.check_delta(lambda: self.hero.statistics.money_earned, self.CARD.GOLD):
                    result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))
    def test_load_account_data_with_meta_action(self):
        bundle_id = 666

        meta_action_battle = meta_actions.ArenaPvP1x1.create(self.storage, self.hero_1, self.hero_2)

        proxy_action_1 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_1, _bundle_id=bundle_id, meta_action=meta_action_battle)
        proxy_action_2 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_2, _bundle_id=bundle_id, meta_action=meta_action_battle)

        self.assertEqual(len(self.storage.meta_actions), 1)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 1)
        self.assertEqual(self.storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1),
                                                                                            LogicStorage.get_action_uid(proxy_action_2)]))

        self.storage.save_changed_data()

        self.assertIs(self.hero_1.actions.current_action.meta_action, self.hero_2.actions.current_action.meta_action)
        self.assertIs(self.hero_1.actions.current_action.saved_meta_action, self.hero_2.actions.current_action.saved_meta_action)

        storage = LogicStorage()
        storage.load_account_data(AccountPrototype.get_by_id(self.account_1.id))
        storage.load_account_data(AccountPrototype.get_by_id(self.account_2.id))

        self.assertEqual(len(storage.meta_actions), 1)
        self.assertEqual(len(storage.meta_actions_to_actions), 1)
        self.assertEqual(storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1),
                                                                                       LogicStorage.get_action_uid(proxy_action_2)]))

        self.assertEqual(storage.bundles_to_accounts, {self.hero_1.actions.current_action.bundle_id: set([self.account_1.id, self.account_2.id])})

        hero_1 = storage.accounts_to_heroes[self.account_1.id]
        hero_2 = storage.accounts_to_heroes[self.account_2.id]

        self.assertIs(hero_1.actions.current_action.meta_action, hero_2.actions.current_action.meta_action)
        self.assertIsNot(hero_1.actions.current_action.saved_meta_action, hero_2.actions.current_action.saved_meta_action)
        self.assertEqual(hero_1.actions.current_action.saved_meta_action.serialize(), hero_2.actions.current_action.saved_meta_action.serialize())
Exemple #6
0
class TestsBase(testcase.TestCase):

    def setUp(self):
        super(TestsBase, self).setUp()

        create_test_map()

        account = self.accounts_factory.create_account(is_fast=True)

        self.storage = LogicStorage()
        self.storage.load_account_data(account)
        self.hero = self.storage.accounts_to_heroes[account.id]

    def get_actors(self):
        mob = mobs_storage.get_random_mob(self.hero)
        actor_1 = battle.Actor(self.hero, BattleContext())
        actor_2 = battle.Actor(mob, BattleContext())

        return actor_1, actor_2


    def set_hero_companion(self):
        companion_record = next(companions_storage.companions.enabled_companions())
        companion = companions_logic.create_companion(companion_record)
        self.hero.set_companion(companion)
    def test_initialize_bots__second_create(self):
        result, account_1_id, bundle_id = register_user("test_user_3")
        result, account_2_id, bundle_id = register_user("bot", "*****@*****.**", "111111", is_bot=True)

        account_1 = AccountPrototype.get_by_id(account_1_id)
        account_2 = AccountPrototype.get_by_id(account_2_id)

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        hero_1._model.level = 50
        self.assertEqual(hero_2.level, 1)

        self.pvp_create_battle(account_1, account_2, BATTLE_1X1_STATE.PROCESSING)
        self.pvp_create_battle(account_2, account_1, BATTLE_1X1_STATE.PROCESSING)

        meta_action = MetaActionArenaPvP1x1Prototype.create(storage, hero_1, hero_2, bundle_id=self.bundle_id + 1)
        meta_action.process_battle_ending()

        MetaActionArenaPvP1x1Prototype.create(storage, hero_1, hero_2, bundle_id=self.bundle_id + 2)

        self.assertEqual(hero_2.level, 50)
        self.assertTrue(len(hero_2.abilities.all) > 1)
        self.assertEqual(hero_2.health, hero_2.max_health)
Exemple #8
0
class ChooseRequestsTests(testcase.TestCase, QuestTestsMixin):

    def setUp(self):
        super(ChooseRequestsTests, self).setUp()
        create_test_map()
        register_user('test_user', '*****@*****.**', '111111')

        account = AccountPrototype.get_by_email('*****@*****.**')

        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account.id))
        self.hero =self.storage.accounts_to_heroes[account.id]

        self.choice_uid = '[ns-0]choice_1'
        self.option_uid = '#option<[ns-0]choice_1, [ns-0]choice_2>'

    @mock.patch('questgen.quests.quests_base.QuestsBase._available_quests', lambda *argv, **kwargs: [QuestWith2ChoicePoints])
    def test_choose_no_account(self):
        self.turn_to_quest(self.storage, self.hero.id)
        response = self.client.post(url('game:quests:api-choose', option_uid=self.option_uid, api_version='1.0', api_client=project_settings.API_CLIENT))
        self.check_ajax_error(response, 'common.login_required')


    @mock.patch('questgen.quests.quests_base.QuestsBase._available_quests', lambda *argv, **kwargs: [QuestWith2ChoicePoints])
    def test_choose_processing(self):
        self.turn_to_quest(self.storage, self.hero.id)

        self.request_login('*****@*****.**')
        response = self.client.post(url('game:quests:api-choose', option_uid=self.option_uid, api_version='1.0', api_client=project_settings.API_CLIENT))

        task = PostponedTaskPrototype._db_get_object(0)
        self.check_ajax_processing(response, task.status_url)
        self.assertEqual(PostponedTask.objects.all().count(), 1)
    def test_process_bot__flame_ability_not_used(self):
        result, account_1_id, bundle_id = register_user("bot", "*****@*****.**", "111111", is_bot=True)
        result, account_2_id, bundle_id = register_user("test_user_3")

        account_1 = AccountPrototype.get_by_id(account_1_id)
        account_2 = AccountPrototype.get_by_id(account_2_id)

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        MetaActionArenaPvP1x1Prototype.create(storage, hero_1, hero_2, bundle_id=self.bundle_id + 1)

        self.assertEqual(hero_2.pvp.energy_speed, 1)

        with mock.patch(
            "the_tale.game.actions.meta_actions.MetaActionArenaPvP1x1Prototype.get_bot_pvp_properties",
            lambda a: {"priorities": {Flame.TYPE: 1}, "ability_chance": 1},
        ):
            with mock.patch("the_tale.game.pvp.abilities.Flame.use") as use:
                for i in xrange(100):
                    self.meta_action_battle.process_bot(hero_1, hero_2)

        self.assertEqual(use.call_count, 0)
class ArenaPvP1x1AcceptBaseTests(UseAbilityTaskMixin, testcase.TestCase):

    def setUp(self):
        super(ArenaPvP1x1AcceptBaseTests, self).setUp()

        self.p1, self.p2, self.p3 = create_test_map()

        result, account_1_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')
        result, account_2_id, bundle_id = register_user('test_user_2', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)
        self.account_2 = AccountPrototype.get_by_id(account_2_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)
        self.storage.load_account_data(self.account_2)

        self.hero_1 = self.storage.accounts_to_heroes[self.account_1.id]
        self.hero_2 = self.storage.accounts_to_heroes[self.account_2.id]

        environment.deinitialize()
        environment.initialize()

        self.pvp_balancer = environment.workers.pvp_balancer
        self.pvp_balancer.process_initialize('pvp_balancer')

        self.battle = self.pvp_balancer.add_to_arena_queue(self.hero_1.id)
Exemple #11
0
class LevelUpTest(testcase.TestCase, CardsTestMixin):
    CARD = LevelUp

    def setUp(self):
        super(LevelUpTest, self).setUp()

        create_test_map()

        self.account_1 = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.abilities = self.hero.abilities

        self.card = self.CARD()


    def test_use(self):

        self.hero.add_experience(self.hero.experience_to_next_level / 2)

        self.assertTrue(self.hero.experience > 0)
        self.assertEqual(self.hero.level, 1)

        with self.check_not_changed(lambda: self.hero.experience):
            with self.check_delta(lambda: self.hero.level, 1):
                result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
                self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))

        saved_hero = heroes_logic.load_hero(hero_id=self.hero.id)
        self.assertEqual(saved_hero.abilities.destiny_points, self.abilities.destiny_points)
    def test_initialize_bots__second_create(self):
        account_1 = self.accounts_factory.create_account()
        account_2 = self.accounts_factory.create_account(is_bot=True)

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        hero_1.level = 50
        self.assertEqual(hero_2.level, 1)

        self.pvp_create_battle(account_1, account_2, BATTLE_1X1_STATE.PROCESSING)
        self.pvp_create_battle(account_2, account_1, BATTLE_1X1_STATE.PROCESSING)

        meta_action = meta_actions.ArenaPvP1x1.create(storage, hero_1, hero_2)
        meta_action.process_battle_ending()

        meta_actions.ArenaPvP1x1.create(storage, hero_1, hero_2)

        self.assertEqual(hero_2.level, 50)
        self.assertTrue(len(hero_2.abilities.all) > 1)
        self.assertEqual(hero_2.health, hero_2.max_health)
Exemple #13
0
class GetCompanionCreateTests(testcase.TestCase):

    def setUp(self):
        super(GetCompanionCreateTests, self).setUp()
        create_test_map()

        self.account_1 = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.disabled_companion = companions_logic.create_random_companion_record('disbled')
        self.manual_companion = companions_logic.create_random_companion_record('manual', mode=companions_relations.MODE.MANUAL)

        self.effect = effects.GetCompanionCommon()


    def test__no_disabled_companions(self):

        for i in range(100):
            card = self.effect.create_card(available_for_auction=True)
            self.assertNotEqual(card.data['companion_id'], self.disabled_companion.id)
            self.assertTrue(companions_storage.companions[card.data['companion_id']].state.is_ENABLED)


    def test__no_manual_companions(self):

        for i in range(100):
            card = self.effect.create_card(available_for_auction=True)
            self.assertNotEqual(card.data['companion_id'], self.manual_companion.id)
            self.assertTrue(companions_storage.companions[card.data['companion_id']].mode.is_AUTOMATIC)
Exemple #14
0
class QuestsTestBase(testcase.TestCase):

    def setUp(self):
        super(QuestsTestBase, self).setUp()
        self.p1, self.p2, self.p3 = create_test_map()

        # add more persons, to lower conflicts
        places_logic.add_person_to_place(self.p1)
        places_logic.add_person_to_place(self.p1)
        places_logic.add_person_to_place(self.p2)
        places_logic.add_person_to_place(self.p2)
        places_logic.add_person_to_place(self.p3)
        places_logic.add_person_to_place(self.p3)

        account = self.accounts_factory.create_account(is_fast=True)

        self.storage = LogicStorage()
        self.storage.load_account_data(account)
        self.hero = self.storage.accounts_to_heroes[account.id]
        self.action_idl = self.hero.actions.current_action

        self.hero.money += 1
        self.hero.preferences.set_mob(mobs_storage.all()[0])
        self.hero.preferences.set_place(self.p1)
        self.hero.preferences.set_friend(self.p1.persons[0])
        self.hero.preferences.set_enemy(self.p2.persons[0])
        self.hero.preferences.set_equipment_slot(EQUIPMENT_SLOT.PLATE)
        self.hero.position.set_place(self.p3)
        heroes_logic.save_hero(self.hero)

        self.p2.set_modifier(places_modifiers.CITY_MODIFIERS.HOLY_CITY)
        places_logic.save_place(self.p2)

        self.p1.persons[0].type = PERSON_TYPE.BLACKSMITH
        persons_logic.save_person(self.p1.persons[0])
Exemple #15
0
class HelpPlaceMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(HelpPlaceMixin, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        result, account_1_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()


    def test_use(self):
        with self.check_delta(lambda: self.hero.places_history._get_places_statisitcs().get(self.place_1.id, 0), self.CARD.HELPS):
            result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero, place_id=self.place_1.id))

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))

    def test_wrong_place(self):
        with self.check_not_changed(lambda: self.hero.places_history._get_places_statisitcs().get(self.place_1.id, 0)):
            result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero, place_id=666))
        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ()))
Exemple #16
0
class LevelUpTest(testcase.TestCase, CardsTestMixin):
    CARD = LevelUp

    def setUp(self):
        super(LevelUpTest, self).setUp()
        create_test_map()

        result, account_1_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()


    def test_use(self):

        self.hero.add_experience(self.hero.experience_to_next_level / 2)

        self.assertTrue(self.hero.experience > 0)
        self.assertEqual(self.hero.level, 1)

        with self.check_not_changed(lambda: self.hero.experience):
            with self.check_delta(lambda: self.hero.level, 1):
                result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))
Exemple #17
0
class LongTeleportTests(CardsTestMixin, testcase.TestCase):
    CARD = effects.LongTeleport

    def setUp(self):
        super(LongTeleportTests, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        result, account_1_id, bundle_id = register_user("test_user", "*****@*****.**", "111111")

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]
        self.hero.position.set_place(self.place_1)

        self.card = self.CARD()

    @mock.patch("the_tale.game.heroes.objects.Hero.is_battle_start_needed", lambda self: False)
    def test_moving(self):
        self.assertFalse(self.hero.actions.current_action.TYPE.is_MOVE_TO)

        result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
        self.assertEqual(
            (result, step, postsave_actions), (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ())
        )

    @mock.patch("the_tale.game.heroes.objects.Hero.is_battle_start_needed", lambda self: False)
    def test_use(self):
        actions_prototypes.ActionMoveToPrototype.create(hero=self.hero, destination=self.place_3)

        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertTrue(self.hero.actions.current_action.state == actions_prototypes.ActionMoveToPrototype.STATE.MOVING)

        self.assertTrue(self.hero.position.percents < 1)

        result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
        self.assertEqual(
            (result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ())
        )

        self.assertTrue(self.hero.position.place.id, self.place_3.id)

    @mock.patch("the_tale.game.heroes.objects.Hero.is_battle_start_needed", lambda self: False)
    def test_use__wrong_state(self):
        actions_prototypes.ActionMoveToPrototype.create(hero=self.hero, destination=self.place_3)
        self.assertTrue(self.hero.actions.current_action.state != actions_prototypes.ActionMoveToPrototype.STATE.MOVING)

        with self.check_not_changed(lambda: self.hero.actions.current_action.percents):
            result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
            self.assertEqual(
                (result, step, postsave_actions), (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ())
            )

        self.assertTrue(self.hero.position.place.id, self.place_1.id)
    def test_merge_bundles(self):

        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3])

        storage.merge_bundles([555, 666], 777)

        self.assertEqual(storage.bundles_to_accounts, {777: set([1, 2, 3])})
class InPlaceActionCompanionDrinkArtifactTests(testcase.TestCase):

    def setUp(self):
        super(InPlaceActionCompanionDrinkArtifactTests, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.action_idl = self.hero.actions.current_action

        self.companion_record = companions_logic.create_random_companion_record('thief', state=companions_relations.STATE.ENABLED)
        self.hero.set_companion(companions_logic.create_companion(self.companion_record))

        self.hero.money = f.expected_gold_in_day(self.hero.level)

        self.hero.position.set_place(self.place_1)
        self.hero.position.update_previous_place()
        self.hero.position.set_place(self.place_2)

        self.artifact = artifacts_storage.generate_artifact_from_list(artifacts_storage.loot, 1, rarity=RARITY.NORMAL)
        self.hero.put_loot(self.artifact)

        self.assertEqual(self.hero.bag.occupation, 1)

        self.hero.position.move_out_place()

    @mock.patch('the_tale.game.heroes.objects.Hero.can_companion_drink_artifact', lambda hero: True)
    def test_dring_artifact(self):
        with self.check_decreased(lambda: self.hero.bag.occupation):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertTrue(self.hero.journal.messages[-1].key.is_ACTION_INPLACE_COMPANION_DRINK_ARTIFACT)


    def check_not_used(self):
        with self.check_not_changed(lambda: self.hero.bag.occupation):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

    @mock.patch('the_tale.game.heroes.objects.Hero.can_companion_drink_artifact', lambda hero: True)
    def test_previouse_place_is_equal(self):
        self.hero.position.update_previous_place()
        self.check_not_used()

    @mock.patch('the_tale.game.heroes.objects.Hero.can_companion_drink_artifact', lambda hero: True)
    def test_no_items(self):
        self.hero.pop_loot(self.artifact)
        self.check_not_used()

    @mock.patch('the_tale.game.heroes.objects.Hero.can_companion_drink_artifact', lambda hero: False)
    def test_companion_does_not_eat(self):
        self.check_not_used()
Exemple #20
0
class ChangeHeroTest(TestCase):
    def setUp(self):
        super(ChangeHeroTest, self).setUp()
        place_1, place_2, place_3 = create_test_map()

        result, account_id, bundle_id = register_user("test_user", "*****@*****.**", "111111")
        self.account = AccountPrototype.get_by_id(account_id)
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)

        self.hero = self.storage.accounts_to_heroes[account_id]
        self.hero.utg_name.properties = self.hero.utg_name.properties.clone(self.hero.gender.utg_id)

        self.noun = names.generator.get_test_name(name="test_name", gender=GENDER.NEUTER)

        self.race = RACE.ELF if RACE.ELF != self.hero.race else RACE.HUMAN
        self.gender = GENDER.NEUTER if not self.hero.gender.is_NEUTER else GENDER.FEMININE

    def tearDown(self):
        pass

    def test_create(self):
        task = ChangeHeroTask(self.hero.id, name=self.noun, race=self.race, gender=self.gender)
        self.assertEqual(task.state, CHANGE_HERO_TASK_STATE.UNPROCESSED)
        self.assertEqual(self.hero.preferences.place, None)

        self.assertEqual(task.name, self.noun)
        self.assertEqual(task.race, self.race)
        self.assertEqual(task.gender, self.gender)

    def test_serialization(self):
        task = ChangeHeroTask(self.hero.id, name=self.noun, race=self.race, gender=self.gender)
        self.assertEqual(task.serialize(), ChangeHeroTask.deserialize(task.serialize()).serialize())

    def test_check_change(self):
        task = ChangeHeroTask(self.hero.id, name=self.noun, race=self.race, gender=self.gender)
        self.assertNotEqual(self.hero.utg_name, self.noun)
        self.assertNotEqual(self.hero.gender, self.gender)
        self.assertNotEqual(self.hero.race, self.race)
        self.assertFalse(self.hero.settings_approved)

        with mock.patch("the_tale.game.heroes.objects.Hero.reset_accessors_cache") as reset_accessors_cache:
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.SUCCESS
            )

        self.assertEqual(reset_accessors_cache.call_count, 1)

        self.assertEqual(task.state, CHANGE_HERO_TASK_STATE.PROCESSED)
        self.assertEqual(self.hero.utg_name.forms, self.noun.forms)
        self.assertEqual(self.hero.utg_name.properties.get(utg_relations.GENDER), self.gender.utg_id)
        self.assertEqual(self.hero.name, self.noun.normal_form())
        self.assertEqual(self.hero.race, self.race)
        self.assertEqual(self.hero.gender, self.gender)
        self.assertTrue(self.hero.settings_approved)
class PersonPowerBonusMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(PersonPowerBonusMixin, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        result, account_1_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')
        result, account_2_id, bundle_id = register_user('test_user_2')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)
        self.account_2 = AccountPrototype.get_by_id(account_2_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)
        self.storage.load_account_data(self.account_2)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()

        environment.deinitialize()
        environment.initialize()

        self.highlevel = environment.workers.highlevel
        self.highlevel.process_initialize(0, 'highlevel')


    def test_use(self):

        person = self.place_1.persons[0]

        result, step, postsave_actions = self.card.use(**self.use_attributes(hero=self.hero, storage=self.storage, person_id=person.id))

        self.assertEqual((result, step), (ComplexChangeTask.RESULT.CONTINUE, ComplexChangeTask.STEP.HIGHLEVEL))
        self.assertEqual(len(postsave_actions), 1)

        with mock.patch('the_tale.game.workers.highlevel.Worker.cmd_logic_task') as highlevel_logic_task_counter:
            postsave_actions[0]()

        self.assertEqual(highlevel_logic_task_counter.call_count, 1)

        with self.check_delta(lambda: person.power_positive, self.CARD.BONUS):
            result, step, postsave_actions = self.card.use(**self.use_attributes(hero=self.hero,
                                                                                 step=step,
                                                                                 highlevel=self.highlevel,
                                                                                 person_id=person.id))

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))


    def test_no_person(self):
        self.assertEqual(self.card.use(**self.use_attributes(hero=self.hero, person_id=666, storage=self.storage)),
                        (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ()))
class HeroLogicAccessorsTestBase(testcase.TestCase):

    def setUp(self):
        super(HeroLogicAccessorsTestBase, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        result, account_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')

        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account_id))
        self.hero = self.storage.accounts_to_heroes[account_id]
Exemple #23
0
class HeroLogicAccessorsTestBase(testcase.TestCase):

    def setUp(self):
        super(HeroLogicAccessorsTestBase, self).setUp()

        self.place_1, self.place_2, self.place_3 = create_test_map()

        account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(account)
        self.hero = self.storage.accounts_to_heroes[account.id]
class ChangeHeroSpendingsMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(ChangeHeroSpendingsMixin, self).setUp()
        create_test_map()

        result, account_1_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()

        old_companion_record = random.choice(companions_storage.companions.all())
        self.hero.set_companion(companions_logic.create_companion(old_companion_record))


    def test_use(self):

        # sure that quests will be loaded and not cal mark_updated
        self.hero.quests.mark_updated()

        for item in ITEMS_OF_EXPENDITURE.records:
            if item == self.CARD.ITEM:
                continue

            self.hero.next_spending = item

            with mock.patch('the_tale.game.quests.container.QuestsContainer.mark_updated') as mark_updated:
                result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))

            self.assertEqual(mark_updated.call_count, 1)

            self.assertEqual(self.hero.next_spending, self.CARD.ITEM)

            self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))


    def test_equal(self):
        self.hero.next_spending = self.CARD.ITEM

        with mock.patch('the_tale.game.quests.container.QuestsContainer.mark_updated') as mark_updated:
            result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))

        self.assertEqual(mark_updated.call_count, 0)

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ()))
class RepairRandomArtifactTests(RepairArtifacsTestMixin, testcase.TestCase):
    CARD = effects.RepairRandomArtifact

    def setUp(self):
        super(RepairRandomArtifactTests, self).setUp()
        create_test_map()

        result, account_1_id, bundle_id = register_user("test_user", "*****@*****.**", "111111")

        self.account_1 = AccountPrototype.get_by_id(account_1_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()

    def test_all_repaired(self):
        self.check_all_equipment_repaired(True)

        result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
        self.assertEqual(
            (result, step, postsave_actions), (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ())
        )

        self.check_all_equipment_repaired(True)

    def test_use(self):
        self.check_all_equipment_repaired(True)

        items = [item for item in self.hero.equipment.values() if item]
        random.shuffle(items)

        items[0].integrity = 0
        items[1].integrity = 0

        self.check_all_equipment_repaired(False)

        result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
        self.assertEqual(
            (result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ())
        )

        self.check_all_equipment_repaired(False)

        result, step, postsave_actions = self.card.use(**self.use_attributes(storage=self.storage, hero=self.hero))
        self.assertEqual(
            (result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ())
        )

        self.check_all_equipment_repaired(True)
Exemple #26
0
class AddPersonPowerMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(AddPersonPowerMixin, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account_1 = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()

        environment.deinitialize()
        environment.initialize()

        self.highlevel = environment.workers.highlevel
        self.highlevel.process_initialize(0, 'highlevel')


    def test_use(self):

        person = self.place_1.persons[0]

        result, step, postsave_actions = self.card.use(**self.use_attributes(hero=self.hero, storage=self.storage, person_id=person.id))

        self.assertEqual((result, step), (ComplexChangeTask.RESULT.CONTINUE, ComplexChangeTask.STEP.HIGHLEVEL))
        self.assertEqual(len(postsave_actions), 1)

        with mock.patch('the_tale.game.workers.highlevel.Worker.cmd_logic_task') as highlevel_logic_task_counter:
            postsave_actions[0]()

        self.assertEqual(highlevel_logic_task_counter.call_count, 1)

        with mock.patch('the_tale.game.persons.logic.PersonPoliticPower.change_power') as change_power:
            result, step, postsave_actions = self.card.use(**self.use_attributes(hero=self.hero,
                                                                                 step=step,
                                                                                 highlevel=self.highlevel,
                                                                                 person_id=person.id))
        self.assertEqual(change_power.call_args_list,
                         [mock.call(hero_id=self.hero.id, person=person, power=self.CARD.BONUS, has_in_preferences=True)])

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))


    def test_no_person(self):
        self.assertEqual(self.card.use(**self.use_attributes(hero=self.hero, person_id=666, storage=self.storage)),
                        (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ()))
Exemple #27
0
class KeepersGoodsMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(KeepersGoodsMixin, self).setUp()

        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account_1 = self.accounts_factory.create_account()
        self.account_2 = self.accounts_factory.create_account(is_fast=True)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)
        self.storage.load_account_data(self.account_2)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        self.card = self.CARD()

        environment.deinitialize()
        environment.initialize()

        self.highlevel = environment.workers.highlevel
        self.highlevel.process_initialize(0, 'highlevel')


    def test_use(self):

        result, step, postsave_actions = self.card.use(**self.use_attributes(hero=self.hero, storage=self.storage, place_id=self.place_1.id))

        self.assertEqual((result, step), (ComplexChangeTask.RESULT.CONTINUE, ComplexChangeTask.STEP.HIGHLEVEL))
        self.assertEqual(len(postsave_actions), 1)

        with mock.patch('the_tale.game.workers.highlevel.Worker.cmd_logic_task') as highlevel_logic_task_counter:
            postsave_actions[0]()

        self.assertEqual(highlevel_logic_task_counter.call_count, 1)

        with self.check_delta(lambda: self.place_1.attrs.keepers_goods, self.CARD.GOODS):
            result, step, postsave_actions = self.card.use(**self.use_attributes(hero=self.hero,
                                                                                 step=step,
                                                                                 highlevel=self.highlevel,
                                                                                 place_id=self.place_1.id))

        self.assertEqual((result, step, postsave_actions), (ComplexChangeTask.RESULT.SUCCESSED, ComplexChangeTask.STEP.SUCCESS, ()))


    def test_use_for_wrong_place_id(self):
        with self.check_not_changed(lambda: self.place_1.attrs.keepers_goods):
            self.assertEqual(self.card.use(**self.use_attributes(hero=self.hero, place_id=666, storage=self.storage)),
                             (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR, ()))
Exemple #28
0
class PrototypesTests(testcase.TestCase):

    def setUp(self):
        super(PrototypesTests, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user_1', '*****@*****.**', '111111')

        self.account = AccountPrototype.get_by_id(account_id)
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.card_effect = effects.EFFECTS[relations.CARD_TYPE.KEEPERS_GOODS_COMMON]
        self.card_1 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON)

        self.hero.cards.add_card(self.card_1)

        self.task_data = {'card_uid': self.card_1.uid}


    def test_check_hero_conditions__has_card(self):
        self.assertTrue(self.card_effect.check_hero_conditions(self.hero, self.task_data))


    def test_check_hero_conditions__has_no_card(self):
        self.hero.cards.remove_card(self.card_1.uid)
        self.assertFalse(self.card_effect.check_hero_conditions(self.hero, self.task_data))


    def test_hero_actions(self):
        card_2 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON)
        self.hero.cards.add_card(card_2)

        self.assertEqual(self.card_1.type, card_2.type)
        self.assertEqual(self.hero.cards.cards_count(), 2)

        with self.check_delta(lambda: self.hero.statistics.cards_used, 1):
            self.card_effect.hero_actions(self.hero, self.task_data)

        self.assertEqual(self.hero.cards.cards_count(), 1)
        self.assertTrue(self.hero.cards.has_card(card_2.uid))
        self.assertFalse(self.hero.cards.has_card(self.card_1.uid))


    def test_activate(self):
        with mock.patch('the_tale.game.workers.supervisor.Worker.cmd_logic_task') as cmd_logic_task:
            task = self.card_effect.activate(self.hero, self.card_1.uid, {'x': 'y'})

        self.assertEqual(cmd_logic_task.call_args_list, [mock.call(self.hero.account_id, task.id)])
class _HeroEquipmentTestsBase(TestCase):

    def setUp(self):
        super(_HeroEquipmentTestsBase, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')

        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account_id))

        self.hero = self.storage.accounts_to_heroes[account_id]
        self.hero._model.level = relations.PREFERENCE_TYPE.EQUIPMENT_SLOT.level_required
        self.hero.save()
Exemple #30
0
class HeroRequestsTestBase(TestCase):

    def setUp(self):
        super(HeroRequestsTestBase, self).setUp()
        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.client = client.Client()
        self.request_login(self.account.email)
class IdlenessActionTest(testcase.TestCase):
    def setUp(self):
        super(IdlenessActionTest, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account(is_fast=True)
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)

        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.action_idl = self.hero.actions.current_action

    def tearDown(self):
        pass

    def test_create(self):
        self.assertEqual(self.action_idl.leader, True)
        self.assertEqual(self.action_idl.percents, 1.0)
        self.assertEqual(
            self.action_idl.state,
            prototypes.ActionIdlenessPrototype.STATE.BEFORE_FIRST_STEPS)
        self.storage._test_save()

    def test_first_steps(self):
        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionFirstStepsPrototype.TYPE)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.FIRST_STEPS)
        self.assertEqual(self.action_idl.bundle_id, self.hero.account_id)
        self.storage._test_save()

    def test_first_quest(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.FIRST_STEPS

        self.storage.process_turn()

        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionQuestPrototype.TYPE)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.QUEST)
        self.assertEqual(self.action_idl.bundle_id, self.hero.account_id)
        self.storage._test_save()

    def test_reset_percents_on_quest_end(self):
        self.action_idl.percents = 1.0
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.QUEST
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(self.action_idl.percents, 0.0)

    def test_inplace(self):
        self.action_idl.percents = 1.0
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.QUEST
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionInPlacePrototype.TYPE)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.IN_PLACE)
        self.storage._test_save()

    def test_waiting(self):
        self.action_idl.percents = 0.0
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.IN_PLACE
        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 1)
        self.assertEqual(self.hero.actions.current_action, self.action_idl)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.WAITING)
        self.storage._test_save()

    def test_regenerate_energy_action_create(self):
        self.hero.preferences.set_energy_regeneration_type(
            heroes_relations.ENERGY_REGENERATION.PRAY)
        self.hero.last_energy_regeneration_at_turn -= max(
            next(zip(*heroes_relations.ENERGY_REGENERATION.select('period'))))

        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.WAITING
        self.action_idl.percents = 0.0

        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionRegenerateEnergyPrototype.TYPE)
        self.storage._test_save()

    def test_regenerate_energy_action_not_create_for_sacrifice(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.WAITING
        self.action_idl.percents = 0

        self.hero.preferences.set_energy_regeneration_type(
            heroes_relations.ENERGY_REGENERATION.SACRIFICE)
        self.hero.last_energy_regeneration_at_turn -= max(
            next(zip(*heroes_relations.ENERGY_REGENERATION.select('period'))))
        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 1)
        self.assertEqual(self.hero.actions.current_action, self.action_idl)
        self.storage._test_save()

    def test_full_waiting(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.WAITING
        self.action_idl.percents = 0

        current_time = TimePrototype.get_current_time()

        for i in range(c.TURNS_TO_IDLE * self.hero.level):
            self.storage.process_turn()
            current_time.increment_turn()
            self.assertEqual(len(self.hero.actions.actions_list), 1)
            self.assertEqual(self.hero.actions.current_action, self.action_idl)

        self.storage.process_turn()

        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionQuestPrototype.TYPE)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.QUEST)

        self.storage._test_save()

    def test_initiate_quest(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.WAITING
        self.action_idl.percents = 0

        self.action_idl.init_quest()

        self.storage.process_turn()

        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionQuestPrototype.TYPE)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.QUEST)

        self.storage._test_save()

    def test_initiate_quest_just_after_quest(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.QUEST
        self.action_idl.percents = 0

        self.action_idl.init_quest()

        self.storage.process_turn()

        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionQuestPrototype.TYPE)
        self.assertEqual(self.action_idl.state,
                         prototypes.ActionIdlenessPrototype.STATE.QUEST)

        self.storage._test_save()

    def test_help_choices__contain_start_quest(self):
        self.action_idl.percents = 0.0
        self.assertTrue(
            HELP_CHOICES.START_QUEST in self.action_idl.HELP_CHOICES)

    def test_help_choices__start_quest_removed(self):
        self.action_idl.percents = 1.0
        self.assertFalse(
            HELP_CHOICES.START_QUEST in self.action_idl.HELP_CHOICES)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_battle_start_needed',
                lambda self: False)
    def test_return_from_road__after_quest(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.QUEST
        self.hero.position.set_road(list(roads_storage.all())[0], percents=0.5)
        self.storage.process_turn()
        self.assertEqual(self.hero.actions.number, 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionMoveToPrototype.TYPE)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_battle_start_needed',
                lambda self: False)
    def test_return_from_wild_terrain__after_quest(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.QUEST
        self.hero.position.set_coordinates(0, 0, 5, 5, percents=0)
        self.storage.process_turn()
        self.assertEqual(self.hero.actions.number, 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionMoveNearPlacePrototype.TYPE)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_battle_start_needed',
                lambda self: False)
    def test_return_from_road__after_resurrect(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.RESURRECT
        self.hero.position.set_road(list(roads_storage.all())[0], percents=0.5)
        self.storage.process_turn()
        self.assertEqual(self.hero.actions.number, 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionMoveToPrototype.TYPE)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_battle_start_needed',
                lambda self: False)
    def test_return_from_wild_terrain__after_resurrect(self):
        self.action_idl.state = prototypes.ActionIdlenessPrototype.STATE.RESURRECT
        self.hero.position.set_coordinates(0, 0, 5, 5, percents=0)
        self.storage.process_turn()
        self.assertEqual(self.hero.actions.number, 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionMoveNearPlacePrototype.TYPE)

    def test_resurrect(self):
        self.hero.is_alive = False
        self.storage.process_turn()
        self.assertEqual(self.hero.actions.number, 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionResurrectPrototype.TYPE)
Exemple #32
0
class LogicStorageTests(testcase.TestCase):

    def setUp(self):
        super(LogicStorageTests, self).setUp()

        self.p1, self.p2, self.p3 = create_test_map()

        self.storage = LogicStorage()

        self.account_1 = self.accounts_factory.create_account()
        self.account_2 = self.accounts_factory.create_account()

        self.storage.load_account_data(self.account_1)
        self.storage.load_account_data(self.account_2)

        self.hero_1 = self.storage.accounts_to_heroes[self.account_1.id]
        self.hero_2 = self.storage.accounts_to_heroes[self.account_2.id]

        self.action_idl_1 = self.hero_1.actions.current_action
        self.action_idl_2 = self.hero_2.actions.current_action

        self.bundle_1_id = self.action_idl_1.bundle_id
        self.bundle_2_id = self.action_idl_2.bundle_id


    def test_load_account_data(self):
        self.assertEqual(len(self.storage.heroes), 2)
        self.assertEqual(len(self.storage.accounts_to_heroes), 2)
        self.assertEqual(self.storage.bundles_to_accounts, {self.hero_1.actions.current_action.bundle_id: set([self.account_1.id]),
                                                            self.hero_2.actions.current_action.bundle_id: set([self.account_2.id])})

        action_regenerate = actions_prototypes.ActionRegenerateEnergyPrototype.create(hero=self.hero_1)

        self.assertEqual(self.action_idl_1.storage, self.storage)
        self.assertEqual(action_regenerate.storage, self.storage)

        storage = LogicStorage()
        storage.load_account_data(AccountPrototype.get_by_id(self.account_1.id))
        storage.load_account_data(AccountPrototype.get_by_id(self.account_2.id))
        self.assertEqual(len(storage.heroes), 2)
        self.assertEqual(len(storage.accounts_to_heroes), 2)
        self.assertEqual(storage.bundles_to_accounts, {self.hero_1.actions.current_action.bundle_id: set([self.account_1.id]),
                                                       self.hero_2.actions.current_action.bundle_id: set([self.account_2.id])})


    def test_load_account_data_with_meta_action(self):
        bundle_id = 666

        meta_action_battle = meta_actions.ArenaPvP1x1.create(self.storage, self.hero_1, self.hero_2)

        proxy_action_1 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_1, _bundle_id=bundle_id, meta_action=meta_action_battle)
        proxy_action_2 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_2, _bundle_id=bundle_id, meta_action=meta_action_battle)

        self.assertEqual(len(self.storage.meta_actions), 1)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 1)
        self.assertEqual(self.storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1),
                                                                                            LogicStorage.get_action_uid(proxy_action_2)]))

        self.storage.save_changed_data()

        self.assertIs(self.hero_1.actions.current_action.meta_action, self.hero_2.actions.current_action.meta_action)
        self.assertIs(self.hero_1.actions.current_action.saved_meta_action, self.hero_2.actions.current_action.saved_meta_action)

        storage = LogicStorage()
        storage.load_account_data(AccountPrototype.get_by_id(self.account_1.id))
        storage.load_account_data(AccountPrototype.get_by_id(self.account_2.id))

        self.assertEqual(len(storage.meta_actions), 1)
        self.assertEqual(len(storage.meta_actions_to_actions), 1)
        self.assertEqual(storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1),
                                                                                       LogicStorage.get_action_uid(proxy_action_2)]))

        self.assertEqual(storage.bundles_to_accounts, {self.hero_1.actions.current_action.bundle_id: set([self.account_1.id, self.account_2.id])})

        hero_1 = storage.accounts_to_heroes[self.account_1.id]
        hero_2 = storage.accounts_to_heroes[self.account_2.id]

        self.assertIs(hero_1.actions.current_action.meta_action, hero_2.actions.current_action.meta_action)
        self.assertIsNot(hero_1.actions.current_action.saved_meta_action, hero_2.actions.current_action.saved_meta_action)
        self.assertEqual(hero_1.actions.current_action.saved_meta_action.serialize(), hero_2.actions.current_action.saved_meta_action.serialize())


    def test_add_duplicate_hero(self):
        self.assertRaises(exceptions.HeroAlreadyRegisteredError, self.storage._add_hero, self.hero_1)


    def test_action_release_account_data(self):

        actions_prototypes.ActionRegenerateEnergyPrototype.create(hero=self.hero_1)

        self.storage.skipped_heroes.add(self.hero_1.id)

        self.storage.release_account_data(self.account_1.id)

        self.assertEqual(len(self.storage.heroes), 1)
        self.assertEqual(len(self.storage.accounts_to_heroes), 1)
        self.assertEqual(self.storage.bundles_to_accounts, {self.hero_2.actions.current_action.bundle_id: set([self.account_2.id])})
        self.assertEqual(self.storage.heroes.values()[0].id, self.hero_2.id)
        self.assertFalse(self.storage.skipped_heroes)

    def test_save_hero_data(self):

        self.hero_1.health = 1
        self.hero_2.health = 1

        self.hero_1.actions.updated = True

        self.storage._save_hero_data(self.hero_1.id)

        self.assertEqual(self.hero_1.health, heroes_logic.load_hero(hero_id=self.hero_1.id).health)
        self.assertNotEqual(self.hero_2.health, heroes_logic.load_hero(hero_id=self.hero_2.id).health)

        self.assertFalse(self.hero_1.actions.updated)

    def test_save_all(self):

        self.hero_1.health = 1
        self.hero_2.health = 1

        self.hero_1.actions.updated = True

        self.storage.save_all()

        self.assertEqual(self.hero_1.health, heroes_logic.load_hero(hero_id=self.hero_1.id).health)
        self.assertEqual(self.hero_2.health, heroes_logic.load_hero(hero_id=self.hero_2.id).health)

        self.assertFalse(self.hero_1.actions.updated)

    def test_save_hero_data_with_meta_action(self):
        bundle_id = 666

        meta_action_battle = meta_actions.ArenaPvP1x1.create(self.storage, self.hero_1, self.hero_2)

        actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_1, _bundle_id=bundle_id, meta_action=meta_action_battle)
        actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_2, _bundle_id=bundle_id, meta_action=meta_action_battle)

        self.storage._save_hero_data(self.hero_1.id)
        self.storage._save_hero_data(self.hero_2.id)

        self.hero_1 = heroes_logic.load_hero(hero_id=self.hero_1.id)
        self.hero_2 = heroes_logic.load_hero(hero_id=self.hero_2.id)


        self.assertEqual(meta_action_battle.serialize(), self.hero_1.actions.current_action.saved_meta_action.serialize())
        self.assertEqual(meta_action_battle.serialize(), self.hero_2.actions.current_action.saved_meta_action.serialize())

    def test_switch_caches(self):
        self.assertEqual(self.storage.previous_cache, {})
        self.assertEqual(self.storage.current_cache, {})

        self.storage.previous_cache[1] = 2
        self.storage.current_cache[3] = 4

        self.storage.switch_caches()

        self.assertEqual(self.storage.previous_cache, {3: 4})
        self.assertEqual(self.storage.current_cache, {})

        self.storage.current_cache[5] = 6

        self.storage.switch_caches()

        self.assertEqual(self.storage.previous_cache, {5: 6})
        self.assertEqual(self.storage.current_cache, {})

    def test_process_cache_queue__with_update(self):
        self.assertEqual(self.storage.cache_queue, set())

        self.storage.cache_queue.add(self.hero_2.id)
        self.storage.cache_queue.add(self.hero_1.id)

        self.storage.process_cache_queue(update_cache=True)

        self.assertItemsEqual(self.storage.current_cache.keys(), (self.hero_1.cached_ui_info_key, self.hero_2.cached_ui_info_key))
        self.assertEqual(self.storage.cache_queue, set())

    def test_process_cache_queue__without_update(self):
        self.assertEqual(self.storage.cache_queue, set())

        self.storage.cache_queue.add(self.hero_2.id)
        self.storage.cache_queue.add(self.hero_1.id)

        self.storage.process_cache_queue(update_cache=False)

        self.assertItemsEqual(self.storage.current_cache.keys(), ())
        self.assertEqual(self.storage.cache_queue, set())

    def test_process_cache_queue__update_cache__with_update(self):
        self.assertEqual(self.storage.cache_queue, set())

        self.storage.current_cache[self.hero_1.cached_ui_info_key] = 1
        self.storage.current_cache[self.hero_2.cached_ui_info_key] = 2

        self.storage.cache_queue.add(self.hero_2.id)

        self.storage.process_cache_queue(update_cache=True)

        self.assertEqual(self.storage.current_cache[self.hero_1.cached_ui_info_key], 1)
        self.assertNotEqual(self.storage.current_cache[self.hero_2.cached_ui_info_key], 2)

    def test_process_cache_queue__update_cache__without_update(self):
        self.assertEqual(self.storage.cache_queue, set())

        self.storage.current_cache[self.hero_1.cached_ui_info_key] = 1
        self.storage.current_cache[self.hero_2.cached_ui_info_key] = 2

        self.storage.cache_queue.add(self.hero_2.id)

        self.storage.process_cache_queue(update_cache=False)

        self.assertEqual(self.storage.current_cache[self.hero_1.cached_ui_info_key], 1)
        self.assertEqual(self.storage.current_cache[self.hero_2.cached_ui_info_key], 2)

    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    def test_process_turn(self):
        self.assertEqual(self.storage.skipped_heroes, set())
        self.storage.process_turn()
        self.assertEqual(self.storage.skipped_heroes, set())

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
            self.storage.save_changed_data()

        self.assertEqual(save_hero_data.call_count, 2)

    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    def test_process_turn__switch_caches(self):
        self.assertEqual(self.storage.previous_cache, {})
        self.assertEqual(self.storage.current_cache, {})

        self.storage.process_turn()
        self.storage.save_changed_data()

        self.assertEqual(self.storage.previous_cache, {})
        self.assertNotEqual(self.storage.current_cache, {})

        old_cache = self.storage.current_cache

        self.storage.process_turn()
        self.storage.save_changed_data()

        self.assertEqual(self.storage.previous_cache, old_cache)
        self.assertNotEqual(self.storage.current_cache, old_cache)

    def test_process_turn_single_hero__runned_outside_storage(self):
        action_1 = actions_prototypes.ActionRegenerateEnergyPrototype.create(hero=self.hero_1)
        action_1.state = action_1.STATE.PROCESSED

        action_2 = actions_prototypes.ActionMoveToPrototype.create(hero=self.hero_1, destination=self.p1)
        action_2.state = action_2.STATE.PROCESSED

        action_3 = actions_prototypes.ActionInPlacePrototype.create(hero=self.hero_1)
        action_3.state = action_3.STATE.PROCESSED

        self.assertEqual(self.hero_1.actions.number, 4)

        self.storage.process_turn__single_hero(hero=self.hero_1,
                                               logger=None,
                                               continue_steps_if_needed=True)

        self.assertEqual(self.hero_1.actions.number, 2)
        self.assertEqual(self.hero_1.actions.current_action.TYPE, actions_prototypes.ActionQuestPrototype.TYPE)

        self.storage.process_turn() # just nothing was broken


    def test_process_turn__process_action_chain(self):
        action_1 = actions_prototypes.ActionRegenerateEnergyPrototype.create(hero=self.hero_1)
        action_1.state = action_1.STATE.PROCESSED

        action_2 = actions_prototypes.ActionMoveToPrototype.create(hero=self.hero_1, destination=self.p1)
        action_2.state = action_2.STATE.PROCESSED

        action_3 = actions_prototypes.ActionInPlacePrototype.create(hero=self.hero_1)
        action_3.state = action_3.STATE.PROCESSED

        self.assertEqual(self.hero_1.actions.number, 4)

        self.storage.process_turn()

        self.assertEqual(self.hero_1.actions.number, 2)
        self.assertEqual(self.hero_1.actions.current_action.TYPE, actions_prototypes.ActionQuestPrototype.TYPE)


    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', False)
    def test_process_turn__without_dump(self):
        self.assertEqual(self.storage.skipped_heroes, set())
        self.storage.process_turn()
        self.assertEqual(self.storage.skipped_heroes, set())

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
            self.storage.save_changed_data()

        self.assertEqual(save_hero_data.call_count, 1) # save only game_settings.SAVED_UNCACHED_HEROES_FRACTION bundles number


    def test_process_turn__process_created_action(self):
        from the_tale.game.actions.prototypes import ActionMoveToPrototype

        place = self.p1

        def process_action(self):
            ActionMoveToPrototype.create(hero=self.hero, destination=place)

        with mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.process', process_action):
            with mock.patch('the_tale.game.actions.prototypes.ActionMoveToPrototype.process') as move_to_process:
                self.storage.process_turn()

        self.assertEqual(move_to_process.call_count, 2)

    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    def test_process_turn_with_skipped_hero(self):
        # skipped heroes saved, but not processed
        self.storage.skipped_heroes.add(self.hero_1.id)

        with mock.patch('the_tale.game.actions.prototypes.ActionBase.process_turn') as action_process_turn:
            self.storage.process_turn()

        self.assertEqual(action_process_turn.call_count, 1)

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
            self.storage.save_changed_data()

        self.assertEqual(save_hero_data.call_count, 2)

    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', False)
    def test_process_turn_with_skipped_hero__without_cache_dump(self):
        # skipped heroes saved, but not processed
        self.storage.skipped_heroes.add(self.hero_1.id)

        with mock.patch('the_tale.game.actions.prototypes.ActionBase.process_turn') as action_process_turn:
            self.storage.process_turn()

        self.assertEqual(action_process_turn.call_count, 1)

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
            self.storage.save_changed_data()

        self.assertEqual(save_hero_data.call_count, 1)

    @mock.patch('the_tale.game.heroes.objects.Hero.can_process_turn', lambda self, turn: True)
    def test_process_turn__can_process_turn(self):
        with mock.patch('the_tale.game.actions.prototypes.ActionBase.process_turn') as action_process_turn:
            self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(action_process_turn.call_count, 2)

    @mock.patch('the_tale.game.heroes.objects.Hero.can_process_turn', lambda self, turn: False)
    def test_process_turn__can_not_process_turn(self):
        with mock.patch('the_tale.game.actions.prototypes.ActionBase.process_turn') as action_process_turn:
            self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(action_process_turn.call_count, 0)

    def test_process_turn___exception_raises(self):
        def process_turn_raise_exception(action):
            if action.hero.id == self.hero_2.id:
                raise Exception('error')

        with mock.patch('the_tale.game.actions.prototypes.ActionBase.process_turn', process_turn_raise_exception):
            with mock.patch('the_tale.game.logic_storage.LogicStorage._save_on_exception') as _save_on_exception:
                with mock.patch('django.conf.settings.TESTS_RUNNING', False):
                    self.storage.process_turn()

        self.assertIn(self.hero_2.actions.current_action.bundle_id, self.storage.ignored_bundles)

        self.assertEqual(_save_on_exception.call_count, 1)
        self.assertEqual(_save_on_exception.call_args, mock.call())

    @mock.patch('the_tale.game.conf.game_settings.SAVE_ON_EXCEPTION_TIMEOUT', 0)
    def test_save_on_exception(self):
        # hero 1 not saved due to one bundle with hero 3
        # hero 2 saved
        # hero 3 not saved
        # hero 4 saved

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')
        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))
        hero_3 = self.storage.accounts_to_heroes[account_3_id]

        result, account_4_id, bundle_4_id = register_user('test_user_4', '*****@*****.**', '111111')
        self.storage.load_account_data(AccountPrototype.get_by_id(account_4_id))
        hero_4 = self.storage.accounts_to_heroes[account_4_id]

        self.hero_1.actions.current_action.bundle_id = hero_3.actions.current_action.bundle_id

        saved_heroes = set()

        def save_hero_data(storage, hero_id, **kwargs):
            saved_heroes.add(hero_id)

        self.storage.ignored_bundles.add(hero_3.actions.current_action.bundle_id)

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data', save_hero_data):
            self.storage._save_on_exception()

        self.assertEqual(saved_heroes, set([self.hero_2.id, hero_4.id]))

    def test_save_on_exception__time_border(self):
        # hero 1 not saved due to one bundle with hero 3
        # hero 2 saved
        # hero 3 not saved
        # hero 4 saved

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')
        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))
        hero_3 = self.storage.accounts_to_heroes[account_3_id]

        result, account_4_id, bundle_4_id = register_user('test_user_4', '*****@*****.**', '111111')
        self.storage.load_account_data(AccountPrototype.get_by_id(account_4_id))
        hero_4 = self.storage.accounts_to_heroes[account_4_id]

        self.hero_1.actions.current_action.bundle_id = hero_3.actions.current_action.bundle_id

        saved_heroes = set()

        self.hero_2.saved_at = datetime.datetime.now() - datetime.timedelta(seconds=conf.game_settings.SAVE_ON_EXCEPTION_TIMEOUT+1)

        def save_hero_data(storage, hero_id, **kwargs):
            saved_heroes.add(hero_id)

        self.storage.ignored_bundles.add(hero_3.actions.current_action.bundle_id)

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data', save_hero_data):
            self.storage._save_on_exception()

        self.assertEqual(saved_heroes, set([self.hero_2.id]))


    def test_save_changed_data(self):
        self.storage.process_turn()

        with mock.patch('dext.common.utils.cache.set_many') as set_many:
            with mock.patch('the_tale.game.heroes.objects.Hero.ui_info') as ui_info:
                self.storage.save_changed_data()

        self.assertEqual(set_many.call_count, 1)
        self.assertEqual(ui_info.call_count, 2)
        self.assertEqual(ui_info.call_args_list, [mock.call(actual_guaranteed=True, old_info=None), mock.call(actual_guaranteed=True, old_info=None)])


    def test_old_info(self):
        self.storage.process_turn()

        calls = []

        def ui_info(hero, **kwargs):
            calls.append(kwargs)
            return {'hero': hero.id}

        with mock.patch('the_tale.game.heroes.objects.Hero.ui_info', ui_info):
            self.storage.save_changed_data()
            self.storage.process_turn()
            self.storage.save_changed_data()

        self.assertEqual(calls, [{'actual_guaranteed': True, 'old_info': None},
                                 {'actual_guaranteed': True, 'old_info': None},
                                 {'actual_guaranteed': True, 'old_info': {'hero': self.hero_1.id}},
                                 {'actual_guaranteed': True, 'old_info': {'hero': self.hero_2.id}}])


    def test_save_changed_data__old_info(self):
        self.storage.process_turn()
        self.storage.save_changed_data()

        self.storage.process_turn()

        with mock.patch('dext.common.utils.cache.set_many') as set_many:
            with mock.patch('the_tale.game.heroes.objects.Hero.ui_info') as ui_info:
                self.storage.save_changed_data()

        self.assertEqual(set_many.call_count, 1)
        self.assertEqual(ui_info.call_count, 2)
        self.assertNotEqual(ui_info.call_args_list[0][1]['old_info'], None)
        self.assertNotEqual(ui_info.call_args_list[1][1]['old_info'], None)


    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    def test_save_changed_data__with_unsaved_bundles(self):
        self.storage.process_turn()

        self.assertEqual(len(self.storage.heroes), 2)

        with mock.patch('the_tale.game.logic_storage.LogicStorage._get_bundles_to_save', lambda x: [self.bundle_2_id]):
            with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
                with mock.patch('the_tale.game.heroes.objects.Hero.ui_info') as ui_info:
                    self.storage.save_changed_data()

        self.assertEqual(ui_info.call_count, 2) # cache all heroes, since they are new
        self.assertEqual(ui_info.call_args_list, [mock.call(actual_guaranteed=True, old_info=None), mock.call(actual_guaranteed=True, old_info=None)])
        self.assertEqual(save_hero_data.call_args, mock.call(self.hero_2.id))

    def test_save_changed_data__with_unsaved_bundles__without_dump(self):
        self.storage.process_turn()

        self.assertEqual(len(self.storage.heroes), 2)

        self.hero_2.ui_caching_started_at = datetime.datetime.fromtimestamp(0)

        with mock.patch('the_tale.game.logic_storage.LogicStorage._get_bundles_to_save', lambda x: [self.bundle_2_id]):
            with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
                with mock.patch('the_tale.game.heroes.objects.Hero.ui_info') as ui_info:
                    self.storage.save_changed_data()

        self.assertEqual(ui_info.call_count, 1) # cache only first hero
        self.assertEqual(ui_info.call_args, mock.call(actual_guaranteed=True, old_info=None))
        self.assertEqual(save_hero_data.call_args, mock.call(self.hero_2.id))

    def test_remove_action__from_middle(self):
        actions_prototypes.ActionRegenerateEnergyPrototype.create(hero=self.hero_1)
        self.assertRaises(exceptions.RemoveActionFromMiddleError, self.storage.remove_action, self.action_idl_1)

    def test_remove_action__metaaction(self):
        bundle_id = 666

        meta_action_battle = meta_actions.ArenaPvP1x1.create(self.storage, self.hero_1, self.hero_2)

        proxy_action_1 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_1, _bundle_id=bundle_id, meta_action=meta_action_battle)
        proxy_action_2 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_2, _bundle_id=bundle_id, meta_action=meta_action_battle)

        self.assertEqual(len(self.storage.meta_actions), 1)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 1)
        self.assertEqual(self.storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1),
                                                                                            LogicStorage.get_action_uid(proxy_action_2)]))

        self.storage.remove_action(proxy_action_2)

        self.assertEqual(len(self.storage.meta_actions), 1)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 1)
        self.assertEqual(self.storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1)]))

        self.storage.remove_action(proxy_action_1)

        self.assertEqual(len(self.storage.meta_actions), 0)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 0)

    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    @mock.patch('the_tale.game.conf.game_settings.SAVED_UNCACHED_HEROES_FRACTION', 0)
    def test_get_bundles_to_save(self):
        # hero 1 not saved
        # hero 2 saved by quota
        # hero 3 saved by caching
        # hero 4 not saved

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')
        result, account_4_id, bundle_4_id = register_user('test_user_4', '*****@*****.**', '111111')
        result, account_5_id, bundle_5_id = register_user('test_user_5', '*****@*****.**', '111111')

        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))
        self.storage.load_account_data(AccountPrototype.get_by_id(account_4_id))
        self.storage.load_account_data(AccountPrototype.get_by_id(account_5_id))

        hero_3 = self.storage.accounts_to_heroes[account_3_id]
        hero_4 = self.storage.accounts_to_heroes[account_4_id]

        self.hero_1.saved_at = datetime.datetime.now()
        self.hero_1.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        self.hero_2.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        hero_4.ui_caching_started_at = datetime.datetime.fromtimestamp(0)

        self.assertTrue(self.hero_1.saved_at > self.hero_2.saved_at)

        self.assertFalse(self.hero_1.is_ui_caching_required)
        self.assertFalse(self.hero_2.is_ui_caching_required)
        self.assertTrue(hero_3.is_ui_caching_required)
        self.assertFalse(hero_4.is_ui_caching_required)

        self.assertEqual(self.storage._get_bundles_to_save(), set([self.bundle_2_id, bundle_3_id, bundle_5_id]))


    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    @mock.patch('the_tale.game.conf.game_settings.SAVED_UNCACHED_HEROES_FRACTION', 0)
    def test_get_bundles_to_save__force_save_required(self):
        # hero 1 not saved
        # hero 2 saved by quota
        # hero 3 saved by caching
        # hero 4 saved by force

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')
        result, account_4_id, bundle_4_id = register_user('test_user_4', '*****@*****.**', '111111')
        result, account_5_id, bundle_5_id = register_user('test_user_5', '*****@*****.**', '111111')

        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))
        self.storage.load_account_data(AccountPrototype.get_by_id(account_4_id))
        self.storage.load_account_data(AccountPrototype.get_by_id(account_5_id))

        hero_3 = self.storage.accounts_to_heroes[account_3_id]
        hero_4 = self.storage.accounts_to_heroes[account_4_id]

        hero_4.force_save_required = True

        self.hero_1.saved_at = datetime.datetime.now()
        self.hero_1.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        self.hero_2.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        hero_4.ui_caching_started_at = datetime.datetime.fromtimestamp(0)

        self.assertTrue(self.hero_1.saved_at > self.hero_2.saved_at)

        self.assertFalse(self.hero_1.is_ui_caching_required)
        self.assertFalse(self.hero_2.is_ui_caching_required)
        self.assertTrue(hero_3.is_ui_caching_required)
        self.assertFalse(hero_4.is_ui_caching_required)

        self.assertEqual(self.storage._get_bundles_to_save(), set([self.bundle_2_id, bundle_3_id, bundle_4_id, bundle_5_id]))

        self.assertFalse(hero_4.force_save_required)


    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', False)
    @mock.patch('the_tale.game.conf.game_settings.SAVED_UNCACHED_HEROES_FRACTION', 0)
    def test_get_bundles_to_save__without_cache_dump(self):
        # hero 1 not saved
        # hero 2 saved by quota
        # hero 3 does not saved by caching
        # hero 4 not saved

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')
        result, account_4_id, bundle_4_id = register_user('test_user_4', '*****@*****.**', '111111')

        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))
        self.storage.load_account_data(AccountPrototype.get_by_id(account_4_id))

        hero_3 = self.storage.accounts_to_heroes[account_3_id]
        hero_4 = self.storage.accounts_to_heroes[account_4_id]

        self.hero_1.saved_at = datetime.datetime.now()
        self.hero_1.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        self.hero_2.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        hero_4.ui_caching_started_at = datetime.datetime.fromtimestamp(0)

        self.assertTrue(self.hero_1.saved_at > self.hero_2.saved_at)

        self.assertFalse(self.hero_1.is_ui_caching_required)
        self.assertFalse(self.hero_2.is_ui_caching_required)
        self.assertTrue(hero_3.is_ui_caching_required)
        self.assertFalse(hero_4.is_ui_caching_required)

        self.assertEqual(self.storage._get_bundles_to_save(), set([self.bundle_2_id]))

    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', True)
    @mock.patch('the_tale.game.conf.game_settings.SAVED_UNCACHED_HEROES_FRACTION', 0)
    def test_save_changed_data__with_multiple_heroes_to_bundle(self):
        # hero 1 saved by bundle from hero 3
        # hero 2 saved by quota
        # hero 3 saved by caching

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')

        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))

        hero_3 = self.storage.accounts_to_heroes[account_3_id]

        self.hero_1.saved_at = datetime.datetime.now()
        self.hero_1.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        self.hero_1.actions.current_action.bundle_id = hero_3.actions.current_action.bundle_id
        self.hero_2.ui_caching_started_at = datetime.datetime.fromtimestamp(0)

        self.assertTrue(self.hero_1.saved_at > self.hero_2.saved_at)
        self.assertFalse(self.hero_1.is_ui_caching_required)
        self.assertFalse(self.hero_2.is_ui_caching_required)
        self.assertTrue(hero_3.is_ui_caching_required)

        self.assertEqual(self.storage._get_bundles_to_save(), set([self.bundle_2_id, bundle_3_id]))

        self.storage.process_turn()

        with mock.patch('dext.common.utils.cache.set_many') as set_many:
            with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
                with mock.patch('the_tale.game.heroes.objects.Hero.ui_info') as ui_info:
                    self.storage.save_changed_data()

        self.assertEqual(set_many.call_count, 1)
        self.assertEqual(save_hero_data.call_count, 3)
        self.assertEqual(ui_info.call_count, 2)
        self.assertEqual(ui_info.call_args_list, [mock.call(actual_guaranteed=True, old_info=None), mock.call(actual_guaranteed=True, old_info=None)])


    @mock.patch('the_tale.game.heroes.conf.heroes_settings.DUMP_CACHED_HEROES', False)
    @mock.patch('the_tale.game.conf.game_settings.SAVED_UNCACHED_HEROES_FRACTION', 0)
    def test_save_changed_data__with_multiple_heroes_to_bundle__without_cache_dump(self):
        # hero 1 saved by bundle from hero 2
        # hero 2 saved by quota
        # hero 3 does not saved by caching

        result, account_3_id, bundle_3_id = register_user('test_user_3', '*****@*****.**', '111111')

        self.storage.load_account_data(AccountPrototype.get_by_id(account_3_id))

        hero_3 = self.storage.accounts_to_heroes[account_3_id]

        self.hero_1.saved_at = datetime.datetime.now()
        self.hero_1.ui_caching_started_at = datetime.datetime.fromtimestamp(0)
        self.hero_1.actions.current_action.bundle_id = self.hero_2.actions.current_action.bundle_id
        self.hero_2.ui_caching_started_at = datetime.datetime.fromtimestamp(0)

        self.assertTrue(self.hero_1.saved_at > self.hero_2.saved_at)
        self.assertFalse(self.hero_1.is_ui_caching_required)
        self.assertFalse(self.hero_2.is_ui_caching_required)
        self.assertTrue(hero_3.is_ui_caching_required)

        self.assertEqual(self.storage._get_bundles_to_save(), set([self.bundle_2_id]))

        self.storage.process_turn()

        with mock.patch('dext.common.utils.cache.set_many') as set_many:
            with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as save_hero_data:
                with mock.patch('the_tale.game.heroes.objects.Hero.ui_info') as ui_info:
                    self.storage.save_changed_data()

        self.assertEqual(set_many.call_count, 1)
        self.assertEqual(save_hero_data.call_count, 2)
        self.assertEqual(ui_info.call_count, 1)
        self.assertEqual(ui_info.call_args, mock.call(actual_guaranteed=True, old_info=None))


    def test_merge_bundles(self):

        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3])

        storage.merge_bundles([555, 666], 777)

        self.assertEqual(storage.bundles_to_accounts, {777: set([1, 2, 3])})


    def test_merge_bundles__in_existed_bundle(self):

        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3])
        storage.bundles_to_accounts[777] = set([4, 5])

        storage.merge_bundles([555, 666], 777)

        self.assertEqual(storage.bundles_to_accounts, {777: set([1, 2, 3, 4, 5])})

    def test_unmerge_bundles__in_existed_bundle(self):
        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3])
        storage.bundles_to_accounts[777] = set([4, 5])

        storage.unmerge_bundles(4, 777, 666)

        self.assertEqual(storage.bundles_to_accounts, {555: set([1, 2]),
                                                       666: set([3, 4]),
                                                       777: set([5])})

    def test_unmerge_bundles__last_account_in_bundle(self):
        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3])
        storage.bundles_to_accounts[777] = set([4, 5])

        storage.unmerge_bundles(3, 666, 555)

        self.assertEqual(storage.bundles_to_accounts, {555: set([1, 2, 3]),
                                                       777: set([4, 5])})

    def test_unmerge_bundles(self):
        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3])
        storage.bundles_to_accounts[777] = set([4, 5])

        storage.unmerge_bundles(4, 777, 888)

        self.assertEqual(storage.bundles_to_accounts, {555: set([1, 2]),
                                                       666: set([3]),
                                                       777: set([5]),
                                                       888: set([4])})


    def test_save_bundle_data(self):

        storage = LogicStorage()

        storage.bundles_to_accounts[555] = set([1, 2])
        storage.bundles_to_accounts[666] = set([3, 7, 9])
        storage.bundles_to_accounts[777] = set([4, 5])

        storage.accounts_to_heroes = {1: mock.Mock(id=1),
                                      2: mock.Mock(id=2),
                                      3: mock.Mock(id=3),
                                      4: mock.Mock(id=4),
                                      5: mock.Mock(id=5),
                                      7: mock.Mock(id=7),
                                      9: mock.Mock(id=9)}

        with mock.patch('the_tale.game.logic_storage.LogicStorage._save_hero_data') as _save_hero_data:
            with mock.patch('the_tale.game.logic_storage.LogicStorage.process_cache_queue') as process_cache_queue:
                storage.save_bundle_data(666)

        self.assertEqual(_save_hero_data.call_count, 3)
        self.assertEqual(storage.cache_queue, set([3, 7, 9]))
        self.assertEqual(process_cache_queue.call_count, 1)

        self.assertEqual(set(call[0][0] for call in _save_hero_data.call_args_list), set([3, 7, 9]))
class InPlaceActionTest(testcase.TestCase, ActionEventsTestsMixin):
    def setUp(self):
        super(InPlaceActionTest, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]
        self.action_idl = self.hero.actions.current_action

        self.hero._model.pos_previous_place_id = None  # test setting prevouse place in action constructor

        self.action_inplace = prototypes.ActionInPlacePrototype.create(
            hero=self.hero)

        self.action_event = self.action_inplace

    def test_create(self):
        self.assertEqual(self.hero.position.previous_place,
                         self.hero.position.place)

        self.assertEqual(self.action_idl.leader, False)
        self.assertEqual(self.action_inplace.leader, True)
        self.assertEqual(self.action_inplace.bundle_id,
                         self.action_idl.bundle_id)

        self.storage._test_save()

    def test_instant_heal_in_resort(self):
        self.hero.health = 1
        self.hero.position.place.modifier = Resort(self.hero.position.place)
        old_messages_len = len(self.hero.messages.messages)
        prototypes.ActionInPlacePrototype.create(hero=self.hero)
        self.assertEqual(self.hero.health, self.hero.max_health)
        self.assertEqual(len(self.hero.messages.messages),
                         old_messages_len + 1)
        self.storage._test_save()

    def test_no_instant_heal_in_resort(self):
        self.hero.health = self.hero.max_health
        self.hero.position.place.modifier = Resort(self.hero.position.place)
        old_messages_len = len(self.hero.messages.messages)
        prototypes.ActionInPlacePrototype.create(hero=self.hero)
        self.assertEqual(self.hero.health, self.hero.max_health)
        self.assertEqual(len(self.hero.messages.messages), old_messages_len)
        self.storage._test_save()

    def test_companion_heal_in_resort__no_companion(self):
        self.assertEqual(self.hero.companion, None)

        self.hero.position.place.modifier = Resort(self.hero.position.place)

        prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.messages.messages[-1].key, None)
        self.storage._test_save()

    def test_companion_heal_in_resort__healed_companion(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.assertEqual(self.hero.companion.health,
                         self.hero.companion.max_health)

        self.hero.position.place.modifier = Resort(self.hero.position.place)

        prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertFalse(self.hero.messages.messages[-1].key.
                         is_ACTION_INPLACE_COMPANION_HEAL)

        self.storage._test_save()

    def test_companion_heal_in_resort__damaged_companion(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.hero.companion.health = 1

        self.hero.position.place.modifier = Resort(self.hero.position.place)

        with self.check_increased(lambda: self.hero.companion.health):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertTrue(self.hero.messages.messages[-1].key.
                        is_ACTION_INPLACE_COMPANION_HEAL)

        self.storage._test_save()

    def test_instant_energy_regen_in_holy_city(self):
        self.hero._model.energy = 0
        self.hero._model.pos_previous_place_id = None

        self.hero.position.place.modifier = HolyCity(self.hero.position.place)

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_delta(lambda: len(self.hero.messages.messages), 1):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.energy,
                         c.ANGEL_ENERGY_INSTANT_REGENERATION_IN_PLACE)

        self.storage._test_save()

    def test_instant_energy_regen_in_holy_city__maximum_energy(self):
        self.hero._model.energy = self.hero.energy_maximum
        self.hero._model.pos_previous_place_id = None

        self.hero.position.place.modifier = HolyCity(self.hero.position.place)

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_not_changed(lambda: len(self.hero.messages.messages)):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.energy, self.hero.energy_maximum)

        self.storage._test_save()

    def test_instant_energy_regen_in_holy_city__no_regen(self):
        self.hero._model.energy = 0
        self.hero._model.pos_previous_place_id = None

        self.hero.position.place.modifier = None

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_not_changed(lambda: len(self.hero.messages.messages)):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.energy, 0)

        self.storage._test_save()

    def test_instant_energy_regen_in_holy_city__place_not_changed(self):
        self.hero._model.energy = 0
        self.hero.position.place.modifier = HolyCity(self.hero.position.place)
        self.hero.position.visit_current_place()

        self.assertEqual(self.hero.position.place,
                         self.hero.position.previous_place)

        with self.check_not_changed(lambda: len(self.hero.messages.messages)):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.energy, 0)

        self.storage._test_save()

    @mock.patch('the_tale.game.map.places.prototypes.PlacePrototype.tax', 0.2)
    def test_tax(self):
        self.hero._model.money = 100
        self.hero._model.pos_previous_place_id = None

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_delta(lambda: len(self.hero.messages.messages), 1):
            with self.check_delta(lambda: self.hero.statistics.money_spend,
                                  20):
                with self.check_delta(
                        lambda: self.hero.statistics.money_spend_for_tax, 20):
                    prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.money, 80)

        self.storage._test_save()

    @mock.patch('the_tale.game.map.places.prototypes.PlacePrototype.tax', 0.2)
    def test_tax__no_money(self):
        self.hero._model.money = 0
        self.hero._model.pos_previous_place_id = None

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_delta(lambda: len(self.hero.messages.messages), 1):
            with self.check_delta(lambda: self.hero.statistics.money_spend, 0):
                with self.check_delta(
                        lambda: self.hero.statistics.money_spend_for_tax, 0):
                    prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.money, 0)

        self.storage._test_save()

    @mock.patch('the_tale.game.map.places.prototypes.PlacePrototype.tax', 0.0)
    def test_tax__no_tax(self):
        self.hero._model.money = 100
        self.hero._model.pos_previous_place_id = None

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_delta(lambda: self.hero.statistics.money_spend, 0):
            with self.check_delta(
                    lambda: self.hero.statistics.money_spend_for_tax, 0):
                prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.money, 100)

        self.storage._test_save()

    @mock.patch('the_tale.game.map.places.prototypes.PlacePrototype.tax', 0.2)
    def test_tax__place_not_changed(self):
        self.hero._model.money = 100

        self.hero.position.visit_current_place()
        self.assertEqual(self.hero.position.place,
                         self.hero.position.previous_place)

        with self.check_delta(lambda: len(self.hero.messages.messages), 0):
            with self.check_delta(lambda: self.hero.statistics.money_spend, 0):
                with self.check_delta(
                        lambda: self.hero.statistics.money_spend_for_tax, 0):
                    prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertEqual(self.hero.money, 100)

        self.storage._test_save()

    @mock.patch(
        'the_tale.game.balance.constants.PLACE_HABITS_EVENT_PROBABILITY', 1.0)
    def test_habit_event(self):
        from the_tale.game.relations import HABIT_HONOR_INTERVAL, HABIT_PEACEFULNESS_INTERVAL

        for honor in HABIT_HONOR_INTERVAL.records:
            for peacefulness in HABIT_PEACEFULNESS_INTERVAL.records:

                self.hero.diary.clear()

                self.hero._model.pos_previous_place_id = None
                self.assertNotEqual(self.hero.position.place,
                                    self.hero.position.previous_place)

                with mock.patch(
                        'the_tale.game.map.places.habits.Honor.interval',
                        honor):
                    with mock.patch(
                            'the_tale.game.map.places.habits.Peacefulness.interval',
                            peacefulness):
                        with self.check_delta(self.hero.diary.messages_number,
                                              1):
                            prototypes.ActionInPlacePrototype.create(
                                hero=self.hero)

        self.storage._test_save()

    @mock.patch(
        'the_tale.game.balance.constants.PLACE_HABITS_EVENT_PROBABILITY', 0.0)
    def test_habit_event__no_event(self):
        self.hero._model.pos_previous_place_id = None

        self.assertNotEqual(self.hero.position.place,
                            self.hero.position.previous_place)

        with self.check_not_changed(lambda: len(self.hero.diary.messages)):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.storage._test_save()

    @mock.patch(
        'the_tale.game.balance.constants.PLACE_HABITS_EVENT_PROBABILITY', 1.0)
    def test_habit_event__not_visit(self):
        self.assertEqual(self.hero.position.place,
                         self.hero.position.previous_place)

        with self.check_not_changed(lambda: len(self.hero.diary.messages)):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.storage._test_save()

    def test_processed(self):
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 1)
        self.assertEqual(self.hero.actions.current_action, self.action_idl)
        self.storage._test_save()

    def test_regenerate_energy_action_create(self):
        self.hero.preferences.set_energy_regeneration_type(
            e.ANGEL_ENERGY_REGENERATION_TYPES.PRAY)
        self.hero.last_energy_regeneration_at_turn -= max([
            f.angel_energy_regeneration_delay(energy_regeneration_type)
            for energy_regeneration_type in
            c.ANGEL_ENERGY_REGENERATION_STEPS.keys()
        ])
        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 3)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionRegenerateEnergyPrototype.TYPE)
        self.storage._test_save()

    def test_regenerate_energy_action_not_create_for_sacrifice(self):
        self.hero.preferences.set_energy_regeneration_type(
            e.ANGEL_ENERGY_REGENERATION_TYPES.SACRIFICE)
        self.hero.last_energy_regeneration_at_turn -= max([
            f.angel_energy_regeneration_delay(energy_regeneration_type)
            for energy_regeneration_type in
            c.ANGEL_ENERGY_REGENERATION_STEPS.keys()
        ])
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 1)
        self.assertEqual(self.hero.actions.current_action, self.action_idl)
        self.storage._test_save()

    def test_heal_action_create(self):
        self.hero.health = 1
        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 3)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionRestPrototype.TYPE)
        self.storage._test_save()

    @mock.patch('the_tale.game.companions.objects.Companion.need_heal', True)
    def test_heal_companion_action_create(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 3)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionHealCompanionPrototype.TYPE)
        self.assertEqual(
            self.action_inplace.state,
            prototypes.ActionInPlacePrototype.STATE.HEALING_COMPANION)
        self.storage._test_save()

        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionInPlacePrototype.TYPE)
        self.storage._test_save()

    @mock.patch('the_tale.game.companions.objects.Companion.need_heal', True)
    def test_heal_companion_action_create__no_companion(self):
        self.assertEqual(self.hero.companion, None)

        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 1)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionIdlenessPrototype.TYPE)
        self.storage._test_save()

    def test_trade_action_create(self):

        for i in xrange(
                int(c.MAX_BAG_SIZE * c.BAG_SIZE_TO_SELL_LOOT_FRACTION) + 1):
            artifact = artifacts_storage.generate_artifact_from_list(
                artifacts_storage.loot, 1, rarity=RARITY.NORMAL)
            self.hero.bag.put_artifact(artifact)

        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 3)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionTradingPrototype.TYPE)

        self.storage._test_save()

    def test_equip_action_create(self):
        artifact = artifacts_storage.generate_artifact_from_list(
            artifacts_storage.artifacts, 1, rarity=RARITY.NORMAL)
        artifact.power = Power(666, 666)
        self.hero.bag.put_artifact(artifact)

        self.storage.process_turn()
        self.assertEqual(len(self.hero.actions.actions_list), 3)
        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionEquippingPrototype.TYPE)

        self.storage._test_save()

    def test_full(self):

        current_time = TimePrototype.get_current_time()

        while len(self.hero.actions.actions_list) != 1:
            self.storage.process_turn()
            current_time.increment_turn()

        self.assertTrue(self.action_idl.leader)

        self.storage._test_save()
class InPlaceActionSpendMoneyTest(testcase.TestCase):
    def setUp(self):
        super(InPlaceActionSpendMoneyTest, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user')

        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account_id))
        self.hero = self.storage.accounts_to_heroes[account_id]
        self.action_idl = self.hero.actions.current_action

        self.action_inplace = prototypes.ActionInPlacePrototype.create(
            hero=self.hero)

    def test_no_money(self):

        self.hero._model.money = 1
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 1)
        self.assertEqual(self.hero.statistics.money_spend, 0)
        self.storage._test_save()

    def test_instant_heal(self):
        while not self.hero.next_spending.is_INSTANT_HEAL:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        self.hero._model.money = money + 666
        self.hero.health = 1
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 666)
        self.assertEqual(self.hero.health, self.hero.max_health)

        self.assertEqual(self.hero.statistics.money_spend, money)
        self.assertEqual(self.hero.statistics.money_spend_for_heal, money)
        self.storage._test_save()

    def test_instant_heal__too_much_health(self):
        while not self.hero.next_spending.is_INSTANT_HEAL:
            self.hero.switch_spending()

        money = self.hero.spend_amount
        health = (self.hero.max_health *
                  c.SPEND_MONEY_FOR_HEAL_HEALTH_FRACTION) + 1

        self.hero._model.money = money + 666
        self.hero.health = health
        self.storage.process_turn()
        self.assertTrue(self.hero.money, money + 666)
        self.assertEqual(self.hero.health, health)

        self.assertEqual(self.hero.statistics.money_spend, 0)
        self.assertEqual(self.hero.statistics.money_spend_for_heal, 0)
        self.storage._test_save()

    def test_instant_heal__low_health(self):
        while not self.hero.next_spending.is_INSTANT_HEAL:
            self.hero.switch_spending()

        money = self.hero.spend_amount
        health = (self.hero.max_health *
                  c.SPEND_MONEY_FOR_HEAL_HEALTH_FRACTION) - 1

        self.hero._model.money = money
        self.hero.health = health
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)
        self.assertEqual(self.hero.health, self.hero.max_health)

        self.assertEqual(self.hero.statistics.money_spend, money)
        self.assertEqual(self.hero.statistics.money_spend_for_heal, money)
        self.storage._test_save()

    def test_bying_artifact_with_hero_preferences(self):
        while not self.hero.next_spending.is_BUYING_ARTIFACT:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        self.assertEqual(self.hero.statistics.money_spend, 0)
        self.assertEqual(self.hero.statistics.money_spend_for_artifacts, 0)
        self.assertEqual(self.hero.statistics.money_earned_from_artifacts, 0)

        #unequip all arefact
        self.hero.equipment._remove_all()
        # self.hero.preferences.set_equipment_slot(EQUIPMENT_SLOT.PLATE)
        self.hero.save()

        #buy artifact
        self.hero._model.money = money
        self.storage.process_turn()
        self.assertTrue(self.hero.money < 1)
        self.assertEqual(len(self.hero.bag.items()), 0)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_artifacts,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.artifacts_had, 1)

        # # hero must not buy artifact in preferences slot, he has special quest for this
        # self.assertEqual(self.hero.equipment.get(EQUIPMENT_SLOT.PLATE), None)
        # self.storage._test_save()

    def test_bying_artifact_without_change(self):
        while not self.hero.next_spending.is_BUYING_ARTIFACT:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        self.assertEqual(self.hero.statistics.money_spend, 0)
        self.assertEqual(self.hero.statistics.money_spend_for_artifacts, 0)
        self.assertEqual(self.hero.statistics.money_earned_from_artifacts, 0)

        #unequip all arefact
        self.hero.equipment._remove_all()
        self.hero.save()

        #buy artifact
        self.hero._model.money = money

        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)
        self.assertEqual(len(self.hero.bag.items()), 0)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_artifacts,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.artifacts_had, 1)
        self.storage._test_save()

    def test_bying_artifact_with_change(self):
        while not self.hero.next_spending.is_BUYING_ARTIFACT:
            self.hero.switch_spending()

        # fill all slots with artifacts
        self.hero.equipment.test_equip_in_all_slots(
            artifacts_storage.generate_artifact_from_list(
                artifacts_storage.artifacts,
                self.hero.level,
                rarity=RARITY.NORMAL))

        money = self.hero.spend_amount

        #buy artifact
        self.hero._model.money = money

        self.assertEqual(self.hero.statistics.money_spend, 0)
        self.assertEqual(self.hero.statistics.money_spend_for_artifacts, 0)
        self.assertEqual(self.hero.statistics.money_earned_from_artifacts, 0)

        self.storage.process_turn()
        self.assertTrue(self.hero.money > 0)
        self.assertEqual(len(self.hero.bag.items()), 0)

        self.assertTrue(
            self.hero.statistics.money_spend > money - self.hero.money)
        self.assertTrue(
            self.hero.statistics.money_spend_for_artifacts > money -
            self.hero.money)
        self.assertEqual(self.hero.statistics.artifacts_had, 1)
        self.assertTrue(self.hero.statistics.money_earned_from_artifacts > 0)
        self.storage._test_save()

    def test_not_bying_artifact__when_has_equip_candidates_in_bag(self):
        while not self.hero.next_spending.is_BUYING_ARTIFACT:
            self.hero.switch_spending()

        # fill all slots with artifacts
        self.hero.equipment.test_equip_in_all_slots(
            artifacts_storage.generate_artifact_from_list(
                artifacts_storage.artifacts,
                self.hero.level,
                rarity=RARITY.NORMAL))

        money = self.hero.spend_amount
        self.hero._model.money = money

        self.hero.bag.put_artifact(
            artifacts_storage.generate_artifact_from_list(
                artifacts_storage.artifacts, 666, rarity=RARITY.EPIC))

        with self.check_not_changed(lambda: self.hero.statistics.money_spend):
            with self.check_not_changed(
                    lambda: self.hero.statistics.money_spend_for_artifacts):
                with self.check_not_changed(lambda: self.hero.statistics.
                                            money_earned_from_artifacts):
                    with self.check_not_changed(
                            lambda: self.hero.statistics.artifacts_had):
                        with self.check_not_changed(
                                lambda: self.hero.bag.occupation):
                            self.storage.process_turn()

    def test_sharpening_artifact(self):
        while not self.hero.next_spending.is_SHARPENING_ARTIFACT:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        old_power = self.hero.power.clone()

        self.hero._model.money = money
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)
        self.assertEqual(old_power.total() + 1, self.hero.power.total())

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_sharpening,
                         money - self.hero.money)
        self.storage._test_save()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_upgrade_prefered_slot',
        True)
    def test_sharpening_artifact_with_hero_preferences(self):
        while not self.hero.next_spending.is_SHARPENING_ARTIFACT:
            self.hero.switch_spending()

        self.hero.preferences.set_equipment_slot(
            heroes_relations.EQUIPMENT_SLOT.PLATE)
        self.hero._model.level = 666  # enshure that equipment power will be less than max allowerd _power
        self.hero.save()

        money = self.hero.spend_amount

        old_power = self.hero.power.clone()
        old_plate_power = self.hero.equipment.get(
            heroes_relations.EQUIPMENT_SLOT.PLATE).power.clone()

        self.hero._model.money = money
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)
        self.assertEqual(old_power.total() + 1, self.hero.power.total())
        self.assertEqual(
            old_plate_power.total() + 1,
            self.hero.equipment.get(
                heroes_relations.EQUIPMENT_SLOT.PLATE).power.total())

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_sharpening,
                         money - self.hero.money)
        self.storage._test_save()

    def test_repair_artifact(self):
        for artifact in self.hero.equipment.values():
            artifact.integrity = artifact.max_integrity

        test_artifact = artifact
        test_artifact.integrity = 0

        while not self.hero.next_spending.is_REPAIRING_ARTIFACT:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        self.hero._model.money = money
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)

        self.assertEqual(test_artifact.integrity, test_artifact.max_integrity)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_repairing,
                         money - self.hero.money)
        self.storage._test_save()

    def test_useless(self):
        while not self.hero.next_spending.is_USELESS:
            self.hero.switch_spending()

        money = self.hero.spend_amount
        self.hero._model.money = money
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_useless,
                         money - self.hero.money)
        self.storage._test_save()

    def test_impact(self):
        while not self.hero.next_spending.is_IMPACT:
            self.hero.switch_spending()

        money = self.hero.spend_amount
        self.hero._model.money = money

        with mock.patch(
                'the_tale.game.persons.prototypes.PersonPrototype.cmd_change_power'
        ) as cmd_change_power:
            self.storage.process_turn()

        self.assertEqual(cmd_change_power.call_count, 0)

        self.assertEqual(self.hero.money, 0)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_impact,
                         money - self.hero.money)
        self.storage._test_save()

    def test_impact__can_change_power(self):
        while not self.hero.next_spending.is_IMPACT:
            self.hero.switch_spending()

        money = self.hero.spend_amount
        self.hero._model.money = money

        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.can_change_person_power',
                lambda self, person: True):
            with mock.patch(
                    'the_tale.game.persons.prototypes.PersonPrototype.cmd_change_power'
            ) as cmd_change_power:
                self.storage.process_turn()

        self.assertEqual(cmd_change_power.call_count, 1)

        self.assertEqual(self.hero.money, 0)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_impact,
                         money - self.hero.money)
        self.storage._test_save()

    def test_experience(self):
        while not self.hero.next_spending.is_EXPERIENCE:
            self.hero.switch_spending()

        money = self.hero.spend_amount
        self.hero._model.money = money
        self.storage.process_turn()
        self.assertEqual(self.hero.money, 0)

        self.assertEqual(self.hero.statistics.money_spend,
                         money - self.hero.money)
        self.assertEqual(self.hero.statistics.money_spend_for_experience,
                         money - self.hero.money)
        self.storage._test_save()

    def test_heal_companion(self):
        self.companion_record = companions_logic.create_random_companion_record(
            'companion', state=companions_relations.STATE.ENABLED)
        self.hero.set_companion(
            companions_logic.create_companion(self.companion_record))

        self.hero.companion.health = 1

        while not self.hero.next_spending.is_HEAL_COMPANION:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        self.hero._model.money = money + 666

        with self.check_increased(lambda: self.hero.companion.health):
            with self.check_delta(lambda: self.hero.money, -money):
                self.storage.process_turn()

        self.assertEqual(self.hero.statistics.money_spend, money)
        self.assertEqual(self.hero.statistics.money_spend_for_companions,
                         money)

        self.storage._test_save()

    def test_healed_companion(self):
        self.companion_record = companions_logic.create_random_companion_record(
            'companion', state=companions_relations.STATE.ENABLED)
        self.hero.set_companion(
            companions_logic.create_companion(self.companion_record))

        self.hero.companion.health = self.hero.companion.max_health

        while not self.hero.next_spending.is_HEAL_COMPANION:
            self.hero.switch_spending()

        money = self.hero.spend_amount

        self.hero._model.money = money + 666

        with self.check_not_changed(lambda: self.hero.statistics.money_spend):
            with self.check_not_changed(
                    lambda: self.hero.statistics.money_spend_for_companions):
                with self.check_not_changed(lambda: self.hero.money):
                    self.storage.process_turn()

        self.storage._test_save()

    def test_heal_companion__no_companion(self):
        self.assertEqual(self.hero.companion, None)

        self.hero._model.next_spending = heroes_relations.ITEMS_OF_EXPENDITURE.HEAL_COMPANION

        money = self.hero.spend_amount

        self.hero._model.money = money + 666

        with self.check_not_changed(lambda: self.hero.statistics.money_spend):
            with self.check_not_changed(
                    lambda: self.hero.statistics.money_spend_for_companions):
                with self.check_not_changed(lambda: self.hero.money):
                    self.storage.process_turn()
Exemple #35
0
    def test_remove_action__metaaction(self):
        bundle_id = 666

        meta_action_battle = meta_actions.ArenaPvP1x1.create(self.storage, self.hero_1, self.hero_2)

        proxy_action_1 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_1, _bundle_id=bundle_id, meta_action=meta_action_battle)
        proxy_action_2 = actions_prototypes.ActionMetaProxyPrototype.create(hero=self.hero_2, _bundle_id=bundle_id, meta_action=meta_action_battle)

        self.assertEqual(len(self.storage.meta_actions), 1)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 1)
        self.assertEqual(self.storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1),
                                                                                            LogicStorage.get_action_uid(proxy_action_2)]))

        self.storage.remove_action(proxy_action_2)

        self.assertEqual(len(self.storage.meta_actions), 1)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 1)
        self.assertEqual(self.storage.meta_actions_to_actions[meta_action_battle.uid], set([LogicStorage.get_action_uid(proxy_action_1)]))

        self.storage.remove_action(proxy_action_1)

        self.assertEqual(len(self.storage.meta_actions), 0)
        self.assertEqual(len(self.storage.meta_actions_to_actions), 0)
Exemple #36
0
class UseAbilityTasksTests(TestCase):

    def setUp(self):
        super(UseAbilityTasksTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.task = UseAbilityTask(processor_id=ABILITY_TYPE.HELP.value,
                                   hero_id=self.hero.id,
                                   data={'hero_id': self.hero.id})

    def test_create(self):
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.UNPROCESSED)

    def test_serialization(self):
        self.assertEqual(self.task.serialize(), UseAbilityTask.deserialize(self.task.serialize()).serialize())

    def test_response_data(self):
        self.assertEqual(self.task.processed_data, {})

    def test_banned(self):
        self.hero.ban_state_end_at = datetime.datetime.now() + datetime.timedelta(days=1)
        heroes_logic.save_hero(self.hero)
        self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.ERROR)
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.BANNED)

    def test_process_no_energy(self):
        self.hero.energy = 0
        self.hero.energy_bonus = 0
        heroes_logic.save_hero(self.hero)
        self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.ERROR)
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.HERO_CONDITIONS_NOT_PASSED)

    def test_process_can_not_process(self):

        with mock.patch('the_tale.game.abilities.deck.help.Help.use', lambda self, task, storage, pvp_balancer, highlevel: (ComplexChangeTask.RESULT.FAILED, None, ())):
            self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.ERROR)
            self.assertEqual(self.task.state, ComplexChangeTask.STATE.CAN_NOT_PROCESS)

    def test_process_success(self):
        self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.SUCCESS)
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.PROCESSED)

    def test_process_second_step_success(self):

        with mock.patch('the_tale.game.abilities.deck.help.Help.use', lambda self, task, storage, pvp_balancer, highlevel: (ComplexChangeTask.RESULT.CONTINUE, ComplexChangeTask.STEP.HIGHLEVEL, ())):
            self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.CONTINUE)

        self.assertTrue(self.task.step.is_HIGHLEVEL)
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.UNPROCESSED)

        self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.SUCCESS)
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.PROCESSED)


    def test_process_second_step_error(self):

        with mock.patch('the_tale.game.abilities.deck.help.Help.use', lambda self, task, storage, pvp_balancer, highlevel: (ComplexChangeTask.RESULT.CONTINUE, ComplexChangeTask.STEP.HIGHLEVEL, ())):
            self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.CONTINUE)

        self.assertTrue(self.task.step.is_HIGHLEVEL)
        self.assertEqual(self.task.state, ComplexChangeTask.STATE.UNPROCESSED)

        with mock.patch('the_tale.game.abilities.deck.help.Help.use', lambda self, task, storage, pvp_balancer, highlevel: (ComplexChangeTask.RESULT.FAILED, None, ())):
            self.assertEqual(self.task.process(FakePostpondTaskPrototype(), self.storage), POSTPONED_TASK_LOGIC_RESULT.ERROR)

        self.assertEqual(self.task.state, ComplexChangeTask.STATE.CAN_NOT_PROCESS)
Exemple #37
0
class PrototypesTests(TestCase):
    def setUp(self):
        super(PrototypesTests, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user_1',
                                                      '*****@*****.**',
                                                      '111111')

        self.account = AccountPrototype.get_by_id(account_id)
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.ability = ABILITIES[ABILITY_TYPE.HELP]()

        self.task_data = {}

    def test_process_no_energy(self):
        self.hero.energy = 0
        self.hero.energy_bonus = 0
        heroes_logic.save_hero(self.hero)
        self.assertFalse(
            self.ability.check_hero_conditions(self.hero, self.task_data))

    @mock.patch('the_tale.game.abilities.relations.ABILITY_TYPE.HELP.cost', 0)
    def test_process_no_energy__no_cost(self):
        self.hero.energy = 0
        self.hero.energy_bonus = 0
        heroes_logic.save_hero(self.hero)
        self.assertTrue(
            self.ability.check_hero_conditions(self.hero, self.task_data))

    @mock.patch('the_tale.game.heroes.objects.Hero.energy_discount', 1)
    def test_process_energy_discount(self):
        self.hero.energy = ABILITY_TYPE.HELP.cost - 1
        self.hero.energy_bonus = 0
        heroes_logic.save_hero(self.hero)
        self.assertTrue(
            self.ability.check_hero_conditions(self.hero, self.task_data))

    @mock.patch('the_tale.game.heroes.objects.Hero.energy_discount', 1)
    def test_process_energy_discount__no_energy(self):
        self.hero.energy = ABILITY_TYPE.HELP.cost - 2
        self.hero.energy_bonus = 0
        heroes_logic.save_hero(self.hero)

        self.assertFalse(
            self.ability.check_hero_conditions(self.hero, self.task_data))

    @mock.patch('the_tale.game.heroes.objects.Hero.energy_discount', 100)
    def test_process_energy_discount__limit_1(self):
        self.hero.energy = 2
        self.hero.energy_bonus = 0
        heroes_logic.save_hero(self.hero)

        self.assertTrue(
            self.ability.check_hero_conditions(self.hero, self.task_data))

        self.ability.hero_actions(self.hero, self.task_data)

        self.assertEqual(self.hero.energy, 1)

    def test_process_bonus_energy(self):
        self.hero.energy = 0
        self.hero.add_energy_bonus(100)
        heroes_logic.save_hero(self.hero)

        self.assertTrue(
            self.ability.check_hero_conditions(self.hero, self.task_data))

    def test_process_energy(self):
        self.hero.energy = self.hero.energy_maximum
        heroes_logic.save_hero(self.hero)

        self.assertTrue(
            self.ability.check_hero_conditions(self.hero, self.task_data))

        self.ability.hero_actions(self.hero, self.task_data)

        self.assertTrue(self.hero.energy < self.hero.energy_maximum)
Exemple #38
0
class ArenaPvP1x1Test(testcase.TestCase, PvPTestsMixin):
    def setUp(self):
        super(ArenaPvP1x1Test, self).setUp()

        create_test_map()

        self.account_1 = self.accounts_factory.create_account()
        self.account_2 = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)
        self.storage.load_account_data(self.account_2)

        self.hero_1 = self.storage.accounts_to_heroes[self.account_1.id]
        self.hero_2 = self.storage.accounts_to_heroes[self.account_2.id]

        # for test data reset
        self.hero_1.health = self.hero_1.max_health / 2
        self.hero_1.pvp.set_advantage(1)
        self.hero_1.pvp.set_effectiveness(0.5)

        # for test data reset
        self.hero_2.pvp.set_advantage(1)
        self.hero_2.pvp.set_effectiveness(0.5)

        self.battle_1 = self.pvp_create_battle(self.account_1, self.account_2,
                                               BATTLE_1X1_STATE.PROCESSING)
        self.battle_1.calculate_rating = True
        self.battle_1.save()

        self.battle_2 = self.pvp_create_battle(self.account_2, self.account_1,
                                               BATTLE_1X1_STATE.PROCESSING)
        self.battle_2.calculate_rating = True
        self.battle_2.save()

        self.meta_action_battle = meta_actions.ArenaPvP1x1.create(
            self.storage, self.hero_1, self.hero_2)
        self.meta_action_battle.set_storage(self.storage)

    def test_serialization(self):
        self.assertEqual(
            self.meta_action_battle.serialize(),
            meta_actions.ArenaPvP1x1.deserialize(
                self.meta_action_battle.serialize()).serialize())

    def test_initialization(self):
        self.assertTrue(self.meta_action_battle.storage)

        self.assertEqual(self.meta_action_battle.hero_1, self.hero_1)
        self.assertEqual(self.meta_action_battle.hero_2, self.hero_2)

        self.assertEqual(
            self.meta_action_battle.uid,
            '%s#%d#%d' % (self.meta_action_battle.TYPE.value, self.hero_1.id,
                          self.hero_2.id))

        # test reset of pvp_data
        self.assertEqual(self.meta_action_battle.hero_1.health,
                         self.hero_1.max_health)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.advantage, 0)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.effectiveness,
                         c.PVP_EFFECTIVENESS_INITIAL)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.energy, 0)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.energy_speed, 1)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.turn_advantage, 0)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.turn_effectiveness,
                         c.PVP_EFFECTIVENESS_INITIAL)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.turn_energy, 0)
        self.assertEqual(self.meta_action_battle.hero_1.pvp.turn_energy_speed,
                         1)
        self.assertTrue(self.meta_action_battle.hero_1_context.
                        pvp_advantage_strike_damage > 0)

        self.assertEqual(self.meta_action_battle.hero_2.health,
                         self.hero_2.max_health)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.advantage, 0)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.effectiveness,
                         c.PVP_EFFECTIVENESS_INITIAL)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.energy, 0)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.energy_speed, 1)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.turn_advantage, 0)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.turn_effectiveness,
                         c.PVP_EFFECTIVENESS_INITIAL)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.turn_energy, 0)
        self.assertEqual(self.meta_action_battle.hero_2.pvp.turn_energy_speed,
                         1)
        self.assertTrue(self.meta_action_battle.hero_2_context.
                        pvp_advantage_strike_damage > 0)

    def test_one_hero_killed(self):
        current_time = TimePrototype.get_current_time()
        self.hero_1.health = 0
        self.meta_action_battle.process()
        self.assertEqual(self.meta_action_battle.state,
                         meta_actions.ArenaPvP1x1.STATE.BATTLE_ENDING)
        current_time.increment_turn()
        self.meta_action_battle.process()

        self.assertEqual(self.meta_action_battle.state,
                         meta_actions.ArenaPvP1x1.STATE.PROCESSED)
        self.assertTrue(self.hero_1.is_alive and self.hero_2.is_alive)
        self.assertEqual(self.hero_1.health, self.hero_1.max_health / 2)
        self.assertEqual(self.hero_2.health, self.hero_2.max_health)

    def check_hero_pvp_statistics(self, hero, battles, victories, draws,
                                  defeats):
        self.assertEqual(hero.statistics.pvp_battles_1x1_number, battles)
        self.assertEqual(hero.statistics.pvp_battles_1x1_victories, victories)
        self.assertEqual(hero.statistics.pvp_battles_1x1_draws, draws)
        self.assertEqual(hero.statistics.pvp_battles_1x1_defeats, defeats)

    def _end_battle(self, hero_1_health, hero_2_health):
        self.hero_1.health = hero_1_health
        self.hero_2.health = hero_2_health
        current_time = TimePrototype.get_current_time()
        self.meta_action_battle.process()
        current_time.increment_turn()
        self.meta_action_battle.process()

    def test_hero_1_win(self):
        self._end_battle(hero_1_health=self.hero_1.max_health, hero_2_health=0)

        self.assertEqual(Battle1x1Prototype._model_class.objects.all().count(),
                         0)

        self.check_hero_pvp_statistics(self.hero_1, 1, 1, 0, 0)
        self.check_hero_pvp_statistics(self.hero_2, 1, 0, 0, 1)

    def test_hero_2_win(self):
        self._end_battle(hero_1_health=0, hero_2_health=self.hero_2.max_health)

        self.assertEqual(Battle1x1Prototype._model_class.objects.all().count(),
                         0)

        self.check_hero_pvp_statistics(self.hero_1, 1, 0, 0, 1)
        self.check_hero_pvp_statistics(self.hero_2, 1, 1, 0, 0)

    def test_draw(self):
        self._end_battle(hero_1_health=0, hero_2_health=0)

        self.assertEqual(Battle1x1Prototype._model_class.objects.all().count(),
                         0)

        self.check_hero_pvp_statistics(self.hero_1, 1, 0, 1, 0)
        self.check_hero_pvp_statistics(self.hero_2, 1, 0, 1, 0)

    @mock.patch(
        'the_tale.game.pvp.prototypes.Battle1x1Prototype.calculate_rating',
        False)
    def test_hero_1_win_no_stats(self):
        self._end_battle(hero_1_health=self.hero_1.max_health, hero_2_health=0)

        self.check_hero_pvp_statistics(self.hero_1, 0, 0, 0, 0)
        self.check_hero_pvp_statistics(self.hero_2, 0, 0, 0, 0)

    @mock.patch(
        'the_tale.game.pvp.prototypes.Battle1x1Prototype.calculate_rating',
        False)
    def test_hero_2_win_no_stats(self):
        self._end_battle(hero_1_health=0, hero_2_health=self.hero_1.max_health)

        self.check_hero_pvp_statistics(self.hero_1, 0, 0, 0, 0)
        self.check_hero_pvp_statistics(self.hero_2, 0, 0, 0, 0)

    @mock.patch(
        'the_tale.game.pvp.prototypes.Battle1x1Prototype.calculate_rating',
        False)
    def test_draw_no_stats(self):
        self._end_battle(hero_1_health=0, hero_2_health=0)

        self.check_hero_pvp_statistics(self.hero_1, 0, 0, 0, 0)
        self.check_hero_pvp_statistics(self.hero_2, 0, 0, 0, 0)

    def test_second_process_call_in_one_turn(self):

        with mock.patch(
                'the_tale.game.actions.meta_actions.ArenaPvP1x1._process'
        ) as meta_action_process_counter:
            self.meta_action_battle.process()
            self.meta_action_battle.process()

        self.assertEqual(meta_action_process_counter.call_count, 1)

    def test_update_hero_pvp_info(self):
        self.hero_2.pvp.set_effectiveness(50)

        self.meta_action_battle.update_hero_pvp_info(self.hero_2)
        self.assertTrue(self.hero_2.pvp.energy > self.hero_1.pvp.energy)

        self.assertTrue(0 < self.hero_2.pvp.effectiveness < 50)

    # rename quest to fixt segmentation fault
    def test_z_advantage_after_turn(self):
        self.hero_1.pvp.set_effectiveness(50)
        self.hero_2.pvp.set_effectiveness(25)

        self.meta_action_battle.process()

        self.assertTrue(self.hero_1.pvp.advantage > 0)
        self.assertTrue(self.hero_2.pvp.advantage < 0)

    def test_full_battle(self):
        current_time = TimePrototype.get_current_time()

        self.assertEqual(
            Battle1x1.objects.filter(
                state=BATTLE_1X1_STATE.PROCESSING).count(), 2)

        while self.meta_action_battle.state != meta_actions.ArenaPvP1x1.STATE.PROCESSED:
            self.meta_action_battle.process()
            current_time.increment_turn()

        self.assertEqual(self.meta_action_battle.state,
                         meta_actions.ArenaPvP1x1.STATE.PROCESSED)
        self.assertTrue(self.hero_1.is_alive and self.hero_2.is_alive)
        self.assertEqual(self.hero_1.health, self.hero_1.max_health / 2)
        self.assertEqual(self.hero_2.health, self.hero_2.max_health)

        self.assertEqual(Battle1x1.objects.all().count(), 0)
        self.assertEqual(Battle1x1Result.objects.all().count(), 1)

        battle_result = Battle1x1Result.objects.all()[0]

        self.assertNotEqual(battle_result.participant_1_id,
                            battle_result.participant_2_id)

    def test_get_bot_pvp_properties(self):
        properties = self.meta_action_battle.bot_pvp_properties

        self.assertEqual(set(properties.keys()),
                         set(('ability_chance', 'priorities')))
        self.assertTrue(0 < properties['ability_chance'] <= 1)
        self.assertEqual(set(properties['priorities']), set(ABILITIES.keys()))

        for ability_priority in properties['priorities']:
            self.assertTrue(ability_priority > 0)

    def test_process_bot_called__hero_1(self):
        self.hero_1._model.is_bot = True

        with mock.patch(
                'the_tale.game.actions.meta_actions.ArenaPvP1x1.process_bot'
        ) as process_bot:
            self.meta_action_battle.process()

        self.assertEqual(process_bot.call_count, 1)
        self.assertEqual(process_bot.call_args[1]['bot'].id, self.hero_1.id)
        self.assertEqual(process_bot.call_args[1]['enemy'].id, self.hero_2.id)

    def test_process_bot_called__hero_2(self):
        self.hero_2._model.is_bot = True

        with mock.patch(
                'the_tale.game.actions.meta_actions.ArenaPvP1x1.process_bot'
        ) as process_bot:
            self.meta_action_battle.process()

        self.assertEqual(process_bot.call_count, 1)
        self.assertEqual(process_bot.call_args[1]['bot'].id, self.hero_2.id)
        self.assertEqual(process_bot.call_args[1]['enemy'].id, self.hero_1.id)

    def test_process_bot_called__use_ability(self):
        self.hero_1._model.is_bot = True
        self.hero_1.pvp.set_energy(10)

        properties = self.meta_action_battle.bot_pvp_properties
        properties['ability_chance'] = 1.0

        self.hero_2.pvp.set_energy_speed(
            2)  # flame abilitie will not be used, if enemy energy speed is 1

        self.meta_action_battle.process()

        self.assertTrue(self.hero_1.pvp.energy in (1, 2))

    def test_initialize_bots__bot_is_second(self):
        account_1 = self.accounts_factory.create_account()
        account_2 = self.accounts_factory.create_account(is_bot=True)

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        hero_1._model.level = 50
        self.assertEqual(hero_2.level, 1)

        meta_actions.ArenaPvP1x1.create(storage, hero_1, hero_2)

        self.assertEqual(hero_2.level, 50)
        self.assertTrue(len(hero_2.abilities.all) > 1)
        self.assertEqual(hero_2.health, hero_2.max_health)

    def test_initialize_bots__bot_is_first(self):
        account_1 = self.accounts_factory.create_account(is_bot=True)
        account_2 = self.accounts_factory.create_account()

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        hero_2._model.level = 50
        self.assertEqual(hero_1.level, 1)

        meta_actions.ArenaPvP1x1.create(storage, hero_1, hero_2)

        self.assertEqual(hero_1.level, 50)
        self.assertTrue(len(hero_1.abilities.all) > 1)
        self.assertEqual(hero_1.health, hero_1.max_health)

    def test_initialize_bots__second_create(self):
        account_1 = self.accounts_factory.create_account()
        account_2 = self.accounts_factory.create_account(is_bot=True)

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        hero_1._model.level = 50
        self.assertEqual(hero_2.level, 1)

        self.pvp_create_battle(account_1, account_2,
                               BATTLE_1X1_STATE.PROCESSING)
        self.pvp_create_battle(account_2, account_1,
                               BATTLE_1X1_STATE.PROCESSING)

        meta_action = meta_actions.ArenaPvP1x1.create(storage, hero_1, hero_2)
        meta_action.process_battle_ending()

        meta_actions.ArenaPvP1x1.create(storage, hero_1, hero_2)

        self.assertEqual(hero_2.level, 50)
        self.assertTrue(len(hero_2.abilities.all) > 1)
        self.assertEqual(hero_2.health, hero_2.max_health)

    def test_process_bot__flame_ability_not_used(self):
        account_1 = self.accounts_factory.create_account(is_bot=True)
        account_2 = self.accounts_factory.create_account()

        storage = LogicStorage()
        storage.load_account_data(account_1)
        storage.load_account_data(account_2)

        hero_1 = storage.accounts_to_heroes[account_1.id]
        hero_2 = storage.accounts_to_heroes[account_2.id]

        self.meta_action_battle.bot_pvp_properties = {
            'priorities': {
                Flame.TYPE: 1
            },
            'ability_chance': 1
        }

        self.assertEqual(hero_2.pvp.energy_speed, 1)

        with mock.patch('the_tale.game.pvp.abilities.Flame.use') as use:
            for i in xrange(100):
                self.meta_action_battle.process_bot(hero_1, hero_2)

        self.assertEqual(use.call_count, 0)
Exemple #39
0
class UsePvPAbilityTests(testcase.TestCase):
    def setUp(self):
        super(UsePvPAbilityTests, self).setUp()

        self.p1, self.p2, self.p3 = create_test_map()

        result, account_1_id, bundle_id = register_user(
            'test_user', '*****@*****.**', '111111')
        result, account_2_id, bundle_id = register_user(
            'test_user_2', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_id(account_1_id)
        self.account_2 = AccountPrototype.get_by_id(account_2_id)

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)
        self.storage.load_account_data(self.account_2)

        self.hero_1 = self.storage.accounts_to_heroes[self.account_1.id]
        self.hero_2 = self.storage.accounts_to_heroes[self.account_2.id]

        self.battle = Battle1x1Prototype.create(self.account_1)
        self.battle.set_enemy(self.account_2)
        self.battle.save()

        self.ability = random.choice(ABILITIES.values())

        self.task = UsePvPAbilityTask(battle_id=self.battle.id,
                                      account_id=self.account_1.id,
                                      ability_id=self.ability.TYPE)

    def test_create(self):
        self.assertEqual(self.task.state,
                         USE_PVP_ABILITY_TASK_STATE.UNPROCESSED)
        self.assertEqual(self.task.battle_id, self.battle.id)
        self.assertEqual(self.task.account_id, self.account_1.id)
        self.assertEqual(self.task.ability_id, self.ability.TYPE)

    def test_serialize(self):
        self.assertEqual(
            self.task.serialize(),
            UsePvPAbilityTask.deserialize(self.task.serialize()).serialize())

    def test_process_battle_not_found(self):
        Battle1x1Prototype._db_all().delete()
        self.task.process(FakePostpondTaskPrototype(), self.storage)
        self.assertEqual(self.task.state,
                         USE_PVP_ABILITY_TASK_STATE.BATTLE_FINISHED)

    def test_process_hero_not_found(self):
        self.storage.release_account_data(self.account_1.id)
        self.task.process(FakePostpondTaskPrototype(), self.storage)
        self.assertEqual(self.task.state,
                         USE_PVP_ABILITY_TASK_STATE.HERO_NOT_FOUND)

    def test_wrong_ability_id(self):
        task = UsePvPAbilityTask(battle_id=self.battle.id,
                                 account_id=self.account_1.id,
                                 ability_id=u'wrong_ability_id')
        task.process(FakePostpondTaskPrototype(), self.storage)
        self.assertEqual(task.state,
                         USE_PVP_ABILITY_TASK_STATE.WRONG_ABILITY_ID)

    def test_no_resources(self):
        self.task.process(FakePostpondTaskPrototype(), self.storage)
        self.assertEqual(self.task.state, USE_PVP_ABILITY_TASK_STATE.NO_ENERGY)

    def test_process_success(self):
        self.hero_1.pvp.set_energy(1)

        old_hero_1_last_message = self.hero_1.messages.messages[-1]
        old_hero_2_last_message = self.hero_2.messages.messages[-1]

        self.assertEqual(
            self.task.process(FakePostpondTaskPrototype(), self.storage),
            POSTPONED_TASK_LOGIC_RESULT.SUCCESS)
        self.assertEqual(self.task.state, USE_PVP_ABILITY_TASK_STATE.PROCESSED)

        self.assertNotEqual(old_hero_1_last_message,
                            self.hero_1.messages.messages[-1])
        self.assertNotEqual(old_hero_2_last_message,
                            self.hero_2.messages.messages[-1])

        self.assertNotEqual(old_hero_1_last_message.ui_info()[-1],
                            self.hero_1.messages.ui_info()[-1][-1])
        self.assertEqual(old_hero_2_last_message.ui_info()[-1],
                         self.hero_2.messages.ui_info()[-1][-1])

        self.assertEqual(self.hero_1.pvp.energy, 0)
Exemple #40
0
class CanCombineCardsTests(testcase.TestCase):
    def setUp(self):
        super(CanCombineCardsTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.card__add_power_common_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)
        self.card__add_power_common_2 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)
        self.card__add_power_common_3 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)
        self.card__add_power_common_4 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)

        self.card__add_bonus_energy_common_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_COMMON)

        self.card__add_bonus_energy_legendary_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_LEGENDARY)
        self.card__add_bonus_energy_legendary_2 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_LEGENDARY)
        self.card__add_bonus_energy_legendary_3 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_LEGENDARY)

        self.card__add_gold_common_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_GOLD_COMMON)

        self.hero.cards.add_card(self.card__add_power_common_1)
        self.hero.cards.add_card(self.card__add_power_common_2)
        self.hero.cards.add_card(self.card__add_power_common_3)
        self.hero.cards.add_card(self.card__add_power_common_4)

        self.hero.cards.add_card(self.card__add_bonus_energy_common_1)

        self.hero.cards.add_card(self.card__add_bonus_energy_legendary_1)
        self.hero.cards.add_card(self.card__add_bonus_energy_legendary_2)
        self.hero.cards.add_card(self.card__add_bonus_energy_legendary_3)

        self.hero.cards.add_card(self.card__add_gold_common_1)

    def test_not_enough_cards(self):
        self.assertTrue(
            self.hero.cards.can_combine_cards([]).is_NOT_ENOUGH_CARDS)
        self.assertTrue(
            self.hero.cards.can_combine_cards([]).is_NOT_ENOUGH_CARDS)
        self.assertFalse(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid
            ]).is_NOT_ENOUGH_CARDS)

    def test_to_many_cards(self):
        self.assertFalse(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid
            ]).is_TO_MANY_CARDS)
        self.assertFalse(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid,
                self.card__add_power_common_3.uid
            ]).is_TO_MANY_CARDS)
        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid,
                self.card__add_power_common_3.uid,
                self.card__add_power_common_4.uid
            ]).is_TO_MANY_CARDS)

    def test_equal_rarity_required(self):
        self.assertNotEqual(
            self.card__add_power_common_1.type.rarity,
            self.card__add_bonus_energy_legendary_1.type.rarity)
        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_bonus_energy_legendary_1.uid
            ]).is_EQUAL_RARITY_REQUIRED)

        self.assertEqual(self.card__add_power_common_1.type.rarity,
                         self.card__add_bonus_energy_common_1.type.rarity)
        self.assertFalse(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_bonus_energy_common_1.uid
            ]).is_EQUAL_RARITY_REQUIRED)

    def test_legendary_x3(self):
        self.assertTrue(
            self.card__add_bonus_energy_legendary_1.type.rarity.is_LEGENDARY)
        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_bonus_energy_legendary_1.uid,
                self.card__add_bonus_energy_legendary_2.uid,
                self.card__add_bonus_energy_legendary_3.uid
            ]).is_LEGENDARY_X3_DISALLOWED)
        self.assertFalse(
            self.hero.cards.can_combine_cards([
                self.card__add_bonus_energy_legendary_1.uid,
                self.card__add_bonus_energy_legendary_2.uid
            ]).is_LEGENDARY_X3_DISALLOWED)

    def test_no_cards(self):
        self.assertTrue(
            self.hero.cards.can_combine_cards([666, 667]).is_HAS_NO_CARDS)
        self.assertTrue(
            self.hero.cards.can_combine_cards(
                [self.card__add_power_common_1.uid, 667]).is_HAS_NO_CARDS)
        self.assertTrue(
            self.hero.cards.can_combine_cards(
                [666, self.card__add_power_common_1.uid]).is_HAS_NO_CARDS)

    def test_allowed(self):
        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid,
            ]).is_ALLOWED)

        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid,
                self.card__add_bonus_energy_common_1.uid
            ]).is_ALLOWED)

        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_power_common_2.uid,
                self.card__add_power_common_3.uid
            ]).is_ALLOWED)

        self.assertTrue(
            self.hero.cards.can_combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_bonus_energy_common_1.uid,
                self.card__add_gold_common_1.uid
            ]).is_ALLOWED)
class MoveNearActionTest(testcase.TestCase):

    def setUp(self):
        super(MoveNearActionTest, self).setUp()

        self.p1, self.p2, self.p3 = create_test_map()

        result, account_id, bundle_id = register_user('test_user')

        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account_id))
        self.hero = self.storage.accounts_to_heroes[account_id]
        self.action_idl = self.hero.actions.current_action

        self.hero.position.set_place(self.p1)

        self.action_move = prototypes.ActionMoveNearPlacePrototype.create(hero=self.hero, place=self.p1, back=False)
    def tearDown(self):
        pass


    def test_create(self):
        self.assertEqual(self.action_idl.leader, False)
        self.assertEqual(self.action_move.leader, True)
        self.assertEqual(self.action_move.bundle_id, self.action_idl.bundle_id)
        self.storage._test_save()

    def test_get_destination_coordinates(self):

        self.assertTrue(len(self.p1.nearest_cells) > 3) # two coordinates will be in coordinates set, other will not

        x_1, y_1 = self.p1.nearest_cells[0]
        map_info_storage.item.terrain[y_1][x_1] = TERRAIN.WATER_DEEP

        x_2, y_2 = self.p1.nearest_cells[1]
        map_info_storage.item.terrain[y_2][x_2] = TERRAIN.WATER_DEEP

        coordinates = set()

        for i in xrange(100):
            coordinates.add(prototypes.ActionMoveNearPlacePrototype._get_destination_coordinates(back=False, place=self.p1, terrains=(TERRAIN.WATER_DEEP,)))

        self.assertEqual(coordinates, set([(x_1, y_1), (x_2, y_2)]))


    def test_get_destination_coordinates__no_terrains(self):

        self.assertTrue(len(self.p1.nearest_cells) > 3) # two coordinates will be in coordinates set, other will not

        coordinates = set()

        for i in xrange(100):
            coordinates.add(prototypes.ActionMoveNearPlacePrototype._get_destination_coordinates(back=False, place=self.p1, terrains=(TERRAIN.WATER_DEEP,)))

        self.assertEqual(coordinates, set(self.p1.nearest_cells))

    def test_get_destination_coordinates__back(self):

        self.assertTrue(len(self.p1.nearest_cells) > 3) # two coordinates will be in coordinates set, other will not

        x_1, y_1 = self.p1.nearest_cells[0]
        map_info_storage.item.terrain[y_1][x_1] = TERRAIN.WATER_DEEP

        x_2, y_2 = self.p1.nearest_cells[1]
        map_info_storage.item.terrain[y_2][x_2] = TERRAIN.WATER_DEEP

        coordinates = set()

        for i in xrange(100):
            coordinates.add(prototypes.ActionMoveNearPlacePrototype._get_destination_coordinates(back=True, place=self.p1, terrains=(TERRAIN.WATER_DEEP,)))

        self.assertEqual(coordinates, set([(self.p1.x, self.p1.y)]))


    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed', lambda self: False)
    def test_processed(self):

        current_time = TimePrototype.get_current_time()

        self.storage.process_turn(continue_steps_if_needed=False)

        x, y = self.action_move.get_destination()
        self.hero.position.set_coordinates(x, y, x, y, percents=1)

        current_time.increment_turn()
        self.storage.process_turn(continue_steps_if_needed=False)

        # can end in field or in start place
        self.assertTrue(self.hero.actions.current_action.TYPE in [prototypes.ActionIdlenessPrototype.TYPE, prototypes.ActionInPlacePrototype.TYPE])
        self.assertTrue(self.hero.position.is_walking or self.hero.position.place)

        self.storage._test_save()


    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed', lambda self: False)
    def test_not_ready(self):
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(len(self.hero.actions.actions_list), 2)
        self.assertEqual(self.hero.actions.current_action, self.action_move)
        self.assertTrue(self.hero.position.is_walking or self.hero.position.place) # can end in start place
        self.storage._test_save()

    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed', lambda self: False)
    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.subroad_len', lambda self: 1)
    def test_modify_speed(self):

        with mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.modify_move_speed',
                        mock.Mock(return_value=self.hero.move_speed)) as speed_modifier_call_counter:
            self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(speed_modifier_call_counter.call_count, 1)

    def test_full_move_and_back(self):

        current_time = TimePrototype.get_current_time()

        while len(self.hero.actions.actions_list) != 1:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionIdlenessPrototype.TYPE)
        self.assertTrue(self.hero.position.is_walking or self.hero.position.place)  # can end in start place

        prototypes.ActionMoveNearPlacePrototype.create(hero=self.hero, place=self.p1, back=True)
        while self.hero.position.place is None or self.hero.position.place.id != self.p1.id:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionInPlacePrototype.TYPE)
        self.assertTrue(not self.hero.position.is_walking)
        self.storage._test_save()

    def test_move_change_place_coordinates_and_back(self):

        current_time = TimePrototype.get_current_time()

        while len(self.hero.actions.actions_list) != 1:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionIdlenessPrototype.TYPE)
        self.assertTrue(self.hero.position.is_walking or self.hero.position.place)  # can end in start place

        prototypes.ActionMoveNearPlacePrototype.create(hero=self.hero, place=self.p1, back=True)
        self.p1._model.x = self.p1.x + 1
        self.p1._model.y = self.p1.y + 1
        self.p1.save()

        while self.hero.position.place is None or self.hero.position.place.id != self.p1.id:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionInPlacePrototype.TYPE)
        self.assertTrue(not self.hero.position.is_walking)
        self.storage._test_save()

    def test_full(self):

        current_time = TimePrototype.get_current_time()

        while len(self.hero.actions.actions_list) != 1:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertTrue(self.action_idl.leader)

        self.storage._test_save()

    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed', lambda self: True)
    def test_battle(self):
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionBattlePvE1x1Prototype.TYPE)
        self.storage._test_save()

    def test_regenerate_energy_on_move(self):
        self.hero.preferences.set_energy_regeneration_type(e.ANGEL_ENERGY_REGENERATION_TYPES.PRAY)
        self.hero.last_energy_regeneration_at_turn -= max([f.angel_energy_regeneration_delay(energy_regeneration_type)
                                                           for energy_regeneration_type in c.ANGEL_ENERGY_REGENERATION_STEPS.keys()])
        self.action_move.state = self.action_move.STATE.MOVING

        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionRegenerateEnergyPrototype.TYPE)

        self.storage._test_save()

    def test_not_regenerate_energy_on_move_for_sacrifice(self):
        self.hero.preferences.set_energy_regeneration_type(e.ANGEL_ENERGY_REGENERATION_TYPES.SACRIFICE)
        self.hero.last_energy_regeneration_at_turn -= max([f.angel_energy_regeneration_delay(energy_regeneration_type)
                                                           for energy_regeneration_type in c.ANGEL_ENERGY_REGENERATION_STEPS.keys()])
        self.action_move.state = self.action_move.STATE.MOVING

        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertNotEqual(self.hero.actions.current_action.TYPE, prototypes.ActionRegenerateEnergyPrototype.TYPE)

        self.storage._test_save()


    def test_regenerate_energy_after_battle_for_sacrifice(self):
        self.hero.preferences.set_energy_regeneration_type(e.ANGEL_ENERGY_REGENERATION_TYPES.SACRIFICE)
        self.hero.last_energy_regeneration_at_turn -= max([f.angel_energy_regeneration_delay(energy_regeneration_type)
                                                           for energy_regeneration_type in c.ANGEL_ENERGY_REGENERATION_STEPS.keys()])
        self.action_move.state = self.action_move.STATE.BATTLE

        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionRegenerateEnergyPrototype.TYPE)

        self.storage._test_save()


    def test_rest(self):
        self.hero.health = 1
        self.action_move.state = self.action_move.STATE.BATTLE
        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionRestPrototype.TYPE)
        self.storage._test_save()


    @mock.patch('the_tale.game.companions.objects.Companion.need_heal', True)
    def test_heal_companion(self):

        self.action_move.state = self.action_move.STATE.BATTLE

        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionMoveNearPlacePrototype.TYPE)

        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionHealCompanionPrototype.TYPE)
        self.assertEqual(self.action_move.state, prototypes.ActionMoveNearPlacePrototype.STATE.HEALING_COMPANION)

        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionMoveNearPlacePrototype.TYPE)
        self.assertEqual(self.hero.actions.current_action.state, prototypes.ActionMoveNearPlacePrototype.STATE.HEALING_COMPANION)


    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed', lambda self: False)
    @mock.patch('the_tale.game.heroes.prototypes.HeroPrototype.can_companion_say_wisdom', lambda hero: True)
    @mock.patch('the_tale.game.balance.constants.COMPANIONS_EXP_PER_MOVE_PROBABILITY', 1.0)
    def test_companion_say_wisdom(self):
        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))

        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(self.action_move.state, self.action_move.STATE.MOVING)

        with self.check_delta(lambda: self.hero.experience, c.COMPANIONS_EXP_PER_MOVE_GET_EXP):
            self.storage.process_turn(continue_steps_if_needed=False)

        self.assertTrue(self.hero.messages.messages[-1].key.is_COMPANIONS_SAY_WISDOM)

        self.storage._test_save()


    def test_resurrect(self):
        self.hero.kill()
        self.action_move.state = self.action_move.STATE.BATTLE
        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(self.hero.actions.current_action.TYPE, prototypes.ActionResurrectPrototype.TYPE)
        self.storage._test_save()


    @mock.patch('the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed', lambda self: False)
    def test_stop_when_quest_required_replane(self):
        while self.action_move.state != prototypes.ActionMoveNearPlacePrototype.STATE.MOVING:
            self.storage.process_turn(continue_steps_if_needed=False)

        self.assertFalse(self.action_move.replane_required)
        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertEqual(self.action_move.state, prototypes.ActionMoveNearPlacePrototype.STATE.MOVING)
        self.action_move.replane_required = True
        self.storage.process_turn(continue_steps_if_needed=False)

        self.assertEqual(self.action_move.state, prototypes.ActionMoveNearPlacePrototype.STATE.PROCESSED)
Exemple #42
0
class CombineCardsTests(testcase.TestCase):
    def setUp(self):
        super(CombineCardsTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.card__add_power_common_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)
        self.card__add_power_common_2 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)
        self.card__add_power_common_3 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)
        self.card__add_power_common_4 = objects.Card(
            type=relations.CARD_TYPE.ADD_POWER_COMMON)

        self.card__add_bonus_energy_common_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_COMMON)

        self.card__add_bonus_energy_legendary_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_LEGENDARY)
        self.card__add_bonus_energy_legendary_2 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_LEGENDARY)
        self.card__add_bonus_energy_legendary_3 = objects.Card(
            type=relations.CARD_TYPE.ADD_BONUS_ENERGY_LEGENDARY)

        self.card__add_gold_common_1 = objects.Card(
            type=relations.CARD_TYPE.ADD_GOLD_COMMON)

        self.hero.cards.add_card(self.card__add_power_common_1)
        self.hero.cards.add_card(self.card__add_power_common_2)
        self.hero.cards.add_card(self.card__add_power_common_3)
        self.hero.cards.add_card(self.card__add_power_common_4)

        self.hero.cards.add_card(self.card__add_bonus_energy_common_1)

        self.hero.cards.add_card(self.card__add_bonus_energy_legendary_1)
        self.hero.cards.add_card(self.card__add_bonus_energy_legendary_2)
        self.hero.cards.add_card(self.card__add_bonus_energy_legendary_3)

        self.hero.cards.add_card(self.card__add_gold_common_1)

    def test_2_cards(self):
        with self.check_delta(self.hero.cards.cards_count, -1):
            card = self.hero.cards.combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_bonus_energy_common_1.uid
            ])

        self.assertFalse(
            self.hero.cards.has_card(self.card__add_power_common_1.uid))
        self.assertFalse(
            self.hero.cards.has_card(self.card__add_bonus_energy_common_1.uid))
        self.assertTrue(self.hero.cards.has_card(card.uid))

        self.assertNotIn(card.type,
                         (self.card__add_bonus_energy_common_1.type,
                          self.card__add_bonus_energy_common_1.type))
        self.assertTrue(card.type.rarity.is_COMMON)

    def test_3_cards(self):
        with self.check_delta(self.hero.cards.cards_count, -2):
            card = self.hero.cards.combine_cards([
                self.card__add_power_common_1.uid,
                self.card__add_bonus_energy_common_1.uid,
                self.card__add_gold_common_1.uid
            ])

        self.assertFalse(
            self.hero.cards.has_card(self.card__add_power_common_1.uid))
        self.assertFalse(
            self.hero.cards.has_card(self.card__add_bonus_energy_common_1.uid))
        self.assertFalse(
            self.hero.cards.has_card(self.card__add_gold_common_1.uid))

        self.assertNotIn(card.type, (self.card__add_bonus_energy_common_1.type,
                                     self.card__add_bonus_energy_common_1.type,
                                     self.card__add_gold_common_1.type))

        self.assertTrue(self.hero.cards.has_card(card.uid))
        self.assertTrue(card.type.rarity.is_UNCOMMON)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_premium', True)
    def test_auction_availability__not_available__hero_premium(self):
        self.card__add_power_common_1.available_for_auction = True
        self.card__add_bonus_energy_common_1.available_for_auction = False
        self.card__add_gold_common_1.available_for_auction = True

        card = self.hero.cards.combine_cards([
            self.card__add_power_common_1.uid,
            self.card__add_bonus_energy_common_1.uid,
            self.card__add_gold_common_1.uid
        ])

        self.assertFalse(card.available_for_auction)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_premium', True)
    def test_auction_availability__available__hero_premium(self):
        self.card__add_power_common_1.available_for_auction = True
        self.card__add_bonus_energy_common_1.available_for_auction = True
        self.card__add_gold_common_1.available_for_auction = True

        card = self.hero.cards.combine_cards([
            self.card__add_power_common_1.uid,
            self.card__add_bonus_energy_common_1.uid,
            self.card__add_gold_common_1.uid
        ])

        self.assertTrue(card.available_for_auction)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_premium', False)
    def test_auction_availability__not_available__hero_not_premium(self):
        self.card__add_power_common_1.available_for_auction = True
        self.card__add_bonus_energy_common_1.available_for_auction = False
        self.card__add_gold_common_1.available_for_auction = True

        card = self.hero.cards.combine_cards([
            self.card__add_power_common_1.uid,
            self.card__add_bonus_energy_common_1.uid,
            self.card__add_gold_common_1.uid
        ])

        self.assertFalse(card.available_for_auction)

    @mock.patch('the_tale.game.heroes.objects.Hero.is_premium', False)
    def test_auction_availability__available__hero_not_premium(self):
        self.card__add_power_common_1.available_for_auction = True
        self.card__add_bonus_energy_common_1.available_for_auction = True
        self.card__add_gold_common_1.available_for_auction = True

        card = self.hero.cards.combine_cards([
            self.card__add_power_common_1.uid,
            self.card__add_bonus_energy_common_1.uid,
            self.card__add_gold_common_1.uid
        ])

        self.assertTrue(card.available_for_auction)
class GetCompanionMixin(helpers.CardsTestMixin):
    CARD = None

    def setUp(self):
        super(GetCompanionMixin, self).setUp()
        create_test_map()

        self.account_1 = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        for rarity, rarity_abilities in companions_helpers.RARITIES_ABILITIES.items(
        ):
            companions_logic.create_random_companion_record(
                '%s companion' % rarity,
                mode=companions_relations.MODE.AUTOMATIC,
                abilities=rarity_abilities,
                state=companions_relations.STATE.ENABLED)

        self.card = self.CARD.effect.create_card(type=self.CARD,
                                                 available_for_auction=True)

    def test_use(self):

        self.assertEqual(self.hero.companion, None)

        result, step, postsave_actions = self.CARD.effect.use(
            **self.use_attributes(
                storage=self.storage, hero=self.hero, card=self.card))

        self.assertEqual((result, step, postsave_actions),
                         (ComplexChangeTask.RESULT.SUCCESSED,
                          ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(self.hero.companion.record.rarity.card_rarity,
                         self.CARD.rarity)

    def test_use__companion_exists(self):

        old_companion_record = random.choice([
            companion for companion in companions_storage.companions.all()
            if companion.rarity.card_rarity != self.CARD.rarity
        ])

        self.hero.set_companion(
            companions_logic.create_companion(old_companion_record))

        result, step, postsave_actions = self.CARD.effect.use(
            **self.use_attributes(
                storage=self.storage, hero=self.hero, card=self.card))
        self.assertEqual((result, step, postsave_actions),
                         (ComplexChangeTask.RESULT.SUCCESSED,
                          ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(self.hero.companion.record.rarity.card_rarity,
                         self.CARD.rarity)
        self.assertNotEqual(self.hero.companion.record.id,
                            old_companion_record.id)

    def test_available(self):
        self.assertTrue(self.CARD.effect.available(self.CARD))

        for companion in companions_storage.companions.all():
            if companion.rarity.card_rarity == self.CARD.rarity:
                companion.state = companions_relations.STATE.DISABLED

        self.assertFalse(self.CARD.effect.available(self.CARD))
Exemple #44
0
class UseCardTaskTests(testcase.TestCase):
    def setUp(self):
        super(UseCardTaskTests, self).setUp()

        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account = self.accounts_factory.create_account()
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.building_1 = BuildingPrototype.create(
            person=self.place_1.persons[0],
            utg_name=names.generator().get_test_name('building-1-name'))

        environment.deinitialize()
        environment.initialize()

        self.highlevel = environment.workers.highlevel
        self.highlevel.process_initialize(0, 'highlevel')

        self.task_data = {
            'place_id': self.place_1.id,
            'person_id': self.place_1.persons[0].id,
            'building_id': self.building_1.id
        }

    def test_create(self):

        for card_effect in list(effects.EFFECTS.values()):
            card = objects.Card(card_effect.TYPE)
            self.hero.cards.add_card(card)

            with self.check_delta(PostponedTaskPrototype._db_count, 1):
                task = card.activate(self.hero, data=self.task_data)

            self.assertTrue(task.internal_logic.state.is_UNPROCESSED)

    def test_serialization(self):
        card_effect = random.choice(list(effects.EFFECTS.values()))
        card = objects.Card(card_effect.TYPE)
        self.hero.cards.add_card(card)

        task = card.activate(self.hero, data=self.task_data).internal_logic

        self.assertEqual(task.serialize(),
                         UseCardTask.deserialize(task.serialize()).serialize())

    def test_response_data(self):
        card_effect = random.choice(list(effects.EFFECTS.values()))
        card = objects.Card(card_effect.TYPE)
        self.hero.cards.add_card(card)

        with mock.patch.object(
                card_effect, 'use', lambda **kwargs:
            (UseCardTask.RESULT.SUCCESSED, None, ())):
            task = card.activate(self.hero, data=self.task_data).internal_logic
            task.process(FakePostpondTaskPrototype(), self.storage)

        self.assertEqual(task.processed_data, {})

    def test_process_can_not_process(self):

        card_effect = random.choice(list(effects.EFFECTS.values()))
        card = objects.Card(card_effect.TYPE)
        self.hero.cards.add_card(card)

        task = card.activate(self.hero, data=self.task_data).internal_logic

        with mock.patch.object(
                card_effect, 'use', lambda **kwargs:
            (UseCardTask.RESULT.FAILED, None, ())):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.ERROR)
            self.assertEqual(task.state, UseCardTask.STATE.CAN_NOT_PROCESS)

    def test_process_success(self):
        card_effect = random.choice(list(effects.EFFECTS.values()))
        card = objects.Card(card_effect.TYPE)
        self.hero.cards.add_card(card)

        task = card.activate(self.hero, data=self.task_data).internal_logic

        with mock.patch.object(
                card_effect, 'use', lambda **kwargs:
            (UseCardTask.RESULT.SUCCESSED, None, ())):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(),
                             storage=self.storage),
                POSTPONED_TASK_LOGIC_RESULT.SUCCESS)

        self.assertEqual(task.state, UseCardTask.STATE.PROCESSED)

    def test_process_second_step_error(self):

        card_effect = random.choice(list(effects.EFFECTS.values()))
        card = objects.Card(card_effect.TYPE)
        self.hero.cards.add_card(card)

        task = card.activate(self.hero, data=self.task_data).internal_logic

        with mock.patch.object(
                card_effect, 'use', lambda **kwargs:
            (UseCardTask.RESULT.CONTINUE, UseCardTask.STEP.HIGHLEVEL, ())):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.CONTINUE)

        self.assertTrue(task.step.is_HIGHLEVEL)
        self.assertEqual(task.state, UseCardTask.STATE.UNPROCESSED)

        with mock.patch.object(
                card_effect, 'use', lambda **kwargs:
            (UseCardTask.RESULT.FAILED, None, ())):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.ERROR)

        self.assertEqual(task.state, UseCardTask.STATE.CAN_NOT_PROCESS)
class AddPersonPowerMixin(CardsTestMixin):
    CARD = None

    def setUp(self):
        super(AddPersonPowerMixin, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account_1 = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account_1)

        self.hero = self.storage.accounts_to_heroes[self.account_1.id]

        environment.deinitialize()
        environment.initialize()

        self.highlevel = environment.workers.highlevel
        self.highlevel.process_initialize(0, 'highlevel')

    def test_use(self):
        for direction in (-1, 1):
            card = self.CARD.effect.create_card(type=self.CARD,
                                                available_for_auction=True,
                                                direction=direction)

            person = self.place_1.persons[0]

            result, step, postsave_actions = card.effect.use(
                **self.use_attributes(hero=self.hero,
                                      storage=self.storage,
                                      value=person.id,
                                      card=card))

            self.assertEqual((result, step),
                             (ComplexChangeTask.RESULT.CONTINUE,
                              ComplexChangeTask.STEP.HIGHLEVEL))
            self.assertEqual(len(postsave_actions), 1)

            with mock.patch(
                    'the_tale.game.workers.highlevel.Worker.cmd_logic_task'
            ) as highlevel_logic_task_counter:
                postsave_actions[0]()

            self.assertEqual(highlevel_logic_task_counter.call_count, 1)

            with mock.patch(
                    'the_tale.game.persons.logic.PersonPoliticPower.change_power'
            ) as change_power:
                result, step, postsave_actions = self.CARD.effect.use(
                    **self.use_attributes(hero=self.hero,
                                          step=step,
                                          highlevel=self.highlevel,
                                          value=person.id,
                                          card=card))
            self.assertEqual(change_power.call_args_list, [
                mock.call(hero_id=self.hero.id,
                          person=person,
                          power=direction * self.CARD.effect.modificator,
                          has_in_preferences=True)
            ])

            self.assertEqual((result, step, postsave_actions),
                             (ComplexChangeTask.RESULT.SUCCESSED,
                              ComplexChangeTask.STEP.SUCCESS, ()))

    def test_no_person(self):
        for direction in (-1, 1):
            card = self.CARD.effect.create_card(type=self.CARD,
                                                available_for_auction=True,
                                                direction=direction)

            self.assertEqual(
                self.CARD.effect.use(**self.use_attributes(
                    hero=self.hero, value=666, storage=self.storage,
                    card=card)),
                (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR,
                 ()))
Exemple #46
0
class ContainerTests(testcase.TestCase):
    def setUp(self):
        super(ContainerTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.container = self.hero.cards

    def test_initialization(self):
        self.assertEqual(self.container._cards, {})

    def test_serialization(self):
        self.container.add_card(
            objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON))
        self.container.add_card(
            objects.Card(relations.CARD_TYPE.ADD_GOLD_COMMON,
                         available_for_auction=True))

        self.container.change_help_count(5)
        with mock.patch('the_tale.game.heroes.objects.Hero.is_premium', True):
            self.container.change_help_count(3)

        self.assertEqual(
            self.container.serialize(),
            container.CardsContainer.deserialize(
                self.container.serialize()).serialize())

    def test_add_card(self):
        card_1 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON)
        card_2 = objects.Card(relations.CARD_TYPE.ADD_GOLD_COMMON,
                              available_for_auction=True)
        card_3 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_LEGENDARY)

        with mock.patch(
                'the_tale.finances.market.goods_types.BaseGoodType.sync_added_item'
        ) as sync_added_item:
            self.container.add_card(card_1)
            self.container.add_card(card_2)
            self.container.add_card(card_3)

        self.assertEqual(sync_added_item.call_args_list, [
            mock.call(self.account.id, card_1),
            mock.call(self.account.id, card_2),
            mock.call(self.account.id, card_3)
        ])

        self.assertEqual(self.container._cards, {
            card_1.uid: card_1,
            card_2.uid: card_2,
            card_3.uid: card_3
        })

    def test_remove_card(self):
        card_1 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON)
        card_2 = objects.Card(relations.CARD_TYPE.ADD_GOLD_COMMON,
                              available_for_auction=True)

        self.container.add_card(card_1)
        self.container.add_card(card_2)

        with mock.patch(
                'the_tale.finances.market.goods_types.BaseGoodType.sync_removed_item'
        ) as sync_removed_item:
            self.container.remove_card(card_1.uid)

        self.assertEqual(sync_removed_item.call_args_list,
                         [mock.call(self.account.id, card_1)])

        self.assertEqual(self.container._cards, {card_2.uid: card_2})

    def test_card_count(self):
        self.assertEqual(len(list(self.container.all_cards())), 0)

        card_1 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON)
        card_2 = objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON,
                              available_for_auction=True)
        card_3 = objects.Card(relations.CARD_TYPE.ADD_GOLD_COMMON,
                              available_for_auction=True)

        self.container.add_card(card_1)
        self.container.add_card(card_2)
        self.container.add_card(card_3)

        cards_counter = collections.Counter(
            card.type for card in self.container.all_cards())

        self.assertEqual(
            cards_counter.get(relations.CARD_TYPE.KEEPERS_GOODS_COMMON), 2)
        self.assertEqual(
            cards_counter.get(relations.CARD_TYPE.ADD_GOLD_COMMON), 1)
        self.assertEqual(cards_counter.get(relations.CARD_TYPE.ADD_GOLD_RARE),
                         None)

    def test_has_cards(self):
        self.assertFalse(self.container.has_cards)
        self.container.add_card(
            objects.Card(relations.CARD_TYPE.KEEPERS_GOODS_COMMON))
        self.assertTrue(self.container.has_cards)

    def test_change_help_count(self):
        self.assertEqual(self.container.help_count, 0)

        self.container.change_help_count(5)
        self.assertEqual(self.container._help_count, 5)
        self.assertEqual(self.container._premium_help_count, 0)

        with mock.patch('the_tale.game.heroes.objects.Hero.is_premium', True):
            self.container.change_help_count(4)
            self.assertEqual(self.container._help_count, 9)
            self.assertEqual(self.container._premium_help_count, 4)

            self.container.change_help_count(-3)
            self.assertEqual(self.container._help_count, 6)
            self.assertEqual(self.container._premium_help_count, 4)

            self.container.change_help_count(-3)
            self.assertEqual(self.container._help_count, 3)
            self.assertEqual(self.container._premium_help_count, 3)

        self.container.change_help_count(2)
        self.assertEqual(self.container._help_count, 5)
        self.assertEqual(self.container._premium_help_count, 3)

        self.container.change_help_count(-5)
        self.assertEqual(self.container._help_count, 0)
        self.assertEqual(self.container._premium_help_count, 0)

    def test_change_help_count__below_zero(self):
        self.assertRaises(exceptions.HelpCountBelowZero,
                          self.container.change_help_count, -5)
Exemple #47
0
class MoveToActionWithBreaksTest(testcase.TestCase):

    FIRST_BREAK_AT = 0.75

    def setUp(self):
        super(MoveToActionWithBreaksTest, self).setUp()
        self.p1, self.p2, self.p3 = create_test_map()

        account = self.accounts_factory.create_account(is_fast=True)

        self.storage = LogicStorage()
        self.storage.load_account_data(account)
        self.hero = self.storage.accounts_to_heroes[account.id]
        self.action_idl = self.hero.actions.current_action

        self.hero.position.set_place(self.p1)

        self.action_move = prototypes.ActionMoveToPrototype.create(
            hero=self.hero, destination=self.p3, break_at=self.FIRST_BREAK_AT)

    def test_sequence_move(self):

        current_time = TimePrototype.get_current_time()

        while self.hero.actions.current_action != self.action_idl:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(self.hero.position.road.point_1_id, self.p2.id)
        self.assertEqual(self.hero.position.road.point_2_id, self.p3.id)

        real_percents = None

        prototypes.ActionMoveToPrototype.create(hero=self.hero,
                                                destination=self.p1,
                                                break_at=0.9)
        while self.hero.actions.current_action != self.action_idl:
            real_percents = self.hero.actions.current_action.percents
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(round(real_percents, 1), 0.9)

        self.assertEqual(self.hero.position.road.point_1_id, self.p1.id)
        self.assertEqual(self.hero.position.road.point_2_id, self.p2.id)

        prototypes.ActionMoveToPrototype.create(hero=self.hero,
                                                destination=self.p2)
        while self.hero.position.place is None or self.hero.position.place.id != self.p2.id:
            self.storage.process_turn(continue_steps_if_needed=False)
            current_time.increment_turn()

        self.assertEqual(self.hero.actions.current_action.TYPE,
                         prototypes.ActionInPlacePrototype.TYPE)
        self.storage._test_save()

    @mock.patch('the_tale.game.heroes.objects.Hero.is_battle_start_needed',
                lambda self: False)
    def test_teleport_to_place__break_at(self):

        self.storage.process_turn(continue_steps_if_needed=False)

        self.action_move.teleport_to_place(create_inplace_action=True)

        self.assertEqual(self.hero.position.place.id, self.p2.id)

        while not self.hero.actions.current_action.TYPE.is_MOVE_TO:
            self.storage.process_turn(continue_steps_if_needed=False)

        self.storage.process_turn(continue_steps_if_needed=False)
        self.assertTrue(
            self.action_move.teleport_to_place(create_inplace_action=True))

        self.assertNotEqual(self.hero.position.road, None)
        self.assertTrue(self.hero.position.percents < 1)

        self.assertTrue(self.hero.actions.current_action.TYPE.is_MOVE_TO)
        self.assertEqual(self.hero.actions.current_action.percents,
                         self.FIRST_BREAK_AT)

        self.assertTrue(self.action_move.leader)

        self.assertEqual(self.hero.position.place, None)

        self.storage._test_save()

    @mock.patch('the_tale.game.heroes.objects.Hero.is_battle_start_needed',
                lambda self: False)
    def test_teleport_to_end__break_at(self):

        self.storage.process_turn(continue_steps_if_needed=False)

        self.action_move.teleport_to_end()

        self.assertNotEqual(self.hero.position.road, None)
        self.assertTrue(self.hero.position.percents < 1.0)

        self.assertEqual(self.p2.id, self.hero.position.road.point_1_id)
        self.assertEqual(self.p3.id, self.hero.position.road.point_2_id)

        self.assertTrue(self.hero.actions.current_action.TYPE.is_MOVE_TO)
        self.assertEqual(self.hero.actions.current_action.percents,
                         self.FIRST_BREAK_AT)

        self.assertTrue(self.action_move.leader)

        self.storage._test_save()
Exemple #48
0
class GetNewCardTest(testcase.TestCase):
    def setUp(self):
        super(GetNewCardTest, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

    def test_single_card(self):
        self.assertTrue(
            self.hero.cards.has_card(self.hero.cards.get_new_card().uid))

    def test_exclude_not_allowrd_effects(self):
        effects = set()

        companions_models.CompanionRecord.objects.all().delete()
        companions_storage.companions.refresh()

        for rarity, rarity_abilities in companions_helpers.RARITIES_ABILITIES.items(
        ):
            companions_logic.create_random_companion_record(
                '%s companion' % rarity,
                mode=companions_relations.MODE.AUTOMATIC,
                abilities=rarity_abilities,
                state=companions_relations.STATE.ENABLED)

        @classmethod
        def effect_availability(cls):
            return bool(cls.TYPE.value % 2)

        with mock.patch('the_tale.game.cards.effects.BaseEffect.available',
                        effect_availability):
            with mock.patch(
                    'the_tale.game.cards.effects.GetCompanionBase.available',
                    effect_availability):
                for i in range(10000):
                    effects.add(self.hero.cards.get_new_card().effect.TYPE)

        for effect_type in relations.CARD_TYPE.records:
            if effect_type.value % 2 == 0:
                self.assertNotIn(effect_type, effects)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_simple(self):

        rarities = set()

        companions_models.CompanionRecord.objects.all().delete()
        companions_storage.companions.refresh()

        for rarity, rarity_abilities in companions_helpers.RARITIES_ABILITIES.items(
        ):
            companions_logic.create_random_companion_record(
                '%s companion' % rarity,
                mode=companions_relations.MODE.AUTOMATIC,
                abilities=rarity_abilities,
                state=companions_relations.STATE.ENABLED)

        for i in range(len(relations.CARD_TYPE.records) * 10):
            card = self.hero.cards.get_new_card()
            rarities.add(card.type.rarity)

        self.assertTrue(
            len(relations.CARD_TYPE.records) >
            len(set(card.type for card in self.hero.cards.all_cards())) / 2)
        self.assertEqual(rarities, set(relations.RARITY.records))

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: False)
    def test_not_premium(self):

        for i in range(len(relations.CARD_TYPE.records) * 10):
            self.hero.cards.get_new_card()

        for card in self.hero.cards.all_cards():
            self.assertFalse(card.type.availability.is_FOR_PREMIUMS)

    def check_is_next_card_premium(self, help_count, premium_help_count,
                                   result):
        self.hero.cards._help_count = help_count
        self.hero.cards._premium_help_count = premium_help_count
        self.assertEqual(self.hero.cards.is_next_card_premium(), result)

    def test_is_next_card_premium(self):
        self.check_is_next_card_premium(0, 0, False)
        self.check_is_next_card_premium(10, 9, False)
        self.check_is_next_card_premium(10, 10, True)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: False)
    def test_auction_availability_not_specified_not_premium(self):
        self.assertFalse(self.hero.cards.get_new_card().available_for_auction)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_auction_availability_not_specified_premium(self):
        self.assertTrue(self.hero.cards.get_new_card().available_for_auction)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: False)
    def test_auction_availability_false_not_premium(self):
        self.assertFalse(
            self.hero.cards.get_new_card(
                available_for_auction=False).available_for_auction)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_auction_availability_false_premium(self):
        self.assertFalse(
            self.hero.cards.get_new_card(
                available_for_auction=False).available_for_auction)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: False)
    def test_auction_availability_true_not_premium(self):
        self.assertTrue(
            self.hero.cards.get_new_card(
                available_for_auction=True).available_for_auction)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_auction_availability_true_premium(self):
        self.assertTrue(
            self.hero.cards.get_new_card(
                available_for_auction=True).available_for_auction)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_priority(self):
        for i in range(len(relations.CARD_TYPE.records) * 100):
            self.hero.cards.get_new_card()

        rarities = collections.Counter(card.type.rarity
                                       for card in self.hero.cards.all_cards())

        last_rarity_count = 999999999999

        for rarity in relations.RARITY.records:
            self.assertTrue(last_rarity_count >= rarities[rarity])
            last_rarity_count = rarities[rarity]

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_rarity(self):
        for rarity in relations.RARITY.records:
            for i in range(100):
                card = self.hero.cards.get_new_card(rarity=rarity)
                self.assertEqual(card.type.rarity, rarity)

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_exclude(self):
        cards = []

        companions_models.CompanionRecord.objects.all().delete()
        companions_storage.companions.refresh()

        for rarity, rarity_abilities in companions_helpers.RARITIES_ABILITIES.items(
        ):
            companions_logic.create_random_companion_record(
                '%s companion' % rarity,
                mode=companions_relations.MODE.AUTOMATIC,
                abilities=rarity_abilities,
                state=companions_relations.STATE.ENABLED)

        for i in range(
                len([
                    card_type for card_type in relations.CARD_TYPE.records
                    if card_type.in_game
                ])):
            card = self.hero.cards.get_new_card(exclude=cards)
            cards.append(card)
            self.assertTrue(card.type.in_game)

        self.assertEqual(self.hero.cards.get_new_card(exclude=cards), None)

        self.assertEqual(
            set(card.type for card in cards),
            set(card_type for card_type in relations.CARD_TYPE.records
                if card_type.in_game))

    @mock.patch(
        'the_tale.game.cards.container.CardsContainer.is_next_card_premium',
        lambda self: True)
    def test_exclude__different_data(self):
        cards = []

        companions_models.CompanionRecord.objects.all().delete()
        companions_storage.companions.refresh()

        for rarity, rarity_abilities in companions_helpers.RARITIES_ABILITIES.items(
        ):
            companions_logic.create_random_companion_record(
                '%s companion' % rarity,
                mode=companions_relations.MODE.AUTOMATIC,
                abilities=rarity_abilities,
                state=companions_relations.STATE.ENABLED)

        for i in range(
                len([
                    card_type for card_type in relations.CARD_TYPE.records
                    if card_type.in_game
                ])):
            card = self.hero.cards.get_new_card(exclude=cards)
            cards.append(card)
            self.assertTrue(card.type.in_game)

        self.assertEqual(self.hero.cards.get_new_card(exclude=cards), None)

        cards[0].data = {'fake-data': True}
        self.assertEqual(cards[0].type,
                         self.hero.cards.get_new_card(exclude=cards).type)

        self.assertEqual(
            set(card.type for card in cards),
            set(card_type for card_type in relations.CARD_TYPE.records
                if card_type.in_game))
Exemple #49
0
class QuestInfoTests(testcase.TestCase, QuestTestsMixin):
    def setUp(self):
        super(QuestInfoTests, self).setUp()

        self.place_1, self.place_2, self.place_3 = create_test_map()

        result, account_id, bundle_id = register_user('test_user')

        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account_id))
        self.hero = self.storage.accounts_to_heroes[account_id]

        self.action_idl = self.hero.actions.current_action
        self.action_idl.state = self.action_idl.STATE.QUEST

        self.quest = self.create_quest()

        self.start = self.quest.knowledge_base.filter(facts.Start).next()

        with mock.patch('the_tale.game.quests.writers.get_writer',
                        lambda **kwargs: FakeWriter(fake_uid='q', **kwargs)):
            self.quest_info = QuestInfo.construct(
                type=self.start.type,
                uid=self.start.uid,
                knowledge_base=self.quest.knowledge_base,
                hero=self.hero)

    @mock.patch('questgen.quests.quests_base.QuestsBase._available_quests',
                lambda *argv, **kwargs: [QuestWith2ChoicePoints])
    def create_quest(self):
        return self.turn_to_quest(self.storage, self.hero.id)

    def test_construct(self):
        self.assertEqual(self.quest_info.type, self.start.type)
        self.assertEqual(self.quest_info.uid, self.start.uid)
        self.assertEqual(self.quest_info.name,
                         'q_quest_quest_with_2_choice_points_name_5')
        self.assertEqual(self.quest_info.action, '')
        self.assertEqual(self.quest_info.choice, None)
        self.assertEqual(self.quest_info.choice_alternatives, [])
        self.assertTrue(self.quest_info.experience > 0)
        self.assertTrue(self.quest_info.power > 0)
        self.assertEqual(
            set(self.quest_info.actors.keys()),
            set([
                'initiator', 'receiver', 'initiator_position',
                'receiver_position'
            ]))

    def test_serialization(self):
        self.assertEqual(
            self.quest_info.serialize(),
            QuestInfo.deserialize(self.quest_info.serialize()).serialize())

    def test_serialization__bonuses_saved(self):
        self.quest_info.experience_bonus = 666
        self.quest_info.power_bonus = 777
        self.assertEqual(
            self.quest_info.serialize(),
            QuestInfo.deserialize(self.quest_info.serialize()).serialize())

        new_quest_info = QuestInfo.deserialize(self.quest_info.serialize())

        self.assertEqual(new_quest_info.experience_bonus, 666)
        self.assertEqual(new_quest_info.power_bonus, 777)

    def get_choices(self, default=True):
        choice = self.quest.knowledge_base['[ns-0]choice_1']
        options = sorted(
            (o for o in self.quest.knowledge_base.filter(facts.Option)
             if o.state_from == choice.uid),
            key=lambda o: o.uid)
        defaults = [
            facts.ChoicePath(choice=choice.uid,
                             option=options[-1].uid,
                             default=default)
        ]

        return choice, options, defaults

    @mock.patch('the_tale.game.quests.writers.get_writer',
                lambda **kwargs: FakeWriter(fake_uid='q', **kwargs))
    def test_sync_choices(self):

        self.quest_info.sync_choices(self.quest.knowledge_base,
                                     self.quest.hero, *self.get_choices())

        self.assertEqual(
            self.quest_info.choice,
            'q_quest_quest_with_2_choice_points_choice_current_opt_1_1')
        self.assertEqual(
            self.quest_info.choice_alternatives,
            [('#option([ns-0]choice_1, [ns-0]choice_2, opt_2)',
              u'q_quest_quest_with_2_choice_points_choice_variant_opt_2_2')])

    @mock.patch('the_tale.game.quests.writers.get_writer',
                lambda **kwargs: FakeWriter(fake_uid='q', **kwargs))
    def test_sync_choices__no_choice(self):
        self.quest_info.sync_choices(self.quest.knowledge_base,
                                     self.quest.hero, *self.get_choices())

        self.quest_info.sync_choices(knowledge_base=self.quest.knowledge_base,
                                     hero=self.quest.hero,
                                     choice=None,
                                     options=(),
                                     defaults=())

        self.assertEqual(self.quest_info.choice, None)
        self.assertEqual(self.quest_info.choice_alternatives, ())

    @mock.patch('the_tale.game.quests.writers.get_writer',
                lambda **kwargs: FakeWriter(fake_uid='q', **kwargs))
    def test_sync_choices__no_choice_made(self):
        self.quest_info.sync_choices(self.quest.knowledge_base,
                                     self.quest.hero,
                                     *self.get_choices(default=False))

        self.assertEqual(
            self.quest_info.choice,
            'q_quest_quest_with_2_choice_points_choice_current_opt_1_1')
        self.assertEqual(self.quest_info.choice_alternatives, ())

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.reward_modifier', 1.0)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.quest_markers_rewards_bonus',
        lambda self: {
            QUEST_OPTION_MARKERS.HONORABLE: 0.2,
            QUEST_OPTION_MARKERS.DISHONORABLE: 0.3,
            QUEST_OPTION_MARKERS.AGGRESSIVE: 0.4,
            QUEST_OPTION_MARKERS.UNAGGRESSIVE: 0.5
        })
    def test_get_real_reward_scale(self):

        self.assertEqual(self.quest_info.get_real_reward_scale(self.hero, 1.0),
                         1.0)

        self.quest_info.used_markers[QUEST_OPTION_MARKERS.DISHONORABLE] = True
        self.assertEqual(self.quest_info.get_real_reward_scale(self.hero, 1.0),
                         1.3)

        self.quest_info.used_markers[QUEST_OPTION_MARKERS.AGGRESSIVE] = False
        self.assertEqual(self.quest_info.get_real_reward_scale(self.hero, 1.0),
                         1.3 * 1.4)

        self.quest_info.used_markers[QUEST_OPTION_MARKERS.HONORABLE] = False
        self.assertEqual(self.quest_info.get_real_reward_scale(self.hero, 1.0),
                         1.3 * 1.4 * 1.2)

        self.quest_info.used_markers[QUEST_OPTION_MARKERS.UNAGGRESSIVE] = True
        self.assertEqual(self.quest_info.get_real_reward_scale(self.hero, 1.0),
                         1.3 * 1.4 * 1.2 * 1.5)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.experience_modifier', 1)
    def test_ui_info__experience(self):
        experience = self.quest_info.ui_info(self.hero)['experience']

        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.experience_modifier',
                self.hero.experience_modifier * 2):
            self.assertEqual(
                self.quest_info.ui_info(self.hero)['experience'],
                experience * 2)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.experience_modifier', 1)
    def test_ui_info__experience__bonus(self):
        experience = self.quest_info.ui_info(self.hero)['experience']

        self.quest_info.experience_bonus = 100

        self.assertEqual(
            self.quest_info.ui_info(self.hero)['experience'], experience + 100)

        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.experience_modifier',
                self.hero.experience_modifier * 2):
            self.assertEqual(
                self.quest_info.ui_info(self.hero)['experience'],
                experience * 2 + 100)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.politics_power_multiplier',
        lambda *argv, **kwargs: 1)
    def test_ui_info__power(self):
        power = self.quest_info.ui_info(self.hero)['power']

        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.politics_power_multiplier',
                lambda *argv, **kwargs: 2):
            self.assertEqual(
                self.quest_info.ui_info(self.hero)['power'], power * 2)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.politics_power_multiplier',
        lambda *argv, **kwargs: 1)
    def test_ui_info__power__bonus(self):
        power = self.quest_info.ui_info(self.hero)['power']

        self.quest_info.power_bonus = 100

        self.assertEqual(
            self.quest_info.ui_info(self.hero)['power'], power + 100)

        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.politics_power_multiplier',
                lambda *argv, **kwargs: 2):
            self.assertEqual(
                self.quest_info.ui_info(self.hero)['power'], power * 2 + 100)
Exemple #50
0
class CompanionTests(testcase.TestCase):
    def setUp(self):
        super(CompanionTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.companion_record = logic.create_companion_record(
            utg_name=names.generator().get_test_name(),
            description='description',
            type=game_relations.BEING_TYPE.random(),
            max_health=10,
            dedication=relations.DEDICATION.random(),
            archetype=game_relations.ARCHETYPE.random(),
            mode=relations.MODE.random(),
            abilities=abilities_container.Container(),
            communication_verbal=game_relations.COMMUNICATION_VERBAL.random(),
            communication_gestures=game_relations.COMMUNICATION_GESTURES.
            random(),
            communication_telepathic=game_relations.COMMUNICATION_TELEPATHIC.
            random(),
            intellect_level=game_relations.INTELLECT_LEVEL.random(),
            state=relations.STATE.ENABLED)
        self.hero.set_companion(logic.create_companion(self.companion_record))
        self.companion = self.hero.companion

    def test_initialization(self):
        self.assertEqual(self.companion.health, 10)
        self.assertEqual(self.companion.experience, 0)
        self.assertEqual(self.companion.coherence, c.COMPANIONS_MIN_COHERENCE)

    def test_serialization(self):
        self.assertEqual(
            self.companion.serialize(),
            objects.Companion.deserialize(
                self.companion.serialize()).serialize())

    def test_experience_to_next_level(self):
        self.assertEqual(self.companion.experience_to_next_level,
                         f.companions_coherence_for_level(1))

        self.companion.coherence = 5
        self.assertEqual(self.companion.experience_to_next_level,
                         f.companions_coherence_for_level(6))

    def test_experience_to_next_level__max_level(self):
        self.companion.coherence = c.COMPANIONS_MAX_COHERENCE - 1

        with self.check_not_changed(
                lambda: self.companion.experience_to_next_level):
            self.companion.coherence = c.COMPANIONS_MAX_COHERENCE

    def test_add_experience__coherence_speed(self):
        self.companion.coherence = 95

        with self.check_delta(lambda: self.companion.experience, 10):
            self.companion.add_experience(10)

        with mock.patch(
                'the_tale.game.heroes.objects.Hero.companion_coherence_speed',
                2):
            with self.check_delta(lambda: self.companion.experience, 20):
                self.companion.add_experience(10)

    def test_add_experience__level_not_changed(self):
        self.companion.coherence = 5

        with mock.patch(
                'the_tale.game.heroes.objects.Hero.reset_accessors_cache'
        ) as reset_accessors_cache:
            with self.check_not_changed(lambda: self.companion.coherence):
                self.companion.add_experience(1)

        self.assertEqual(reset_accessors_cache.call_count, 0)

        self.assertEqual(self.companion.experience, 1)

    def test_add_experience__level_changed(self):
        self.companion.coherence = 5

        with mock.patch(
                'the_tale.game.heroes.objects.Hero.reset_accessors_cache'
        ) as reset_accessors_cache:
            with self.check_delta(lambda: self.companion.coherence, 1):
                self.companion.add_experience(
                    self.companion.experience_to_next_level + 2)

        self.assertEqual(reset_accessors_cache.call_count, 1)

        self.assertEqual(self.companion.experience, 2)

    def test_add_experience__2_levels_changed(self):
        self.companion.coherence = 5

        with self.check_delta(lambda: self.companion.coherence, 2):
            self.companion.add_experience(
                self.companion.experience_to_next_level +
                f.companions_coherence_for_level(7) + 2)

        self.assertEqual(self.companion.experience, 2)

    @mock.patch('the_tale.game.companions.objects.Companion.max_coherence',
                c.COMPANIONS_MAX_COHERENCE)
    def test_add_experience__max_level(self):
        self.companion.coherence = 1

        self.companion.add_experience(66666666666)

        self.assertEqual(self.companion.coherence, c.COMPANIONS_MAX_COHERENCE)
        self.assertEqual(self.companion.experience,
                         self.companion.experience_to_next_level)

    def test_add_experience__max_level__not_changed(self):
        self.companion.coherence = c.COMPANIONS_MAX_COHERENCE

        with self.check_not_changed(lambda: self.companion.coherence):
            self.companion.add_experience(66666666666)

        self.assertEqual(self.companion.experience,
                         self.companion.experience_to_next_level)

    @mock.patch('the_tale.game.companions.objects.Companion.max_coherence',
                c.COMPANIONS_MAX_COHERENCE / 2)
    def test_add_experience__max_level_restricted(self):
        self.companion.coherence = 1

        self.companion.add_experience(66666666666)

        self.assertEqual(self.companion.coherence,
                         c.COMPANIONS_MAX_COHERENCE / 2)
        self.assertEqual(self.companion.experience,
                         self.companion.experience_to_next_level - 1)

    def test_max_health(self):

        max_health = self.companion.max_health

        with self.check_delta(lambda: max_health, max_health * 0.5):
            with mock.patch(
                    'the_tale.game.heroes.objects.Hero.companion_max_health_multiplier',
                    1.5):
                max_health = self.companion.max_health

    def test_on_accessors_cache_changed(self):
        self.companion.health = 1
        self.companion.on_accessors_cache_changed()
        self.assertEqual(self.companion.health, 1)

        self.companion.health = self.companion.max_health + 1
        self.companion.on_accessors_cache_changed()
        self.assertEqual(self.companion.health, self.companion.max_health)

    def test_max_coherence(self):

        max_coherence = self.companion.max_coherence

        with self.check_delta(lambda: max_coherence, 40):
            with mock.patch(
                    'the_tale.game.heroes.objects.Hero.companion_max_coherence',
                    60):
                max_coherence = self.companion.max_coherence

    def test_coherence_greater_then_maximum(self):

        with mock.patch(
                'the_tale.game.heroes.objects.Hero.companion_max_coherence',
                60):
            self.companion.add_experience(6666666)
            self.assertEqual(self.companion.experience,
                             self.companion.experience_to_next_level - 1)

        self.assertEqual(self.companion.max_coherence, 20)
        self.assertEqual(self.companion.coherence, 60)
        self.assertEqual(self.companion.experience,
                         self.companion.experience_to_next_level - 1)

        self.companion.add_experience(6666666666666)

        self.assertEqual(self.companion.max_coherence, 20)
        self.assertEqual(self.companion.coherence, 60)
        self.assertEqual(self.companion.experience,
                         self.companion.experience_to_next_level - 1)

    def test_modify_attribute(self):
        checked_abilities = [
            ability
            for ability in heroes_companions_abilities.ABILITIES.values()
            if issubclass(
                ability, heroes_companions_abilities._CompanionAbilityModifier)
        ]

        for ability_class in checked_abilities:
            for companion_ability in companions_effects.ABILITIES.records:
                if ability_class.EFFECT_TYPE != companion_ability.effect.TYPE.metatype:
                    continue

                if hasattr(companion_ability.effect,
                           'ABILITY'):  # skip battle abilities
                    continue

                if companion_ability.effect.MODIFIER is None:  # skip complex abilities
                    continue

                self.hero.abilities.reset()
                self.hero.reset_accessors_cache()

                self.companion_record.abilities = abilities_container.Container(
                    start=(companion_ability, ))

                with self.check_changed(
                        lambda: self.companion.modify_attribute(
                            companion_ability.effect.MODIFIER,
                            companion_ability.effect.MODIFIER.default())):
                    self.hero.abilities.add(
                        ability_class.get_id(),
                        random.randint(1, ability_class.MAX_LEVEL))

    def test_actual_coherence(self):
        self.companion.coherence = 50

        with mock.patch(
                'the_tale.game.companions.objects.Companion.max_coherence',
                20):
            self.assertEqual(self.companion.actual_coherence, 20)

        with mock.patch(
                'the_tale.game.companions.objects.Companion.max_coherence',
                70):
            self.assertEqual(self.companion.actual_coherence, 50)

    def test_modification_coherence(self):
        self.companion.coherence = 50

        with mock.patch(
                'the_tale.game.companions.objects.Companion.max_coherence',
                20):
            self.assertEqual(
                self.companion.modification_coherence(
                    heroes_relations.MODIFIERS.COMPANION_MAX_COHERENCE), 50)
            self.assertEqual(
                self.companion.modification_coherence(
                    heroes_relations.MODIFIERS.random(exclude=(
                        heroes_relations.MODIFIERS.COMPANION_MAX_COHERENCE,
                    ))), 20)

        with mock.patch(
                'the_tale.game.companions.objects.Companion.max_coherence',
                70):
            self.assertEqual(
                self.companion.modification_coherence(
                    heroes_relations.MODIFIERS.COMPANION_MAX_COHERENCE), 50)
            self.assertEqual(
                self.companion.modification_coherence(
                    heroes_relations.MODIFIERS.random(exclude=(
                        heroes_relations.MODIFIERS.COMPANION_MAX_COHERENCE,
                    ))), 50)

    @mock.patch('the_tale.game.balance.constants.COMPANIONS_HEALS_IN_HOUR', 1)
    def test_need_heal(self):
        self.companion.healed_at_turn -= c.TURNS_IN_HOUR
        self.companion.health = self.companion.max_health

        self.assertFalse(self.companion.need_heal)

        self.companion.health -= 1

        self.assertTrue(self.companion.need_heal)

    @mock.patch('the_tale.game.balance.constants.COMPANIONS_HEALS_IN_HOUR', 1)
    def test_need_heal__no_time(self):
        self.companion.healed_at_turn -= c.TURNS_IN_HOUR / 2
        self.companion.health = self.companion.max_health

        self.assertFalse(self.companion.need_heal)

        self.companion.health -= 1

        self.assertFalse(self.companion.need_heal)

    def test_defend_in_battle_probability__hero_dedication(self):
        self.hero.set_companion(self.companion)

        with self.check_increased(
                lambda: self.hero.companion.defend_in_battle_probability):
            self.hero.preferences.set_companion_dedication(
                heroes_relations.COMPANION_DEDICATION.EGOISM)

        with self.check_decreased(
                lambda: self.hero.companion.defend_in_battle_probability):
            self.hero.preferences.set_companion_dedication(
                heroes_relations.COMPANION_DEDICATION.NORMAL)

        with self.check_decreased(
                lambda: self.hero.companion.defend_in_battle_probability):
            self.hero.preferences.set_companion_dedication(
                heroes_relations.COMPANION_DEDICATION.ALTRUISM)

    def test_defend_in_battle_probability__companion_dedication(self):
        self.companion_record.dedication = relations.DEDICATION.records[0]
        self.hero.set_companion(self.companion)

        for dedication in relations.DEDICATION.records[1:]:
            with self.check_increased(
                    lambda: self.hero.companion.defend_in_battle_probability):
                self.companion_record.dedication = dedication

    def test_defend_in_battle_probability__coherence(self):
        self.hero.set_companion(self.companion)

        with self.check_increased(
                lambda: self.hero.companion.defend_in_battle_probability):
            self.hero.companion.coherence = 100
Exemple #51
0
class CommonTests(testcase.TestCase):

    def setUp(self):
        super(CommonTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]


    def test_rarities_abilities(self):
        for rarity, rarity_abilities in helpers.RARITIES_ABILITIES.items():
            companion = logic.create_random_companion_record('%s companion' % rarity,
                                                             abilities=rarity_abilities)
            self.assertEqual(companion.rarity, rarity)


    @mock.patch('the_tale.game.companions.objects.Companion.max_coherence', 100)
    @mock.patch('the_tale.game.heroes.habilities.companions.THOUGHTFUL.MULTIPLIER', [1, 1, 1, 1, 1])
    @mock.patch('the_tale.game.heroes.habilities.companions._CompanionHealBase.PROBABILITY', [0, 0, 0, 0, 0])
    def _test_companion_death_speed(self):
        current_time = game_prototypes.TimePrototype.get_current_time()

        companion_record = logic.create_random_companion_record('test companion',
                                                                state=relations.STATE.ENABLED,
                                                                dedication=relations.DEDICATION.BRAVE)#,#,;
                                                                # abilities=abilities_container.Container(start=(effects.ABILITIES.BODYGUARD,)),# effects.ABILITIES.PUNY)),
                                                                # dedication=relations.DEDICATION.HEROIC)
                                                                # abilities=abilities_container.Container(common=(effects.ABILITIES.COWARDLY, )),
                                                                # dedication=relations.DEDICATION.INDECISIVE)
        companion = logic.create_companion(companion_record)
        self.hero.set_companion(companion)
        # self.hero.preferences.set_companion_dedication(heroes_relations.COMPANION_DEDICATION.EGOISM)
        self.hero.preferences.set_companion_dedication(heroes_relations.COMPANION_DEDICATION.NORMAL)
        # self.hero.preferences.set_companion_dedication(heroes_relations.COMPANION_DEDICATION.ALTRUISM)
        # self.hero.preferences.set_companion_dedication(heroes_relations.COMPANION_DEDICATION.EVERY_MAN_FOR_HIMSELF)

        old_health = self.hero.companion.health

        # print('defend_probability: ', self.hero.companion.defend_in_battle_probability)

        # for i in xrange(50):
        #     self.hero.randomized_level_up(increment_level=True)

        while self.hero.companion:
            self.hero.companion.coherence = 50

            self.storage.process_turn()
            current_time.increment_turn()

            self.hero.randomized_level_up()

            if not self.hero.is_alive:
                if hasattr(self.hero.actions.current_action, 'fast_resurrect'):
                    self.hero.actions.current_action.fast_resurrect()

            if self.hero.companion:
                # if old_health != self.hero.companion.health:
                #     print('%.2f:\t%s -> %s [%s] c%s' % ( (current_time.turn_number / c.TURNS_IN_HOUR / 24.0),
                #                                           self.hero.companion.health - self.hero.companion.max_health,
                #                                           self.hero.companion.health,
                #                                           self.hero.companion.health - old_health,
                #                                           self.hero.companion.coherence))

                old_health = self.hero.companion.health
Exemple #52
0
class HeroPreferencesPlaceTest(TestCase):
    PREFERENCE_TYPE = relations.PREFERENCE_TYPE.PLACE

    def setUp(self):
        super(HeroPreferencesPlaceTest, self).setUp()

        self.place, self.place_2, self.place_3 = create_test_map()

        self.account = self.accounts_factory.create_account()
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.hero.level = relations.PREFERENCE_TYPE.PLACE.level_required
        logic.save_hero(self.hero)

    def test_preferences_serialization(self):
        self.hero.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        data = self.hero.preferences.serialize()
        self.assertEqual(data, HeroPreferences.deserialize(data).serialize())

    def test_save(self):
        self.hero.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        logic.save_hero(self.hero)
        self.hero = logic.load_hero(hero_id=self.hero.id)
        self.assertEqual(self.hero.preferences.place.id, self.place.id)


    def test_get_citizens_number(self):
        hero_1 = self.hero
        hero_1.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_1.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=60)
        logic.save_hero(hero_1)

        account_2 = self.accounts_factory.create_account()
        hero_2 = logic.load_hero(account_id=account_2.id)
        hero_2.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        logic.save_hero(hero_2)

        account_3 = self.accounts_factory.create_account()
        hero_3 = logic.load_hero(account_id=account_3.id)
        hero_3.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_3.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=60)
        logic.save_hero(hero_3)

        account_4 = self.accounts_factory.create_account(is_fast=True)
        hero_4 = logic.load_hero(account_id=account_4.id)
        hero_4.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        logic.save_hero(hero_4)

        account_5 = self.accounts_factory.create_account()
        hero_5 = logic.load_hero(account_id=account_5.id)
        hero_5.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_5.ban_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=60)
        logic.save_hero(hero_5)

        account_6 = self.accounts_factory.create_account()
        hero_6 = logic.load_hero(account_id=account_6.id)
        hero_6.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place_2)
        hero_6.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=60)
        logic.save_hero(hero_6)

        account_7 = self.accounts_factory.create_account()
        hero_7 = logic.load_hero(account_id=account_7.id)
        hero_7.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_7.active_state_end_at = datetime.datetime.now() - datetime.timedelta(seconds=60)
        logic.save_hero(hero_7)

        self.assertEqual(set([h.id for h in HeroPreferences.get_citizens_of(self.place, all=False)]), set([hero_1.id, hero_3.id]))
        self.assertEqual(set([h.id for h in HeroPreferences.get_citizens_of(self.place, all=True)]), set([hero_1.id, hero_2.id, hero_3.id]))


    def test_count_habit_values(self):
        hero_1 = self.hero
        hero_1.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_1.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=60)
        hero_1.habit_honor.change(-1)
        hero_1.habit_peacefulness.change(1)
        logic.save_hero(hero_1)

        account_2 = self.accounts_factory.create_account()
        hero_2 = logic.load_hero(account_id=account_2.id)
        hero_2.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_2.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=60)
        hero_2.habit_honor.change(2)
        hero_2.habit_peacefulness.change(-2)
        logic.save_hero(hero_2)

        account_3 = self.accounts_factory.create_account()
        hero_3 = logic.load_hero(account_id=account_3.id)
        hero_3.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place_2)
        hero_3.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=30)
        hero_3.habit_honor.change(-4)
        hero_3.habit_peacefulness.change(4)
        logic.save_hero(hero_3)

        account_4 = self.accounts_factory.create_account()
        hero_4 = logic.load_hero(account_id=account_4.id)
        hero_4.preferences.set(relations.PREFERENCE_TYPE.PLACE, self.place)
        hero_4.premium_state_end_at = datetime.datetime.now() + datetime.timedelta(seconds=30)
        hero_4.habit_honor.change(8)
        hero_4.habit_peacefulness.change(-8)
        logic.save_hero(hero_4)

        self.assertEqual(HeroPreferences.count_habit_values(self.place, all=False), ((10, -1), (1, -10)))
        self.assertEqual(HeroPreferences.count_habit_values(self.place_2, all=False), ((0, -4), (4, 0)))

        self.assertEqual(HeroPreferences.count_habit_values(self.place, all=True), ((10, -1), (1, -10)))
        self.assertEqual(HeroPreferences.count_habit_values(self.place_2, all=True), ((0, -4), (4, 0)))
class InPlaceActionCompanionDrinkArtifactTests(testcase.TestCase):
    def setUp(self):
        super(InPlaceActionCompanionDrinkArtifactTests, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.action_idl = self.hero.actions.current_action

        self.companion_record = companions_logic.create_random_companion_record(
            'thief', state=companions_relations.STATE.ENABLED)
        self.hero.set_companion(
            companions_logic.create_companion(self.companion_record))

        self.hero._model.money = f.expected_gold_in_day(self.hero.level)

        self.hero.position.set_place(self.place_1)
        self.hero.position.visit_current_place()
        self.hero.position.set_place(self.place_2)

        self.artifact = artifacts_storage.generate_artifact_from_list(
            artifacts_storage.loot, 1, rarity=RARITY.NORMAL)
        self.hero.put_loot(self.artifact)

        self.assertEqual(self.hero.bag.occupation, 1)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_drink_artifact',
        lambda hero: True)
    def test_dring_artifact(self):
        with contextlib.nested(
                self.check_decreased(lambda: self.hero.bag.occupation),
                self.check_increased(lambda: len(self.hero.messages))):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

        self.assertTrue(self.hero.messages.messages[-1].key.
                        is_ACTION_INPLACE_COMPANION_DRINK_ARTIFACT)

    def check_not_used(self):
        with contextlib.nested(
                self.check_not_changed(lambda: self.hero.bag.occupation),
                self.check_not_changed(lambda: len(self.hero.messages))):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_drink_artifact',
        lambda hero: True)
    def test_no_previouse_place(self):
        self.hero._model.pos_previous_place = None
        self.check_not_used()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_drink_artifact',
        lambda hero: True)
    def test_previouse_place_is_equal(self):
        self.hero.position.visit_current_place()
        self.check_not_used()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_drink_artifact',
        lambda hero: True)
    def test_no_items(self):
        self.hero.pop_loot(self.artifact)
        self.check_not_used()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_drink_artifact',
        lambda hero: False)
    def test_companion_does_not_eat(self):
        self.check_not_used()
class CombineCardsTaskTest(TestCase):
    def setUp(self):
        super(CombineCardsTaskTest, self).setUp()
        place_1, place_2, place_3 = create_test_map()

        result, account_id, bundle_id = register_user('test_user',
                                                      '*****@*****.**',
                                                      '111111')
        self.account = AccountPrototype.get_by_id(account_id)
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)

        self.hero = self.storage.accounts_to_heroes[account_id]

    def test_create(self):
        task = CombineCardsTask(self.hero.id, cards=[])
        self.assertTrue(task.state.is_UNPROCESSED)

    def test_serialization(self):
        card_1 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)
        card_2 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)

        self.hero.cards.add_card(card_1)
        self.hero.cards.add_card(card_2)

        task = CombineCardsTask(self.hero.id,
                                cards=[card_1.uid, card_2.uid],
                                message='test message')
        self.assertEqual(
            task.serialize(),
            CombineCardsTask.deserialize(task.serialize()).serialize())

    def test__can_not_combine(self):
        for combine_status in cards_relations.CARDS_COMBINING_STATUS.records:
            if combine_status.is_ALLOWED:
                continue

            task = CombineCardsTask(self.hero.id, cards=[])

            with mock.patch(
                    'the_tale.game.cards.container.CardsContainer.can_combine_cards',
                    lambda self, cards: combine_status):
                with self.check_not_changed(self.hero.cards.cards_count):
                    self.assertEqual(
                        task.process(FakePostpondTaskPrototype(),
                                     self.storage),
                        POSTPONED_TASK_LOGIC_RESULT.ERROR)

        self.assertFalse(self.hero.cards.has_cards)
        self.assertTrue(task.state.is_CAN_NOT_COMBINE)

    def test_success__2_cards(self):
        card_1 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)
        card_2 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)

        self.hero.cards.add_card(card_1)
        self.hero.cards.add_card(card_2)

        task = CombineCardsTask(self.hero.id, cards=[card_1.uid, card_2.uid])

        with self.check_delta(self.hero.cards.cards_count, -1):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.SUCCESS)

        self.assertTrue(self.hero.cards.has_cards)
        self.assertEqual(self.hero.cards.cards_count(), 1)

        self.assertTrue(
            self.hero.cards.all_cards().next().type.rarity.is_COMMON)

        self.assertTrue(self.hero.cards.all_cards().next().type.text.lower() in
                        task.processed_data['message'].lower())
        self.assertTrue(self.hero.cards.all_cards().next().effect.DESCRIPTION.
                        lower() in task.processed_data['message'].lower())

        self.assertTrue(task.state.is_PROCESSED)

    def test_success__3_cards(self):
        card_1 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)
        card_2 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)
        card_3 = cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON)

        self.hero.cards.add_card(card_1)
        self.hero.cards.add_card(card_2)
        self.hero.cards.add_card(card_3)

        task = CombineCardsTask(self.hero.id,
                                cards=[card_1.uid, card_2.uid, card_3.uid])

        with self.check_delta(self.hero.cards.cards_count, -2):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.SUCCESS)

        self.assertTrue(self.hero.cards.has_cards)

        self.assertTrue(
            self.hero.cards.all_cards().next().type.rarity.is_UNCOMMON)

        self.assertTrue(self.hero.cards.all_cards().next().name.lower() in
                        task.processed_data['message'].lower())
        self.assertTrue(self.hero.cards.all_cards().next().effect.DESCRIPTION.
                        lower() in task.processed_data['message'].lower())

        self.assertTrue(task.state.is_PROCESSED)

    def test_success__remove_cards(self):
        cards = [
            cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON),
            cards_objects.Card(
                cards_relations.CARD_TYPE.ADD_EXPERIENCE_COMMON),
            cards_objects.Card(
                cards_relations.CARD_TYPE.ADD_EXPERIENCE_COMMON),
            cards_objects.Card(
                cards_relations.CARD_TYPE.ADD_BONUS_ENERGY_COMMON),
            cards_objects.Card(cards_relations.CARD_TYPE.
                               CHANGE_HERO_SPENDINGS_TO_INSTANT_HEAL),
            cards_objects.Card(cards_relations.CARD_TYPE.LEVEL_UP)
        ]

        for card in cards:
            self.hero.cards.add_card(card)

        task = CombineCardsTask(
            self.hero.id, cards=[cards[0].uid, cards[2].uid, cards[3].uid])

        with self.check_delta(self.hero.cards.cards_count, -2):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.SUCCESS)

        self.assertFalse(self.hero.cards.has_card(cards[0].uid))
        self.assertTrue(self.hero.cards.has_card(cards[1].uid))
        self.assertFalse(self.hero.cards.has_card(cards[2].uid))
        self.assertFalse(self.hero.cards.has_card(cards[3].uid))
        self.assertTrue(self.hero.cards.has_card(cards[4].uid))
        self.assertTrue(self.hero.cards.has_card(cards[5].uid))

        self.assertTrue(task.state.is_PROCESSED)

    def test_success__remove_duplicates(self):
        cards = [
            cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON),
            cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON),
            cards_objects.Card(cards_relations.CARD_TYPE.ADD_GOLD_COMMON),
            cards_objects.Card(
                cards_relations.CARD_TYPE.ADD_EXPERIENCE_COMMON),
            cards_objects.Card(
                cards_relations.CARD_TYPE.ADD_EXPERIENCE_COMMON),
            cards_objects.Card(
                cards_relations.CARD_TYPE.ADD_BONUS_ENERGY_COMMON),
            cards_objects.Card(cards_relations.CARD_TYPE.
                               CHANGE_HERO_SPENDINGS_TO_INSTANT_HEAL),
            cards_objects.Card(cards_relations.CARD_TYPE.LEVEL_UP)
        ]

        for card in cards:
            self.hero.cards.add_card(card)

        task = CombineCardsTask(
            self.hero.id, cards=[cards[1].uid, cards[2].uid, cards[5].uid])

        with self.check_delta(self.hero.cards.cards_count, -2):
            self.assertEqual(
                task.process(FakePostpondTaskPrototype(), self.storage),
                POSTPONED_TASK_LOGIC_RESULT.SUCCESS)

        self.assertTrue(self.hero.cards.has_card(cards[0].uid))
        self.assertFalse(self.hero.cards.has_card(cards[1].uid))
        self.assertFalse(self.hero.cards.has_card(cards[2].uid))
        self.assertTrue(self.hero.cards.has_card(cards[3].uid))
        self.assertTrue(self.hero.cards.has_card(cards[4].uid))
        self.assertFalse(self.hero.cards.has_card(cards[5].uid))
        self.assertTrue(self.hero.cards.has_card(cards[6].uid))
        self.assertTrue(self.hero.cards.has_card(cards[7].uid))

        self.assertTrue(task.state.is_PROCESSED)
class InPlaceActionCompanionBuyMealTests(testcase.TestCase):
    def setUp(self):
        super(InPlaceActionCompanionBuyMealTests, self).setUp()
        self.place_1, self.place_2, self.place_3 = create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.action_idl = self.hero.actions.current_action

        self.companion_record = companions_logic.create_random_companion_record(
            'thief', state=companions_relations.STATE.ENABLED)
        self.hero.set_companion(
            companions_logic.create_companion(self.companion_record))

        self.hero._model.money = f.expected_gold_in_day(self.hero.level)

        self.hero.position.set_place(self.place_1)
        self.hero.position.visit_current_place()
        self.hero.position.set_place(self.place_2)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.companion_money_for_food_multiplier',
        0.5)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_eat',
        lambda hero: True)
    def test_buy_meal(self):
        with contextlib.nested(
                self.check_decreased(lambda: self.hero.money),
                self.check_increased(
                    lambda: self.hero.statistics.money_spend_for_companions),
                self.check_increased(lambda: len(self.hero.messages))):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

    def check_not_used(self):
        with contextlib.nested(
                self.check_not_changed(lambda: self.hero.money),
                self.check_not_changed(
                    lambda: self.hero.statistics.money_spend_for_companions)):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.companion_money_for_food_multiplier',
        0.5)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_eat',
        lambda hero: True)
    def test_no_previouse_place(self):
        self.hero._model.pos_previous_place = None
        self.check_not_used()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.companion_money_for_food_multiplier',
        0.5)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_eat',
        lambda hero: True)
    def test_previouse_place_is_equal(self):
        self.hero.position.visit_current_place()
        self.check_not_used()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.companion_money_for_food_multiplier',
        66666666)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_eat',
        lambda hero: True)
    def test_not_enough_money(self):
        with contextlib.nested(
                self.check_delta(lambda: self.hero.money, -self.hero.money),
                self.check_delta(
                    lambda: self.hero.statistics.money_spend_for_companions,
                    self.hero.money),
                self.check_increased(lambda: len(self.hero.messages))):
            prototypes.ActionInPlacePrototype.create(hero=self.hero)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.companion_money_for_food_multiplier',
        66666666)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_eat',
        lambda hero: True)
    def test_no_money(self):
        self.hero._model.money = 0
        self.check_not_used()

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.companion_money_for_food_multiplier',
        0.5)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.can_companion_eat',
        lambda hero: False)
    def test_companion_does_not_eat(self):
        self.check_not_used()
Exemple #56
0
class GeneralTest(testcase.TestCase):

    def setUp(self):
        super(GeneralTest, self).setUp()
        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.action_idl = self.hero.actions.current_action

        self.bundle_id = self.action_idl.bundle_id

    def tearDown(self):
        pass

    def test_HELP_CHOICES(self):
        for action_class in ACTION_TYPES.values():
            self.assertTrue('HELP_CHOICES' in action_class.__dict__)
            if (not action_class.TYPE.is_IDLENESS and           # TODO: check
                not action_class.TYPE.is_BATTLE_PVE_1X1 and     # TODO: check
                not action_class.TYPE.is_MOVE_TO and            # TODO: check
                not action_class.TYPE.is_HEAL_COMPANION and
                not action_class.TYPE.is_RESURRECT):
                self.assertIn(HELP_CHOICES.MONEY, action_class.HELP_CHOICES) # every action MUST has MONEY choice, or it will be great disbalance in energy & experience receiving

    def test_TEXTGEN_TYPE(self):
        for action_class in ACTION_TYPES.values():
            self.assertTrue('TEXTGEN_TYPE' in action_class.__dict__)

    def test_get_help_choice_has_heal(self):
        self.hero.health = 1

        heal_found = False
        for i in xrange(100):
            heal_found = heal_found or (self.action_idl.get_help_choice() == HELP_CHOICES.HEAL)

        self.assertTrue(heal_found)

    def check_heal_in_choices(self, result):
        heal_found = False
        for i in xrange(100):
            heal_found = heal_found or (self.action_idl.get_help_choice() == HELP_CHOICES.HEAL)

        self.assertEqual(heal_found, result)


    def check_heal_companion_in_choices(self, result):
        heal_found = False
        for i in xrange(100):
            heal_found = heal_found or (self.action_idl.get_help_choice() == HELP_CHOICES.HEAL_COMPANION)

        self.assertEqual(heal_found, result)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL,)))
    def test_help_choice_has_heal__for_full_health_without_alternative(self):
        self.check_heal_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL, HELP_CHOICES.MONEY)))
    def test_help_choice_has_heal__for_full_health_with_alternative(self):
        self.check_heal_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL,)))
    def test_help_choice_has_heal__for_large_health_without_alternative(self):
        self.hero.health = self.hero.max_health - 1
        self.check_heal_in_choices(True)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL, HELP_CHOICES.MONEY)))
    def test_help_choice_has_heal__for_large_health_with_alternative(self):
        self.hero.health = self.hero.max_health - 1
        self.check_heal_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL,)))
    def test_help_choice_has_heal__for_low_health_without_alternative(self):
        self.hero.health = 1
        self.check_heal_in_choices(True)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL, HELP_CHOICES.MONEY)))
    def test_help_choice_has_heal__for_low_health_with_alternative(self):
        self.hero.health = 1
        self.check_heal_in_choices(True)


    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION,)))
    def test_help_choice_has_heal_companion__for_no_companion(self):
        self.check_heal_companion_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION, HELP_CHOICES.MONEY)))
    def test_help_choice_has_heal_companion__for_no_companion_with_alternative(self):
        self.check_heal_companion_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION,)))
    def test_help_choice_has_heal_companion__for_full_health_without_alternative(self):
        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))
        self.check_heal_companion_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION,)))
    @mock.patch('the_tale.game.heroes.prototypes.HeroPrototype.companion_heal_disabled', lambda hero: True)
    def test_help_choice_has_heal_companion__for_companion_heal_disabled(self):
        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))
        self.check_heal_companion_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION, HELP_CHOICES.MONEY)))
    def test_help_choice_has_heal_companion__for_full_health_with_alternative(self):
        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))
        self.check_heal_companion_in_choices(False)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION,)))
    def test_help_choice_has_heal_companion__for_low_health_without_alternative(self):
        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))
        self.hero.companion.health = 1
        self.check_heal_companion_in_choices(True)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.HEAL_COMPANION, HELP_CHOICES.MONEY)))
    def test_help_choice_has_heal_companion__for_low_health_with_alternative(self):
        companion_record = companions_storage.companions.enabled_companions().next()
        self.hero.set_companion(companions_logic.create_companion(companion_record))
        self.hero.companion.health = 1
        self.check_heal_companion_in_choices(True)


    def check_stock_up_energy_in_choices(self, result):
        stock_found = False
        for i in xrange(1000):
            stock_found = stock_found or (self.action_idl.get_help_choice() == HELP_CHOICES.STOCK_UP_ENERGY)

        self.assertEqual(stock_found, result)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.STOCK_UP_ENERGY, HELP_CHOICES.MONEY)))
    def test_help_choice_has_stock_up_energy__can_stock(self):
        self.hero.energy_charges = 0
        self.check_stock_up_energy_in_choices(True)

    @mock.patch('the_tale.game.actions.prototypes.ActionIdlenessPrototype.HELP_CHOICES', set((HELP_CHOICES.STOCK_UP_ENERGY, HELP_CHOICES.MONEY)))
    def test_help_choice_has_stock_up_energy__can_not_stock(self):
        self.hero.energy_bonus = c.ANGEL_FREE_ENERGY_MAXIMUM
        self.check_stock_up_energy_in_choices(False)

    def test_percents_consistency(self):
        current_time = TimePrototype.get_current_time()

        # just test that quest will be ended
        while not self.action_idl.leader:
            self.storage.process_turn()
            current_time.increment_turn()
            self.assertEqual(self.storage.tests_get_last_action().percents, self.hero.last_action_percents)

    def test_help_choice_heal_not_in_choices_for_dead_hero(self):

        self.hero.health = 1
        self.hero.save()

        self.assertTrue(HELP_CHOICES.HEAL in self.action_idl.help_choices)

        self.hero.kill()
        self.hero.save()

        self.assertFalse(HELP_CHOICES.HEAL in self.action_idl.help_choices)

    def test_action_default_serialization(self):
        # class TestAction(ActionBase):
        #     TYPE = 'test-action'

        default_action = TestAction( hero=self.hero,
                                     bundle_id=self.bundle_id,
                                     state=TestAction.STATE.UNINITIALIZED)

        self.assertEqual(default_action.serialize(), {'bundle_id': self.bundle_id,
                                                      'state': TestAction.STATE.UNINITIALIZED,
                                                      'percents': 0.0,
                                                      'description': None,
                                                      'type': TestAction.TYPE.value,
                                                      'created_at_turn': TimePrototype.get_current_turn_number()})

        self.assertEqual(default_action, TestAction.deserialize(self.hero, default_action.serialize()))

    def test_action_full_serialization(self):
        mob = mobs_storage.create_mob_for_hero(self.hero)

        account_2 = self.accounts_factory.create_account()

        self.storage.load_account_data(account_2)
        hero_2 = self.storage.accounts_to_heroes[account_2.id]


        meta_action = meta_actions.ArenaPvP1x1.create(self.storage, self.hero, hero_2)

        default_action = TestAction( hero=self.hero,
                                     bundle_id=self.bundle_id,
                                     state=TestAction.STATE.UNINITIALIZED,
                                     created_at_turn=666,
                                     context=TestAction.CONTEXT_MANAGER(),
                                     description=u'description',
                                     place_id=2,
                                     mob=mob,
                                     data={'xxx': 'yyy'},
                                     break_at=0.75,
                                     length=777,
                                     destination_x=20,
                                     destination_y=30,
                                     percents_barier=77,
                                     extra_probability=0.6,
                                     mob_context=TestAction.CONTEXT_MANAGER(),
                                     textgen_id='textgen_id',
                                     back=True,
                                     info_link='/bla-bla',
                                     meta_action=meta_action,
                                     replane_required=True)

        self.assertEqual(default_action.serialize(), {'bundle_id': self.bundle_id,
                                                      'state': TestAction.STATE.UNINITIALIZED,
                                                      'context': TestAction.CONTEXT_MANAGER().serialize(),
                                                      'mob_context': TestAction.CONTEXT_MANAGER().serialize(),
                                                      'mob': mob.serialize(),
                                                      'length': 777,
                                                      'back': True,
                                                      'textgen_id': 'textgen_id',
                                                      'extra_probability': 0.6,
                                                      'percents_barier': 77,
                                                      'destination_x': 20,
                                                      'destination_y': 30,
                                                      'percents': 0.0,
                                                      'description': u'description',
                                                      'type': TestAction.TYPE.value,
                                                      'created_at_turn': 666,
                                                      'place_id': 2,
                                                      'data': {'xxx': 'yyy'},
                                                      'info_link': '/bla-bla',
                                                      'break_at': 0.75,
                                                      'meta_action': meta_action.serialize(),
                                                      'replane_required': True})

        self.assertEqual(default_action, TestAction.deserialize(self.hero, default_action.serialize()))
Exemple #57
0
class HabilitiesCompanionsTest(testcase.TestCase):
    def setUp(self):
        super(HabilitiesCompanionsTest, self).setUp()
        create_test_map()

        self.account = self.accounts_factory.create_account()
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

    def test_walker(self):
        self.assertEqual(
            companions.WALKER().modify_attribute(
                MODIFIERS.COMPANION_ABILITIES_LEVELS, {}),
            {companions_abilities_relations.METATYPE.TRAVEL: 1})
        self.assertEqual(
            companions.WALKER().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_ABILITIES_LEVELS, )), {}), {})

        self.assertEqual(self.hero.companion_abilities_levels, {})
        self.hero.abilities.add(companions.WALKER.get_id(), 3)
        self.assertEqual(self.hero.companion_abilities_levels,
                         {companions_abilities_relations.METATYPE.TRAVEL: 3})

    def test_comrade(self):
        self.assertEqual(
            companions.COMRADE().modify_attribute(
                MODIFIERS.COMPANION_ABILITIES_LEVELS, {}),
            {companions_abilities_relations.METATYPE.BATTLE: 1})
        self.assertEqual(
            companions.COMRADE().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_ABILITIES_LEVELS, )), {}), {})

        self.assertEqual(self.hero.companion_abilities_levels, {})
        self.hero.abilities.add(companions.COMRADE.get_id(), 3)
        self.assertEqual(self.hero.companion_abilities_levels,
                         {companions_abilities_relations.METATYPE.BATTLE: 3})

    def test_improviser(self):
        self.assertEqual(
            companions.IMPROVISER().modify_attribute(
                MODIFIERS.COMPANION_ABILITIES_LEVELS, {}),
            {companions_abilities_relations.METATYPE.OTHER: 1})
        self.assertEqual(
            companions.IMPROVISER().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_ABILITIES_LEVELS, )), {}), {})

        self.assertEqual(self.hero.companion_abilities_levels, {})
        self.hero.abilities.add(companions.IMPROVISER.get_id(), 3)
        self.assertEqual(self.hero.companion_abilities_levels,
                         {companions_abilities_relations.METATYPE.OTHER: 3})

    def test_economic(self):
        self.assertEqual(
            companions.ECONOMIC().modify_attribute(
                MODIFIERS.COMPANION_ABILITIES_LEVELS, {}),
            {companions_abilities_relations.METATYPE.MONEY: 1})
        self.assertEqual(
            companions.ECONOMIC().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_ABILITIES_LEVELS, )), {}), {})

        self.assertEqual(self.hero.companion_abilities_levels, {})
        self.hero.abilities.add(companions.ECONOMIC.get_id(), 3)
        self.assertEqual(self.hero.companion_abilities_levels,
                         {companions_abilities_relations.METATYPE.MONEY: 3})

    def test_thoughtful(self):
        self.assertEqual(
            companions.THOUGHTFUL().modify_attribute(
                MODIFIERS.COMPANION_MAX_HEALTH, 1.0), 1.1)
        self.assertEqual(
            companions.THOUGHTFUL().modify_attribute(
                MODIFIERS.random(exclude=(MODIFIERS.COMPANION_MAX_HEALTH, )),
                1), 1)

        self.assertEqual(self.hero.companion_max_health_multiplier, 1)
        self.hero.abilities.add(companions.THOUGHTFUL.get_id(), 3)
        self.assertEqual(self.hero.companion_max_health_multiplier, 1.3)

    def test_coherence(self):
        self.assertEqual(
            companions.COHERENCE().modify_attribute(
                MODIFIERS.COMPANION_MAX_COHERENCE, 0), 20)
        self.assertEqual(
            companions.COHERENCE().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_MAX_COHERENCE, )), 1), 1)

        self.assertEqual(self.hero.companion_max_coherence,
                         20)  # coherence lvl 1 — default hero ability
        self.hero.abilities.add(companions.COHERENCE.get_id(), 3)
        self.assertEqual(self.hero.companion_max_coherence, 60)

    def test_healing(self):
        self.assertEqual(
            companions.HEALING().modify_attribute(
                MODIFIERS.COMPANION_LIVING_HEAL, 0), 0.0462962962962963)
        self.assertEqual(
            companions.HEALING().modify_attribute(
                MODIFIERS.random(exclude=(MODIFIERS.COMPANION_LIVING_HEAL, )),
                0), 0)

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        with mock.patch(
                'the_tale.game.companions.objects.CompanionRecord.type',
                game_relations.BEING_TYPE.ANIMAL):
            self.assertEqual(self.hero.companion_heal_probability, 0)
            self.hero.abilities.add(companions.HEALING.get_id(), 3)
            self.assertEqual(self.hero.companion_heal_probability,
                             0.1388888888888889)

    def test_mage_mechanincs(self):
        self.assertEqual(
            companions.MAGE_MECHANICS().modify_attribute(
                MODIFIERS.COMPANION_CONSTRUCT_HEAL, 0), 0.0462962962962963)
        self.assertEqual(
            companions.MAGE_MECHANICS().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_CONSTRUCT_HEAL, )), 0), 0)

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        with mock.patch(
                'the_tale.game.companions.objects.CompanionRecord.type',
                game_relations.BEING_TYPE.MECHANICAL):
            self.assertEqual(self.hero.companion_heal_probability, 0)
            self.hero.abilities.add(companions.MAGE_MECHANICS.get_id(), 3)
            self.assertEqual(self.hero.companion_heal_probability,
                             0.1388888888888889)

    def test_witchcraft(self):
        self.assertEqual(
            companions.WITCHCRAFT().modify_attribute(
                MODIFIERS.COMPANION_UNUSUAL_HEAL, 0), 0.0462962962962963)
        self.assertEqual(
            companions.WITCHCRAFT().modify_attribute(
                MODIFIERS.random(exclude=(MODIFIERS.COMPANION_UNUSUAL_HEAL, )),
                0), 0)

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        with mock.patch(
                'the_tale.game.companions.objects.CompanionRecord.type',
                game_relations.BEING_TYPE.SUPERNATURAL):
            self.assertEqual(self.hero.companion_heal_probability, 0)
            self.hero.abilities.add(companions.WITCHCRAFT.get_id(), 3)
            self.assertEqual(self.hero.companion_heal_probability,
                             0.1388888888888889)

    def test_sociability(self):
        self.assertEqual(
            companions.SOCIABILITY().modify_attribute(
                MODIFIERS.COMPANION_LIVING_COHERENCE_SPEED, 1), 1.2)
        self.assertEqual(
            companions.SOCIABILITY().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_LIVING_COHERENCE_SPEED, )),
                1), 1)

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        with mock.patch(
                'the_tale.game.companions.objects.CompanionRecord.type',
                game_relations.BEING_TYPE.ANIMAL):
            self.assertEqual(self.hero.companion_coherence_speed, 1)
            self.hero.abilities.add(companions.SOCIABILITY.get_id(), 3)
            self.assertEqual(self.hero.companion_coherence_speed, 1.6)

    def test_service(self):
        self.assertEqual(
            companions.SERVICE().modify_attribute(
                MODIFIERS.COMPANION_CONSTRUCT_COHERENCE_SPEED, 1), 1.2)
        self.assertEqual(
            companions.SERVICE().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_CONSTRUCT_COHERENCE_SPEED, )),
                1), 1)

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        with mock.patch(
                'the_tale.game.companions.objects.CompanionRecord.type',
                game_relations.BEING_TYPE.MECHANICAL):
            self.assertEqual(self.hero.companion_coherence_speed, 1)
            self.hero.abilities.add(companions.SERVICE.get_id(), 3)
            self.assertEqual(self.hero.companion_coherence_speed, 1.6)

    def test_sacredness(self):
        self.assertEqual(
            companions.SACREDNESS().modify_attribute(
                MODIFIERS.COMPANION_UNUSUAL_COHERENCE_SPEED, 1), 1.2)
        self.assertEqual(
            companions.SACREDNESS().modify_attribute(
                MODIFIERS.random(
                    exclude=(MODIFIERS.COMPANION_UNUSUAL_COHERENCE_SPEED, )),
                1), 1)

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        with mock.patch(
                'the_tale.game.companions.objects.CompanionRecord.type',
                game_relations.BEING_TYPE.SUPERNATURAL):
            self.assertEqual(self.hero.companion_coherence_speed, 1)
            self.hero.abilities.add(companions.SACREDNESS.get_id(), 3)
            self.assertEqual(self.hero.companion_coherence_speed, 1.6)
Exemple #58
0
class JobsMethodsTests(testcase.TestCase):
    def setUp(self):
        super(JobsMethodsTests, self).setUp()

        create_test_map()

        self.account = self.accounts_factory.create_account()

        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]

        self.place = places_storage.places.all()[0]
        self.person = self.place.persons[0]

    def check_job_message(self, place_id, person_id):
        with self.check_delta(lambda: len(self.hero.diary), 1):
            self.hero.job_message(
                place_id=place_id,
                person_id=person_id,
                message_type='job_diary_person_hero_money_positive_enemies',
                job_power=None)

    def check_job_money(self, place_id, person_id):
        old_money = self.hero.money

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_increased(
                    lambda: self.hero.statistics.money_earned_from_masters):
                self.hero.job_money(
                    place_id=place_id,
                    person_id=person_id,
                    message_type='job_diary_person_hero_money_positive_enemies',
                    job_power=1)

        middle_money = self.hero.money

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_increased(
                    lambda: self.hero.statistics.money_earned_from_masters):
                self.hero.job_money(
                    place_id=place_id,
                    person_id=person_id,
                    message_type='job_diary_person_hero_money_positive_enemies',
                    job_power=2)

        self.assertTrue(
            middle_money - old_money < self.hero.money - middle_money)

    def check_job_artifact(self, place_id, person_id):
        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_delta(lambda: self.hero.bag.occupation, 1):
                with self.check_delta(
                        lambda: self.hero.statistics.artifacts_had, 1):
                    self.hero.job_artifact(
                        place_id=place_id,
                        person_id=person_id,
                        message_type=
                        'job_diary_person_hero_artifact_positive_enemies',
                        job_power=1)

        rating = self.hero.bag.values()[0].preference_rating(
            self.hero.preferences.archetype.power_distribution)
        self.hero.bag.drop_cheapest_item(
            self.hero.preferences.archetype.power_distribution)

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_delta(lambda: self.hero.bag.occupation, 1):
                with self.check_delta(
                        lambda: self.hero.statistics.artifacts_had, 1):
                    self.hero.job_artifact(
                        place_id=place_id,
                        person_id=person_id,
                        message_type=
                        'job_diary_person_hero_artifact_positive_enemies',
                        job_power=2)

        self.assertTrue(
            rating,
            self.hero.bag.values()[0].preference_rating(
                self.hero.preferences.archetype.power_distribution))

    def check_job_experience(self, place_id, person_id):
        self.hero.level = 100

        old_experience = self.hero.experience

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_increased(lambda: self.hero.experience):
                self.hero.job_experience(
                    place_id=place_id,
                    person_id=person_id,
                    message_type=
                    'job_diary_person_hero_experience_positive_enemies',
                    job_power=1)

        middle_experience = self.hero.experience

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_increased(lambda: self.hero.experience):
                self.hero.job_experience(
                    place_id=place_id,
                    person_id=person_id,
                    message_type=
                    'job_diary_person_hero_experience_positive_enemies',
                    job_power=2)

        self.assertTrue(
            middle_experience - old_experience < self.hero.experience -
            middle_experience)

    def check_job_energy(self, place_id, person_id):
        old_energy = self.hero.energy_bonus

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_increased(lambda: self.hero.energy_bonus):
                self.hero.job_energy(
                    place_id=place_id,
                    person_id=person_id,
                    message_type=
                    'job_diary_person_hero_energy_positive_enemies',
                    job_power=1)

        middle_energy = self.hero.energy_bonus

        with self.check_delta(lambda: len(self.hero.diary), 1):
            with self.check_increased(lambda: self.hero.energy_bonus):
                self.hero.job_energy(
                    place_id=place_id,
                    person_id=person_id,
                    message_type=
                    'job_diary_person_hero_energy_positive_enemies',
                    job_power=2)

        self.assertTrue(middle_energy - old_energy < self.hero.energy_bonus -
                        middle_energy)

    def test_job_message(self):
        self.check_job_message(place_id=self.place.id,
                               person_id=self.person.id)
        self.check_job_message(place_id=self.place.id, person_id=None)

    def test_job_money(self):
        self.check_job_money(place_id=self.place.id, person_id=self.person.id)
        self.check_job_money(place_id=self.place.id, person_id=None)

    def test_job_artifact(self):
        self.check_job_artifact(place_id=self.place.id,
                                person_id=self.person.id)
        self.check_job_artifact(place_id=self.place.id, person_id=None)

    def test_job_experience(self):
        self.check_job_experience(place_id=self.place.id,
                                  person_id=self.person.id)
        self.check_job_experience(place_id=self.place.id, person_id=None)

    def test_job_energy(self):
        self.check_job_energy(place_id=self.place.id, person_id=self.person.id)
        self.check_job_energy(place_id=self.place.id, person_id=None)
Exemple #59
0
class HelpAbilityTest(UseAbilityTaskMixin, testcase.TestCase):
    ABILITY = Help

    def setUp(self):
        super(HelpAbilityTest, self).setUp()
        self.p1, self.p2, self.p3 = create_test_map()

        result, account_id, bundle_id = register_user('test_user_1',
                                                      '*****@*****.**',
                                                      '111111')

        self.account = AccountPrototype.get_by_id(account_id)
        self.storage = LogicStorage()
        self.storage.load_account_data(self.account)
        self.hero = self.storage.accounts_to_heroes[self.account.id]
        self.action_idl = self.hero.actions.current_action

        self.ability = self.ABILITY()

    @property
    def use_attributes(self):
        return super(HelpAbilityTest,
                     self).use_attributes(hero=self.hero, storage=self.storage)

    def test_none(self):
        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: None):
            with self.check_not_changed(
                    lambda: self.hero.statistics.help_count):
                with self.check_not_changed(
                        lambda: self.hero.cards.help_count):
                    self.assertEqual(self.ability.use(**self.use_attributes),
                                     (ComplexChangeTask.RESULT.FAILED,
                                      ComplexChangeTask.STEP.ERROR, ()))

    def test_success(self):
        with mock.patch('the_tale.game.heroes.prototypes.HeroPrototype.on_help'
                        ) as on_help:
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                with self.check_delta(lambda: self.hero.cards.help_count, 1):
                    self.assertEqual(self.ability.use(**self.use_attributes),
                                     (ComplexChangeTask.RESULT.SUCCESSED,
                                      ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(on_help.call_count, 1)

    @mock.patch('the_tale.game.heroes.prototypes.HeroPrototype.can_be_helped',
                lambda hero: False)
    def test_help_restricted(self):
        with self.check_not_changed(lambda: self.hero.statistics.help_count):
            with self.check_not_changed(lambda: self.hero.cards.help_count):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.FAILED,
                                  ComplexChangeTask.STEP.ERROR, ()))

    def test_help_when_battle_waiting(self):
        battle = Battle1x1Prototype.create(self.account)
        self.assertTrue(battle.state.is_WAITING)
        with self.check_delta(lambda: self.hero.statistics.help_count, 1):
            self.assertEqual(self.ability.use(**self.use_attributes),
                             (ComplexChangeTask.RESULT.SUCCESSED,
                              ComplexChangeTask.STEP.SUCCESS, ()))

    def test_help_when_battle_not_waiting(self):
        battle = Battle1x1Prototype.create(self.account)
        battle.state = BATTLE_1X1_STATE.PREPAIRING
        battle.save()

        self.assertFalse(battle.state.is_WAITING)
        with self.check_not_changed(lambda: self.hero.statistics.help_count):
            self.assertEqual(
                self.ability.use(**self.use_attributes),
                (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR,
                 ()))

    def test_heal(self):
        self.hero.health = 1
        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))
                self.assertTrue(self.hero.health > 1)

    def test_start_quest(self):
        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.START_QUEST):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))
                self.assertTrue(self.action_idl.percents >= 1)

    def test_experience(self):
        old_experience = self.hero.experience
        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.EXPERIENCE):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertTrue(old_experience < self.hero.experience)

    def test_stock_up_energy(self):

        with self.check_changed(lambda: self.hero.energy_bonus):
            with mock.patch(
                    'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                    lambda x: HELP_CHOICES.STOCK_UP_ENERGY):
                with self.check_delta(lambda: self.hero.statistics.help_count,
                                      1):
                    self.assertEqual(self.ability.use(**self.use_attributes),
                                     (ComplexChangeTask.RESULT.SUCCESSED,
                                      ComplexChangeTask.STEP.SUCCESS, ()))

    def test_money(self):
        old_hero_money = self.hero.money
        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.MONEY):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))
                self.assertTrue(self.hero.money > old_hero_money)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed',
        lambda self: False)
    def test_teleport(self):
        move_place = self.p3
        if move_place.id == self.hero.position.place.id:
            move_place = self.p1

        current_time = TimePrototype.get_current_time()

        action_move = actions_prototypes.ActionMoveToPrototype.create(
            hero=self.hero, destination=move_place)

        current_time.increment_turn()
        self.storage.process_turn()

        old_road_percents = self.hero.position.percents
        old_percents = action_move.percents

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.TELEPORT):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertTrue(old_road_percents < self.hero.position.percents)
        self.assertTrue(old_percents < action_move.percents)
        self.assertEqual(self.hero.actions.current_action.percents,
                         action_move.percents)

    @mock.patch(
        'the_tale.game.balance.constants.ANGEL_HELP_CRIT_TELEPORT_DISTANCE',
        9999999999)
    @mock.patch('the_tale.game.balance.constants.ANGEL_HELP_TELEPORT_DISTANCE',
                9999999999)
    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPositionPrototype.is_battle_start_needed',
        lambda self: False)
    def test_teleport__inplace_action_created(self):
        move_place = self.p3
        if move_place.id == self.hero.position.place.id:
            move_place = self.p1

        current_time = TimePrototype.get_current_time()

        actions_prototypes.ActionMoveToPrototype.create(hero=self.hero,
                                                        destination=move_place)

        current_time.increment_turn()
        self.storage.process_turn()

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.TELEPORT):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(self.hero.actions.current_action.TYPE,
                         actions_prototypes.ActionInPlacePrototype.TYPE)

    def test_lighting(self):
        current_time = TimePrototype.get_current_time()
        action_battle = actions_prototypes.ActionBattlePvE1x1Prototype.create(
            hero=self.hero, mob=mobs_storage.create_mob_for_hero(self.hero))

        current_time.increment_turn()
        self.storage.process_turn()

        old_mob_health = action_battle.mob.health
        old_percents = action_battle.percents

        self.assertTrue(HELP_CHOICES.LIGHTING in action_battle.help_choices)

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.LIGHTING):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertTrue(old_mob_health > action_battle.mob.health)
        self.assertEqual(self.hero.actions.current_action.percents,
                         action_battle.percents)
        self.assertTrue(old_percents < action_battle.percents)

    def test_lighting_when_mob_killed(self):
        current_time = TimePrototype.get_current_time()
        action_battle = actions_prototypes.ActionBattlePvE1x1Prototype.create(
            hero=self.hero, mob=mobs_storage.create_mob_for_hero(self.hero))

        current_time.increment_turn()
        self.storage.process_turn()

        action_battle.mob.health = 0

        self.assertFalse(HELP_CHOICES.LIGHTING in action_battle.help_choices)

    def test_resurrect(self):
        current_time = TimePrototype.get_current_time()

        self.hero.kill()
        action_resurrect = actions_prototypes.ActionResurrectPrototype.create(
            hero=self.hero)

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.RESURRECT):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                current_time.increment_turn()
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(self.hero.health, self.hero.max_health)
        self.assertEqual(self.hero.is_alive, True)
        self.assertEqual(action_resurrect.state,
                         action_resurrect.STATE.PROCESSED)

    def test_process_turn_called_if_current_action_processed(self):
        current_time = TimePrototype.get_current_time()

        self.hero.kill()
        actions_prototypes.ActionResurrectPrototype.create(hero=self.hero)

        with mock.patch(
                'the_tale.game.logic_storage.LogicStorage.process_turn__single_hero'
        ) as process_turn__single_hero:
            with mock.patch(
                    'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                    lambda x: HELP_CHOICES.RESURRECT):
                with self.check_delta(lambda: self.hero.statistics.help_count,
                                      1):
                    current_time.increment_turn()
                    self.assertEqual(self.ability.use(**self.use_attributes),
                                     (ComplexChangeTask.RESULT.SUCCESSED,
                                      ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(process_turn__single_hero.call_args_list, [
            mock.call(
                hero=self.hero, logger=None, continue_steps_if_needed=True)
        ])

    def test_resurrect__two_times(self):
        current_time = TimePrototype.get_current_time()

        self.hero.kill()
        actions_prototypes.ActionResurrectPrototype.create(hero=self.hero)

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.RESURRECT):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                current_time.increment_turn()
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.RESURRECT):
            with self.check_not_changed(
                    lambda: self.hero.statistics.help_count):
                current_time.increment_turn()
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.IGNORE,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

    @mock.patch(
        'the_tale.game.actions.prototypes.ActionIdlenessPrototype.HABIT_MODE',
        actions_relations.ACTION_HABIT_MODE.AGGRESSIVE)
    def test_update_habits__aggressive_action(self):

        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.update_habits'
        ) as update_habits:
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(update_habits.call_args_list,
                         [mock.call(HABIT_CHANGE_SOURCE.HELP_AGGRESSIVE)])

    @mock.patch(
        'the_tale.game.actions.prototypes.ActionIdlenessPrototype.HABIT_MODE',
        actions_relations.ACTION_HABIT_MODE.PEACEFUL)
    def test_update_habits__unaggressive_action(self):
        with mock.patch(
                'the_tale.game.heroes.prototypes.HeroPrototype.update_habits'
        ) as update_habits:
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(update_habits.call_args_list,
                         [mock.call(HABIT_CHANGE_SOURCE.HELP_UNAGGRESSIVE)])

    @mock.patch('the_tale.game.artifacts.effects.Health.REMOVE_ON_HELP', True)
    def test_return_child_gifts(self):
        not_child_gift, child_gift, removed_artifact = artifacts_storage.all(
        )[:3]

        child_gift.special_effect = artifacts_relations.ARTIFACT_EFFECT.CHILD_GIFT
        removed_artifact.rare_effect = artifacts_relations.ARTIFACT_EFFECT.HEALTH

        self.hero.bag.put_artifact(
            not_child_gift.create_artifact(level=1, power=0))
        self.hero.bag.put_artifact(
            not_child_gift.create_artifact(level=1, power=0))
        self.hero.bag.put_artifact(
            not_child_gift.create_artifact(level=1, power=0))

        self.hero.bag.put_artifact(child_gift.create_artifact(level=1,
                                                              power=0))
        self.hero.bag.put_artifact(child_gift.create_artifact(level=1,
                                                              power=0))

        self.hero.bag.put_artifact(
            removed_artifact.create_artifact(level=1, power=0))
        self.hero.bag.put_artifact(
            removed_artifact.create_artifact(
                level=1, power=0, rarity=artifacts_relations.RARITY.RARE))

        with self.check_delta(lambda: self.hero.statistics.gifts_returned, 2):
            with self.check_delta(lambda: self.hero.bag.occupation, -3):
                self.ability.use(**self.use_attributes)

    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion__no_companion(self):
        self.assertEqual(self.hero.companion, None)

        with self.check_not_changed(lambda: self.hero.statistics.help_count):
            self.assertEqual(
                self.ability.use(**self.use_attributes),
                (ComplexChangeTask.RESULT.FAILED, ComplexChangeTask.STEP.ERROR,
                 ()))

        self.assertEqual(self.hero.messages.messages[-1].key, None)

    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.hero.companion.health = 1

        with self.check_delta(lambda: self.hero.companion.health,
                              c.COMPANIONS_HEAL_AMOUNT):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertTrue(self.hero.messages.messages[-1].key.
                        is_ANGEL_ABILITY_HEAL_COMPANION)
        self.assertFalse(self.hero.messages.messages[-1].key.
                         is_ANGEL_ABILITY_HEAL_COMPANION_CRIT)

    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion__full_health(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.assertEqual(self.hero.companion.health,
                         self.hero.companion.max_health)

        with self.check_not_changed(lambda: self.hero.companion.health):
            with self.check_not_changed(
                    lambda: self.hero.statistics.help_count):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.FAILED,
                                  ComplexChangeTask.STEP.ERROR, ()))

        self.assertFalse(self.hero.messages.messages[-1].key.
                         is_ANGEL_ABILITY_HEAL_COMPANION)
        self.assertFalse(self.hero.messages.messages[-1].key.
                         is_ANGEL_ABILITY_HEAL_COMPANION_CRIT)

    @mock.patch(
        'the_tale.game.heroes.prototypes.HeroPrototype.might_crit_chance', 1)
    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion__crit(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.hero.companion.health = 1

        with self.check_delta(lambda: self.hero.companion.health,
                              c.COMPANIONS_HEAL_CRIT_AMOUNT):
            with self.check_delta(lambda: self.hero.statistics.help_count, 1):
                self.assertEqual(self.ability.use(**self.use_attributes),
                                 (ComplexChangeTask.RESULT.SUCCESSED,
                                  ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertFalse(self.hero.messages.messages[-1].key.
                         is_ANGEL_ABILITY_HEAL_COMPANION)
        self.assertTrue(self.hero.messages.messages[-1].key.
                        is_ANGEL_ABILITY_HEAL_COMPANION_CRIT)

    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion__on_heal_called(self):
        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.hero.companion.health = 1

        with mock.patch(
                'the_tale.game.actions.prototypes.ActionBase.on_heal_companion'
        ) as on_heal_companion:
            self.assertEqual(self.ability.use(**self.use_attributes),
                             (ComplexChangeTask.RESULT.SUCCESSED,
                              ComplexChangeTask.STEP.SUCCESS, ()))

        self.assertEqual(on_heal_companion.call_count, 1)

    @mock.patch(
        'the_tale.game.actions.prototypes.ActionIdlenessPrototype.HABIT_MODE',
        actions_relations.ACTION_HABIT_MODE.COMPANION)
    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion__on_heal_action_habits_changed(self):
        habit_effect = random.choice([
            ability for ability in companions_effects.ABILITIES.records
            if isinstance(ability.effect, companions_effects.ChangeHabits)
        ])

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        companion_record.abilities = companions_container.Container(
            start=[habit_effect])
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.hero.habit_honor.change(100)
        self.hero.habit_peacefulness.change(-100)

        self.hero.companion.health = 1

        with self.check_changed(lambda: self.hero.habit_honor.raw_value + self.
                                hero.habit_peacefulness.raw_value):
            self.assertEqual(self.ability.use(**self.use_attributes),
                             (ComplexChangeTask.RESULT.SUCCESSED,
                              ComplexChangeTask.STEP.SUCCESS, ()))

    @mock.patch(
        'the_tale.game.actions.prototypes.ActionIdlenessPrototype.HABIT_MODE',
        actions_relations.ACTION_HABIT_MODE.COMPANION)
    @mock.patch('the_tale.game.actions.prototypes.ActionBase.get_help_choice',
                lambda x: HELP_CHOICES.HEAL_COMPANION)
    def test_heal_companion__on_heal_action_habits_not_changed(self):
        habit_effect = random.choice([
            ability for ability in companions_effects.ABILITIES.records
            if not isinstance(ability.effect, companions_effects.ChangeHabits)
        ])

        companion_record = companions_storage.companions.enabled_companions(
        ).next()
        companion_record.abilities = companions_container.Container(
            start=[habit_effect])
        self.hero.set_companion(
            companions_logic.create_companion(companion_record))

        self.hero.habit_honor.change(100)
        self.hero.habit_peacefulness.change(-100)

        self.hero.companion.health = 1

        with self.check_not_changed(lambda: self.hero.habit_honor.raw_value +
                                    self.hero.habit_peacefulness.raw_value):
            self.assertEqual(self.ability.use(**self.use_attributes),
                             (ComplexChangeTask.RESULT.SUCCESSED,
                              ComplexChangeTask.STEP.SUCCESS, ()))
Exemple #60
0
    def setUp(self):
        super(LogicStorageTestsCommon, self).setUp()

        self.p1, self.p2, self.p3 = create_test_map()

        self.storage = LogicStorage()