def setUp(self): super(RefrigeratorTests, self).setUp() environment.deinitialize() environment.initialize() self.worker = environment.workers.refrigerator self.worker.initialize() self.task_1 = PostponedTaskPrototype.create(FakePostponedInternalTask(result_state=POSTPONED_TASK_LOGIC_RESULT.WAIT)) self.task_2 = PostponedTaskPrototype.create(FakePostponedInternalTask())
def initialize(self): self.clean_queues() self.gracefull_stop_required = False self.time = prototypes.TimePrototype.get_current_time() PostponedTaskPrototype.reset_all() self.logic_workers = {worker.name: worker for worker in (environment.workers.logic_1, environment.workers.logic_2)} self.logger.info('initialize logic') self.logic_multicast('initialize', arguments=dict(turn_number=self.time.turn_number), worker_id=True, wait_answer=True) if conf.game_settings.ENABLE_WORKER_HIGHLEVEL: self.logger.info('initialize highlevel') environment.workers.highlevel.cmd_initialize(turn_number=self.time.turn_number, worker_id='highlevel') self.wait_answers_from('initialize', workers=['highlevel']) else: self.logger.info('skip initialization of highlevel') if conf.game_settings.ENABLE_PVP: self.logger.info('initialize pvp balancer') environment.workers.pvp_balancer.cmd_initialize(worker_id='pvp_balancer') self.wait_answers_from('initialize', workers=['pvp_balancer']) else: self.logger.info('skip initialization of pvp balancer') self.logger.info('child workers initialized') self.logger.info('register task') self.tasks = {} self.accounts_for_tasks = {} self.accounts_owners = {} self.accounts_queues = {} self.logic_accounts_number = {logic_worker_name: 0 for logic_worker_name in self.logic_workers.keys()} for task_model in models.SupervisorTask.objects.filter(state=relations.SUPERVISOR_TASK_STATE.WAITING).iterator(): task = prototypes.SupervisorTaskPrototype(task_model) self.register_task(task, release_accounts=False) self.logger.info('distribute accounts') for account_id in Account.objects.all().order_by('id').values_list('id', flat=True).iterator(): self.register_account(account_id) self.initialized = True self.wait_next_turn_answer = False prototypes.GameState.start() self.logger.info('SUPERVISOR INITIALIZED')
def handle(self, *args, **options): from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype from the_tale.forum.prototypes import SubCategoryReadInfoPrototype, ThreadReadInfoPrototype from the_tale.post_service.prototypes import MessagePrototype PostponedTaskPrototype.remove_old_tasks() ThreadReadInfoPrototype.remove_old_infos() SubCategoryReadInfoPrototype.remove_old_infos() MessagePrototype.remove_old_messages()
def test_1_process(self): self.assertEqual(PostponedTaskPrototype._model_class.objects.all().count(), 0) self.assertEqual(ChangeCredentialsTaskPrototype._model_class.objects.all().count(), 0) new_password = self.task.process(logger=mock.Mock()) self.assertTrue(self.task.is_processed) self.assertEqual(django_authenticate(nick='test_user', password='******').id, self.account.id) self.assertEqual(PostponedTaskPrototype._model_class.objects.all().count(), 1) self.assertEqual(ChangeCredentialsTaskPrototype._model_class.objects.all().count(), 1) PostponedTaskPrototype._db_get_object(0).process(logger=mock.Mock()) self.assertEqual(django_authenticate(nick='test_user', password='******'), None) self.assertEqual(django_authenticate(nick='test_user', password=new_password).id, self.account.id)
def test_choose_ability_request_ok(self): self.request_login("*****@*****.**") response = self.client.post( reverse("game:heroes:choose-ability", args=[self.hero.id]) + "?ability_id=" + self.get_new_ability_id() ) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url)
def test_reset_all(self): task = PostponedTaskPrototype.create(FakePostponedInternalTask()) task.state = POSTPONED_TASK_STATE.PROCESSED task.save() self.assertEqual(PostponedTask.objects.all().count(), 2) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 1) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.PROCESSED).count(), 1) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.RESETED).count(), 0) PostponedTaskPrototype.reset_all() self.assertEqual(PostponedTask.objects.all().count(), 2) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 0) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.PROCESSED).count(), 1) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.RESETED).count(), 1)
def purchase_lot(buyer_id, lot): from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype from the_tale.finances.market import postponed_tasks invoice = bank_prototypes.InvoicePrototype.create(recipient_type=bank_relations.ENTITY_TYPE.GAME_ACCOUNT, recipient_id=lot.seller_id, sender_type=bank_relations.ENTITY_TYPE.GAME_ACCOUNT, sender_id=buyer_id, currency=bank_relations.CURRENCY_TYPE.PREMIUM, amount=lot.price, description_for_sender=u'Покупка «%s»' % lot.name, description_for_recipient=u'Продажа «%s»' % lot.name, operation_uid=u'market-buy-lot-%s' % lot.type) transaction = bank_transaction.Transaction(invoice.id) logic_task = postponed_tasks.BuyLotTask(seller_id=lot.seller_id, buyer_id=buyer_id, lot_id=lot.id, transaction=transaction) task = PostponedTaskPrototype.create(logic_task) amqp_environment.environment.workers.refrigerator.cmd_wait_task(task.id) return task
def api_get(context): u''' Взять новую карту в колоду игрока. - **адрес:** /game/cards/api/get - **http-метод:** POST - **версии:** 1.0 - **параметры:** нет - **возможные ошибки**: нет Метод является «неблокирующей операцией» (см. документацию), формат ответа соответствует ответу для всех «неблокирующих операций». При завершении операции возвращается дополнительная инфрмация: { "message": "строка", // описание результата в формате html "card": <card_info> // описание полученной карты, формат см. в описании формата информации о герое } ''' choose_task = heroes_postponed_tasks.GetCardTask(hero_id=context.account_hero.id) task = PostponedTaskPrototype.create(choose_task) amqp_environment.environment.workers.supervisor.cmd_logic_task(context.account.id, task.id) return dext_views.AjaxProcessing(task.status_url)
def api_combine(context): u''' Объединить карты из колоды игрока. - **адрес:** /game/cards/api/combine - **http-метод:** POST - **версии:** 1.0 - **параметры:** * GET: cards — перечень уникальный идентификаторов карт в колоде игрока через запятую - **возможные ошибки**: * cards.api-combine.wrong_cards — указанные карты нельзя объединить Метод является «неблокирующей операцией» (см. документацию), формат ответа соответствует ответу для всех «неблокирующих операций». При завершении операции возвращается дополнительная инфрмация: { "message": "строка", // описание результата в формате html "card": <card_info> // описание полученной карты, формат см. в описании формата информации о герое } ''' can_combine_status = context.account_hero.cards.can_combine_cards([card.uid for card in context.account_cards]) if not can_combine_status.is_ALLOWED: raise dext_views.ViewError(code=u'wrong_cards', message=can_combine_status.text) choose_task = heroes_postponed_tasks.CombineCardsTask(hero_id=context.account_hero.id, cards=[card.uid for card in context.account_cards]) task = PostponedTaskPrototype.create(choose_task) amqp_environment.environment.workers.supervisor.cmd_logic_task(context.account.id, task.id) return dext_views.AjaxProcessing(task.status_url)
def test_buy(self): self.assertEqual(PostponedTaskPrototype._model_class.objects.all().count(), 0) self.assertEqual(InvoicePrototype._model_class.objects.all().count(), 0) with mock.patch('the_tale.common.postponed_tasks.prototypes.PostponedTaskPrototype.cmd_wait') as cmd_wait: self.purchase.buy(account=self.account) self.assertEqual(cmd_wait.call_count, 1) self.assertEqual(PostponedTaskPrototype._model_class.objects.all().count(), 1) self.assertEqual(InvoicePrototype._model_class.objects.all().count(), 1) postponed_logic = PostponedTaskPrototype._db_get_object(0).internal_logic self.assertTrue(isinstance(postponed_logic, BuyPremium)) self.assertEqual(postponed_logic.account_id, self.account.id) self.assertEqual(postponed_logic.days, self.days) invoice = InvoicePrototype.get_by_id(postponed_logic.transaction.invoice_id) self.assertEqual(invoice.recipient_type, ENTITY_TYPE.GAME_ACCOUNT) self.assertEqual(invoice.recipient_id, self.account.id) self.assertEqual(invoice.sender_type, ENTITY_TYPE.GAME_LOGIC) self.assertEqual(invoice.sender_id, 0) self.assertEqual(invoice.currency, CURRENCY_TYPE.PREMIUM) self.assertEqual(invoice.amount, -self.cost) self.assertEqual(invoice.description_for_sender, 'premium-days-transaction-description') self.assertEqual(invoice.description_for_recipient, 'premium-days-transaction-description')
def test_success(self): self.assertEqual(PostponedTask.objects.all().count(), 0) response = self.post_ajax_json(url('game:heroes:reset-abilities', self.hero.id)) self.assertEqual(PostponedTask.objects.all().count(), 1) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url)
def test_check_tasks(self): self.worker.process_wait_task(self.task_2.id) self.worker.process_wait_task(self.task_1.id) self.worker.process_wait_task(PostponedTaskPrototype.create(FakePostponedInternalTask(result_state=POSTPONED_TASK_LOGIC_RESULT.CONTINUE)).id) self.worker.check_tasks() self.assertEqual(set(self.worker.tasks.keys()), set([self.task_1.id]))
def test_profile_confirm_email_for_unlogined(self): self.request_login(self.account.email) self.client.post(reverse("accounts:profile:update"), {"email": "*****@*****.**", "nick": "test_nick"}) self.request_logout() uuid = ChangeCredentialsTask.objects.all()[0].uuid response = self.client.get(reverse("accounts:profile:confirm-email") + "?uuid=" + uuid) self.check_response_redirect(response, PostponedTaskPrototype._db_get_object(0).wait_url)
def change_credentials(self): from the_tale.accounts.postponed_tasks import ChangeCredentials change_credentials_task = ChangeCredentials(task_id=self.id) task = PostponedTaskPrototype.create(change_credentials_task) environment.workers.accounts_manager.cmd_task(task.id) return task
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_profile_update_password(self): self.request_login(self.account.email) response = self.client.post( reverse("accounts:profile:update"), {"email": self.account.email, "password": "******", "nick": "test_user"} ) self.assertEqual(response.status_code, 200) self.check_ajax_processing(response, PostponedTaskPrototype._db_get_object(0).status_url) self.assertEqual(ChangeCredentialsTask.objects.all().count(), 1) self.assertEqual(ChangeCredentialsTask.objects.all()[0].state, relations.CHANGE_CREDENTIALS_TASK_STATE.CHANGING)
def test_created(self): self.request_login(self.account.email) with self.check_delta(PostponedTaskPrototype._db_count, 1): response = self.post_ajax_json(logic.get_card_url()) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url)
def test_handle_registration__task_not_processed(self): registration_task = RegistrationTask(account_id=None, referer=None, referral_of_id=None, action_id=None) task = PostponedTaskPrototype.create(registration_task) with mock.patch('the_tale.accounts.middleware.login_user') as login_user: result = self.middleware.handle_registration(self.make_request_html('/', session={accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY: task.id})) self.assertTrue(result.is_TASK_NOT_PROCESSED) self.assertEqual(login_user.call_count, 0)
def test_success_multiply_accoutns(self): with self.check_delta(PostponedTaskPrototype._db_count, 1): self.check_ajax_processing(self.post_ajax_json(url('accounts:messages:create'), {'text': 'test-message', 'recipients': ('%d,%d' % (self.account2.id, self.account3.id))})) task = PostponedTaskPrototype._db_latest() self.assertEqual(task.internal_logic.message, 'test-message') self.assertEqual(task.internal_logic.account_id, self.account1.id) self.assertEqual(task.internal_logic.recipients, [self.account2.id, self.account3.id])
def choose_ability(self, ability_id): choose_task = postponed_tasks.ChooseHeroAbilityTask(hero_id=self.hero.id, ability_id=ability_id) task = PostponedTaskPrototype.create(choose_task) environment.workers.supervisor.cmd_logic_task(self.account.id, task.id) return self.json_processing(task.status_url)
def invoke_hero_method(self, account_id, hero_id, method_name, method_kwargs): from the_tale.game.heroes import postponed_tasks as heroes_postponed_tasks logic_task = heroes_postponed_tasks.InvokeHeroMethodTask(hero_id=hero_id, method_name=method_name, method_kwargs=method_kwargs) task = PostponedTaskPrototype.create(logic_task) return lambda: environment.workers.supervisor.cmd_logic_task(account_id=account_id, task_id=task.id)
def fast(self): if self.account.is_authenticated: return self.json_error("accounts.registration.fast.already_registered", "Вы уже зарегистрированы") if conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY in self.request.session: task_id = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY] task = PostponedTaskPrototype.get_by_id(task_id) if task is not None: if task.state.is_processed: return self.json_error( "accounts.registration.fast.already_processed", "Вы уже зарегистрированы, обновите страницу" ) if task.state.is_waiting: return self.json_processing(task.status_url) # in other case create new task referer = None if conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY in self.request.session: referer = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY] referral_of_id = None if conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY in self.request.session: referral_of_id = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY] action_id = None if conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY in self.request.session: action_id = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY] registration_task = postponed_tasks.RegistrationTask( account_id=None, referer=referer, referral_of_id=referral_of_id, action_id=action_id ) task = PostponedTaskPrototype.create(registration_task, live_time=conf.accounts_settings.REGISTRATION_TIMEOUT) self.request.session[conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY] = task.id environment.workers.registration.cmd_task(task.id) return self.json_processing(task.status_url)
def reset_name(self): change_task = postponed_tasks.ChangeHeroTask(hero_id=self.hero.id, name=names.generator().get_name(self.hero.race, self.hero.gender), race=self.hero.race, gender=self.hero.gender) task = PostponedTaskPrototype.create(change_task) environment.workers.supervisor.cmd_logic_task(self.hero.account_id, task.id) return self.json_processing(task.status_url)
def reset_abilities(self): if not self.hero.abilities.can_reset: return self.json_error('heroes.reset_abilities.reset_timeout', 'Сброс способностей пока не доступен') reset_task = postponed_tasks.ResetHeroAbilitiesTask(hero_id=self.hero.id) task = PostponedTaskPrototype.create(reset_task) environment.workers.supervisor.cmd_logic_task(self.account.id, task.id) return self.json_processing(task.status_url)
def activate(self, hero, card_uid, data): data["hero_id"] = hero.id data["account_id"] = hero.account_id data["card_uid"] = card_uid card_task = UseCardTask(processor_id=self.TYPE.value, hero_id=hero.id, data=data) task = PostponedTaskPrototype.create(card_task) environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id) return task
def test_initialization(self): from the_tale.common.postponed_tasks.models import PostponedTask from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype, POSTPONED_TASK_STATE from the_tale.common.postponed_tasks.postponed_tasks import FakePostponedInternalTask PostponedTaskPrototype.create(FakePostponedInternalTask()) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 1) self.worker.process_initialize() self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 0) self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.RESETED).count(), 1) self.assertEqual(self.worker.tasks, {}) self.assertEqual(self.worker.accounts_for_tasks, {}) self.assertEqual(self.worker.accounts_owners, {self.account_1.id: 'game_logic_1', self.account_2.id: 'game_logic_2'}) self.assertEqual(self.worker.accounts_queues, {}) self.assertTrue(self.worker.initialized) self.assertFalse(self.worker.wait_next_turn_answer) self.assertTrue(GameState.is_working())
def create(context): check_recipients(context.form) logic_task = postponed_tasks.SendMessagesTask(account_id=context.account.id, recipients=context.form.c.recipients, message=context.form.c.text) task = PostponedTaskPrototype.create(logic_task) amqp_environment.environment.workers.accounts_manager.cmd_task(task.id) return dext_views.AjaxProcessing(status_url=task.status_url)
def test_success(self): self.request_login(self.account.email) self.hero.cards.add_card(self.card) heroes_logic.save_hero(self.hero) response = self.post_ajax_json(logic.use_card_url(self.card.uid), self.post_data(self.card.uid)) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url) task.remove()
def test_change_hero(self): self.assertEqual(PostponedTask.objects.all().count(), 0) response = self.client.post(url('game:heroes:change-hero', self.hero.id), self.get_post_data()) self.assertEqual(PostponedTask.objects.all().count(), 1) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url) self.assertEqual(task.internal_logic.name, names.generator.get_test_name(name=u'новое имя')) self.assertEqual(task.internal_logic.gender, GENDER.MASCULINE) self.assertEqual(task.internal_logic.race, RACE.DWARF)
def test_profile_confirm_email(self): self.request_login(self.account.email) self.client.post(reverse("accounts:profile:update"), {"email": "*****@*****.**", "nick": "test_nick"}) self.assertEqual(PostponedTaskPrototype._model_class.objects.all().count(), 0) uuid = ChangeCredentialsTask.objects.all()[0].uuid response = self.client.get(reverse("accounts:profile:confirm-email") + "?uuid=" + uuid) self.check_response_redirect(response, PostponedTaskPrototype._db_get_object(0).wait_url) self.assertEqual(ChangeCredentialsTask.objects.all().count(), 1) self.assertEqual(ChangeCredentialsTask.objects.all()[0].state, relations.CHANGE_CREDENTIALS_TASK_STATE.CHANGING) self.assertEqual(Message.objects.all().count(), 1)
def test_success(self): self.pvp_create_battle(self.account_1, self.account_2, BATTLE_1X1_STATE.PROCESSING) response = self.client.post(reverse('game:pvp:say'), {'text': 'some text'}) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url)
def test_success(self): self.pvp_create_battle(self.account_1, self.account_2, BATTLE_1X1_STATE.PROCESSING) response = self.client.post(self.change_style_url) task = PostponedTaskPrototype._db_get_object(0) self.check_ajax_processing(response, task.status_url)
def initialize(self): self.initialized = True self.next_task_process_time = datetime.datetime.now() self.tasks = {} PostponedTaskPrototype.reset_all() self.logger.info('REFRIGERATOR INITIALIZED')
def process_wait_task(self, task_id): self.tasks[task_id] = PostponedTaskPrototype.get_by_id(task_id)
def setUp(self): super(RequestsTests, self).setUp() self.task = PostponedTaskPrototype.create(FakePostponedInternalTask()) self.client = client.Client()
def process_logic_task(self, account_id, task_id): # pylint: disable=W0613 task = PostponedTaskPrototype.get_by_id(task_id) task.process(self.logger, highlevel=self) task.do_postsave_actions()