Esempio n. 1
0
    def test_get_templates_count(self):
        key_1 = random.choice(keys.LEXICON_KEY.records)
        key_2 = random.choice(keys.LEXICON_KEY.records)

        utg_template_1 = utg_templates.Template()
        utg_template_1.parse('some-text', externals=[v.value for v in key_1.variables])

        utg_template_2 = utg_templates.Template()
        utg_template_2.parse('some-text-2', externals=[v.value for v in key_2.variables])

        template_1_1 = prototypes.TemplatePrototype.create(key=key_1, raw_template='template-1-1', utg_template=utg_template_1, verificators=[], author=None)
        template_1_2 = prototypes.TemplatePrototype.create(key=key_1, raw_template='template-1-2', utg_template=utg_template_1, verificators=[], author=None)

        template_2_1 = prototypes.TemplatePrototype.create(key=key_2, raw_template='template-2-1', utg_template=utg_template_2, verificators=[], author=None)

        template_1_1.state = relations.TEMPLATE_STATE.IN_GAME
        template_1_1.save()

        template_1_2.state = relations.TEMPLATE_STATE.IN_GAME
        template_1_2.save()

        template_2_1.state = relations.TEMPLATE_STATE.IN_GAME
        template_2_1.save()

        groups_count, keys_count = logic.get_templates_count()

        if key_1.group == key_2.group:
            for group in groups_relations.LEXICON_GROUP.records:
                if group == key_1.group:
                    self.assertEqual(groups_count[group], 3)
                else:
                    self.assertEqual(groups_count[group], 0)

        else:
            for group in groups_relations.LEXICON_GROUP.records:
                if group == key_1.group:
                    self.assertEqual(groups_count[group], 2)
                elif group == key_2.group:
                    self.assertEqual(groups_count[group], 1)
                else:
                    self.assertEqual(groups_count[group], 0)


        if key_1 == key_2:
            for key in keys.LEXICON_KEY.records:
                if key == key_1:
                    self.assertEqual(keys_count[key], 3)
                else:
                    self.assertEqual(keys_count[key], 0)
        else:
            for key in keys.LEXICON_KEY.records:
                if key == key_1:
                    self.assertEqual(keys_count[key], 2)
                elif key == key_2:
                    self.assertEqual(keys_count[key], 1)
                else:
                    self.assertEqual(keys_count[key], 0)
Esempio n. 2
0
    def test_get_errors__verificators_errors(self):
        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        TEXT = u'[hero|загл] [level] [неизвестное слово|hero|вн]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero'])

        verificator_1 = prototypes.Verificator(text=u'абракадабра',
                                               externals={
                                                   'hero': (u'героиня', u''),
                                                   'level': (1, u'')
                                               })
        verificator_2 = prototypes.Verificator(
            text=u'Рыцари 5 w-1-полнприл,мн,вн,од,пол',
            externals={
                'hero': (u'рыцарь', u'мн'),
                'level': (5, u'')
            })
        verificator_3 = prototypes.Verificator(text=u'Герой 2 w-1-ед,вн',
                                               externals={
                                                   'hero': (u'герой', u''),
                                                   'level': (2, u'')
                                               })
        verificator_4 = prototypes.Verificator(text=u'',
                                               externals={
                                                   'hero':
                                                   (u'привидение', u''),
                                                   'level': (5, u'')
                                               })

        dictionary = storage.game_dictionary.item

        word = utg_words.Word.create_test_word(
            type=utg_relations.WORD_TYPE.ADJECTIVE,
            prefix=u'w-1-',
            only_required=True)
        word.forms[0] = u'неизвестное слово'

        dictionary.add_word(word)

        prototype = prototypes.TemplatePrototype.create(key=key,
                                                        utg_template=template,
                                                        raw_template=TEXT,
                                                        verificators=[
                                                            verificator_1,
                                                            verificator_2,
                                                            verificator_3,
                                                            verificator_4
                                                        ],
                                                        author=self.account_1)

        errors = prototype.get_errors()

        self.assertEqual(errors, [
            u'Проверочный текст не совпадает с интерпретацией шаблона<br/>Героиня 1 w-1-полнприл,ед,вн,жр,од,пол<br/>абракадабра',
            u'Проверочный текст не совпадает с интерпретацией шаблона<br/>Герой 2 w-1-полнприл,ед,вн,мр,од,пол<br/>Герой 2 w-1-ед,вн',
            u'Проверочный текст не совпадает с интерпретацией шаблона<br/>Привидение 5 w-1-полнприл,ед,вн,ср,од,пол<br/>'
        ])
def remove_technical_template_parts(apps, schema_editor):
    from utg import templates as utg_templates
    from the_tale.linguistics.lexicon import keys as linguistics_keys

    Template = apps.get_model("linguistics", "Template")

    for template in Template.objects.iterator():
        data = json.loads(template.data)

        template.raw_template = processor(template.raw_template)

        key = linguistics_keys.LEXICON_KEY.index_value.get(template.key)

        if key is None:
            continue

        utg_template = utg_templates.Template()

        try:
            utg_template.parse(template.raw_template,
                               externals=[v.value for v in key.variables])
        except:
            continue

        for verificator in data['verificators']:
            verificator['text'] = processor(verificator['text'])

        data['template'] = utg_template.serialize()

        template.data = json.dumps(data, ensure_ascii=False)
        template.save()
Esempio n. 4
0
    def test_get_errors__no_errors(self):
        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        TEXT = u'[hero|загл] [level] [неизвестное слово|hero|вн]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero'])

        verificator_1 = prototypes.Verificator(
            text=u'Героиня 1 w-1-полнприл,пол,од,ед,вн,жр',
            externals={
                'hero': (u'героиня', u''),
                'level': (1, u'')
            })
        verificator_2 = prototypes.Verificator(
            text=u'Рыцари 5 w-1-полнприл,пол,од,мн,вн',
            externals={
                'hero': (u'рыцарь', u'мн'),
                'level': (5, u'')
            })
        verificator_3 = prototypes.Verificator(
            text=u'Герой 2 w-1-полнприл,пол,од,ед,вн,мр',
            externals={
                'hero': (u'герой', u''),
                'level': (2, u'')
            })
        verificator_4 = prototypes.Verificator(
            text=u'Привидение 5 w-1-полнприл,пол,од,ед,вн,ср',
            externals={
                'hero': (u'привидение', u''),
                'level': (5, u'')
            })

        dictionary = storage.game_dictionary.item

        word = utg_words.Word.create_test_word(
            type=utg_relations.WORD_TYPE.ADJECTIVE,
            prefix=u'w-1-',
            only_required=True)
        word.forms[0] = u'неизвестное слово'

        dictionary.add_word(word)

        prototype = prototypes.TemplatePrototype.create(key=key,
                                                        raw_template=TEXT,
                                                        utg_template=template,
                                                        verificators=[
                                                            verificator_1,
                                                            verificator_2,
                                                            verificator_3,
                                                            verificator_4
                                                        ],
                                                        author=self.account_1)

        self.assertTrue(prototype.errors_status.is_NO_ERRORS)

        errors = prototype.get_errors()

        self.assertEqual(errors, [])
Esempio n. 5
0
    def test_get_undictionaried_words(self):
        word_1 = words.Word.create_test_word(type=r.WORD_TYPE.NOUN,
                                             prefix='w-',
                                             properties=words.Properties(
                                                 r.GENDER.FEMININE,
                                                 r.ANIMALITY.INANIMATE,
                                                 r.NUMBER.PLURAL))
        word_2 = words.Word.create_test_word(type=r.WORD_TYPE.NOUN,
                                             prefix='x-',
                                             properties=words.Properties(
                                                 r.GENDER.FEMININE,
                                                 r.ANIMALITY.INANIMATE))
        word_3 = words.Word.create_test_word(type=r.WORD_TYPE.NOUN,
                                             prefix='y-',
                                             properties=words.Properties(
                                                 r.GENDER.FEMININE,
                                                 r.ANIMALITY.INANIMATE,
                                                 r.NUMBER.PLURAL))

        dictionary = Dictionary()

        dictionary.add_word(word_1)
        dictionary.add_word(word_2)
        dictionary.add_word(word_3)

        TEXT = '[external_1|загл] 1 [x-нс,ед,тв|external_2|буд] 2 [слово|тв,ед] [бла-бла]'

        template = templates.Template()

        template.parse(TEXT, externals=['external_1', 'external_2'])

        self.assertEqual(
            template.get_undictionaried_words(
                externals=['external_1', 'external_2'], dictionary=dictionary),
            ['слово', 'бла-бла'])
Esempio n. 6
0
    def test_parse(self):
        TEXT = '[external_1|загл] 1 [ед3|external_2|буд] 2 [external_2|тв,ед]'

        template = templates.Template()

        template.parse(TEXT, externals=['external_1', 'external_2'])

        self.assertEqual(template.template, '%s 1 %s 2 %s')

        self.assertEqual(len(template._substitutions), 3)

        substitution = template._substitutions[0]
        self.assertEqual(substitution.id, 'external_1')
        self.assertEqual(substitution.dependencies,
                         [words.Properties(r.WORD_CASE.UPPER)])

        substitution = template._substitutions[1]
        self.assertEqual(substitution.id, 'ед3')
        self.assertEqual(
            substitution.dependencies,
            ['external_2', words.Properties(r.TIME.FUTURE)])

        substitution = template._substitutions[2]
        self.assertEqual(substitution.id, 'external_2')
        self.assertEqual(
            substitution.dependencies,
            [words.Properties(r.CASE.INSTRUMENTAL, r.NUMBER.SINGULAR)])
Esempio n. 7
0
    def create(self, key):

        form = forms.TemplateForm(
            key, prototypes.TemplatePrototype.get_start_verificatos(key=key),
            self.request.POST)

        if not form.is_valid():
            return self.json_error('linguistics.templates.create.form_errors',
                                   form.errors)

        utg_template = utg_templates.Template()
        utg_template.parse(form.c.template,
                           externals=[v.value for v in key.variables])

        template = prototypes.TemplatePrototype.create(
            key=key,
            raw_template=form.c.template,
            utg_template=utg_template,
            verificators=form.verificators,
            author=self.account,
            restrictions=form.get_restrictions())

        prototypes.ContributionPrototype.get_for_or_create(
            type=relations.CONTRIBUTION_TYPE.TEMPLATE,
            account_id=template.author_id,
            entity_id=template.id,
            source=relations.CONTRIBUTION_SOURCE.MODERATOR
            if self.can_moderate_templates else
            relations.CONTRIBUTION_SOURCE.PLAYER,
            state=template.state.contribution_state)

        return self.json_ok(
            data={'next_url': url('linguistics:templates:show', template.id)})
Esempio n. 8
0
    def update(self):

        if self._template.state.is_ON_REVIEW and not self.can_edit_templates and self._template.author_id != self.account.id:
            return self.auto_error('linguistics.templates.update.can_not_edit_anothers_template',
                                   u'Вы не можете редактировать вариант фразы, созданный другим игроком. Подождите пока его проверит модератор.')

        if self._template.get_child():
            return self.auto_error('linguistics.templates.update.template_has_child',
                                   u'У этой фразы уже есть копия. Отредактируйте её или попросите автора копии сделать это.')


        form = forms.TemplateForm(self._template.key,
                                  self._template.get_all_verificatos(),
                                  self.request.POST)

        if not form.is_valid():
            return self.json_error('linguistics.templates.update.form_errors', form.errors)

        utg_template = utg_templates.Template()
        utg_template.parse(form.c.template, externals=[v.value for v in self._template.key.variables])

        if (form.verificators == self._template.get_all_verificatos() and
            form.c.template == self._template.raw_template and
            form.get_restrictions() == self._template.raw_restrictions):
            return self.json_error('linguistics.templates.update.full_copy_restricted', u'Вы пытаетесь создать полную копию шаблона, в этом нет необходимости.')


        if self.can_edit_templates or (self._template.author_id == self.account.id and self._template.state.is_ON_REVIEW):
            self._template.update(raw_template=form.c.template,
                                  utg_template=utg_template,
                                  verificators=form.verificators,
                                  restrictions=form.get_restrictions())

            prototypes.ContributionPrototype.get_for_or_create(type=relations.CONTRIBUTION_TYPE.TEMPLATE,
                                                               account_id=self.account.id,
                                                               entity_id=self._template.id,
                                                               source=relations.CONTRIBUTION_SOURCE.MODERATOR if self.can_edit_templates else relations.CONTRIBUTION_SOURCE.PLAYER,
                                                               state=self._template.state.contribution_state)


            return self.json_ok(data={'next_url': url('linguistics:templates:show', self._template.id)})


        template = prototypes.TemplatePrototype.create(key=self._template.key,
                                                       raw_template=form.c.template,
                                                       utg_template=utg_template,
                                                       verificators=form.verificators,
                                                       restrictions=form.get_restrictions(),
                                                       author=self.account,
                                                       parent=self._template)

        prototypes.ContributionPrototype.get_for_or_create(type=relations.CONTRIBUTION_TYPE.TEMPLATE,
                                                           account_id=template.author_id,
                                                           entity_id=template.id,
                                                           source=relations.CONTRIBUTION_SOURCE.MODERATOR if self.can_edit_templates else relations.CONTRIBUTION_SOURCE.PLAYER,
                                                           state=template.state.contribution_state)


        return self.json_ok(data={'next_url': url('linguistics:templates:show', template.id)})
Esempio n. 9
0
    def test_parse__percent_symbol(self):
        TEXT = '[external_1|загл] 1 [ед3|external_2|буд] 2% [external_2|тв,ед]'

        template = templates.Template()

        template.parse(TEXT, externals=['external_1', 'external_2'])

        self.assertEqual(template.template, '%s 1 %s 2%% %s')
Esempio n. 10
0
    def test_serialization(self):
        TEXT = '[external_1|загл] 1 [ед3|external_2|буд] 2 [external_2|тв,ед]'
        template = templates.Template()
        template.parse(TEXT, externals=['external_1', 'external_2'])

        self.assertEqual(
            template.serialize(),
            templates.Template.deserialize(template.serialize()).serialize())
Esempio n. 11
0
    def test_update_words_usage_info__ignore_duplicates(self):
        word_1 = prototypes.WordPrototype.create(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True))
        word_2 = prototypes.WordPrototype.create(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-2-', only_required=True))
        word_3 = prototypes.WordPrototype.create(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-3-', only_required=True))

        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        word_1.utg_word.forms[1] = word_1.utg_word.forms[0]
        word_1.save()

        text_1 = '[w-1-нс,ед,им|hero]'
        text_2 = '[w-1-нс,ед,им|hero] [w-2-нс,ед,им|hero]'

        utg_template = utg_templates.Template()
        utg_template.parse(text_1, externals=['hero', 'level'])
        template = prototypes.TemplatePrototype.create(key=key, raw_template=text_1, utg_template=utg_template, verificators=[], author=None)
        template.state = relations.TEMPLATE_STATE.IN_GAME
        template.save()

        utg_template = utg_templates.Template()
        utg_template.parse(text_2, externals=['hero', 'level'])
        template = prototypes.TemplatePrototype.create(key=key, raw_template=text_2, utg_template=utg_template, verificators=[], author=None)
        self.assertTrue(template.state.is_ON_REVIEW)

        utg_template = utg_templates.Template()
        utg_template.parse(text_2, externals=['hero', 'level'])
        template = prototypes.TemplatePrototype.create(key=key, raw_template=text_2, utg_template=utg_template, verificators=[], author=None)
        self.assertTrue(template.state.is_ON_REVIEW)

        logic.update_words_usage_info()

        word_1.reload()
        word_2.reload()
        word_3.reload()

        self.assertEqual(word_1.used_in_ingame_templates, 1)
        self.assertEqual(word_1.used_in_onreview_templates, 2)
        self.assertTrue(word_1.used_in_status.is_IN_INGAME_TEMPLATES)

        self.assertEqual(word_2.used_in_ingame_templates, 0)
        self.assertEqual(word_2.used_in_onreview_templates, 2)
        self.assertTrue(word_2.used_in_status.is_IN_ONREVIEW_TEMPLATES)

        self.assertEqual(word_3.used_in_ingame_templates, 0)
        self.assertEqual(word_3.used_in_onreview_templates, 0)
        self.assertTrue(word_3.used_in_status.is_NOT_USED)
Esempio n. 12
0
    def create_template(self, key, word):
        text = '[%(external)s|загл] 1 [%(word)s|%(external)s|буд,вн]' % {'external': key.variables[0].value, 'word': word}

        template = utg_templates.Template()

        template.parse(text, externals=[v.value for v in key.variables])

        return text, template
Esempio n. 13
0
    def test_get_text__linguistics_variables(self):

        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        dictionary = storage.game_dictionary.item

        word_1 = utg_words.Word.create_test_word(
            type=utg_relations.WORD_TYPE.NOUN,
            prefix='w-3-',
            only_required=True)
        word_1.forms[3] = 'дубль'
        self.assertEqual(word_1.form(utg_relations.CASE.ACCUSATIVE), 'дубль')

        dictionary.add_word(word_1)

        TEXT = '[hero|загл] [level] [дубль|hero|дт]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero', 'level'])

        prototypes.TemplatePrototype.create(key=key,
                                            raw_template=TEXT,
                                            utg_template=template,
                                            verificators=[],
                                            author=None)

        # update template errors_status and state to enshure, that it will be loaded in game lexicon
        prototypes.TemplatePrototype._db_all().update(
            errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS,
            state=relations.TEMPLATE_STATE.IN_GAME)
        storage.game_lexicon.refresh()

        weapon_restrictions = [
            storage.restrictions_storage.all()[0].id,
            storage.restrictions_storage.all()[100].id
        ]

        weapon_mock = mock.Mock(
            utg_name_form=lexicon_dictinonary.DICTIONARY.get_word('меч'),
            linguistics_restrictions=lambda: weapon_restrictions)

        hero_mock = mock.Mock(
            utg_name_form=lexicon_dictinonary.DICTIONARY.get_word('герой'),
            linguistics_restrictions=lambda: [],
            linguistics_variables=lambda: [('weapon', weapon_mock)])

        lexicon_key, externals, restrictions = logic.prepair_get_text(
            key.name, args={
                'hero': hero_mock,
                'level': 1
            })

        self.assertEqual(externals['hero.weapon'],
                         lexicon_dictinonary.DICTIONARY.get_word('меч'))

        self.assertIn(('hero.weapon', weapon_restrictions[0]), restrictions)
        self.assertIn(('hero.weapon', weapon_restrictions[1]), restrictions)
Esempio n. 14
0
    def clean_template(self):
        data = self.cleaned_data['template'].strip()

        # TODO: test exceptions
        try:
            template = utg_templates.Template()
            template.parse(data, externals=[v.value for v in self.key.variables])
        except utg_exceptions.WrongDependencyFormatError, e:
            raise django_forms.ValidationError(u'Ошибка в формате подстановки: %s' % e.arguments['dependency'])
Esempio n. 15
0
 def create_removed_template(self):
     TEXT = '[hero|загл] [level] [дубль|hero|дт]'
     utg_template = utg_templates.Template()
     utg_template.parse(TEXT, externals=['hero', 'level'])
     template = prototypes.TemplatePrototype.create(key=keys.LEXICON_KEY.random(),
                                                    raw_template=TEXT,
                                                    utg_template=utg_template,
                                                    verificators=[],
                                                    author=None,
                                                    state=relations.TEMPLATE_STATE.REMOVED)
     return template
Esempio n. 16
0
    def update_templates_errors(self):
        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        TEXT = '[hero|загл] [level] [неизвестное слово|hero|вн]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero'])

        verificator_1 = prototypes.Verificator(text='Героиня 1 w-1-ед,вн,жр,од,пол', externals={'hero': ('героиня', ''), 'level': (1, '')})
        verificator_2 = prototypes.Verificator(text='Рыцари 5 w-1-мн,вн,од,пол', externals={'hero': ('рыцарь', 'мн'), 'level': (5, '')})
        verificator_3 = prototypes.Verificator(text='Герой 2 w-1-ед,вн,мр,од,пол', externals={'hero': ('герой', ''), 'level': (2, '')})
        verificator_4 = prototypes.Verificator(text='Привидение 5 w-1-ед,вн,ср,од,пол', externals={'hero': ('привидение', ''), 'level': (5, '')})

        dictionary = storage.game_dictionary.item

        word = utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.ADJECTIVE, prefix='w-1-', only_required=True)
        word.forms[0] = 'неизвестное слово'

        dictionary.add_word(word)

        prototype_1 = prototypes.TemplatePrototype.create(key=key,
                                                        raw_template=TEXT,
                                                        utg_template=template,
                                                        verificators=[verificator_1, verificator_2, verificator_3, verificator_4],
                                                        author=self.account_1)

        prototype_2 = prototypes.TemplatePrototype.create(key=key,
                                                        raw_template=TEXT,
                                                        utg_template=template,
                                                        verificators=[],
                                                        author=self.account_1)

        prototypes.TemplatePrototype._db_filter(id=prototype_1.id).update(errors_status=relations.TEMPLATE_ERRORS_STATUS.HAS_ERRORS)
        prototypes.TemplatePrototype._db_filter(id=prototype_2.id).update(errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS)

        prototype_1.reload()
        prototype_2.reload()

        self.assertTrue(prototype_1.errors_status.is_HAS_ERRORS)
        self.assertTrue(prototype_2.errors_status.is_NO_ERRORS)

        logic.update_templates_errors()

        prototype_1.reload()
        prototype_2.reload()

        self.assertTrue(prototype_1.errors_status.is_NO_ERRORS)
        self.assertTrue(prototype_2.errors_status.is_HAS_ERRORS)
Esempio n. 17
0
    def test_add_word_restrictions_into_variable_restrictions(self):

        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        TEXT = '[hero|загл] [level] [дубль|hero|дт]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero', 'level'])

        prototypes.TemplatePrototype.create(key=key,
                                            raw_template=TEXT,
                                            utg_template=template,
                                            verificators=[],
                                            author=None)

        # update template errors_status and state to enshure, that it will be loaded in game lexicon
        prototypes.TemplatePrototype._db_all().update(errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS,
                                                      state=relations.TEMPLATE_STATE.IN_GAME)
        storage.game_lexicon.refresh()

        normal_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True))
        singular_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True,
                                                                           properties=utg_words.Properties(utg_relations.NUMBER.SINGULAR)))
        plural_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True,
                                                                         properties=utg_words.Properties(utg_relations.NUMBER.PLURAL)))

        hero_mock = mock.Mock(utg_name_form=normal_noun, linguistics_restrictions=lambda: [])
        lexicon_key, externals, restrictions = logic.prepair_get_text(key.name,  args={'hero': hero_mock, 'level': 1})
        self.assertIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM,
                                                                            relations.WORD_HAS_PLURAL_FORM.HAS.value).id), restrictions)
        self.assertNotIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM,
                                                                               relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id), restrictions)

        hero_mock = mock.Mock(utg_name_form=singular_noun, linguistics_restrictions=lambda: [])
        lexicon_key, externals, restrictions = logic.prepair_get_text(key.name,  args={'hero': hero_mock, 'level': 1})
        self.assertNotIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM,
                                                                               relations.WORD_HAS_PLURAL_FORM.HAS.value).id), restrictions)
        self.assertIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM,
                                                                            relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id), restrictions)

        hero_mock = mock.Mock(utg_name_form=plural_noun, linguistics_restrictions=lambda: [])
        lexicon_key, externals, restrictions = logic.prepair_get_text(key.name,  args={'hero': hero_mock, 'level': 1})
        self.assertIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM,
                                                                            relations.WORD_HAS_PLURAL_FORM.HAS.value).id), restrictions)
        self.assertNotIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM,
                                                                               relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id), restrictions)
Esempio n. 18
0
    def test_get_text__real(self):

        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        dictionary = storage.game_dictionary.item

        word_1 = utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix=u'w-3-', only_required=True)
        word_1.forms[3] = u'дубль'
        self.assertEqual(word_1.form(utg_relations.CASE.ACCUSATIVE), u'дубль')

        dictionary.add_word(word_1)

        TEXT = u'[hero|загл] [level] [дубль|hero|дт]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero', 'level'])

        prototypes.TemplatePrototype.create(key=key,
                                            raw_template=TEXT,
                                            utg_template=template,
                                            verificators=[],
                                            author=None)

        # update template errors_status and state to enshure, that it will be loaded in game lexicon
        prototypes.TemplatePrototype._db_all().update(errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS,
                                                      state=relations.TEMPLATE_STATE.IN_GAME)
        storage.game_lexicon.refresh()

        hero_mock = mock.Mock(utg_name_form=lexicon_dictinonary.DICTIONARY.get_word(u'герой'), linguistics_restrictions=lambda: [])

        lexicon_key, externals, restrictions = logic.prepair_get_text(key.name,  args={'hero': hero_mock, 'level': 1})

        self.assertEqual(logic.render_text(lexicon_key, externals, restrictions),
                         u'Герой 1 w-3-нс,ед,дт')


        word_2 = utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix=u'w-2-', only_required=True)
        word_2.forms[1] = u'дубль'
        self.assertEqual(word_2.form(utg_relations.CASE.GENITIVE), u'дубль')
        dictionary.add_word(word_2)

        lexicon_key, externals, restrictions = logic.prepair_get_text(key.name, args={'hero': hero_mock, 'level': 1})

        self.assertEqual(logic.render_text(lexicon_key, externals, restrictions),
                         u'Герой 1 w-2-нс,ед,дт')
Esempio n. 19
0
    def test_get_errors__no_word_errors(self):
        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        TEXT = u'[hero|загл] [level] [неизвестное слово|hero|вн]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero'])

        # verificators with error that would not be returned becouse of words_errors
        verificator_1 = prototypes.Verificator(text=u'абракадабра',
                                               externals={
                                                   'hero': (u'героиня', u''),
                                                   'level': (1, u'')
                                               })
        verificator_2 = prototypes.Verificator(text=u'Рыцарь 5 w-1-ед,вн',
                                               externals={
                                                   'hero': (u'рыцарь', u'мн'),
                                                   'level': (5, u'')
                                               })
        verificator_3 = prototypes.Verificator(text=u'Герой 2 w-1-ед,вн',
                                               externals={
                                                   'hero': (u'герой', u''),
                                                   'level': (2, u'')
                                               })
        verificator_4 = prototypes.Verificator(text=u'',
                                               externals={
                                                   'hero':
                                                   (u'привидение', u''),
                                                   'level': (5, u'')
                                               })

        prototype = prototypes.TemplatePrototype.create(key=key,
                                                        raw_template=TEXT,
                                                        utg_template=template,
                                                        verificators=[
                                                            verificator_1,
                                                            verificator_2,
                                                            verificator_3,
                                                            verificator_4
                                                        ],
                                                        author=self.account_1)

        errors = prototype.get_errors()

        self.assertEqual(errors, [u'Неизвестное слово: «неизвестное слово»'])
Esempio n. 20
0
    def clean_template(self):
        data = self.cleaned_data['template'].strip()

        # TODO: test exceptions
        try:
            template = utg_templates.Template()
            template.parse(data,
                           externals=[v.value for v in self.key.variables])
        except utg_exceptions.WrongDependencyFormatError as e:
            raise django_forms.ValidationError(
                'Ошибка в формате подстановки: %s' % e.arguments['dependency'])
        except utg_exceptions.UnknownVerboseIdError as e:
            raise django_forms.ValidationError('Неизвестная форма слова: %s' %
                                               e.arguments['verbose_id'])
        except utg_exceptions.ExternalDependecyNotFoundError as e:
            raise django_forms.ValidationError('Неизвестная переменная: %s' %
                                               e.arguments['dependency'])

        return data
Esempio n. 21
0
    def test_substitute__percent_symbol(self):
        TEXT = '[external_1|загл] 1 [w-нс,ед,тв|external_2|буд] 2% [external_2|тв,ед]'

        # TEXT = u'[external_2|тв,ед]'

        word_1 = words.Word.create_test_word(type=r.WORD_TYPE.NOUN,
                                             prefix='w-',
                                             properties=words.Properties(
                                                 r.GENDER.FEMININE,
                                                 r.ANIMALITY.INANIMATE))
        word_2 = words.Word.create_test_word(type=r.WORD_TYPE.NOUN,
                                             prefix='x-',
                                             properties=words.Properties(
                                                 r.GENDER.FEMININE,
                                                 r.ANIMALITY.INANIMATE))
        word_3 = words.Word.create_test_word(type=r.WORD_TYPE.NOUN,
                                             prefix='y-',
                                             properties=words.Properties(
                                                 r.GENDER.FEMININE,
                                                 r.ANIMALITY.INANIMATE,
                                                 r.NUMBER.PLURAL))

        dictionary = Dictionary()

        dictionary.add_word(word_1)
        dictionary.add_word(word_2)
        dictionary.add_word(word_3)

        template = templates.Template()

        template.parse(TEXT, externals=['external_1', 'external_2'])

        result = template.substitute(externals={
            'external_1':
            dictionary.get_word('x-нс,ед,им'),
            'external_2':
            dictionary.get_word('y-нс,мн,им'),
        },
                                     dictionary=dictionary)

        self.assertEqual(result, 'X-нс,ед,им 1 w-нс,мн,им 2% y-нс,мн,тв')
Esempio n. 22
0
    def test_templates_query(self):
        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        text = '[w-1-ед,им|hero]'

        utg_template = utg_templates.Template()
        utg_template.parse(text, externals=['hero', 'level'])
        template_1 = prototypes.TemplatePrototype.create(
            key=key,
            raw_template=text,
            utg_template=utg_template,
            verificators=[],
            author=None)
        template_2 = prototypes.TemplatePrototype.create(
            key=key,
            raw_template=text,
            utg_template=utg_template,
            verificators=[],
            author=None)
        template_3 = prototypes.TemplatePrototype.create(
            key=key,
            raw_template=text,
            utg_template=utg_template,
            verificators=[],
            author=None)

        prototypes.TemplatePrototype._db_filter(
            id__in=[template_1.id, template_2.id]).update(
                state=relations.TEMPLATE_STATE.IN_GAME)

        self.assertEqual(storage.game_lexicon._templates_query().count(), 0)

        prototypes.TemplatePrototype._db_filter(id=template_2.id).update(
            errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS)

        self.assertEqual(storage.game_lexicon._templates_query().count(), 1)

        prototypes.TemplatePrototype._db_filter(id=template_3.id).update(
            errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS)

        self.assertEqual(storage.game_lexicon._templates_query().count(), 1)
Esempio n. 23
0
def fill_empty_keys_with_fake_phrases(prefix):
    from utg import templates as utg_templates

    models.Template.objects.filter(raw_template__startswith=prefix).delete()

    for i, key in enumerate(keys.LEXICON_KEY.records):
        if key not in game_lexicon._item:
            text = '%s-%d' % (prefix, i)
            template = utg_templates.Template()
            template.parse(text, externals=[v.value for v in key.variables])
            prototype = prototypes.TemplatePrototype.create(key=key,
                                                raw_template=text,
                                                utg_template=template,
                                                verificators=[],
                                                state=relations.TEMPLATE_STATE.IN_GAME,
                                                author=None)
            verifiactos = prototype.get_all_verificatos()
            for verificator in verifiactos:
                verificator.text = text

            prototype.update(verificators=verifiactos)

    game_lexicon.refresh()
Esempio n. 24
0
    def test_get_errors__duplicate_word(self):
        key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP

        dictionary = storage.game_dictionary.item

        word_1 = utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True)
        word_1.forms[2] = 'дубль'
        self.assertEqual(word_1.form(utg_relations.CASE.DATIVE), 'дубль')

        word_2 = utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-2-', only_required=True)
        word_2.forms[2] = 'дубль'
        self.assertEqual(word_2.form(utg_relations.CASE.DATIVE), 'дубль')

        dictionary.add_word(word_1)
        dictionary.add_word(word_2)

        TEXT = '[hero|загл] [level] [дубль|hero|дт]'

        template = utg_templates.Template()

        template.parse(TEXT, externals=['hero'])

        # verificators with error that would not be returned becouse of words_errors
        verificator_1 = prototypes.Verificator(text='Героиня 1 дубль', externals={'hero': ('героиня', ''), 'level': (1, '')})
        verificator_2 = prototypes.Verificator(text='Рыцари 5 w-1-нс,мн,дт', externals={'hero': ('рыцарь', 'мн'), 'level': (5, '')})
        verificator_3 = prototypes.Verificator(text='Герой 2 дубль', externals={'hero': ('герой', ''), 'level': (2, '')})
        verificator_4 = prototypes.Verificator(text='Привидение 5 дубль', externals={'hero': ('привидение', ''), 'level': (5, '')})

        prototype = prototypes.TemplatePrototype.create(key=key,
                                                        raw_template=TEXT,
                                                        utg_template=template,
                                                        verificators=[verificator_1, verificator_2, verificator_3, verificator_4],
                                                        author=self.account_1)

        errors = prototype.get_errors()

        self.assertEqual(errors, [])
Esempio n. 25
0
                            u'играми', u'играх', u'игры', u'игр', u'играм',
                            u'игры', u'играми', u'играх'
                        ],
                        properties=words.Properties(r.ANIMALITY.INANIMATE,
                                                    r.GENDER.FEMININE))

action_word = words.Word(
    type=r.WORD_TYPE.VERB,
    forms=[u'дать', u'дал', u'дало', u'дала', u'дали'] + [u''] *
    (len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5),
    properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT))
action_word.autofill_missed_forms()

test_dictionary = dictionary.Dictionary(words=[games_word, action_word])

template = templates.Template()

template.parse(u'[Npc] [дал|npc] [hero|дт] [games] [игра|games|вн].',
               externals=('hero', 'npc', 'games'))

hero = words.WordForm(
    words.Word(type=r.WORD_TYPE.NOUN,
               forms=[
                   u'герой', u'героя', u'герою', u'героя', u'героем', u'герое',
                   u'герои', u'героев', u'героям', u'героев', u'героями',
                   u'героях', u'герои', u'героев', u'героям', u'героев',
                   u'героями', u'героях'
               ],
               properties=words.Properties(r.ANIMALITY.ANIMATE,
                                           r.GENDER.MASCULINE)))
Esempio n. 26
0
 def test_init(self):
     template = templates.Template()
     self.assertEqual(template._substitutions, [])
     self.assertEqual(template.template, None)
Esempio n. 27
0
    def setUp(self):
        super(GiveRewardForTemplateTests, self).setUp()

        create_test_map()

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

        cards_tt_api.debug_clear_service()
        pm_tt_api.debug_clear_service()

        logic.sync_static_restrictions()

        storage.game_dictionary.refresh()
        storage.game_lexicon.refresh()

        TEXT = '[hero|загл] [level] [дубль|hero|дт]'
        utg_template = utg_templates.Template()
        utg_template.parse(TEXT, externals=['hero', 'level'])

        self.template_1 = prototypes.TemplatePrototype.create(
            key=keys.LEXICON_KEY.random(),
            raw_template=TEXT,
            utg_template=utg_template,
            verificators=[],
            author=None,
            state=relations.TEMPLATE_STATE.REMOVED)

        self.template_2 = prototypes.TemplatePrototype.create(
            key=keys.LEXICON_KEY.random(),
            raw_template=TEXT,
            utg_template=utg_template,
            verificators=[],
            author=self.account_2,
            state=relations.TEMPLATE_STATE.REMOVED)

        prototypes.ContributionPrototype.create(
            type=relations.CONTRIBUTION_TYPE.TEMPLATE,
            account_id=self.account_2.id,
            entity_id=self.template_2.id,
            source=relations.CONTRIBUTION_SOURCE.PLAYER,
            state=relations.CONTRIBUTION_STATE.IN_GAME)

        self.template_3 = prototypes.TemplatePrototype.create(
            key=keys.LEXICON_KEY.random(),
            raw_template=TEXT,
            utg_template=utg_template,
            verificators=[],
            author=self.account_3,
            state=relations.TEMPLATE_STATE.REMOVED)

        prototypes.ContributionPrototype.create(
            type=relations.CONTRIBUTION_TYPE.TEMPLATE,
            account_id=self.account_3.id,
            entity_id=self.template_3.id,
            source=relations.CONTRIBUTION_SOURCE.PLAYER,
            state=relations.CONTRIBUTION_STATE.IN_GAME)

        self.non_author_contribution = prototypes.ContributionPrototype.create(
            type=relations.CONTRIBUTION_TYPE.TEMPLATE,
            account_id=self.account_4.id,
            entity_id=self.template_2.id,
            source=relations.CONTRIBUTION_SOURCE.PLAYER,
            state=relations.CONTRIBUTION_STATE.IN_GAME)
Esempio n. 28
0
               properties=words.Properties(r.ANIMALITY.ANIMATE,
                                           r.GENDER.FEMININE)))

eleph = words.WordForm(
    words.Word(type=r.WORD_TYPE.NOUN,
               forms=[
                   u'слон', u'слона', u'слону', u'слона', u'слоном', u'слоне',
                   u'слоны', u'слонов', u'слонам', u'слонов', u'слонами',
                   u'слонах', u'слоны', u'слонов', u'слонам', u'слонов',
                   u'слонами', u'слонах'
               ],
               properties=words.Properties(r.ANIMALITY.ANIMATE,
                                           r.GENDER.MASCULINE)))

#создаем шаблон
template1 = templates.Template()
template2 = templates.Template()
template3 = templates.Template()
template1.parse(
    u'[fairy] [подарил|fairy] [hero|дт] [coins] [монета|coins|вн].',
    externals=('hero', 'fairy', 'coins'))
result1 = template1.substitute(externals={
    'hero': hero,
    'fairy': fairy,
    'coins': constructors.construct_integer(125)
},
                               dictionary=test_dictionary)

template2.parse(
    u'[fairy] и [eleph] [подарил|мн] [hero|дт] [coins] [монета|coins|вн].',
    externals=('hero', 'eleph', 'fairy', 'coins'))
Esempio n. 29
0
    def test_full_usage(self):
        # описываем существительное для словаря
        coins_word = words.Word(
            type=r.WORD_TYPE.NOUN,
            forms=[
                'монета',
                'монеты',
                'монете',
                'монету',
                'монетой',
                'монете',  # единственнео число
                'монеты',
                'монет',
                'монетам',
                'монеты',
                'монетами',
                'монетах',  # множественное число
                'монеты',
                'монет',
                'монетам',
                'монеты',
                'монетами',
                'монетах'
            ],  # счётное число (заполнено для пример, может быть заполнено методом autofill_missed_forms)
            properties=words.Properties(
                r.ANIMALITY.INANIMATE,
                r.GENDER.FEMININE))  # свойства: неодушевлённое, женский род

        # описываем глагол для словаря
        action_word = words.Word(
            type=r.WORD_TYPE.VERB,
            # описываем только нужны нам формы слова (порядок важен и определён в utg.data.WORDS_CACHES[r.WORD_TYPE.VERB])
            forms=['подарить', 'подарил', 'подарило', 'подарила', 'подарили'] +
            [''] * (len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5),
            properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT))
        action_word.autofill_missed_forms(
        )  # заполняем пропущенные формы на основе введённых (выбираются наиболее близкие)

        # создаём словарь для использования в шаблонах
        test_dictionary = dictionary.Dictionary(
            words=[coins_word, action_word])

        # создаём шаблон
        template = templates.Template()

        # externals — внешние переменные, не обязаны быть в словаре
        template.parse(
            '[Npc] [подарил|npc] [hero|дт] [coins] [монета|coins|вн].',
            externals=('hero', 'npc', 'coins'))

        # описываем внешние переменные
        hero = words.WordForm(
            words.Word(type=r.WORD_TYPE.NOUN,
                       forms=[
                           'герой', 'героя', 'герою', 'героя', 'героем',
                           'герое', 'герои', 'героев', 'героям', 'героев',
                           'героями', 'героях', 'герои', 'героев', 'героям',
                           'героев', 'героями', 'героях'
                       ],
                       properties=words.Properties(r.ANIMALITY.ANIMATE,
                                                   r.GENDER.MASCULINE)))

        npc = words.WordForm(
            words.Word(type=r.WORD_TYPE.NOUN,
                       forms=[
                           'русалка', 'русалки', 'русалке', 'русалку',
                           'русалкой', 'русалке', 'русалки', 'русалок',
                           'русалкам', 'русалок', 'русалками', 'русалках',
                           'русалки', 'русалок', 'русалкам', 'русалок',
                           'русалками', 'русалках'
                       ],
                       properties=words.Properties(r.ANIMALITY.ANIMATE,
                                                   r.GENDER.FEMININE)))

        # осуществляем подстановку
        result = template.substitute(externals={
            'hero':
            hero,
            'npc':
            npc,
            'coins':
            constructors.construct_integer(125)
        },
                                     dictionary=test_dictionary)

        self.assertEqual(result, 'Русалка подарила герою 125 монет.')