Esempio n. 1
0
    def test_reserve_lot(self):
        with self.check_delta(models.Lot.objects.count, 1):
            lot = logic.reserve_lot(account_id=self.account_1.id,
                                    good=self.good_2,
                                    price=777)

        lot_model = models.Lot.objects.latest()

        self.assertEqual(lot.id, lot_model.id)
        self.assertEqual(lot.type, lot_model.type)
        self.assertEqual(lot.seller_id, lot_model.seller_id)
        self.assertEqual(lot.buyer_id, lot_model.buyer_id)
        self.assertEqual(lot.name, lot_model.name)
        self.assertEqual(lot.state, lot_model.state)
        self.assertEqual(lot.price, lot_model.price)
        self.assertTrue(lot.closed_at-lot.created_at > datetime.timedelta(days=conf.settings.LOT_LIVE_TIME, seconds=-1))
        self.assertEqual(lot.good.serialize(), s11n.from_json(lot_model.data)['good'])

        self.assertEqual(lot.type, self.good_2.type)
        self.assertEqual(lot.seller_id, self.account_1.id)
        self.assertEqual(lot.buyer_id, None)
        self.assertEqual(lot.name, self.good_2.name)
        self.assertTrue(lot.state.is_RESERVED)
        self.assertEqual(lot.price, 777)
        self.assertEqual(lot.commission, 54)
        self.assertTrue(lot.closed_at-lot.created_at > datetime.timedelta(days=conf.settings.LOT_LIVE_TIME, seconds=-1))
        self.assertEqual(lot.good.serialize(), self.good_2.serialize())
 def test_choose_ability_request_wrong_ability(self):
     self.request_login('*****@*****.**')
     response = self.client.post(
         reverse('game:heroes:choose-ability', args=[self.hero.id + 1]) +
         '?ability_id=xxxyyy')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(s11n.from_json(response.content)['status'], 'error')
Esempio n. 3
0
def load_person(person_id=None, person_model=None):
    # TODO: get values instead model
    # TODO: check that load_hero everywhere called with correct arguments
    try:
        if person_id is not None:
            person_model = models.Person.objects.get(id=person_id)
        elif person_model is None:
            return None
    except models.Person.DoesNotExist:
        return None

    data = s11n.from_json(person_model.data)

    return objects.Person(
        id=person_model.id,
        created_at_turn=person_model.created_at_turn,
        updated_at_turn=person_model.updated_at_turn,
        place_id=person_model.place_id,
        gender=person_model.gender,
        race=person_model.race,
        type=person_model.type,
        attrs=attributes.Attributes.deserialize(data.get("attributes", {})),
        politic_power=PersonPoliticPower.deserialize(data["politic_power"])
        if "politic_power" in data
        else PersonPoliticPower.create(),
        utg_name=utg_words.Word.deserialize(data["name"]),
        job=PersonJob.deserialize(data["job"])
        if "job" in data
        else PersonJob.create(normal_power=NORMAL_PERSON_JOB_POWER),
        personality_cosmetic=relations.PERSONALITY_COSMETIC(data["personality"]["cosmetic"]),
        personality_practical=relations.PERSONALITY_PRACTICAL(data["personality"]["practical"]),
        moved_at_turn=data.get("moved_at_turn", 0),
        updated_at=person_model.updated_at,
    )
Esempio n. 4
0
 def statistics(self):
     statistics = s11n.from_json(self._model.statistics)
     statistics['race_percents'] = dict( (RACE(int(key)), value) for key, value in statistics['race_percents'].items())
     statistics['person_race_percents'] = dict( (RACE(int(key)), value) for key, value in statistics['person_race_percents'].items())
     statistics['race_cities'] = dict( (RACE(int(key)), value) for key, value in statistics['race_cities'].items())
     statistics['terrain_percents'] = dict( (MAP_STATISTICS(int(key)), value) for key, value in statistics['terrain_percents'].items())
     return statistics
Esempio n. 5
0
    def test_download(self):
        word_type = relations.ALLOWED_WORD_TYPE.random().utg_type

        parent_word = utg_words.Word.create_test_word(word_type, prefix='parent-')
        child_word = utg_words.Word.create_test_word(word_type, prefix='child-')
        ingame_word = utg_words.Word.create_test_word(word_type, prefix='ingame-')
        outgame_word = utg_words.Word.create_test_word(word_type, prefix='outgame-')

        parent = prototypes.WordPrototype.create(parent_word)
        parent.state = relations.WORD_STATE.IN_GAME
        parent.save()

        prototypes.WordPrototype.create(child_word, parent=parent) # child

        ingame = prototypes.WordPrototype.create(ingame_word)
        ingame.state = relations.WORD_STATE.IN_GAME
        ingame.save()

        prototypes.WordPrototype.create(outgame_word) # outgame

        response = self.client.get(url('linguistics:words:dictionary-download'))

        data = s11n.from_json(response.content.decode('utf-8'))

        self.assertEqual(len(data['words']), 2)
        self.assertIn(parent.utg_word.serialize(), data['words'])
        self.assertIn(ingame.utg_word.serialize(), data['words'])
Esempio n. 6
0
 def test_logined(self):
     response = self.client.get(self.game_info_url_1)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(
         set(s11n.from_json(response.content)['data'].keys()),
         set(('turn', 'mode', 'map_version', 'account', 'enemy',
              'game_state')))
Esempio n. 7
0
    def test_full__logged_out_before_token_accept(self):

        api_client = Client()

        request_token_url = url('accounts:third-party:tokens:request-authorisation', api_version='1.0', api_client=project_settings.API_CLIENT)

        response = api_client.post(request_token_url, {'application_name': 'app-name',
                                                       'application_info': 'app-info',
                                                       'application_description': 'app-descr'})

        self.check_ajax_ok(response)

        token_url = s11n.from_json(response.content.decode('utf-8'))['data']['authorisation_page']

        token = prototypes.AccessTokenPrototype._db_latest()

        self.assertEqual(url('accounts:third-party:tokens:show', token.uid), token_url)

        self.check_html_ok(self.request_html(token_url), texts=['app-name', 'app-info', 'app-descr'])


        authorisation_state_url = url('accounts:third-party:tokens:authorisation-state', api_version='1.0', api_client=project_settings.API_CLIENT)

        self.check_ajax_ok(api_client.get(authorisation_state_url),
                           data={'account_id': None,
                                 'account_name': None,
                                 'state': relations.AUTHORISATION_STATE.UNPROCESSED.value,
                                 'session_expire_at': 666.6})

        self.check_ajax_ok(api_client.post(logout_url()))

        self.assertNotIn('_auth_user_id', api_client.session)

        self.assertNotEqual(prototypes.AccessTokenPrototype.get_by_uid(token.uid), None)
        self.assertNotIn(third_party_settings.ACCESS_TOKEN_SESSION_KEY, api_client.session)
Esempio n. 8
0
    def test_reserve_lot(self):
        with self.check_delta(models.Lot.objects.count, 1):
            lot = logic.reserve_lot(account_id=self.account_1.id,
                                    good=self.good_2,
                                    price=777)

        lot_model = models.Lot.objects.latest()

        self.assertEqual(lot.id, lot_model.id)
        self.assertEqual(lot.type, lot_model.type)
        self.assertEqual(lot.seller_id, lot_model.seller_id)
        self.assertEqual(lot.buyer_id, lot_model.buyer_id)
        self.assertEqual(lot.name, lot_model.name)
        self.assertEqual(lot.state, lot_model.state)
        self.assertEqual(lot.price, lot_model.price)
        self.assertTrue(lot.closed_at-lot.created_at > datetime.timedelta(days=conf.settings.LOT_LIVE_TIME, seconds=-1))
        self.assertEqual(lot.good.serialize(), s11n.from_json(lot_model.data)['good'])

        self.assertEqual(lot.type, self.good_2.type)
        self.assertEqual(lot.seller_id, self.account_1.id)
        self.assertEqual(lot.buyer_id, None)
        self.assertEqual(lot.name, self.good_2.name)
        self.assertTrue(lot.state.is_RESERVED)
        self.assertEqual(lot.price, 777)
        self.assertEqual(lot.commission, 54)
        self.assertTrue(lot.closed_at-lot.created_at > datetime.timedelta(days=conf.settings.LOT_LIVE_TIME, seconds=-1))
        self.assertEqual(lot.good.serialize(), self.good_2.serialize())
Esempio n. 9
0
    def from_model(cls, model):
        from the_tale.game.artifacts import objects as artifacts_objects

        data = s11n.from_json(model.data)

        weapons = [
            artifacts_objects.Weapon.deserialize(weapon_data)
            for weapon_data in data.get('weapons', ())
        ]

        return cls(id=model.id,
                   state=model.state,
                   type=model.type,
                   max_health=model.max_health,
                   dedication=model.dedication,
                   archetype=model.archetype,
                   mode=model.mode,
                   communication_verbal=model.communication_verbal,
                   communication_gestures=model.communication_gestures,
                   communication_telepathic=model.communication_telepathic,
                   intellect_level=model.intellect_level,
                   abilities=abilities_container.Container.deserialize(
                       data.get('abilities', {})),
                   utg_name=utg_words.Word.deserialize(data['name']),
                   description=data['description'],
                   structure=beings_relations.STRUCTURE(
                       data.get('structure', 0)),
                   features=frozenset(
                       beings_relations.FEATURE(feature)
                       for feature in data.get('features', ())),
                   movement=beings_relations.MOVEMENT(data.get('movement', 0)),
                   body=beings_relations.BODY(data.get('body', 0)),
                   size=beings_relations.SIZE(data.get('size', 0)),
                   weapons=weapons)
Esempio n. 10
0
 def test_choose_ability_request_wrong_ability(self):
     self.request_login("*****@*****.**")
     response = self.client.post(
         reverse("game:heroes:choose-ability", args=[self.hero.id + 1]) + "?ability_id=xxxyyy"
     )
     self.assertEqual(response.status_code, 200)
     self.assertEqual(s11n.from_json(response.content)["status"], "error")
Esempio n. 11
0
    def preferences(self):
        from the_tale.game.heroes.preferences import HeroPreferences

        preferences = HeroPreferences.deserialize(hero=self,
                                                  data=s11n.from_json(
                                                      self._model.preferences))

        if preferences.energy_regeneration_type is None:
            preferences.set_energy_regeneration_type(
                self.race.energy_regeneration,
                change_time=datetime.datetime.fromtimestamp(0))
        if preferences.risk_level is None:
            preferences.set_risk_level(
                relations.RISK_LEVEL.NORMAL,
                change_time=datetime.datetime.fromtimestamp(0))
        if preferences.archetype is None:
            preferences.set_archetype(
                game_relations.ARCHETYPE.NEUTRAL,
                change_time=datetime.datetime.fromtimestamp(0))
        if preferences.companion_dedication is None:
            preferences.set_companion_dedication(
                relations.COMPANION_DEDICATION.NORMAL,
                change_time=datetime.datetime.fromtimestamp(0))
        if preferences.companion_empathy is None:
            preferences.set_companion_empathy(
                relations.COMPANION_EMPATHY.ORDINAL,
                change_time=datetime.datetime.fromtimestamp(0))

        return preferences
Esempio n. 12
0
def load_person(person_id=None, person_model=None):
    # TODO: get values instead model
    # TODO: check that load_hero everywhere called with correct arguments
    try:
        if person_id is not None:
            person_model = models.Person.objects.get(id=person_id)
        elif person_model is None:
            return None
    except models.Person.DoesNotExist:
        return None

    data = s11n.from_json(person_model.data)

    return objects.Person(
        id=person_model.id,
        created_at_turn=person_model.created_at_turn,
        updated_at_turn=person_model.updated_at_turn,
        place_id=person_model.place_id,
        gender=person_model.gender,
        race=person_model.race,
        type=person_model.type,
        attrs=attributes.Attributes.deserialize(data.get('attributes', {})),
        politic_power=PersonPoliticPower.deserialize(data['politic_power'])
        if 'politic_power' in data else PersonPoliticPower.create(),
        utg_name=utg_words.Word.deserialize(data['name']),
        job=PersonJob.deserialize(data['job']) if 'job' in data else
        PersonJob.create(normal_power=NORMAL_PERSON_JOB_POWER),
        personality_cosmetic=relations.PERSONALITY_COSMETIC(
            data['personality']['cosmetic']),
        personality_practical=relations.PERSONALITY_PRACTICAL(
            data['personality']['practical']),
        moved_at_turn=data.get('moved_at_turn', 0),
        updated_at=person_model.updated_at)
Esempio n. 13
0
 def terrain(self):
     data =  s11n.from_json(self._model.terrain)
     terrain = []
     for row in data:
         terrain.append([])
         for cell in row:
             terrain[-1].append(TERRAIN(cell))
     return terrain
Esempio n. 14
0
    def refresh(self):
        self.clear()

        for forms in self._words_query().iterator():
            word = utg_words.Word.deserialize(s11n.from_json(forms))
            self._item.add_word(word)

        self._version = settings.get(self.SETTINGS_KEY)
Esempio n. 15
0
    def to_python(self, value):
        if not value:
            return None

        try:
            return s11n.from_json(value)
        except:
            raise forms.ValidationError("Неверный формат json")
Esempio n. 16
0
    def refresh(self):
        self.clear()

        for forms in self._words_query().iterator():
            word = utg_words.Word.deserialize(s11n.from_json(forms))
            self._item.add_word(word)

        self._version = settings.get(self.SETTINGS_KEY)
Esempio n. 17
0
 def test_choose_ability_request_anonymous(self):
     response = self.client.post(
         reverse('game:heroes:choose-ability', args=[self.hero.id]) +
         '?ability_id=' + self.get_new_ability_id())
     self.assertEqual(response.status_code, 200)
     self.assertEqual(
         s11n.from_json(response.content.decode('utf-8'))['status'],
         'error')
Esempio n. 18
0
    def check_ajax_error(self, response, code, content_type='application/json', encoding='utf-8', status_code=200):
        self.assertTrue(content_type in response['Content-Type'])
        self.assertTrue(encoding in response['Content-Type'])

        self.assertEqual(response.status_code, status_code)
        data = s11n.from_json(response.content.decode(encoding))
        self.assertEqual(data['status'], 'error')
        self.assertEqual(data['code'], code)
Esempio n. 19
0
 def from_model(cls, model):
     return cls(id=model.id,
                state=model.state,
                data=s11n.from_json(model.data),
                type=model.type,
                max_health=model.max_health,
                dedication=model.dedication,
                archetype=model.archetype,
                mode=model.mode)
Esempio n. 20
0
 def from_model(cls, model):
     return cls(id=model.id,
                state=model.state,
                data=s11n.from_json(model.data),
                type=model.type,
                max_health=model.max_health,
                dedication=model.dedication,
                archetype=model.archetype,
                mode=model.mode)
Esempio n. 21
0
    def check_ajax_processing(self, response, status_url=None, content_type='application/json', encoding='utf-8'):
        self.assertTrue(content_type in response['Content-Type'])
        self.assertTrue(encoding in response['Content-Type'])

        self.assertEqual(response.status_code, 200)
        data = s11n.from_json(response.content.decode(encoding))
        self.assertEqual(data['status'], 'processing')
        if status_url:
            self.assertEqual(data['status_url'], status_url)
Esempio n. 22
0
    def from_model(cls, model):
        data = s11n.from_json(model.data)

        goods = {}
        for good_data in data.get('goods', ()):
            good = Good.deserialize(good_data)
            goods[good.uid] = good

        return cls(id=model.id, account_id=model.account_id, goods=goods)
Esempio n. 23
0
def construct_from_model(model):

    data = s11n.from_json(model.data)

    abilities = frozenset(s11n.from_json(model.abilities))
    terrains = frozenset(
        map_relations.TERRAIN(terrain)
        for terrain in s11n.from_json(model.terrains))
    features = frozenset(
        beings_relations.FEATURE(feature)
        for feature in data.get('features', ()))

    weapons = [
        artifacts_objects.Weapon.deserialize(weapon_data)
        for weapon_data in data.get('weapons', ())
    ]

    mob = objects.MobRecord(
        id=model.id,
        editor_id=model.editor_id,
        level=model.level,
        uuid=model.uuid,
        description=model.description,
        state=model.state,
        type=model.type,
        archetype=model.archetype,
        communication_verbal=model.communication_verbal,
        communication_gestures=model.communication_gestures,
        communication_telepathic=model.communication_telepathic,
        intellect_level=model.intellect_level,
        is_mercenary=model.is_mercenary,
        is_eatable=model.is_eatable,
        abilities=abilities,
        terrains=terrains,
        structure=beings_relations.STRUCTURE(data.get('structure', 0)),
        features=features,
        movement=beings_relations.MOVEMENT(data.get('movement', 0)),
        body=beings_relations.BODY(data.get('body', 0)),
        size=beings_relations.SIZE(data.get('size', 0)),
        orientation=beings_relations.ORIENTATION(data.get('orientation', 0)),
        weapons=weapons,
        utg_name=utg_words.Word.deserialize(data['name']))
    return mob
Esempio n. 24
0
    def refresh(self):
        self.clear()

        for key, data in self._templates_query().iterator():
            data = s11n.from_json(data)
            template = utg_templates.Template.deserialize(data['template'])
            restrictions = frozenset(
                tuple(key) for key in data.get('restrictions', ()))
            self._item.add_template(key, template, restrictions=restrictions)

        self._version = settings.get(self.SETTINGS_KEY)
Esempio n. 25
0
    def from_model(cls, model):
        data = s11n.from_json(model.data)

        goods = {}
        for good_data in data.get('goods', ()):
            good = Good.deserialize(good_data)
            goods[good.uid] = good

        return cls(id=model.id,
                   account_id=model.account_id,
                   goods=goods)
Esempio n. 26
0
    def test_login(self):
        response = self.client.post(url('accounts:auth:api-login', api_version='1.0', api_client='test-1.0', next_url='/bla-bla'),
                                    {'email': '*****@*****.**', 'password': '******'})
        self.check_ajax_ok(response)

        data = s11n.from_json(response.content)

        self.assertEqual(data['data']['next_url'], '/bla-bla')
        self.assertEqual(data['data']['account_id'], self.account_id)
        self.assertEqual(data['data']['account_name'], 'test_user')
        self.assertTrue(data['data']['session_expire_at'] > time.time())
Esempio n. 27
0
 def test_handler(self):
     self.assertEqual(
         s11n.from_json(
             self.resource.test_view(
                 arg_1=6, api_version='1.1',
                 api_client='client-v0.1').content.decode('utf-8')), {
                     'status': 'ok',
                     'data': {
                         'arg_1': 6
                     }
                 })
Esempio n. 28
0
 def test_handler__depricated_api_version(self):
     self.assertEqual(
         s11n.from_json(
             self.resource.test_view(arg_1=6,
                                     api_version='1.0',
                                     api_client='client-v0.1').content), {
                                         'status': 'ok',
                                         'data': {
                                             'arg_1': 6
                                         },
                                         'depricated': True
                                     })
Esempio n. 29
0
    def refresh(self):
        from the_tale.linguistics.lexicon.keys import LEXICON_KEY

        self.clear()

        for key, data in self._templates_query().iterator():
            data = s11n.from_json(data)
            template = utg_templates.Template.deserialize(data["template"])
            restrictions = frozenset(tuple(key) for key in data.get("restrictions", ()))
            self._item.add_template(LEXICON_KEY(key), template, restrictions=restrictions)

        self._version = settings.get(self.SETTINGS_KEY)
Esempio n. 30
0
 def from_model(cls, model):
     return cls(id=model.id,
                state=model.state,
                data=s11n.from_json(model.data),
                type=model.type,
                max_health=model.max_health,
                dedication=model.dedication,
                archetype=model.archetype,
                mode=model.mode,
                communication_verbal=model.communication_verbal,
                communication_gestures=model.communication_gestures,
                communication_telepathic=model.communication_telepathic,
                intellect_level=model.intellect_level)
Esempio n. 31
0
    def check_ajax_ok(self, response, data=None, content_type='application/json', encoding='utf-8'):
        self.assertTrue(content_type in response['Content-Type'])
        self.assertTrue(encoding in response['Content-Type'])

        self.assertEqual(response.status_code, 200)
        content = s11n.from_json(response.content.decode(encoding))

        self.assertEqual(content['status'], 'ok')

        if data is not None:
            self.assertEqual(content['data'], data)

        return content.get('data')
Esempio n. 32
0
 def from_model(cls, model):
     return cls(id=model.id,
                state=model.state,
                data=s11n.from_json(model.data),
                type=model.type,
                max_health=model.max_health,
                dedication=model.dedication,
                archetype=model.archetype,
                mode=model.mode,
                communication_verbal=model.communication_verbal,
                communication_gestures=model.communication_gestures,
                communication_telepathic=model.communication_telepathic,
                intellect_level=model.intellect_level)
    def handle(self, *args, **options):

        for companion in models.CompanionRecord.objects.all().order_by(
                'id').iterator():
            print('process companion {}'.format(companion.id))

            data = s11n.from_json(companion.data)

            data['weapons'] = [{'weapon': 0, 'material': 0, 'power_type': 2}]

            companion.data = s11n.to_json(data)

            companion.save()
Esempio n. 34
0
def load_place(place_id=None, place_model=None):

    # TODO: get values instead model
    # TODO: check that load_hero everywhere called with correct arguments
    try:
        if place_id is not None:
            place_model = models.Place.objects.get(id=place_id)
        elif place_model is None:
            return None
    except models.Place.DoesNotExist:
        return None

    data = s11n.from_json(place_model.data)

    if 'nearest_cells' in data:
        data['nearest_cells'] = list(map(tuple, data['nearest_cells']))

    place = objects.Place(
        id=place_model.id,
        x=place_model.x,
        y=place_model.y,
        created_at_turn=place_model.created_at_turn,
        updated_at_turn=place_model.updated_at_turn,
        updated_at=place_model.updated_at,
        created_at=place_model.created_at,
        habit_honor=habits.Honor(raw_value=place_model.habit_honor),
        habit_honor_positive=place_model.habit_honor_positive,
        habit_honor_negative=place_model.habit_honor_negative,
        habit_peacefulness=habits.Peacefulness(
            raw_value=place_model.habit_peacefulness),
        habit_peacefulness_positive=place_model.habit_peacefulness_positive,
        habit_peacefulness_negative=place_model.habit_peacefulness_negative,
        is_frontier=place_model.is_frontier,
        description=place_model.description,
        race=place_model.race,
        persons_changed_at_turn=place_model.persons_changed_at_turn,
        politic_power=PlacePoliticPower.deserialize(data['politic_power'])
        if 'politic_power' in data else PlacePoliticPower.create(),
        utg_name=utg_words.Word.deserialize(data['name']),
        attrs=attributes.Attributes.deserialize(data.get('attributes', {})),
        races=races.Races.deserialize(data['races']),
        nearest_cells=data.get('nearest_cells', []),
        effects=EffectsContainer.deserialize(data.get('effects')),
        job=PlaceJob.deserialize(data['job']) if 'job' in data else
        PlaceJob.create(normal_power=NORMAL_PLACE_JOB_POWER),
        modifier=place_model.modifier)

    place.attrs.sync()

    return place
Esempio n. 35
0
    def from_model(cls, model):
        data = s11n.from_json(model.data)

        return cls(id=model.id,
                   created_at=model.created_at,
                   type=model.type,
                   name=model.name,
                   seller_id=model.seller_id,
                   buyer_id=model.buyer_id,
                   state=model.state,
                   good=Good.deserialize(data['good']),
                   price=model.price,
                   closed_at=model.closed_at,
                   commission=model.commission,
                   group_id=model.group_id)
Esempio n. 36
0
def get_currencies_info(base_currency, currencies_list):

    if base_currency not in currencies_list:
        currencies_list.append(base_currency)

    resource = urllib2.urlopen(utils_settings.OPEN_EXCHANGE_RATES_API_LATEST_URL + '?app_id=' + utils_settings.OPEN_EXCHANGE_RATES_API_ID)
    data = s11n.from_json(resource.read())
    resource.close()

    currencies = {}

    for currency in currencies_list:
        currencies[currency] = float(data['rates'][currency]) / data['rates'][base_currency]

    return currencies
Esempio n. 37
0
    def from_model(cls, model):
        data = s11n.from_json(model.data)

        return cls(id=model.id,
                   created_at=model.created_at,
                   type=model.type,
                   name=model.name,
                   seller_id=model.seller_id,
                   buyer_id=model.buyer_id,
                   state=model.state,
                   good=Good.deserialize(data['good']),
                   price=model.price,
                   closed_at=model.closed_at,
                   commission=model.commission,
                   group_id=model.group_id)
Esempio n. 38
0
    def refresh(self):
        from the_tale.linguistics.lexicon.keys import LEXICON_KEY

        self.clear()

        for key, data in self._templates_query().iterator():
            data = s11n.from_json(data)
            template = utg_templates.Template.deserialize(data['template'])
            restrictions = frozenset(
                tuple(key) for key in data.get('restrictions', ()))
            self._item.add_template(LEXICON_KEY(key),
                                    template,
                                    restrictions=restrictions)

        self._version = settings.get(self.SETTINGS_KEY)
Esempio n. 39
0
    def test_sync(self):
        self.assertEqual(len(self.storage._data), 3)

        self.assertNotEqual(self.p1.attrs.size, 7)

        place = Place.objects.get(id=self.p1.id)
        data = s11n.from_json(place.data)
        data['attributes']['size'] = 7
        place.data = s11n.to_json(data)
        place.save()

        self.storage.sync()
        self.assertNotEqual(self.storage[self.p1.id].attrs.size, 7)

        self.storage.sync(force=True)
        self.assertEqual(self.storage[self.p1.id].attrs.size, 7)
Esempio n. 40
0
def load_cards(account_id):
    answer = tt_api.sync_request(
        url=conf.settings.TT_STORAGE_GET_ITEMS_URL,
        data=storage_pb2.GetItemsRequest(owner_id=account_id),
        AnswerType=storage_pb2.GetItemsResponse)

    cards = {}

    for item in answer.items:
        id = uuid.UUID(item.id)
        cards[id] = objects.Card.deserialize(uid=id,
                                             data=s11n.from_json(item.data),
                                             storage=relations.STORAGE(
                                                 item.storage_id))

    return cards
Esempio n. 41
0
    def test_sync(self):
        self.assertEqual(len(self.storage._data), 3)

        self.assertNotEqual(self.p1.attrs.size, 7)

        place = Place.objects.get(id=self.p1.id)
        data = s11n.from_json(place.data)
        data['attributes']['size'] = 7
        place.data = s11n.to_json(data)
        place.save()

        self.storage.sync()
        self.assertNotEqual(self.storage[self.p1.id].attrs.size, 7)

        self.storage.sync(force=True)
        self.assertEqual(self.storage[self.p1.id].attrs.size, 7)
Esempio n. 42
0
def load_place(place_id=None, place_model=None):

    # TODO: get values instead model
    # TODO: check that load_hero everywhere called with correct arguments
    try:
        if place_id is not None:
            place_model = models.Place.objects.get(id=place_id)
        elif place_model is None:
            return None
    except models.Place.DoesNotExist:
        return None

    data = s11n.from_json(place_model.data)

    if 'nearest_cells' in data:
        data['nearest_cells'] = list(map(tuple, data['nearest_cells']))

    place = objects.Place(id=place_model.id,
                          x=place_model.x,
                          y=place_model.y,
                          created_at_turn=place_model.created_at_turn,
                          updated_at_turn=place_model.updated_at_turn,
                          updated_at=place_model.updated_at,
                          created_at=place_model.created_at,
                          habit_honor=habits.Honor(raw_value=place_model.habit_honor),
                          habit_honor_positive=place_model.habit_honor_positive,
                          habit_honor_negative=place_model.habit_honor_negative,
                          habit_peacefulness=habits.Peacefulness(raw_value=place_model.habit_peacefulness),
                          habit_peacefulness_positive=place_model.habit_peacefulness_positive,
                          habit_peacefulness_negative=place_model.habit_peacefulness_negative,
                          is_frontier=place_model.is_frontier,
                          description=place_model.description,
                          race=place_model.race,
                          persons_changed_at_turn=place_model.persons_changed_at_turn,
                          politic_power=PlacePoliticPower.deserialize(data['politic_power']) if 'politic_power'in data else PlacePoliticPower.create(),
                          utg_name=utg_words.Word.deserialize(data['name']),
                          attrs=attributes.Attributes.deserialize(data.get('attributes', {})),
                          races=races.Races.deserialize(data['races']),
                          nearest_cells=data.get('nearest_cells', []),
                          effects=EffectsContainer.deserialize(data.get('effects')),
                          job=PlaceJob.deserialize(data['job']) if 'job' in data else PlaceJob.create(normal_power=NORMAL_PLACE_JOB_POWER),
                          modifier=place_model.modifier)

    place.attrs.sync()

    return place
Esempio n. 43
0
    def handle(self, *args, **options):

        for artifact in models.ArtifactRecord.objects.all().order_by(
                'id').iterator():
            print('process artifact {}'.format(artifact.id))

            if artifact.id not in WEAPONS:
                continue

            data = s11n.from_json(artifact.data)

            data['weapon_type'] = WEAPONS[artifact.id][0].value
            data['material'] = WEAPONS[artifact.id][-1].value

            artifact.data = s11n.to_json(data)

            artifact.save()
Esempio n. 44
0
    def clean_words(self):
        data = self.cleaned_data.get('words')

        if data is None:
            raise ValidationError(u'Нет данных', code='not_json')

        try:
            words_data = s11n.from_json(data)
        except ValueError:
            raise ValidationError(u'Данные должны быть в формате JSON', code='not_json')

        try:
            words = [utg_words.Word.deserialize(word_data) for word_data in words_data.get('words')]
        except:
            raise ValidationError(u'Неверный формат описания слов', code='wrong_words_format')

        return words
Esempio n. 45
0
    def preferences(self):
        from the_tale.game.heroes.preferences import HeroPreferences

        preferences = HeroPreferences.deserialize(hero=self, data=s11n.from_json(self._model.preferences))

        if preferences.energy_regeneration_type is None:
            preferences.set_energy_regeneration_type(self.race.energy_regeneration, change_time=datetime.datetime.fromtimestamp(0))
        if preferences.risk_level is None:
            preferences.set_risk_level(relations.RISK_LEVEL.NORMAL, change_time=datetime.datetime.fromtimestamp(0))
        if preferences.archetype is None:
            preferences.set_archetype(game_relations.ARCHETYPE.NEUTRAL, change_time=datetime.datetime.fromtimestamp(0))
        if preferences.companion_dedication is None:
            preferences.set_companion_dedication(relations.COMPANION_DEDICATION.NORMAL, change_time=datetime.datetime.fromtimestamp(0))
        if preferences.companion_empathy is None:
            preferences.set_companion_empathy(relations.COMPANION_EMPATHY.ORDINAL, change_time=datetime.datetime.fromtimestamp(0))

        return preferences
Esempio n. 46
0
    def test_sync_after_settings_update(self):
        self.assertEqual(len(self.storage._data), 3)

        self.assertNotEqual(self.p1.attrs.size, 7)

        place = Place.objects.get(id=self.p1.id)
        data = s11n.from_json(place.data)
        data['attributes']['size'] = 7
        place.data = s11n.to_json(data)
        place.save()

        self.storage.sync()
        self.assertNotEqual(self.storage[self.p1.id].attrs.size, 7)

        settings[self.storage.SETTINGS_KEY] = uuid.uuid4().hex

        self.storage.sync()
        self.assertEqual(self.storage[self.p1.id].attrs.size, 7)
Esempio n. 47
0
    def test_sync_after_settings_update(self):
        self.assertEqual(len(self.storage._data), 3)

        self.assertNotEqual(self.p1.attrs.size, 7)

        place = Place.objects.get(id=self.p1.id)
        data = s11n.from_json(place.data)
        data['attributes']['size'] = 7
        place.data = s11n.to_json(data)
        place.save()

        self.storage.sync()
        self.assertNotEqual(self.storage[self.p1.id].attrs.size, 7)

        settings[self.storage.SETTINGS_KEY] = uuid.uuid4().hex

        self.storage.sync()
        self.assertEqual(self.storage[self.p1.id].attrs.size, 7)
Esempio n. 48
0
def load_place(place_id=None, place_model=None):
    try:
        if place_id is not None:
            place_model = models.Place.objects.get(id=place_id)
        elif place_model is None:
            return None
    except models.Place.DoesNotExist:
        return None

    data = s11n.from_json(place_model.data)

    if 'nearest_cells' in data:
        data['nearest_cells'] = list(map(tuple, data['nearest_cells']))

    place = objects.Place(
        id=place_model.id,
        x=place_model.x,
        y=place_model.y,
        created_at_turn=place_model.created_at_turn,
        updated_at_turn=place_model.updated_at_turn,
        updated_at=place_model.updated_at,
        created_at=place_model.created_at,
        habit_honor=habits.Honor(raw_value=place_model.habit_honor),
        habit_honor_positive=place_model.habit_honor_positive,
        habit_honor_negative=place_model.habit_honor_negative,
        habit_peacefulness=habits.Peacefulness(
            raw_value=place_model.habit_peacefulness),
        habit_peacefulness_positive=place_model.habit_peacefulness_positive,
        habit_peacefulness_negative=place_model.habit_peacefulness_negative,
        is_frontier=place_model.is_frontier,
        description=place_model.description,
        race=place_model.race,
        persons_changed_at_turn=place_model.persons_changed_at_turn,
        utg_name=utg_words.Word.deserialize(data['name']),
        attrs=attributes.Attributes.deserialize(data.get('attributes', {})),
        races=races.Races.deserialize(data['races']),
        nearest_cells=data.get('nearest_cells', []),
        effects=EffectsContainer.deserialize(data.get('effects')),
        job=PlaceJob.deserialize(data['job']),
        modifier=place_model.modifier)

    place.attrs.sync()

    return place
Esempio n. 49
0
def load_building(building_id=None, building_model=None):
    try:
        if building_id is not None:
            building_model = models.Building.objects.get(id=building_id)
        elif building_model is None:
            return None
    except models.Building.DoesNotExist:
        return None

    data = s11n.from_json(building_model.data)

    building = objects.Building(id=building_model.id,
                                x=building_model.x,
                                y=building_model.y,
                                created_at_turn=building_model.created_at_turn,
                                utg_name=utg_words.Word.deserialize(data['name']),
                                type=building_model.type,
                                integrity=building_model.integrity,
                                state=building_model.state,
                                person_id=building_model.person_id)

    return building
Esempio n. 50
0
    def test_full__reject(self):

        api_client = Client()

        request_token_url = url('accounts:third-party:tokens:request-authorisation', api_version='1.0', api_client=project_settings.API_CLIENT)

        response = api_client.post(request_token_url, {'application_name': 'app-name',
                                                       'application_info': 'app-info',
                                                       'application_description': 'app-descr'})

        self.check_ajax_ok(response)

        token_url = s11n.from_json(response.content)['data']['authorisation_page']

        token = prototypes.AccessTokenPrototype._db_latest()

        self.assertEqual(url('accounts:third-party:tokens:show', token.uid), token_url)

        self.check_html_ok(self.request_html(token_url), texts=['app-name', 'app-info', 'app-descr'])


        authorisation_state_url = url('accounts:third-party:tokens:authorisation-state', api_version='1.0', api_client=project_settings.API_CLIENT)

        self.check_ajax_ok(api_client.get(authorisation_state_url),
                           data={'account_id': None,
                                 'account_name': None,
                                 'state': relations.AUTHORISATION_STATE.UNPROCESSED.value,
                                 'session_expire_at': 666.6})

        token.remove()

        self.check_ajax_ok(api_client.get(authorisation_state_url),
                           data={'account_id': None,
                                 'account_name': None,
                                 'state': relations.AUTHORISATION_STATE.REJECTED.value,
                                 'session_expire_at': 666.6})
Esempio n. 51
0
 def test_logined(self):
     response = self.client.get(self.game_info_url_1)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(set(s11n.from_json(response.content)['data'].keys()), set(('turn', 'mode', 'map_version', 'account', 'enemy', 'game_state')))
Esempio n. 52
0
def load_hero(hero_id=None, account_id=None, hero_model=None):

    # TODO: get values instead model
    # TODO: check that load_hero everywhere called with correct arguments
    try:
        if hero_id is not None:
            hero_model = models.Hero.objects.get(id=hero_id)
        elif account_id is not None:
            hero_model = models.Hero.objects.get(account_id=account_id)
        elif hero_model is None:
            return None
    except models.Hero.DoesNotExist:
        return None

    if isinstance(hero_model.data, str):
        data = s11n.from_json(hero_model.data)
    else:
        data = hero_model.data

    companion_data = data.get('companion')
    companion = companions_objects.Companion.deserialize(companion_data) if companion_data else None

    return objects.Hero(id=hero_model.id,
                        account_id=hero_model.account_id,
                        health=hero_model.health,
                        level=hero_model.level,
                        experience=hero_model.experience,
                        energy=hero_model.energy,
                        energy_bonus=hero_model.energy_bonus,
                        money=hero_model.money,
                        next_spending=hero_model.next_spending,
                        habit_honor=habits.Honor(raw_value=hero_model.habit_honor),
                        habit_peacefulness=habits.Peacefulness(raw_value=hero_model.habit_peacefulness),
                        position=hero_position_from_model(hero_model),
                        statistics=hero_statistics_from_model(hero_model),
                        preferences=preferences.HeroPreferences.deserialize(data=s11n.from_json(hero_model.preferences)),
                        actions=actions_container.ActionsContainer.deserialize(s11n.from_json(hero_model.actions)),
                        companion=companion,
                        journal=messages.JournalContainer(), # we are not storrings journal in database, since messages in it replaced very fast
                        quests=quests_container.QuestsContainer.deserialize(data.get('quests', {})),
                        places_history=places_help_statistics.PlacesHelpStatistics.deserialize(data['places_history']),
                        cards=cards_container.CardsContainer.deserialize(s11n.from_json(hero_model.cards)),
                        abilities=habilities.AbilitiesPrototype.deserialize(s11n.from_json(hero_model.abilities)),
                        bag=bag.Bag.deserialize(data['bag']),
                        equipment=bag.Equipment.deserialize(data['equipment']),
                        created_at_turn=hero_model.created_at_turn,
                        saved_at_turn=hero_model.saved_at_turn,
                        saved_at=hero_model.saved_at,
                        is_bot=hero_model.is_bot,
                        is_alive=hero_model.is_alive,
                        is_fast=hero_model.is_fast,
                        gender=hero_model.gender,
                        race=hero_model.race,
                        last_energy_regeneration_at_turn=hero_model.last_energy_regeneration_at_turn,
                        might=hero_model.might,
                        ui_caching_started_at=hero_model.ui_caching_started_at,
                        active_state_end_at=hero_model.active_state_end_at,
                        premium_state_end_at=hero_model.premium_state_end_at,
                        ban_state_end_at=hero_model.ban_state_end_at,
                        last_rare_operation_at_turn=hero_model.last_rare_operation_at_turn,
                        settings_approved=hero_model.settings_approved,
                        actual_bills=data['actual_bills'],
                        utg_name=utg_words.Word.deserialize(data['name']))
Esempio n. 53
0
    def data(self): return s11n.from_json(self._model.data)

    @property
Esempio n. 54
0
 def hero_2_context(self):
     if not hasattr(self, '_hero_2_context'):
         self._hero_2_context = contexts.BattleContext.deserialize(s11n.from_json(self.members_by_roles[self.ROLES.HERO_2].context))
         self._hero_2_context.use_pvp_advantage_stike_damage(self.hero_2.basic_damage * c.DAMAGE_PVP_FULL_ADVANTAGE_STRIKE_MODIFIER)
     return self._hero_2_context
Esempio n. 55
0
 def data(self):
     from the_tale.game.bills.bills import deserialize_bill
     if not hasattr(self, '_data'):
         self._data = deserialize_bill(s11n.from_json(self._model.technical_data))
     return self._data