Example #1
0
    def setUp(self):
        super(RepairBuildingTests, 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')

        self.building_1 = BuildingPrototype.create(person=self.place_1.persons[0], utg_name=names.generator.get_test_name('building-1-name'))
        self.building_2 = BuildingPrototype.create(person=self.place_2.persons[0], utg_name=names.generator.get_test_name('building-1-name'))

        self.building_1.amortize(c.TURNS_IN_HOUR*24)
        self.building_2.amortize(c.TURNS_IN_HOUR*24)
Example #2
0
    def __init__(self):
        register_user('forum_user', '*****@*****.**', '111111')
        register_user('forum_user_2', '*****@*****.**', '111111')

        self.account_1 = AccountPrototype.get_by_nick('forum_user')
        self.account_2 = AccountPrototype.get_by_nick('forum_user_2')

        # cat1
        # |-subcat1
        # | |-thread1
        # | | |-post1
        # | |-thread2
        # |-subcat2
        # cat2
        # | subcat3
        # | |- thread3
        # cat3

        self.cat_1 = CategoryPrototype.create(caption='cat1-caption', slug='cat1-slug', order=0)
        # to test, that subcat.id not correlate with order
        self.subcat_2 = SubCategoryPrototype.create(category=self.cat_1, caption='subcat2-caption', order=1, closed=True)
        self.subcat_1 = SubCategoryPrototype.create(category=self.cat_1, caption='subcat1-caption', order=0)
        self.cat_2 = CategoryPrototype.create(caption='cat2-caption', slug='cat2-slug', order=0)
        self.subcat_3 = SubCategoryPrototype.create(category=self.cat_2, caption='subcat3-caption', order=0)
        self.cat_3 = CategoryPrototype.create(caption='cat3-caption', slug='cat3-slug', order=0)

        self.thread_1 = ThreadPrototype.create(self.subcat_1, 'thread1-caption', self.account_1, 'thread1-text')
        self.thread_2 = ThreadPrototype.create(self.subcat_1, 'thread2-caption', self.account_1, 'thread2-text')
        self.thread_3 = ThreadPrototype.create(self.subcat_3, 'thread3-caption', self.account_1, 'thread3-text')

        self.post_1 = PostPrototype.create(self.thread_1, self.account_1, 'post1-text')

        # create test clan and clean it's forum artifacts
        self.clan_category = CategoryPrototype.create(caption='category-1', slug=clans_settings.FORUM_CATEGORY_SLUG, order=0)
        self.clan_1 = ClanPrototype.create(self.account_1, abbr=u'abbr1', name=u'name1', motto=u'motto', description=u'description')
Example #3
0
    def setUp(self):
        super(TestModeration, self).setUp()
        create_test_map()
        register_user('main_user', '*****@*****.**', '111111')
        register_user('moderator', '*****@*****.**', '111111')
        register_user('second_user', '*****@*****.**', '111111')

        self.main_account = AccountPrototype.get_by_nick('main_user')
        self.moderator = AccountPrototype.get_by_nick('moderator')
        self.second_account = AccountPrototype.get_by_nick('second_user')

        group = sync_group(forum_settings.MODERATOR_GROUP_NAME, ['forum.moderate_post', 'forum.moderate_thread'])

        group.user_set.add(self.moderator._model)

        self.client = client.Client()

        self.category = CategoryPrototype.create(caption='cat-caption', slug='cat-slug', order=0)
        self.subcategory = SubCategoryPrototype.create(category=self.category, caption='subcat-caption', order=0)
        self.subcategory2 = SubCategoryPrototype.create(category=self.category, caption='subcat2-caption', order=1, closed=True)
        self.thread = ThreadPrototype.create(self.subcategory, 'thread-caption', self.main_account, 'thread-text')
        self.post = PostPrototype.create(self.thread, self.main_account, 'post-text')
        self.post2 = PostPrototype.create(self.thread, self.main_account, 'post2-text')
        self.post5 = PostPrototype.create(self.thread, self.main_account, 'post5-text', technical=True)

        self.thread2 = ThreadPrototype.create(self.subcategory, 'thread2-caption', self.main_account, 'thread2-text')
        self.post3 = PostPrototype.create(self.thread2, self.main_account, 'post3-text')
        self.post4 = PostPrototype.create(self.thread2, self.second_account, 'post4-text')

        self.thread3 = ThreadPrototype.create(self.subcategory, 'thread3-caption', self.second_account, 'thread3-text')
Example #4
0
    def _initiate_battle(self, record_1, record_2, calculate_ratings=False):
        from the_tale.accounts.prototypes import AccountPrototype

        account_1 = AccountPrototype.get_by_id(record_1.account_id)
        account_2 = AccountPrototype.get_by_id(record_2.account_id)

        self.logger.info("start battle between accounts %d and %d" % (account_1.id, account_2.id))

        with transaction.atomic():
            battle_1 = Battle1x1Prototype.get_by_id(record_1.battle_id)
            battle_2 = Battle1x1Prototype.get_by_id(record_2.battle_id)

            battle_1.set_enemy(account_2)
            battle_2.set_enemy(account_1)

            if (
                calculate_ratings
                and abs(record_1.hero_level - record_2.hero_level) <= pvp_settings.BALANCING_MIN_LEVEL_DELTA
            ):
                battle_1.calculate_rating = True
                battle_2.calculate_rating = True

            battle_1.save()
            battle_2.save()

            task = SupervisorTaskPrototype.create_arena_pvp_1x1(account_1, account_2)

        environment.workers.supervisor.cmd_add_task(task.id)
    def setUp(self):
        super(MetaProxyActionForArenaPvP1x1Tests, 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(AccountPrototype.get_by_id(self.account_1.id))
        self.storage.load_account_data(AccountPrototype.get_by_id(self.account_2.id))

        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.pvp_create_battle(self.account_1, self.account_2, BATTLE_1X1_STATE.PROCESSING)
        self.pvp_create_battle(self.account_2, self.account_1, BATTLE_1X1_STATE.PROCESSING)

        self.bundle_id = 666

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

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

        self.storage.merge_bundles([self.action_idl_1.bundle_id, self.action_idl_2.bundle_id], self.bundle_id)

        self.meta_action_battle = self.storage.meta_actions.values()[0]
    def setUp(self):
        super(ArenaPvP1x1AbilityTest, 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")

        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.ability_1 = self.PROCESSOR()
        self.ability_2 = self.PROCESSOR()

        environment.deinitialize()
        environment.initialize()

        self.pvp_balancer = environment.workers.pvp_balancer
        self.pvp_balancer.process_initialize("pvp_balancer")
    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)
    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)
    def setUp(self):
        super(MetaProxyActionForArenaPvP1x1Tests, self).setUp()

        create_test_map()

        result, account_1_id, bundle_id = register_user('test_user_1', '*****@*****.**', '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(AccountPrototype.get_by_id(self.account_1.id))
        self.storage.load_account_data(AccountPrototype.get_by_id(self.account_2.id))

        self.hero_1 = self.storage.accounts_to_heroes[account_1_id]
        self.hero_2 = self.storage.accounts_to_heroes[account_2_id]

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

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

        self.bundle_id = 666

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

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

        self.storage.merge_bundles([self.action_idl_1.bundle_id, self.action_idl_2.bundle_id], self.bundle_id)

        self.meta_action_battle = self.storage.meta_actions.values()[0]
Example #10
0
    def test_subcategories_visible_to_account_with_permissions(self):
        register_user('test_user', '*****@*****.**', '111111')
        register_user('granted_user', '*****@*****.**', '111111')
        register_user('wrong_user', '*****@*****.**', '111111')

        granted_account = AccountPrototype.get_by_nick('granted_user')
        wrong_account = AccountPrototype.get_by_nick('wrong_user')

        category = CategoryPrototype.create(caption='cat-caption', slug='cat-slug', order=0)
        subcategory_1 = SubCategoryPrototype.create(category=category, caption='subcat-1-caption', order=2)

        SubCategoryPrototype.create(category=category, caption='subcat-2-caption', order=1, restricted=True)

        restricted_subcategory = SubCategoryPrototype.create(category=category, caption='subcat-restricted-caption', order=0, restricted=True)

        PermissionPrototype.create(granted_account, restricted_subcategory)

        self.assertEqual([s.id for s in SubCategoryPrototype.subcategories_visible_to_account(account=None)],
                         [subcategory_1.id])

        self.assertEqual([s.id for s in SubCategoryPrototype.subcategories_visible_to_account(account=granted_account)],
                         [restricted_subcategory.id, subcategory_1.id])

        self.assertEqual([s.id for s in SubCategoryPrototype.subcategories_visible_to_account(account=wrong_account)],
                         [subcategory_1.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())
Example #12
0
    def setUp(self):
        super(BaseRequestTests, self).setUp()

        create_test_map()

        result, account_id, bundle_id = register_user('test_user_1', '*****@*****.**', '111111')
        self.account_1 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user_2', '*****@*****.**', '111111')
        self.account_2 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user_3', '*****@*****.**', '111111')
        self.account_3 = AccountPrototype.get_by_id(account_id)

        group_edit_item = sync_group('edit item', ['collections.edit_item'])
        group_moderate_item = sync_group('moderate item', ['collections.moderate_item'])

        group_edit = sync_group('edit kit', ['collections.edit_kit'])
        group_moderate = sync_group('moderate kit', ['collections.moderate_kit'])

        group_edit_item.user_set.add(self.account_2._model)
        group_moderate_item.user_set.add(self.account_3._model)

        group_edit.user_set.add(self.account_2._model)
        group_moderate.user_set.add(self.account_3._model)

        self.collection_1 = CollectionPrototype.create(caption=u'collection_1', description=u'description_1')
        self.collection_2 = CollectionPrototype.create(caption=u'collection_2', description=u'description_2')

        self.kit_1 = KitPrototype.create(collection=self.collection_1, caption=u'kit_1', description=u'description_1', approved=True)
        self.kit_2 = KitPrototype.create(collection=self.collection_1, caption=u'kit_2', description=u'description_2')

        self.item_1_1 = ItemPrototype.create(kit=self.kit_1, caption=u'item_1_1', text=u'text_1_1')
        self.item_1_2 = ItemPrototype.create(kit=self.kit_1, caption=u'item_1_2', text=u'text_1_2', approved=True)
Example #13
0
    def handle(self, *args, **options):

        actions = set(AccountPrototype._db_exclude(action_id=None).values_list('action_id', flat=True).order_by('action_id').distinct())

        for action_id in actions:
            print()
            print('----%s----' % action_id)
            registered_ids = set(AccountPrototype._db_filter(action_id=action_id, is_fast=False).values_list('id', flat=True))

            print('registrations: %d' % len(registered_ids))

            payers_ids = set(InvoicePrototype._db_filter(models.Q(state=INVOICE_STATE.CONFIRMED)|models.Q(state=INVOICE_STATE.FORCED),
                                                        sender_type=ENTITY_TYPE.XSOLLA,
                                                        currency=CURRENCY_TYPE.PREMIUM).values_list('recipient_id', flat=True))

            payers_ids &= registered_ids

            print('payers: %d' % len(payers_ids))

            amounts = InvoicePrototype._db_filter(models.Q(state=INVOICE_STATE.CONFIRMED)|models.Q(state=INVOICE_STATE.FORCED),
                                                  sender_type=ENTITY_TYPE.XSOLLA,
                                                  recipient_id__in=payers_ids,
                                                  currency=CURRENCY_TYPE.PREMIUM).values_list('amount', flat=True)

            amount = sum(amounts)

            print('total gold: %d' % amount)

            if registered_ids:
                print('per account: %.2f' % (float(amount) / len(registered_ids)))

            if payers_ids:
                print('per payer: %.2f' % (float(amount) / len(payers_ids)))
Example #14
0
    def setUp(self):
        super(BaseTestRequests, self).setUp()

        self.place1, self.place2, self.place3 = create_test_map()

        result, account_id, bundle_id = register_user('test_user1', '*****@*****.**', '111111')
        self.account1 = AccountPrototype.get_by_id(account_id)
        self.account1.prolong_premium(30)
        self.account1._model.created_at -= datetime.timedelta(days=bills_settings.MINIMUM_BILL_OWNER_AGE)
        self.account1.save()

        result, account_id, bundle_id = register_user('test_user2', '*****@*****.**', '111111')
        self.account2 = AccountPrototype.get_by_id(account_id)
        self.account2.prolong_premium(30)
        self.account2._model.created_at -= datetime.timedelta(days=bills_settings.MINIMUM_BILL_OWNER_AGE)
        self.account2.save()

        self.client = client.Client()

        self.request_login('*****@*****.**')

        from the_tale.forum.models import Category, SubCategory

        forum_category = Category.objects.create(caption='Category-1', slug='category-1')
        SubCategory.objects.create(caption=bills_settings.FORUM_CATEGORY_UID + '-caption',
                                   uid=bills_settings.FORUM_CATEGORY_UID,
                                   category=forum_category)
Example #15
0
    def setUp(self):
        super(_BaseRequestTests, self).setUp()

        create_test_map()

        result, account_id, bundle_id = register_user('test_user_1', '*****@*****.**', '111111')
        self.account_1 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user_2', '*****@*****.**', '111111')
        self.account_2 = AccountPrototype.get_by_id(account_id)

        group_edit = sync_group('edit achievement', ['achievements.edit_achievement'])

        group_edit.user_set.add(self.account_2._model)

        self.achievement_1 = AchievementPrototype.create(group=ACHIEVEMENT_GROUP.MONEY, type=ACHIEVEMENT_TYPE.MONEY, barrier=0, points=10,
                                                         caption=u'achievement_1', description=u'description_1', approved=True)
        self.achievement_2 = AchievementPrototype.create(group=ACHIEVEMENT_GROUP.MONEY, type=ACHIEVEMENT_TYPE.MONEY, barrier=2, points=10,
                                                         caption=u'achievement_2', description=u'description_2', approved=False)
        self.achievement_3 = AchievementPrototype.create(group=ACHIEVEMENT_GROUP.TIME, type=ACHIEVEMENT_TYPE.TIME, barrier=3, points=10,
                                                         caption=u'achievement_3', description=u'description_3', approved=True)

        self.collection_1 = CollectionPrototype.create(caption=u'collection_1', description=u'description_1', approved=True)
        self.kit_1 = KitPrototype.create(collection=self.collection_1, caption=u'kit_1', description=u'description_1', approved=True)
        self.item_1_1 = ItemPrototype.create(kit=self.kit_1, caption=u'item_1_1', text=u'text_1_1', approved=True)
        self.item_1_2 = ItemPrototype.create(kit=self.kit_1, caption=u'item_1_2', text=u'text_1_2', approved=True)

        self.account_achievements_1 = AccountAchievementsPrototype.get_by_account_id(self.account_1.id)
        self.account_achievements_1.achievements.add_achievement(self.achievement_1)
        self.account_achievements_1.save()
Example #16
0
    def setUp(self):
        super(BuildingRepairTest, 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_1 = self.storage.accounts_to_heroes[self.account_1.id]
        self.hero_2 = self.storage.accounts_to_heroes[self.account_2.id]

        self.ability_1 = self.PROCESSOR()
        self.ability_2 = self.PROCESSOR()

        environment.deinitialize()
        environment.initialize()

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

        self.building = BuildingPrototype.create(self.place_1.persons[0], utg_name=names.generator.get_test_name('building-name'))
        self.building._model.integrity = 0.5
        self.building.save()
    def setUp(self):
        super(AchievementsManagerTests, self).setUp()

        create_test_map()

        result, account_id, bundle_id = register_user('test_user_1', '*****@*****.**', '111111')
        self.account_1 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user_2', '*****@*****.**', '111111')
        self.account_2 = AccountPrototype.get_by_id(account_id)

        group_edit = sync_group('edit achievement', ['achievements.edit_achievement'])

        group_edit.user_set.add(self.account_2._model)

        self.achievement_1 = AchievementPrototype.create(group=ACHIEVEMENT_GROUP.MONEY, type=ACHIEVEMENT_TYPE.MONEY, barrier=0, points=10,
                                                         caption=u'achievement_1', description=u'description_1', approved=True)
        self.achievement_2 = AchievementPrototype.create(group=ACHIEVEMENT_GROUP.MONEY, type=ACHIEVEMENT_TYPE.MONEY, barrier=5, points=10,
                                                         caption=u'achievement_2', description=u'description_2', approved=False)
        self.achievement_3 = AchievementPrototype.create(group=ACHIEVEMENT_GROUP.TIME, type=ACHIEVEMENT_TYPE.DEATHS, barrier=4, points=10,
                                                         caption=u'achievement_3', description=u'description_3', approved=True)


        self.account_achievements_1 = AccountAchievementsPrototype.get_by_account_id(self.account_1.id)
        self.account_achievements_1.achievements.add_achievement(self.achievement_1)
        self.account_achievements_1.save()

        self.worker = environment.workers.achievements_manager
        self.worker.initialize()
    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_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]))
Example #20
0
    def process_battle_ending(self):
        battle_1 = Battle1x1Prototype.get_by_account_id(self.hero_1.account_id)
        battle_2 = Battle1x1Prototype.get_by_account_id(self.hero_2.account_id)

        participant_1 = AccountPrototype.get_by_id(self.hero_1.account_id)
        participant_2 = AccountPrototype.get_by_id(self.hero_2.account_id)

        if self.hero_1.health <= 0:
            if self.hero_2.health <= 0:
                Battle1x1ResultPrototype.create(participant_1=participant_1, participant_2=participant_2, result =BATTLE_1X1_RESULT.DRAW)

                if battle_1.calculate_rating and battle_2.calculate_rating:
                    self.hero_1.statistics.change_pvp_battles_1x1_draws(1)
                    self.hero_2.statistics.change_pvp_battles_1x1_draws(1)
            else:
                Battle1x1ResultPrototype.create(participant_1=participant_1, participant_2=participant_2, result =BATTLE_1X1_RESULT.DEFEAT)

                if battle_1.calculate_rating and battle_2.calculate_rating:
                    self.hero_2.statistics.change_pvp_battles_1x1_victories(1)
                    self.hero_1.statistics.change_pvp_battles_1x1_defeats(1)
        else:
            Battle1x1ResultPrototype.create(participant_1=participant_1, participant_2=participant_2, result =BATTLE_1X1_RESULT.VICTORY)

            if battle_1.calculate_rating and battle_2.calculate_rating:
                self.hero_1.statistics.change_pvp_battles_1x1_victories(1)
                self.hero_2.statistics.change_pvp_battles_1x1_defeats(1)

        battle_1.remove()
        battle_2.remove()

        self.hero_1.health = self.hero_1_old_health
        self.hero_2.health = self.hero_2_old_health

        self.state = self.STATE.PROCESSED
    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._model.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_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._model.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]))
    def test_change_credentials__with_referral(self):
        self.fast_account._model.referral_of = self.account._model
        self.fast_account.save()

        self.assertTrue(AccountPrototype.get_by_id(self.fast_account.id).is_fast)

        with mock.patch("the_tale.game.workers.supervisor.Worker.cmd_update_hero_with_account_data") as fake_cmd:
            with mock.patch(
                "the_tale.accounts.workers.accounts_manager.Worker.cmd_run_account_method"
            ) as cmd_run_account_method:
                self.fast_account.change_credentials(
                    new_email="*****@*****.**", new_password=make_password("222222"), new_nick="test_nick"
                )

        self.assertEqual(cmd_run_account_method.call_count, 1)
        self.assertEqual(
            cmd_run_account_method.call_args,
            mock.call(
                account_id=self.account.id, method_name=AccountPrototype.update_referrals_number.__name__, data={}
            ),
        )

        self.assertEqual(django_authenticate(nick="test_nick", password="******").id, self.fast_account.id)
        self.assertFalse(AccountPrototype.get_by_id(self.fast_account.id).is_fast)
        self.assertEqual(fake_cmd.call_count, 1)
        self.assertFalse(fake_cmd.call_args[1]["is_fast"])
    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)
    def handle(self, *args, **options): # pylint: disable=R0914

        # account = AccountPrototype.get_by_nick('compare_abilities_user')
        # if account:
        #     account.remove()

        # account = AccountPrototype.get_by_nick('compare_abilities_user_2')
        # if account:
        #     account.remove()

        result, account_1_id, bundle_id = register_user('compare_abilities_user') # pylint: disable=W0612
        result, account_2_id, bundle_id = register_user('compare_abilities_user_2') # pylint: disable=W0612

        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]

        set_heroes_companion(hero_1, hero_2)

        try:

            abilities = [ability_class
                         for ability_class in ABILITIES.values()
                         if (ability_class.AVAILABILITY.value & ABILITY_AVAILABILITY.FOR_PLAYERS.value and
                             ability_class.get_id() != 'hit' and
                             ability_class.TYPE == ABILITY_TYPE.BATTLE) ]

            ability_matches = compare_abilities(hero_1, hero_2, abilities, level=LEVEL)

            ability_statistics = dict( (ability.get_id(), 0) for ability in abilities)
            ability_wins = dict( (ability.get_id(), []) for ability in abilities)

            for (ability_1_id, ability_2_id), (ability_1_wins, ability_2_wins) in ability_matches.items():
                ability_statistics[ability_1_id] = ability_statistics.get(ability_1_id, 0) + ability_1_wins
                ability_statistics[ability_2_id] = ability_statistics.get(ability_2_id, 0) + ability_2_wins

                ability_wins[ability_1_id].append(ability_1_wins)
                ability_wins[ability_2_id].append(ability_2_wins)

            statistics = sorted(ability_statistics.items(), key=lambda stat: -stat[1])

            battles_per_ability = TEST_BATTLES_NUMBER * (len(abilities)-1)

            for ability_id, wins in statistics:
                print '%d\t%.0f%%\t%s' % (wins, 100*float(wins)/(battles_per_ability*len(HERO_LEVELS)), ability_id)

            save_ability_power_statistics(statistics)
            save_ability_mathces_statistics(statistics, ability_matches)
            save_ability_wins_distribution(statistics, ability_wins)

        finally:
            remove_account(account_1)
            remove_account(account_2)
    def setUp(self):
        super(AccountPrototypeTests, 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.account = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user("fast_user")
        self.fast_account = AccountPrototype.get_by_id(account_id)
Example #27
0
    def setUp(self):
        super(FormGameInfoTests, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user_1')
        self.account_1 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user_2')
        self.account_2 = AccountPrototype.get_by_id(account_id)
    def setUp(self):
        super(TestChangeCredentialsTask, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user', '*****@*****.**', '111111')
        self.test_account = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('fast_user')
        self.fast_account = AccountPrototype.get_by_id(account_id)
Example #29
0
    def setUp(self):
        super(SupervisorTaskTests, 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)
Example #30
0
    def setUp(self):
        super(SendMailTests, self).setUp()

        create_test_map()

        register_user('user_1', '*****@*****.**', '111111')
        self.account_1 = AccountPrototype.get_by_nick('user_1')

        register_user('user_2', '*****@*****.**', '111111')
        self.account_2 = AccountPrototype.get_by_nick('user_2')
Example #31
0
 def get_accounts_for_thread(cls, thread):
     accounts = Account.objects.filter(subscription__thread_id=thread.id)
     return [AccountPrototype(model=account) for account in accounts]
Example #32
0
    def sender(self): return AccountPrototype.get_by_id(self.sender_id)

    @lazy_property
Example #33
0
    def index(self):

        if portal_settings.ENABLE_FIRST_TIME_REDIRECT and accounts_logic.is_first_time_visit(
                self.request):
            return self.redirect(
                random.choice(portal_settings.FIRST_TIME_LANDING_URLS))

        news = news_logic.load_news_from_query(
            news_models.News.objects.all().order_by(
                '-created_at')[:portal_settings.NEWS_ON_INDEX])

        bills = BillPrototype.get_recently_modified_bills(
            portal_settings.BILLS_ON_INDEX)

        account_of_the_day_id = settings.get(
            portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY)

        hero_of_the_day = None
        account_of_the_day = None
        clan_of_the_day = None

        if account_of_the_day_id is not None:
            hero_of_the_day = heroes_logic.load_hero(
                account_id=account_of_the_day_id)
            account_of_the_day = AccountPrototype.get_by_id(
                account_of_the_day_id)

            if account_of_the_day and account_of_the_day.clan_id is not None:
                clan_of_the_day = ClanPrototype.get_by_id(
                    account_of_the_day.clan_id)

        forum_threads = ThreadPrototype.get_last_threads(
            account=self.account if self.account.is_authenticated else None,
            limit=portal_settings.FORUM_THREADS_ON_INDEX)

        blog_posts = [
            BlogPostPrototype(blog_post_model)
            for blog_post_model in BlogPost.objects.filter(state__in=[
                BLOG_POST_STATE.ACCEPTED, BLOG_POST_STATE.NOT_MODERATED
            ],
                                                           votes__gte=0).
            order_by('-created_at')[:portal_settings.BLOG_POSTS_ON_INDEX]
        ]

        map_info = map_info_storage.item

        chronicle_records = ChronicleRecordPrototype.get_last_records(
            portal_settings.CHRONICLE_RECORDS_ON_INDEX)

        chronicle_actors = RecordToActorPrototype.get_actors_for_records(
            chronicle_records)

        return self.template(
            'portal/index.html', {
                'news': news,
                'forum_threads': forum_threads,
                'bills': bills,
                'hero_of_the_day': hero_of_the_day,
                'account_of_the_day': account_of_the_day,
                'clan_of_the_day': clan_of_the_day,
                'map_info': map_info,
                'blog_posts': blog_posts,
                'TERRAIN': TERRAIN,
                'MAP_STATISTICS': MAP_STATISTICS,
                'chronicle_records': chronicle_records,
                'chronicle_actors': chronicle_actors,
                'RACE': RACE
            })
Example #34
0
    def test_corridor(self):

        # fill_empty_keys_with_fake_phrases(u'test_hero_level_companion')

        result, account_id, bundle_id = register_user(uuid.uuid4().hex)  # pylint: disable=W0612
        self.storage = LogicStorage()
        self.storage.load_account_data(AccountPrototype.get_by_id(account_id))
        self.hero = self.storage.accounts_to_heroes[account_id]

        self.set_hero_companion()

        current_time = TimePrototype.get_current_time()

        for level in xrange(1, 100):
            print
            print '-----------------------------------------------------------------------'
            print 'process level %d\texpected turns: %d\texpected days: %.2f' % (
                level, f.turns_on_lvl(level), f.time_on_lvl(level) / 24)

            for i in xrange(f.turns_on_lvl(level)):  # pylint: disable=W0612
                self.storage.process_turn()
                current_time.increment_turn()

                # simulate user behaviour on healing companion
                if self.hero.companion.health < self.hero.companion.max_health / 2:
                    self.hero.companion.health = self.hero.companion.max_health

            self.hero.randomized_level_up()

            exp_to_next_level = float(self.hero.experience) / f.exp_on_lvl(
                self.hero.level) * 100
            exp_from_expected = float(
                f.total_exp_to_lvl(self.hero.level) +
                self.hero.experience) / f.total_exp_to_lvl(level + 1) * 100
            exp_untaken = f.total_exp_to_lvl(level + 1) - f.total_exp_to_lvl(
                self.hero.level) - self.hero.experience
            quests_untaken = float(exp_untaken) / f.experience_for_quest(
                c.QUEST_AREA_RADIUS)
            print u'hero level: %d\texp: %.2f%%\texp from expected: %.2f%% (%d exp, %.2f quests)\ttotal quests %d' % (
                self.hero.level, exp_to_next_level, exp_from_expected,
                exp_untaken, quests_untaken, self.hero.statistics.quests_done)
            print u'abilities: %s' % ' '.join(u'%s-%d' %
                                              (ability_id, ability.level)
                                              for ability_id, ability in self.
                                              hero.abilities.abilities.items())
            print u'deaths: %d' % self.hero.statistics.pve_deaths

            total_gold = f.total_gold_at_lvl(self.hero.level)
            print u'total money: %d from expected %d (x%.2f)' % (
                self.hero.statistics.money_earned, total_gold,
                float(self.hero.statistics.money_earned) /
                total_gold if total_gold > 0 else 0)

            total_artifacts = int(
                f.total_time_for_lvl(self.hero.level) / 24 *
                c.ARTIFACTS_LOOT_PER_DAY)
            print u'total artifacts: %d from expected %d (x%.2f)' % (
                self.hero.statistics.artifacts_had, total_artifacts,
                float(self.hero.statistics.artifacts_had) /
                total_artifacts if total_artifacts > 0 else 0)
            print u'power: %r from expected %r' % (
                self.hero.power,
                Power.power_to_level(
                    self.hero.preferences.archetype.power_distribution,
                    self.hero.level))
            print u'power total: %d from expected %r (x%.2f)' % (
                self.hero.power.total(),
                Power.power_to_level(
                    self.hero.preferences.archetype.power_distribution,
                    self.hero.level).total(),
                float(self.hero.power.total()) / Power.power_to_level(
                    self.hero.preferences.archetype.power_distribution,
                    self.hero.level).total())
Example #35
0
 def process_register_account(self, account_id):
     from the_tale.accounts.prototypes import AccountPrototype
     account = AccountPrototype.get_by_id(account_id)
     if account is None:
         raise LogicException('can not get account with id "%d"' % (account_id,))
     self.storage.load_account_data(account)
    def setUp(self):
        super(ChangeEmailNotificationTests, self).setUp()
        create_test_map()

        register_user('user_1', '*****@*****.**', '111111')
        self.account = AccountPrototype.get_by_nick('user_1')
Example #37
0
    def account(self): return AccountPrototype.get_by_id(self.account_id) if self.account_id is not None else None

    def process_transaction_requested(self, main_task):
Example #38
0
    def author(self): return AccountPrototype(self._model.author) if self._model.author else None

    @property
Example #39
0
    def recipient(self): return AccountPrototype.get_by_id(self.recipient_id)

    def process(self, main_task):
Example #40
0
    def index(self,
              page=1,
              author_id=None,
              order_by=ORDER_BY.CREATED_AT,
              tag_id=None):

        posts_query = models.Post.objects.filter(state__in=[
            relations.POST_STATE.NOT_MODERATED, relations.POST_STATE.ACCEPTED
        ])

        is_filtering = False

        author_account = None

        if author_id is not None:

            try:
                author_id = int(author_id)
            except ValueError:
                return self.redirect(reverse('blogs:posts:'), permanent=False)

            author_account = AccountPrototype.get_by_id(author_id)
            if author_account:
                posts_query = posts_query.filter(author_id=author_account.id)
                is_filtering = True
            else:
                posts_query = models.Post.objects.none()

        if tag_id is not None:
            posts_query = posts_query.filter(
                id__in=models.Tagged.objects.filter(
                    tag_id=tag_id).values_list('post_id', flat=True))

        if order_by is not None:
            if order_by == ORDER_BY.ALPHABET:
                posts_query = posts_query.order_by('caption')
            elif order_by == ORDER_BY.CREATED_AT:
                posts_query = posts_query.order_by('-created_at')
            elif order_by == ORDER_BY.RATING:
                posts_query = posts_query.order_by('-votes')
            elif order_by == ORDER_BY.MIGHT:
                posts_query = posts_query.order_by('-rating')
            else:
                order_by = ORDER_BY.CREATED_AT
                posts_query = posts_query.order_by('-created_at')

        url_builder = UrlBuilder(reverse('blogs:posts:'),
                                 arguments={
                                     'author_id': author_id,
                                     'order_by': order_by,
                                     'tag_id': tag_id
                                 })

        posts_count = posts_query.count()

        page = int(page) - 1

        paginator = Paginator(page, posts_count, conf.settings.POSTS_ON_PAGE,
                              url_builder)

        if paginator.wrong_page_number:
            return self.redirect(paginator.last_page_url, permanent=False)

        post_from, post_to = paginator.page_borders(page)

        posts = [
            prototypes.PostPrototype(post)
            for post in posts_query.select_related()[post_from:post_to]
        ]

        votes = {}

        if self.account.is_authenticated:
            votes = dict((vote.post_id, prototypes.VotePrototype(vote))
                         for vote in models.Vote.objects.filter(
                             post_id__in=[post.id for post in posts],
                             voter=self.account._model))

        return self.template(
            'blogs/index.html', {
                'posts':
                posts,
                'page_type':
                'index',
                'votes':
                votes,
                'FORUM_TAGS_THREAD':
                conf.settings.FORUM_TAGS_THREAD,
                'order_by':
                order_by,
                'current_tag':
                models.Tag.objects.get(
                    id=tag_id) if tag_id is not None else None,
                'ORDER_BY':
                ORDER_BY,
                'is_filtering':
                is_filtering,
                'current_page_number':
                page,
                'author_account':
                author_account,
                'paginator':
                paginator,
                'url_builder':
                url_builder
            })
Example #41
0
    def index(self,
              key=None,
              state=None,
              filter=None,
              restriction=None,
              errors_status=None,
              page=1,
              contributor=None,
              order_by=relations.INDEX_ORDER_BY.UPDATED_AT):
        templates_query = prototypes.TemplatePrototype._db_all().order_by(
            'raw_template')

        if contributor is not None:
            entities_ids = prototypes.ContributionPrototype._db_filter(
                type=relations.CONTRIBUTION_TYPE.TEMPLATE,
                account_id=contributor.id).values_list('entity_id', flat=True)
            templates_query = templates_query.filter(
                models.Q(id__in=entities_ids)
                | models.Q(author_id=contributor.id))

        if key:
            templates_query = templates_query.filter(key=key)

        if state:
            templates_query = templates_query.filter(state=state)

        if errors_status:
            templates_query = templates_query.filter(
                errors_status=errors_status)

        if restriction:
            templates_query = templates_query.filter(
                templaterestriction__restriction_id=restriction.id)

        if filter:
            templates_query = templates_query.filter(
                raw_template__icontains=filter)

        if order_by.is_UPDATED_AT:
            templates_query = templates_query.order_by('-updated_at')
        elif order_by.is_TEXT:
            templates_query = templates_query.order_by('raw_template')

        page = int(page) - 1

        templates_count = templates_query.count()

        url_builder = UrlBuilder(
            reverse('linguistics:templates:'),
            arguments={
                'state': state.value if state else None,
                'errors_status':
                errors_status.value if errors_status else None,
                'contributor': contributor.id if contributor else None,
                'order_by': order_by.value,
                'filter': filter,
                'restriction':
                restriction.id if restriction is not None else None,
                'key': key.value if key is not None else None
            })

        index_filter = TemplatesIndexFilter(
            url_builder=url_builder,
            values={
                'state': state.value if state else None,
                'errors_status':
                errors_status.value if errors_status else None,
                'contributor': contributor.nick if contributor else None,
                'order_by': order_by.value,
                'filter': filter,
                'restriction':
                restriction.id if restriction is not None else None,
                'key': key.value if key is not None else None,
                'count': templates_query.count()
            })

        paginator = Paginator(page, templates_count,
                              linguistics_settings.TEMPLATES_ON_PAGE,
                              url_builder)

        if paginator.wrong_page_number:
            return self.redirect(paginator.last_page_url, permanent=False)

        template_from, template_to = paginator.page_borders(page)

        templates = prototypes.TemplatePrototype.from_query(
            templates_query[template_from:template_to])

        authors = {
            account.id: account
            for account in AccountPrototype.from_query(
                AccountPrototype.get_list_by_id(
                    [template.author_id for template in templates]))
        }
        clans = {
            clan.id: clan
            for clan in ClanPrototype.from_query(
                ClanPrototype.get_list_by_id(
                    [author.clan_id for author in authors.itervalues()]))
        }

        return self.template(
            'linguistics/templates/index.html', {
                'key': key,
                'templates': templates,
                'index_filter': index_filter,
                'page_type': 'all-templates',
                'paginator': paginator,
                'authors': authors,
                'clans': clans,
                'LEXICON_KEY': keys.LEXICON_KEY
            })
 def test_process__only_active_initiator(self):
     AccountPrototype._db_all().update(
         active_end_at=datetime.datetime.now() + datetime.timedelta(days=1))
     self.account_2.remove()
     self.request.process()
     self.check_not_processed()
Example #43
0
 def account(self):
     return AccountPrototype(model=self._model.account)
Example #44
0
    def account(self): return AccountPrototype.get_by_id(self.account_id) if self.account_id is not None else None

    def get_unique_nick(self):
 def test_process__no_active_accounts(self):
     AccountPrototype._db_all().update(
         active_end_at=datetime.datetime.now())
     self.request.process()
     self.check_not_processed()
Example #46
0
 def get_accounts_for_subcategory(cls, subcategory):
     accounts = Account.objects.filter(subscription__subcategory_id=subcategory.id)
     return [AccountPrototype(model=account) for account in accounts]
Example #47
0
    def initialize(self, account, thread, page, inline=False):

        self.account = account
        self.thread = thread

        url_builder = UrlBuilder(reverse('forum:threads:show',
                                         args=[self.thread.id]),
                                 arguments={'page': page})

        page -= 1

        self.paginator = Paginator(page, thread.posts_count + 1,
                                   forum_settings.POSTS_ON_PAGE, url_builder)

        if self.paginator.wrong_page_number:
            return False

        post_from, post_to = self.paginator.page_borders(page)
        self.post_from = post_from

        self.posts = [
            PostPrototype(post_model)
            for post_model in Post.objects.filter(thread=self.thread._model).
            order_by('created_at')[post_from:post_to]
        ]

        self.authors = {
            author.id: author
            for author in AccountPrototype.get_list_by_id(
                [post.author_id for post in self.posts])
        }

        self.game_objects = {
            game_object.account_id: game_object
            for game_object in heroes_logic.load_heroes_by_account_ids(
                [post.author_id for post in self.posts])
        }

        pages_on_page_slice = self.posts
        if post_from == 0:
            pages_on_page_slice = pages_on_page_slice[1:]

        self.has_post_on_page = any([
            post.author.id == self.account.id for post in pages_on_page_slice
        ])
        self.new_post_form = forms.NewPostForm()
        self.start_posts_from = page * forum_settings.POSTS_ON_PAGE

        self.inline = inline

        self.can_delete_posts = can_delete_posts(self.account, self.thread)
        self.can_change_posts = can_change_posts(self.account)
        self.can_delete_thread = not self.inline and can_delete_thread(
            self.account)
        self.can_change_thread = not self.inline and can_change_thread(
            self.account, self.thread)

        self.ignore_first_post = (self.inline
                                  and self.paginator.current_page_number == 0)
        self.can_post = self.account.is_authenticated(
        ) and not self.account.is_fast

        self.no_posts = (len(self.posts) == 0) or (self.ignore_first_post
                                                   and len(self.posts) == 1)
        self.can_subscribe = self.account.is_authenticated(
        ) and not self.account.is_fast

        self.has_subscription = SubscriptionPrototype.has_subscription(
            self.account, self.thread)

        return True
Example #48
0
    def last_poster(self): return AccountPrototype(self._model.last_poster) if self._model.last_poster else None

    @lazy_property
Example #49
0
    def handle(self, *args, **options):  # pylint: disable=R0914

        # account = AccountPrototype.get_by_nick('compare_abilities_user')
        # if account:
        #     account.remove()

        # account = AccountPrototype.get_by_nick('compare_abilities_user_2')
        # if account:
        #     account.remove()

        result, account_1_id, bundle_id = register_user(
            'compare_abilities_user')  # pylint: disable=W0612
        result, account_2_id, bundle_id = register_user(
            'compare_abilities_user_2')  # pylint: disable=W0612

        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]

        set_heroes_companion(hero_1, hero_2)

        try:

            abilities = [
                ability_class for ability_class in ABILITIES.values()
                if (ability_class.AVAILABILITY.value
                    & ABILITY_AVAILABILITY.FOR_PLAYERS.value
                    and ability_class.get_id() != 'hit'
                    and ability_class.TYPE == ABILITY_TYPE.BATTLE)
            ]

            ability_matches = compare_abilities(hero_1,
                                                hero_2,
                                                abilities,
                                                level=LEVEL)

            ability_statistics = dict(
                (ability.get_id(), 0) for ability in abilities)
            ability_wins = dict(
                (ability.get_id(), []) for ability in abilities)

            for (ability_1_id,
                 ability_2_id), (ability_1_wins,
                                 ability_2_wins) in ability_matches.items():
                ability_statistics[ability_1_id] = ability_statistics.get(
                    ability_1_id, 0) + ability_1_wins
                ability_statistics[ability_2_id] = ability_statistics.get(
                    ability_2_id, 0) + ability_2_wins

                ability_wins[ability_1_id].append(ability_1_wins)
                ability_wins[ability_2_id].append(ability_2_wins)

            statistics = sorted(ability_statistics.items(),
                                key=lambda stat: -stat[1])

            battles_per_ability = TEST_BATTLES_NUMBER * (len(abilities) - 1)

            for ability_id, wins in statistics:
                print '%d\t%.0f%%\t%s' % (
                    wins, 100 * float(wins) /
                    (battles_per_ability * len(HERO_LEVELS)), ability_id)

            save_ability_power_statistics(statistics)
            save_ability_mathces_statistics(statistics, ability_matches)
            save_ability_wins_distribution(statistics, ability_wins)

        finally:
            remove_account(account_1)
            remove_account(account_2)
 def test_process__only_fast_accounts(self):
     AccountPrototype._db_all().update(
         active_end_at=datetime.datetime.now() + datetime.timedelta(days=1),
         is_fast=True)
     self.request.process()
     self.check_not_processed()
Example #51
0
    def test_send_premium_expired_notifications(self):
        self.assertEqual(PersonalMessagePrototype._db_count(), 0)

        register_user('test_user_2', '*****@*****.**', '111111')
        register_user('test_user_3', '*****@*****.**', '111111')
        register_user('test_user_4', '*****@*****.**', '111111')

        account_1 = self.account
        account_2 = AccountPrototype.get_by_nick('test_user_2')
        account_3 = AccountPrototype.get_by_nick('test_user_3')
        account_4 = AccountPrototype.get_by_nick('test_user_4')

        account_1.prolong_premium(
            accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days - 1)
        account_1.save()

        account_3.prolong_premium(
            accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days - 1)
        account_3.save()

        account_4.prolong_premium(
            accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days + 1)
        account_4.save()

        zero_time = datetime.datetime.fromtimestamp(0)

        self.assertEqual(account_1._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertEqual(account_3._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at,
                         zero_time)

        AccountPrototype.send_premium_expired_notifications()

        account_1.reload()
        account_2.reload()
        account_3.reload()
        account_4.reload()

        self.assertNotEqual(
            account_1._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertNotEqual(
            account_3._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at,
                         zero_time)

        current_time = datetime.datetime.now()

        self.assertTrue(
            current_time - datetime.timedelta(seconds=60) < account_1._model.
            premium_expired_notification_send_at < current_time)
        self.assertTrue(
            current_time - datetime.timedelta(seconds=60) < account_3._model.
            premium_expired_notification_send_at < current_time)

        self.assertEqual(PersonalMessagePrototype._db_count(), 2)
Example #52
0
 def filter_recipients(cls, ids):
     return set(
         AccountPrototype._db_exclude(
             membership__account__in=ids).values_list('id', flat=True))
Example #53
0
    def index(self):

        registration_attemps_number = AccountPrototype._model_class.objects.all(
        ).aggregate(models.Max('id'))['id__max']
        accounts_total = AccountPrototype._model_class.objects.all().count()
        accounts_bots = AccountPrototype._model_class.objects.filter(
            is_bot=True).count()
        accounts_registered = AccountPrototype.live_query().count()
        accounts_active = AccountPrototype.live_query().filter(
            active_end_at__gt=datetime.datetime.now()).count()
        accounts_premium = AccountPrototype.live_query().filter(
            premium_end_at__gt=datetime.datetime.now()).count()
        accounts_active_and_premium = AccountPrototype.live_query().filter(
            active_end_at__gt=datetime.datetime.now(),
            premium_end_at__gt=datetime.datetime.now()).count()

        accounts_referrals = AccountPrototype.live_query().exclude(
            referral_of=None).count()
        accounts_referrals_and_premium = AccountPrototype.live_query().exclude(
            referral_of=None).filter(
                premium_end_at__gt=datetime.datetime.now()).count()
        accounts_referrals_and_active = AccountPrototype.live_query().exclude(
            referral_of=None).filter(
                active_end_at__gt=datetime.datetime.now(),
                premium_end_at__gt=datetime.datetime.now()).count()

        gold = {}
        gold_total_spent = 0
        gold_total_received = 0
        real_gold_total_spent = 0
        real_gold_total_received = 0

        for record in BANK_ENTITY_TYPE.records:
            spent = -BankAccountPrototype._money_spent(from_type=record)
            received = BankAccountPrototype._money_received(from_type=record)
            gold[record.text] = {'spent': spent, 'received': received}

            gold_total_spent += spent
            gold_total_received += received

            if record.is_real:
                real_gold_total_spent += spent
                real_gold_total_received += received

        gold_in_game = gold_total_received - gold_total_spent
        real_gold_in_game = real_gold_total_received - real_gold_total_spent

        return self.template(
            'developers_info/index.html', {
                'registration_attemps_number':
                registration_attemps_number,
                'accounts_total':
                accounts_total,
                'accounts_bots':
                accounts_bots,
                'accounts_registered':
                accounts_registered,
                'accounts_active':
                accounts_active,
                'accounts_premium':
                accounts_premium,
                'accounts_active_and_premium':
                accounts_active_and_premium,
                'accounts_referrals':
                accounts_referrals,
                'accounts_referrals_and_premium':
                accounts_referrals_and_premium,
                'accounts_referrals_and_active':
                accounts_referrals_and_active,
                'gold':
                gold,
                'gold_total_spent':
                gold_total_spent,
                'gold_total_received':
                gold_total_received,
                'gold_in_game':
                gold_in_game,
                'real_gold_in_game':
                real_gold_in_game,
                'referers_statistics':
                get_referers_statistics(),
                'invoice_statistics':
                get_invoice_statistics(),
                'invoice_count':
                InvoiceQuery.count(),
                'repeatable_payments_statistics':
                get_repeatable_payments_statistics(),
                'PAYMENT_GROUPS':
                PAYMENT_GROUPS,
                'PREMIUM_DAYS_FOR_HERO_OF_THE_DAY':
                portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY,
                'page_type':
                'index'
            })
Example #54
0
 def test_process_add_to_arena_queue_two_requests_from_one_account(self):
     battle_1 = Battle1x1Prototype.create(AccountPrototype.get_by_id(self.account_1.id))
     battle_2 = Battle1x1Prototype.create(AccountPrototype.get_by_id(self.account_1.id))
     self.assertEqual(Battle1x1.objects.all().count(), 1)
     self.assertEqual(battle_1.id, battle_2.id)
Example #55
0
    def process(self, main_task, storage):

        hero = storage.heroes[self.hero_id]

        account = AccountPrototype.get_by_id(hero.account_id)

        if not hero.preferences.can_update(self.preference_type,
                                           datetime.datetime.now()):
            main_task.comment = u'blocked since time delay'
            self.state = CHOOSE_PREFERENCES_TASK_STATE.COOLDOWN
            return POSTPONED_TASK_LOGIC_RESULT.ERROR

        if not hero.preferences.is_available(self.preference_type, account):
            main_task.comment = u'hero level < required level (%d < %d)' % (
                hero.level, self.preference_type.level_required)
            self.state = CHOOSE_PREFERENCES_TASK_STATE.LOW_LEVEL
            return POSTPONED_TASK_LOGIC_RESULT.ERROR

        if self.preference_type.is_ENERGY_REGENERATION_TYPE:
            result = self.process_energy_regeneration(main_task, hero)

        elif self.preference_type.is_MOB:
            result = self.process_mob(main_task, hero)

        elif self.preference_type.is_PLACE:
            result = self.process_place(main_task, hero)

        elif self.preference_type.is_FRIEND:
            result = self.process_friend(main_task, hero)

        elif self.preference_type.is_ENEMY:
            result = self.process_enemy(main_task, hero)

        elif self.preference_type.is_EQUIPMENT_SLOT:
            result = self.process_equipment_slot(main_task, hero)

        elif self.preference_type.is_RISK_LEVEL:
            result = self.process_risk_level(main_task, hero)

        elif self.preference_type.is_FAVORITE_ITEM:
            result = self.process_favorite_item(main_task, hero)

        elif self.preference_type.is_ARCHETYPE:
            result = self.process_archetype(main_task, hero)

        elif self.preference_type.is_COMPANION_DEDICATION:
            result = self.process_companion_dedication(main_task, hero)

        elif self.preference_type.is_COMPANION_EMPATHY:
            result = self.process_companion_empathy(main_task, hero)

        else:
            main_task.comment = u'unknown preference type: %s' % (
                self.preference_type, )
            self.state = CHOOSE_PREFERENCES_TASK_STATE.UNKNOWN_PREFERENCE
            return POSTPONED_TASK_LOGIC_RESULT.ERROR

        if result == POSTPONED_TASK_LOGIC_RESULT.SUCCESS:

            storage.save_bundle_data(hero.actions.current_action.bundle_id)

            self.state = CHOOSE_PREFERENCES_TASK_STATE.PROCESSED

        return result
Example #56
0
 def owner(self):
     return AccountPrototype(self._model.owner)
Example #57
0
 def owner(self):
     if not hasattr(self, '_owner'):
         self._owner = AccountPrototype(self._model.owner)
     return self._owner
Example #58
0
    def account(self): return AccountPrototype.get_by_id(self.account_id)

    @property
Example #59
0
 def accept_request(self, request):
     accepted_account = AccountPrototype.get_by_id(request.account_id)
     self.clan_info.clan.add_member(accepted_account)
     request.create_accept_request_message(initiator=self.account)
     request.remove()
     return self.json_ok()
Example #60
0
    def index(self,
              page=1,
              state=None,
              type=None,
              filter=None,
              contributor=None,
              order_by=relations.INDEX_ORDER_BY.UPDATED_AT):

        words_query = prototypes.WordPrototype._db_all().order_by(
            'normal_form')

        if contributor is not None:
            entities_ids = prototypes.ContributionPrototype._db_filter(
                type=relations.CONTRIBUTION_TYPE.WORD,
                account_id=contributor.id).values_list('entity_id', flat=True)
            words_query = words_query.filter(
                models.Q(id__in=entities_ids)
                | models.Q(author_id=contributor.id))

        if state:
            words_query = words_query.filter(state=state)

        if type:
            words_query = words_query.filter(type=type.utg_type)

        if filter:
            words_query = words_query.filter(
                normal_form__istartswith=filter.lower())

        if order_by.is_UPDATED_AT:
            words_query = words_query.order_by('-updated_at')
        elif order_by.is_TEXT:
            words_query = words_query.order_by('normal_form')

        words_count = words_query.count()

        url_builder = UrlBuilder(reverse('linguistics:words:'),
                                 arguments={
                                     'state':
                                     state.value if state else None,
                                     'type':
                                     type.value if type else None,
                                     'contributor':
                                     contributor.id if contributor else None,
                                     'order_by':
                                     order_by.value,
                                     'filter':
                                     filter
                                 })

        index_filter = WordsIndexFilter(
            url_builder=url_builder,
            values={
                'state': state.value if state else None,
                'type': type.value if type else None,
                'filter': filter,
                'contributor': contributor.nick if contributor else None,
                'order_by': order_by.value,
                'count': words_count
            })

        page = int(page) - 1

        paginator = Paginator(page, words_count,
                              linguistics_settings.WORDS_ON_PAGE, url_builder)

        if paginator.wrong_page_number:
            return self.redirect(paginator.last_page_url, permanent=False)

        words_from, words_to = paginator.page_borders(page)

        words = prototypes.WordPrototype.from_query(
            words_query[words_from:words_to])

        authors = {
            account.id: account
            for account in AccountPrototype.from_query(
                AccountPrototype.get_list_by_id(
                    [word.author_id for word in words]))
        }
        clans = {
            clan.id: clan
            for clan in ClanPrototype.from_query(
                ClanPrototype.get_list_by_id(
                    [author.clan_id for author in authors.itervalues()]))
        }

        return self.template(
            'linguistics/words/index.html', {
                'words': words,
                'page_type': 'dictionary',
                'paginator': paginator,
                'authors': authors,
                'clans': clans,
                'ALLOWED_WORD_TYPE': relations.ALLOWED_WORD_TYPE,
                'index_filter': index_filter
            })