Beispiel #1
0
    def test_patch(self):
        self.login('*****@*****.**')

        with cas_mockup_server(), self.given(
                'Testing the patch method on APIv1',
                verb='PATCH',
                url='/apiv1',
                json=[
                    dict(op='MENTION',
                         path=f'targets/{self.room.id}/mentions',
                         value={
                             'body': 'sample message',
                             'originTargetId': self.room.id
                         }),
                    dict(op='MENTION',
                         path=f'members/{self.user2.id}/mentions',
                         value={
                             'body': 'abc',
                             'originTargetId': self.room.id
                         }),
                ]):
            assert status == 200
            assert len(response.json) == 2
            assert response.json[0]['id'] is not None
            assert response.json[1]['id'] is not None

            when(
                'One of requests response faces non 200 OK',
                json=[dict(op='MENTION', path='targets/0/mentions', value={})])
            assert status == 404
Beispiel #2
0
def test_stream(app, Given):
    endresponseiscalled = 0

    @app.when
    def endresponse(resp):
        nonlocal endresponseiscalled
        endresponseiscalled += 1

    @app.route()
    @yhttp.text
    def get(req):
        yield 'foo'
        yield 'bar'
        yield 'baz'

    @app.route('/binary')
    def get(req):  # noqa: W0404
        req.response.length = 9
        yield b'foo'
        yield b'bar'
        yield b'baz'

    with Given():
        assert status == 200
        assert response.text == 'foobarbaz'
        assert endresponseiscalled == 1

        when('/binary')
        assert status == 200
        assert response.text == 'foobarbaz'
        assert response.headers['content-length'] == '9'
        assert endresponseiscalled == 2
    def test_jsonpatch(self):
        with self.given('Testing the patch method',
                        verb='PATCH',
                        url='/',
                        json=[
                            dict(op='CREATE',
                                 path='',
                                 value=dict(title='first')),
                            dict(op='CREATE',
                                 path='',
                                 value=dict(title='second'))
                        ]):
            assert status == 200
            assert len(response.json) == 2
            assert response.json[0]['id'] is not None
            assert response.json[1]['id'] is not None

            when('Testing the list method using patch',
                 json=[dict(op='LIST', path='')])
            assert len(response.json) == 1
            assert len(response.json[0]) == 3

            when('Trying to pass without value',
                 json=[
                     dict(op='CREATE', path='', value=dict(title='third')),
                     dict(op='CREATE', path=''),
                 ])
            assert status == 400
Beispiel #4
0
    def test_update_from_request(self):
        with self.given(
            'Posting a datetime in form',
            verb='POST',
            form=dict(
                when='2001-01-01T00:01',
            )
        ):
            assert status == 200
            assert response.json == '2001-01-01T00:01:00'

            when(
                'Posting a date instead of datetime',
                form=dict(
                    when='2001-01-01'
                )
            )

            assert status == 200
            assert response.json == '2001-01-01T00:00:00'

            when(
                'Posting an invalid datetime',
                form=dict(
                    when='2001-00-01'
                )
            )

            assert status == '400 Invalid date or time: 2001-00-01'
Beispiel #5
0
def test_status(app, Given):
    @app.route()
    @statuscode('201 Created')
    def post(req):
        return b''

    @app.route()
    @statuscode('205 Reset Content')
    def put(req):
        return b''

    @app.route()
    @statuscode(nocontent)  # 204 No Content
    def delete(req):
        return b''

    with Given(verb='POST'):
        assert status == '201 Created'

        when(verb='PUT')
        assert status == 205

        when(verb='DELETE')
        assert status == 204
        assert response == ''
Beispiel #6
0
    def test_update(self):
        self.login(email='*****@*****.**', password='******')

        with self.given(
                'delete member',
                f'/apiv1/members/id: {self.member1.id}',
                'DELETE',
        ):
            assert status == 200
            assert response.json['id'] == self.member1.id
            assert response.json['title'] == self.member1.title
            assert response.json['email'] == self.member1.email
            assert response.json['firstName'] == self.member1.first_name
            assert response.json['lastName'] == self.member1.last_name
            assert response.json['gender'] == self.member1.gender

            session = self.create_session()
            assert not session.query(Member) \
                .filter(Member.id == self.member1.id) \
                .one_or_none()

            when('Request is not authorized', authorization=None)
            assert status == 401

        self.logout()
Beispiel #7
0
def test_routing_basic(app, Given):

    @app.route()
    def get(req):
        return 'get index'

    @app.route()
    def post(req):
        return 'post index'

    @app.route(verb=['delete', 'remove'])
    def delete_remove(req):
        return 'delete remove'

    with Given():
        assert status == 200
        assert response == 'get index'

        when(verb='post')
        assert status == 200
        assert response == 'post index'

        when(verb='invalid')
        assert status == 405

        when('/invalid')
        assert status == 404

        when(verb='delete')
        assert status == 200
        assert response == 'delete remove'

        when(verb='remove')
        assert status == 200
        assert response == 'delete remove'
Beispiel #8
0
def test_equality():

    call = dict(
        title=\
            'Binding and registering the device after verifying the '
            'activation code',
        description=\
            'As a new visitor I have to bind my device with activation '
            'code and phone number',
        url='/apiv1/devices/name: SM-12345678',
        verb='POST',
        as_='visitor',
        query=dict(
            a=1,
            b=2
        ),
        form=dict(
            activationCode='746727',
            phone='+9897654321'
        )
    )
    with Given(wsgi_application, **call):
        assert response.status == '200 OK'
        assert response.status == 200
        assert response == '{"code": 745525}'
        assert response == {
            'code': 745525,
        }

        when('Trying invalid code', form=dict(activationCode='badCode'))
        assert response.status == 400
Beispiel #9
0
def test_redirector(redismock):
    redismock.set('foo', 'https://example.com')
    with Given(app, url='/foo'):
        assert status == 302
        assert response.headers['LOCATION'] == 'https://example.com'

        when(url='/notexists')
        assert status == 404
Beispiel #10
0
    def test_sql_errors(self):
        with self.given('Testing SQL exceptions',
                        '/',
                        'POST',
                        form=dict(title='test')):
            assert response.json['title'] == 'test'

            when('Posting gain to raise a unique_violation sql error')
            assert status == 409
Beispiel #11
0
    def test_server_timestamp_header(self):
        with self.given('Geting server\'s timestamp'):
            assert status == 200
            assert 'X-Server-Timestamp' in response.headers

            settings.merge('timestamp: false')
            when('With default configuration')
            assert status == 200
            assert 'X-Server-Timestamp' not in response.headers
 def test_commit_decorator(self):
     with self.given('Testing the operation of commit decorator',
                     verb='POST',
                     url='/',
                     form=dict(title='first')):
         when('Geting the result of appling commit decorator',
              verb='GET',
              url='/first')
         assert response.json['title'] == 'first'
         assert response.json['id'] == 1
Beispiel #13
0
def test_append_form_field():
    call = dict(title='test raw request body', verb='POST', body=b'abcd')

    with Given(wsgi_application, **call):
        assert status == 200
        assert response.text == 'abcd'

        when('Another try!', body=b'1234')
        assert status == 200
        assert response.text == '1234'
Beispiel #14
0
def test_shortener(randommock, redismock):
    with Given(app, verb='POST', json=dict(url='http://example.com')):
        assert status == 201
        assert response.text == 'f00'

        when(json=dict(url='invalidurl'))
        assert status == 400

        when(json=given - 'url')
        assert status == '400 Field missing: url'
 def test_commit_on_raise_http_success(self):
     with self.given(
             'Testing the operation of commit decorator on raise 2xx',
             verb='SUCCESS',
             url='/',
             form=dict(title='HTTPSuccess')):
         when('Geting the result of appling commit decorator',
              verb='GET',
              url='/HTTPSuccess')
         assert response.json['title'] == 'HTTPSuccess'
 def test_commit_on_raise_http_redirect(self):
     with self.given(
             'Testing the operation of commit decorator on raise 3xx',
             verb='REDIRECT',
             url='/',
             form=dict(title='HTTPRedirect')):
         when('Geting the result of appling commit decorator',
              verb='GET',
              url='/HTTPRedirect')
         assert response.json['title'] == 'HTTPRedirect'
Beispiel #17
0
def test_readonly(app, Given):
    @app.route()
    @validate(fields=dict(bar=dict(readonly=True), ))
    def post(req):
        pass

    with Given(verb='post'):
        assert status == 200

        when(form=dict(bar='bar'))
        assert status == '400 Field bar is readonly'
Beispiel #18
0
def test_nobody(app, Given):
    @app.route()
    @validate(nobody=True)
    def foo(req):
        assert req.form == {}

    with Given(verb='foo'):
        assert status == 200

        when(form=dict(bar='baz'))
        assert status == '400 Body Not Allowed'
Beispiel #19
0
def test_type(app, Given):
    @app.route()
    @validate(fields=dict(bar=dict(type_=int), ))
    def post(req):
        pass

    with Given(verb='post'):
        assert status == 200

        when(json=dict(bar='bar'))
        assert status == '400 Invalid type: bar'
Beispiel #20
0
def test_markdownserver(app):
    with Given(app):
        assert status == 200
        assertbody(EXPECTED_TOC)

        when('/foo')
        assert status == 200
        assertbody('<h2 id="foo-bar-baz">Foo Bar Baz</h2>\n')

        when('/notexists')
        assert status == 404
Beispiel #21
0
def test_nobody_get(app, Given):

    @app.route()
    @validate(nobody=True)
    def get(req, *, bar=None):
        assert req.form.get('bar') == bar

    with Given():
        assert status == 200

        when(query=dict(bar='baz'))
        assert status == 200
Beispiel #22
0
def test_querystring(app, Given):
    @app.route()
    def get(req, *, baz=None):
        return f'{req.query.get("foo")} {baz}'

    with Given('/?foo=bar&baz=qux'):
        assert status == 200
        assert response.text == 'bar qux'

        when(query=given - 'baz')
        assert status == 200
        assert response.text == 'bar None'
 def test_commit_decorator_and_json_patch(self):
     with self.given(
             'The commit decorator should not to do anything if the request\
         is a jsonpatch.',
             verb='PATCH',
             url='/',
             json=[
                 dict(op='post', path='', value=dict(title='second')),
                 dict(op='post', path='', value=dict(title='third'))
             ]):
         when('Inset form parameter to body', verb='GET', url='/third')
         assert response.json['title'] == 'third'
Beispiel #24
0
    def test_logout(self):
        with self.given('Log in to get a token and refresh token cookie',
                        '/login',
                        'POST',
                        form=dict(email='*****@*****.**', password='******')):
            assert status == 200
            assert 'token' in response.json
            assert response.headers['X-Identity'] == '1'
            self._authentication_token = response.json['token']

            when('Logging out', '/logout', 'DELETE')
            assert 'X-Identity' not in response.headers
Beispiel #25
0
def test_routing_encodedurl_route(app, Given):

    @app.route(r'/([ a-z]+)', re.I)
    def get(req, id_):
        return id_

    with Given('/id: foo%20bar'):
        assert status == 200
        assert response == 'foo bar'

        when(url_parameters=given | dict(id='foo Bar'))
        assert status == 200
        assert response == 'foo Bar'
    def test_create(self):
        email = '*****@*****.**'
        password = '******'

        with self.given(
                'get token',
                '/apiv1/tokens',
                'CREATE',
                json=dict(
                    email=email,
                    password=password,
                ),
        ):
            assert status == 200
            assert 'token' in response.json

            when('Invalid password', json=given | dict(password='******'))
            assert status == '400 Incorrect Email Or Password'

            when('Not exist email',
                 json=given | dict(email='*****@*****.**'))
            assert status == '400 Incorrect Email Or Password'

            when('Invalid email format', json=given | dict(email='member.com'))
            assert status == '400 Invalid Email Format'

            when('Trying to pass with empty form', json={})
            assert status == '400 Empty Form'
Beispiel #27
0
def test_multipartform(app, Given):
    app.settings.debug = False

    @app.route()
    def post(req):
        assert req.contenttype.startswith('multipart/form')
        assert req.form['foo'] == 'bar'

    with Given(verb='post', multipart=dict(foo='bar')):
        assert status == 200

        when(body='', content_type='multipart/form-data; boundary=')
        assert status == 400
        assert response == '400 Cannot parse the request'
Beispiel #28
0
def test_querystringform(app, Given):
    @app.route('/empty')
    def get(req):
        assert req.form == {}

    @app.route()
    def get(req):
        assert req.form['foo'] == 'bar'

    with Given(query=dict(foo='bar')):
        assert status == 200

        when('/empty', query={})
        assert status == 200
Beispiel #29
0
    def test_pagination(self):
        with self.given('Getting a single object using pagination',
                        query=dict(take=1)):

            assert len(response.json) == 1
            assert response.json[0]['title'] == 'test'
            assert response.json[0]['visible'] == False

            when('Trying to get an non-existence db object',
                 '/non-existence-user')
            assert status == 404

            when('Getting a plain dictionary', '/me')
            assert response.json == {'title': 'me'}
Beispiel #30
0
    def test_login(self):
        with self.given('Logging-in',
                        verb='LOGIN',
                        form=dict(email='*****@*****.**',
                                  password='******')):

            assert status == '200 OK'
            assert len(response.text.split('.')) == 3

            when('Invalid user', form=given | dict(email='not-exists'))
            assert status == 400

            when('No user', form=given - 'email')
            assert status == 400