Ejemplo n.º 1
0
async def v1_play(request, socket):
    await socket.send(dumps({'type': 'authorization-request'}))

    response = Document(loads(await socket.recv()))

    if not response.event.type == 'authorization-response':
        await socket.close()

    if not response.data:
        await socket.close()

    if not response.data.token and isinstance(response.data.token, str):
        await socket.close()

    token = Document(jwt.decode(response.data.token, secret=PS.secret))

    Connections.set_socket_by_character_id(socket, token.data.character.id)

    socket = Connections.socket_by_character_id(token.data.character.id)

    socket.disconnect = PS.disconnect
    Connections.on('reconnect', PS.reconnect)
    Connections.on('login', PS.login)
    Connections.on('logout', PS.logout)

    Connections.on('player-set-location', PS.player_location)
    Connections.on('player-request-stats', PS.player_request_stats)
Ejemplo n.º 2
0
    async def test_create_type_mismatch(self):

        #response = await Mixin._create(Document({
        #    'json': {
        #        'data': {
        #            'type': 'invalid'
        #        }
        #    }
        #}))

        decorator = Mixin._check_create(None)

        response = await decorator(Document({
            'json': {
                'data': {
                    'type': 'invalid'
                }
            }
        }))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Provided type does not match resource type.')

        await Mixin.drop()
Ejemplo n.º 3
0
    async def test_no_data(self):

        response = await WebToken._post(Document({'json': {}}))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'No data provided.')
Ejemplo n.º 4
0
    async def test_create_type_missing(self):

        #response = await Mixin._create(Document({
        #    'json': {
        #        'data': {
        #            'test': 'ing'
        #        }
        #    }
        #}))

        decorator = Mixin._check_create(None)

        response = await decorator(Document({
            'json': {
                'data': {
                    'test': 'ing'
                }
            }
        }))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Type is missing.')

        await Mixin.drop()
Ejemplo n.º 5
0
    async def test_update_id_mismatch(self):

        #response = await Mixin._update(Document({
        #    'json': {
        #        'data': {
        #            'type': 'mixins',
        #            'id': 'alpha'
        #        }
        #    }
        #}), 'beta')

        decorator = Mixin._check_update(None)

        response = await decorator(Document({
            'json': {
                'data': {
                    'type': 'mixins',
                    'id': 'alpha'
                }
            }
        }), 'beta')

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'ID provided does not match ID in the URL.')
Ejemplo n.º 6
0
    async def test_read_multiple_no_data_found(self):

        response = await Mixin._read(Document({
            'args': { }
        }))

        response = decode(response)

        self.assertEqual(len(response.data), 0)
Ejemplo n.º 7
0
    async def test_read_by_id_no_data_found(self):

        response = await Mixin._read(Document({
            'args': { }
        }), 'aabbccddeeffaabbccddeeff')

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'No data found.')
Ejemplo n.º 8
0
    async def test_data_not_a_dict(self):

        response = await WebToken._post(Document({'json': {
            'data': 'invalid'
        }}))

        response = decode(response)

        self.assertEqual(response.errors[0].detail,
                         'Data is not a JSON object.')
Ejemplo n.º 9
0
    async def test_no_password(self):

        response = await WebToken._post(
            Document({'json': {
                'data': {
                    'attributes': {
                        'username': '******'
                    }
                }
            }}))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Missing password.')
Ejemplo n.º 10
0
    async def test_read_by_id(self):

        test = Mixin()

        await test.save()

        response = await Mixin._read(Document({
            'args': { }
        }), test.id)

        response = decode(response)

        self.assertEqual(response.data.id, test.id)

        await Mixin.drop()
Ejemplo n.º 11
0
    async def test_no_username(self):

        response = await WebToken._post(
            Document(
                {'json': {
                    'data': {
                        'attributes': {
                            'non-existent': 'value'
                        }
                    }
                }}))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Missing username.')
Ejemplo n.º 12
0
    async def test_read_multiple_query(self):

        await Mixin.add({
            'field': 'value'
        })

        response = await Mixin._read(Document({
            'args': {
                'query': '{ "field": "value" }'
            }
        }))

        response = decode(response)

        self.assertEqual(response.data[0].attributes.field, 'value')

        await Mixin.drop()
Ejemplo n.º 13
0
    async def test_read_multiple(self):

        await Mixin.add([
            { },
            { },
            { }
        ])

        response = await Mixin._read(Document({
            'args': { }
        }))

        response = decode(response)

        self.assertEqual(len(response.data), 3)

        await Mixin.drop()
Ejemplo n.º 14
0
    async def test_delete_id_missing(self):

        test = Mixin()

        await test.save()

        response = await Mixin._delete(Document({
            'json': { }
        }), test.id)

        response = decode(response)

        self.assertDictEqual(response, {
            'data': {
                'id': test.id
            }
        })
Ejemplo n.º 15
0
    async def test_create_from_json_exception(self):

        response = await Mixin._create(Document({
            'json': {
                'data': {
                    'type': 'mixins',
                    'attributes': {
                        'undefined_field': 'invalid'
                    }
                }
            }
        }))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Mixin has undefined fields: undefined_field')

        await Mixin.drop()
Ejemplo n.º 16
0
    async def test_web_token(self):
        class Model(MemoryModel):
            username = Field()
            password = Field()

            @classmethod
            async def find_one(cls, query):
                for id in cls.db:
                    data = cls.db[id].copy()
                    del data['id']
                    if data == query:
                        return cls(cls.db[id])
                return None

        class Authentication(WebToken):
            @classmethod
            async def payload(cls, username, password):
                user = await Model.find_one({
                    'username': username,
                    'password': password
                })

                return user.serialize()

        await Model.add({'username': '******', 'password': '******'})

        response = await Authentication._post(
            Document({
                'json': {
                    'data': {
                        'attributes': {
                            'username': '******',
                            'password': '******'
                        }
                    }
                }
            }))

        response = decode(response)

        self.assertTrue(response.data.attributes.token)
Ejemplo n.º 17
0
    async def test_read_multiple_offset(self):

        await Mixin.add([
            { 'field': '1' },
            { 'field': '2' },
            { 'field': '3'}
        ])

        response = await Mixin._read(Document({
            'args': {
                'page[limit]': 1,
                'page[offset]': 1,
                'sort': 'field'
            }
        }))

        response = decode(response)

        self.assertEqual(response.data[0].attributes.field, '2')

        await Mixin.drop()
Ejemplo n.º 18
0
    async def test_read_multiple_sort_descending(self):

        await Mixin.add([
            { 'field': '2' },
            { 'field': '1' },
            { 'field': '3' }
        ])

        response = await Mixin._read(Document({
            'args': {
                'sort': '-field'
            }
        }))

        response = decode(response)

        count = 3

        for data in response.data:
            self.assertEqual(data.attributes.field, str(count))
            count -= 1

        await Mixin.drop()
Ejemplo n.º 19
0
    async def test_read_multiple_sort_missing(self):

        await Mixin.add([
            { 'field': '2' },
            { 'field': '1' },
            { 'field': '3' }
        ])

        response = await Mixin._read(Document({
            'args': { }
        }))

        response = decode(response)

        count = 0

        results = [ '2', '1', '3' ]

        for data in response.data:
            self.assertEqual(data.attributes.field, results[count])
            count += 1

        await Mixin.drop()
Ejemplo n.º 20
0
    async def test_update_type_missing(self):

        #response = await Mixin._update(Document({
        #    'json': {
        #        'data': {
        #            'non-existent': 'value'
        #        }
        #    }
        #}))

        decorator = Mixin._check_update(None)

        response = await decorator(Document({
            'json': {
                'data': {
                    'non-existent': 'value'
                }
            }
        }))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Type is missing.')
Ejemplo n.º 21
0
    async def test_create_id_already_exists(self):

        test = Mixin()

        await test.save()

        response = await Mixin._create(Document({
            'json': {
                'data': {
                    'type': 'mixins',
                    'id': test.id,
                    'attributes': {
                        'field': 'value'
                    }
                }
            }
        }))

        response = decode(response)

        self.assertTrue(response.errors[0].detail.endswith('already exists.'))

        await Mixin.drop()
Ejemplo n.º 22
0
    async def test_update_type_mismatch(self):

        #response = await Mixin._update(Document({
        #    'json': {
        #        'data': {
        #            'type': 'invalid'
        #        }
        #    }
        #}))

        decorator = Mixin._check_update(None)

        response = await decorator(Document({
            'json': {
                'data': {
                    'type': 'invalid'
                }
            }
        }))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'Type in payload does not match collection type.')
Ejemplo n.º 23
0
    async def test_update_id_missing(self):

        #response = await Mixin._update(Document({
        #    'json': {
        #        'data': {
        #            'type': 'mixins'
        #        }
        #    }
        #}))

        decorator = Mixin._check_update(None)

        response = await decorator(Document({
            'json': {
                'data': {
                    'type': 'mixins'
                }
            }
        }))

        response = decode(response)

        self.assertEqual(response.errors[0].detail, 'ID is missing.')
Ejemplo n.º 24
0
class TestDocument(TestCase):

    test_data = {
        'alpha': 'a',
        'beta': 'b',
        'gamma': 'g',
        'delta': {
            'epsilon': 'e',
            'zeta': 'z',
        },
    }

    def setUp(self):
        self.doc = Document(self.test_data)

    def test_getattribute(self):
        self.assertEqual(self.doc.alpha, 'a')

    def test_getattribute_nested(self):
        self.assertEqual(self.doc.delta.zeta, 'z')

    def test_getattribute_default(self):
        self.assertIsNone(self.doc.iota)

    def test_setattr(self):
        self.doc.theta = 't'
        self.assertEqual(self.doc.theta, 't')
        self.assertEqual(self.doc.get('theta'), 't')

    def test_fromkeys(self):
        doc = Document.fromkeys(['test', 'ing'], 'value')
        self.assertDictEqual(doc, {'test': 'value', 'ing': 'value'})
        self.assertTrue(isinstance(doc, Document))

    def test_get(self):
        value = self.doc.get('alpha')
        self.assertEqual(value, self.test_data['alpha'])
        value = self.doc.get('nonexistent', 'test')
        self.assertEqual(value, 'test')
        value = self.doc.get('nonexistent')
        self.assertIsNone(value)

    def test_items(self):
        items = self.doc.items()
        self.assertEqual(items, [('alpha', 'a'), ('beta', 'b'), ('gamma', 'g'),
                                 ('delta', {
                                     'epsilon': 'e',
                                     'zeta': 'z'
                                 })])

    def test_values(self):
        values = self.doc.values()
        self.assertEqual(values,
                         ['a', 'b', 'g', {
                             'epsilon': 'e',
                             'zeta': 'z'
                         }])

    def test_iteritems(self):
        iteritems = self.doc.iteritems()
        self.assertTrue(isgenerator(iteritems))

    def test_itervalues(self):
        itervalues = self.doc.itervalues()
        self.assertTrue(isgenerator(itervalues))

    def test_pop(self):
        value = self.doc.pop('alpha')
        self.assertEqual(value, self.test_data['alpha'])
        value = self.doc.pop('nonexistent', 'test')
        self.assertEqual(value, 'test')
        value = self.doc.pop('nonexistent')
        self.assertIsNone(value)

    def test_popitem(self):
        k, v = self.doc.popitem()
        self.assertIsNotNone(k)
        self.assertIsNotNone(v)

    @skip('not tested')
    def test_viewitems(self):
        pass

    @skip('not tested')
    def test_viewvalues(self):
        pass
Ejemplo n.º 25
0
 def test_fromkeys(self):
     doc = Document.fromkeys(['test', 'ing'], 'value')
     self.assertDictEqual(doc, {'test': 'value', 'ing': 'value'})
     self.assertTrue(isinstance(doc, Document))
Ejemplo n.º 26
0
 def setUp(self):
     self.doc = Document(self.test_data)
Ejemplo n.º 27
0
def decode(response):
    return Document(json.loads(response.body.decode()))
Ejemplo n.º 28
0
async def create(request, token):

    if not token:
        error = Error(title='Create Character Error',
                      detail='You are not logged in.',
                      status=403)
        return jsonapi({"errors": [error.serialize()]}, status=403)

    token = Document(token)

    data = request.json.get('data')
    attributes = data.get('attributes')

    character = await Character.find_one({'profile': token.data.id})

    if character:
        error = Error(title='Create Character Error',
                      detail='You already have a character.',
                      status=403)
        return jsonapi({"errors": [error.serialize()]}, status=403)

    try:
        character = Character(attributes)
    except:
        error = Error(title='Create Character Error',
                      detail='Invalid attributes.',
                      status=403)
        return jsonapi({"errors": [error.serialize()]}, status=403)

    character.profile = token.data.id

    if not character.race in WorldCache.races:
        error = Error(title='Create Character Error',
                      detail='Invalid race.',
                      status=403)
        return jsonapi({"errors": [error.serialize()]}, status=403)

    if not len(character.name.first) > 5:
        error = Error(title='Create Character Error',
                      detail='Invalid first name.',
                      status=403)
        return jsonapi({"errors": [error.serialize()]}, status=403)

    character.level = {'current': 1, 'experience': 0, 'next': 1000}
    character.attributes = WorldCache.races[character.race]['attributes']
    character.health = 0
    character.state = {
        'target': None,
        'hostile': False,
        'retaliate': False,
        'dead': False,
        'casting': False
    }

    await character.save()

    return jsonapi({
        'data': {
            'attributes': {
                'message': 'Character created.',
                'url': f'/v1/characters/{character.id}'
            }
        }
    })