Exemple #1
0
def test_url_parameters():
    call = dict(
        title='Multiple url parameters',
        url='/apiv1/devices/name: SM-12345678/id: 1',
        verb='POST',
        form=dict(activationCode='746727', phone='+9897654321'),
    )

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

        with pytest.raises(InvalidUrlParametersError):
            when(title='Incomplete url parameters', url_parameters=dict(id=2))

        with pytest.raises(InvalidUrlParametersError):
            when(title='Extra url parameters',
                 url_parameters=dict(name='any', id=3, garbage='yes'))

        with pytest.raises(InvalidUrlParametersError):
            when(title='Without url parameters', url_parameters=None)

    call = dict(
        title='No url parameters',
        url='/apiv1/devices',
        verb='POST',
        form=dict(activationCode='746727', phone='+9897654321'),
    )

    with Given(wsgi_application, **call):
        assert response.status == '200 OK'
Exemple #2
0
def test_update_json_fields():
    call = dict(
        title='test remove form fields',
        url='/apiv1/devices/name: SM-12345678/id: 1',
        verb='POST',
        json=dict(
            a='1',
            b=2
        )
    )

    with Given(wsgi_application, **call):
        assert response.status =='200 OK'
        assert response.json == dict(a='1', b=2)

        when(
            'Adding new field',
            json=given + dict(c=3)
        )
        assert response.json == dict(a='1', b=2, c=3)

        when(
            'Updating a field with None',
            json=given | dict(b=None)
        )
        assert response.json == dict(a='1', b=None)

        when(
            'Removing a field',
            json=given - 'a'
        )
        assert response.json == dict(b=2)
def test_update_from_fields():
    call = dict(title='test remove form fields',
                url='/apiv1/devices/name: SM-12345678/id: 1',
                verb='POST',
                form=dict(activationCode='746727', email='*****@*****.**'))

    with Given(wsgi_application, **call):
        assert response.status == '200 OK'
        assert response.json == dict(activationCode='746727',
                                     email='*****@*****.**')

        when('Updating email and phone fields',
             form=Update(email='*****@*****.**', phone='+98123456789'))
        assert response.json == dict(activationCode='746727',
                                     phone='+98123456789',
                                     email='*****@*****.**')

        when('Updating only acitvation code',
             form=Update(activationCode='666'))
        assert response.json == dict(activationCode='666',
                                     email='*****@*****.**')

        when('Not updating at all')
        assert response.json == dict(activationCode='746727',
                                     email='*****@*****.**')
Exemple #4
0
def test_append_headers_field():
    with Given(
        wsgi_application,
        'test add header field',
        headers={'header1': '1'}
    ):
        assert status == '200 OK'
        assert response.json['header1'] == '1'

        # Using dictionary to manipulate lists, expecting error.
        with pytest.raises(ValueError):
            when('Abusing', headers=Append(header2='2'))

        when(
            'Adding new header: 2-tuple',
            headers=Append(('header2', '2'))
        )
        assert response.json['header1'] == '1'
        assert response.json['header2'] == '2'

        when(
            'Adding new header: single string',
            headers=Append('header3: 3')
        )
        assert response.json['header1'] == '1'
        assert response.json['header3'] == '3'
        assert 'header2' not in response.json
Exemple #5
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
Exemple #6
0
def test_rewrite_encodedurl():
    root = yhttp.Application()
    foo = yhttp.Application()
    app = yhttp.Rewrite(default=root)
    app.route(r'/foo/?(.*)', r'/\1', foo)

    @root.route()
    def get(req):
        return 'root'

    @foo.route(r'/(.+)')
    @yhttp.statuscode('201 Created')
    def get(req, arg):
        resp = f'foo: {arg}'
        if req.query:
            qs = ', '.join(f'{k}={v}' for k, v in req.query.items())
            resp += f' qs: {qs}'

        return resp

    with Given(app):
        assert status == 200
        assert response.text == 'root'

        when('/foo/bar')
        assert status == 201
        assert response.text == 'foo: bar'

        when(quote('/foo/الف'))
        assert status == 201
        assert response.text == 'foo: الف'

        when(quote('/foo/الف?a=ابجد'))
        assert status == 201
        assert response.text == 'foo: الف?a=ابجد'
Exemple #7
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
def test_form_operators():
    call = dict(
        title='test form fields operators: + and -',
        verb='POST',
        form=dict(
            a='1',
            b='2'
        )
    )

    with Given(wsgi_application, **call):
        assert response.status =='200 OK'
        assert response.json == dict(
            a='1',
            b='2'
        )

        when('Removing an item', form=given - 'a')
        assert response.json == dict(
            b='2'
        )

        when('Removing multiple items', form=given - ['a', 'b'])
        assert response.json == dict()

        when('Appending an item', form=given + dict(c=3))
        assert response.json == dict(
            a='1',
            b='2',
            c='3'
        )

        when('Updating some items', form=given | dict(c=3, b=4))
        assert response.json == dict(
            a='1',
            b='4',
            c='3',
        )

        when(
            'Combining with the other manipulation types',
            form=Append(d=4) - 'b' + dict(c=3) | dict(z=1, a=2)
        )
        assert response.json == dict(
            a='2',
            c='3',
            d='4',
            z='1',
        )

        when(
            'Remove an item with more than one character',
            form=given + dict(word='alphabet') - 'word'
        )
        assert response.json == dict(
            a='1',
            b='2',
        )
def test_upload_binary_file_fileio():

    call = dict(title='Uploading an image using fileio',
                verb='POST',
                multipart=dict(a=io.FileIO(SAMPLEFILE)))

    with Given(wsgi_application, **call):
        assert status == '200 OK'
        assert base64.decodebytes(response.body) == SAMPLEFILE_CONTENT_HASH
def test_upload_binary_file():

    call = dict(title='Uploading an image',
                verb='POST',
                multipart=dict(a=io.BytesIO(BINARY_CONTENT)))

    with Given(wsgi_application, **call):
        assert status == '200 OK'
        assert base64.decodebytes(response.body) == BINARY_CONTENT_HASH
Exemple #11
0
def test_urlpost(app, redis, urandommock):
    app.ready()

    with Given(title='Creating a new url',
               application=app,
               url='/apiv1/urls',
               verb='POST',
               json=dict(url='http://example.com')):
        assert status == 201
        assert response.json['id'] == 'LJO1vnZOE4'
Exemple #12
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'
Exemple #13
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'
Exemple #14
0
def test_autodump_file_object():
    file = io.StringIO()
    with Given(
            wsgi_application,
            title='Testing auto dump',
            url='/apiv1/devices/name: SM-12345678',
            autodump=file,
    ):
        assert response.status == 200

    assert len(file.getvalue()) > 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
Exemple #16
0
def test_autodump_filename():
    filename = tempfile.mktemp()
    with Given(
            wsgi_application,
            title='Testing auto dump',
            url='/apiv1/devices/name: SM-12345678',
            autodump=filename,
    ):
        assert response.status == 200

    assert path.exists(filename)
def test_none_parameters_within_form():
    form = dict(a=None)

    with Given(wsgi_application,
               title='test none parameters in a url-encoded form',
               verb='POST',
               form=form):
        assert status == 200
        assert response.json['a'] == 'None'

    with Given(wsgi_application,
               title='test none parameters in a json form',
               verb='POST',
               json=form):
        assert status == 200
        assert response.json['a'] is None

    with Given(wsgi_application,
               title='test none parameters in a multipart form',
               verb='POST',
               multipart=form):
        assert status == 200
        assert response.json['a'] == 'None'
    def given(self, *a, autodoc=True, **kw):
        if self._authentication_token is not None:
            kw.setdefault('authorization', self._authentication_token)

        if self.__story_directory__:
            kw['autodump'] = self._get_story_filename

        if autodoc and self.__api_documentation_directory__:
            kw['autodoc'] = self._get_markdown_filename

        if self.__metadata__:
            kw['fieldinfo'] = self._get_field_info

        return Given(self.__application__, *a, **kw)
Exemple #19
0
def test_upload_list_of_file():
    call = dict(title='Uploading two files',
                verb='POST',
                multipart=dict(a=[
                    io.BytesIO(BINARY_CONTENT1),
                    io.BytesIO(BINARY_CONTENT2),
                ]))

    with Given(wsgi_application, **call):
        assert status == '200 OK'
        assert base64.decodebytes(response.json['file1'].encode()) \
            == BINARY_CONTENT_HASH1

        assert base64.decodebytes(response.json['file2'].encode()) \
            == BINARY_CONTENT_HASH2
Exemple #20
0
def test_url_overriding():
    call = dict(
        title='Multiple url parameters',
        url='/apiv1/devices/name: SM-12345678/id: 1',
        verb='POST',
        form=dict(activationCode='746727', phone='+9897654321'),
    )

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

        modified_call = when(url='/apiv1/devices?a=b&c=d')
        assert modified_call.url_parameters is None
        assert response.status == 200
        assert response.json['query'] == 'a=b&c=d'
Exemple #21
0
def test_remove_headers_field():
    with Given(wsgi_application,
               'test remove  header field',
               headers={'header1': '1'}):
        assert status == '200 OK'
        assert response.json['header1'] == '1'

        when('Removing an existing header: 2-tuple',
             headers=Remove(('header1', '1')))
        assert 'header1' not in response.json

        when('Remove header by key', headers=Remove('header1'))

        # Remove an invalid header(Not exists)
        with pytest.raises(ValueError):
            when('Invalid  key', headers=Remove('invalid header'))
Exemple #22
0
def test_dump_load():
    call = dict(title='Binding',
                url='/apiv1/devices/name: SM-12345678',
                verb='POST',
                as_='visitor',
                form=dict(activationCode='746727', phone='+9897654321'),
                headers=[('X-H1', 'Header Value')])
    with Given(wsgi_application, **call):
        assert response.status == '200 OK'
        when('Trying invalid code', form=dict(activationCode='badCode'))
        assert response.status == 400

        dumped_story = story.dumps()
        loaded_story = Story.loads(dumped_story)
        assert story.to_dict() == loaded_story.to_dict()
        loaded_story.validate()
def test_append_form_field():
    call = dict(
        title='test add form field',
        url='/apiv1/devices/name: SM-12345678/id: 1',
        verb='POST',
        form=dict(activationCode='746727', phone='+9897654321'),
    )

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

        modified_call = when('Adding another field',
                             form=Append(email='*****@*****.**'))
        assert response.json == dict(activationCode='746727',
                                     phone='+9897654321',
                                     email='*****@*****.**')
Exemple #24
0
def test_dump_load_file():
    with tempfile.TemporaryFile(mode='w+', encoding='utf-8') as temp_file:
        call = dict(title='Binding',
                    url='/apiv1/devices/name: SM-12345678',
                    verb='POST',
                    as_='visitor',
                    form=dict(activationCode='746727', phone='+9897654321'),
                    headers=[('X-H1', 'Header Value')])
        with Given(wsgi_application, **call):
            assert response.status == '200 OK'
            when('Trying invalid code', form=dict(activationCode='badCode'))
            story.dump(temp_file)

        temp_file.seek(0)
        loaded_story = Story.load(temp_file)
        assert loaded_story.verify(wsgi_application) is None
Exemple #25
0
def test_shortener(app, urandommock, redis):
    app.settings.merge(r'''
    blacklist:
      - ^https?://(www\.)?vurl\.ir.*
    ''')
    app.ready()

    with Given(
        app,
        verb='POST',
        json=dict(url='http://example.com/')
    ):
        assert status == 201
        assert response.text == 'LJO1vnZOE4'

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

        when(json=given - 'url')
        assert status == '400 Field missing: url'

        # Blacklist
        when(json=dict(url='http://vurl.ir'))
        assert status == 409

        when(json=dict(url='https://vurl.ir'))
        assert status == 409

        when(json=dict(url='http://www.vurl.ir'))
        assert status == 409

        when(json=dict(url='https://www.vurl.ir'))
        assert status == 409

        when(json=dict(url='https://vurl.ir/foo'))
        assert status == 409

        # Encoding
        redis.flushdb()
        when(json=dict(url='https://example.com/#/baz'))
        assert status == 201
        assert redis.get(response.text) == b'https://example.com/#/baz'

        redis.flushdb()
        when(json=dict(url='https://example.com/\u265F/baz'))
        assert status == 201
        assert redis.get(response.text) == b'https://example.com/%E2%99%9F/baz'
Exemple #26
0
def test_to_dict():
    call = dict(title='Binding',
                description='Awesome given description',
                url='/apiv1/devices/name: SM-12345678',
                verb='POST',
                as_='visitor',
                form=dict(activationCode='746727', phone='+9897654321'),
                headers=[('X-H1', 'Header Value')])
    with Given(wsgi_application, **call):
        assert response.status == '200 OK'
        when(title='Trying invalid code',
             description='Awesome invalid code description',
             form=dict(activationCode='badCode'))
        assert response.status == 400

        story_dict = story.to_dict()
        assert story_dict['base_call'] == dict(
            title='Binding',
            description='Awesome given description',
            url='/apiv1/devices/:name',
            verb='POST',
            as_='visitor',
            url_parameters=dict(name='SM-12345678'),
            form=dict(activationCode='746727', phone='+9897654321'),
            headers=[
                'X-H1: Header Value',
            ],
            response=dict(status='200 OK',
                          headers=[
                              'Content-Type: application/json;charset=utf-8',
                              'X-Pagination-Count: 10'
                          ],
                          json={
                              'secret': 'ABCDEF',
                              'code': 745525,
                              'query': None,
                              'url': '/apiv1/devices/SM-12345678'
                          }))
        assert story_dict['calls'][0] == dict(
            title='Trying invalid code',
            description='Awesome invalid code description',
            form=dict(activationCode='badCode'),
            response=dict(
                headers=['Content-Type: text/plain;utf-8'],
                status='400 Bad Request',
            ))
Exemple #27
0
def test_authorization():
    def wsgi_application(environ, start_response):
        result = {}
        identity = environ.get('HTTP_AUTHORIZATION')
        if identity:
            result['identity'] = identity
        start_response('200 OK', [
            ('Content-Type', 'application/json;charset=utf-8'),
        ])

        yield json.dumps(result).encode()

    with Given(wsgi_application,
               title='Testing authorization header',
               url='/',
               authorization='testuser'):
        assert response.json['identity'] == 'testuser'
    def test_append_change_attribute(self):
        self.log = None
        self.verb = 'POST'

        def callback(audit_logs):
            self.log = audit_logs

        middleware = MiddleWareFactory(callback)
        app = middleware(wsgi_application)

        call = dict(
            title='Testing the append change attribute method',
            url='/apiv1',
            verb=self.verb,
        )
        with Given(app, **call):
            assert status == 200
            assert len(self.log) == 2
Exemple #29
0
def test_verify():
    call = dict(title='Binding',
                url='/apiv1/devices/name: SM-12345678',
                verb='POST',
                as_='visitor',
                form=dict(activationCode='746727', phone='+9897654321'),
                headers=[('X-H1', 'Header Value')])
    with Given(wsgi_application, **call):
        assert response.status == '200 OK'
        when('Trying invalid code', form=dict(activationCode='badCode'))
        dumped_story = story.dumps()

    loaded_story = Story.loads(dumped_story)
    loaded_story.verify(wsgi_application)

    loaded_story.base_call.response.body = '{"a": 1}'

    with pytest.raises(CallVerifyError):
        loaded_story.verify(wsgi_application)
def test_remove_from_fields():
    call = dict(title='test remove form fields',
                url='/apiv1/devices/name: SM-12345678/id: 1',
                verb='POST',
                form=dict(activationCode='746727',
                          phone='+9897654321',
                          email='*****@*****.**'))

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

        when('Removing fields', form=Remove('email', 'phone'))
        assert response.json == dict(activationCode='746727')

        with pytest.raises(ValueError):
            Remove('a').apply(['b', 'c'])

        with pytest.raises(ValueError):
            Remove('a').apply({'b': 'c'})