Пример #1
0
    def test_simple(self):
        doc = '{"messages": {"ttl": 600}}'

        # Create
        env = testing.create_environ('/v1/480924/queues/gumshoe',
                                     method="PUT", body=doc)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_201)

        location = ('Location', '/v1/480924/queues/gumshoe')
        self.assertIn(location, self.srmock.headers)

        env = testing.create_environ('/v1/480924/queues/gumshoe')
        result = self.app(env, self.srmock)
        result_doc = json.loads(result[0])
        self.assertEquals(self.srmock.status, falcon.HTTP_200)
        self.assertEquals(result_doc, json.loads(doc))

        # Delete
        env = testing.create_environ('/v1/480924/queues/gumshoe',
                                     method="DELETE")

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_204)

        # Get non-existing
        env = testing.create_environ('/v1/480924/queues/gumshoe')

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_404)
Пример #2
0
    def test_list(self):
        # List empty
        env = testing.create_environ('/v1/480924/queues')

        result = self.app(env, self.srmock)
        result_doc = json.loads(result[0])
        self.assertEquals(result_doc['queues'], [])

        # Create some
        env = testing.create_environ('/v1/480924/queues/q1',
                                     method="PUT",
                                     body='{ "_ttl": 30 }')
        self.app(env, self.srmock)

        env = testing.create_environ('/v1/480924/queues/q2',
                                     method="PUT",
                                     body='{}')
        self.app(env, self.srmock)

        # List
        env = testing.create_environ('/v1/480924/queues')

        result = self.app(env, self.srmock)
        result_doc = json.loads(result[0])

        self.assertEquals(self.srmock.status, falcon.HTTP_200)
        self.assertEquals(self.srmock.headers_dict['Content-Location'],
                          env['PATH_INFO'])

        for queue in result_doc['queues']:
            env = testing.create_environ(queue['href'])
            result = self.app(env, self.srmock)
            result_doc = json.loads(result[0])
            self.assertEquals(result_doc, queue['metadata'])
Пример #3
0
    def test_simple(self):
        doc = '{"messages": {"ttl": 600}}'
        env = testing.create_environ('/v1/480924/queues/gumshoe',
                                     method="PUT", body=doc)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_503)

        location = ('Location', '/v1/480924/queues/gumshoe')
        self.assertNotIn(location, self.srmock.headers)

        env = testing.create_environ('/v1/480924/queues/gumshoe')
        result = self.app(env, self.srmock)
        result_doc = json.loads(result[0])
        self.assertEquals(self.srmock.status, falcon.HTTP_503)
        self.assertNotEquals(result_doc, json.loads(doc))

        env = testing.create_environ('/v1/480924/queues')
        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_503)

        env = testing.create_environ('/v1/480924/queues/gumshoe',
                                     method='DELETE')
        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_503)
Пример #4
0
    def test_uri_https(self):
        # =======================================================
        # Default port, implicit
        # =======================================================
        req = Request(testing.create_environ(
            path='/hello', scheme='https'))
        uri = ('https://' + testing.DEFAULT_HOST + '/hello')

        self.assertEqual(req.uri, uri)

        # =======================================================
        # Default port, explicit
        # =======================================================
        req = Request(testing.create_environ(
            path='/hello', scheme='https', port=443))
        uri = ('https://' + testing.DEFAULT_HOST + '/hello')

        self.assertEqual(req.uri, uri)

        # =======================================================
        # Non-default port
        # =======================================================
        req = Request(testing.create_environ(
            path='/hello', scheme='https', port=22))
        uri = ('https://' + testing.DEFAULT_HOST + ':22/hello')

        self.assertEqual(req.uri, uri)
Пример #5
0
    def _test_attribute_header(self, name, value, attr, default=None):
        headers = {name: value}
        req = Request(testing.create_environ(headers=headers))
        self.assertEqual(getattr(req, attr), value)

        req = Request(testing.create_environ())
        self.assertEqual(getattr(req, attr), default)
Пример #6
0
    def test_client_accepts_props(self):
        headers = {'Accept': 'application/xml'}
        req = Request(testing.create_environ(headers=headers))
        self.assertTrue(req.client_accepts_xml)
        self.assertFalse(req.client_accepts_json)
        self.assertFalse(req.client_accepts_msgpack)

        headers = {'Accept': 'application/*'}
        req = Request(testing.create_environ(headers=headers))
        self.assertTrue(req.client_accepts_xml)
        self.assertTrue(req.client_accepts_json)
        self.assertTrue(req.client_accepts_msgpack)

        headers = {'Accept': 'application/json'}
        req = Request(testing.create_environ(headers=headers))
        self.assertFalse(req.client_accepts_xml)
        self.assertTrue(req.client_accepts_json)
        self.assertFalse(req.client_accepts_msgpack)

        headers = {'Accept': 'application/x-msgpack'}
        req = Request(testing.create_environ(headers=headers))
        self.assertFalse(req.client_accepts_xml)
        self.assertFalse(req.client_accepts_json)
        self.assertTrue(req.client_accepts_msgpack)

        headers = {
            'Accept': 'application/json,application/xml,application/x-msgpack'
        }
        req = Request(testing.create_environ(headers=headers))
        self.assertTrue(req.client_accepts_xml)
        self.assertTrue(req.client_accepts_json)
        self.assertTrue(req.client_accepts_msgpack)
Пример #7
0
    def test_relative_uri(self):
        assert self.req.relative_uri == self.app + self.relative_uri
        assert self.req_noqs.relative_uri == self.app + self.path

        req_noapp = Request(testing.create_environ(
            path='/hello',
            query_string=self.qs,
            headers=self.headers))

        assert req_noapp.relative_uri == self.relative_uri

        req_noapp = Request(testing.create_environ(
            path='/hello/',
            query_string=self.qs,
            headers=self.headers))

        relative_trailing_uri = self.path + '/?' + self.qs
        # NOTE(kgriffs): Call twice to check caching works
        assert req_noapp.relative_uri == relative_trailing_uri
        assert req_noapp.relative_uri == relative_trailing_uri

        options = RequestOptions()
        options.strip_url_path_trailing_slash = False
        req_noapp = Request(testing.create_environ(
            path='/hello/',
            query_string=self.qs,
            headers=self.headers),
            options=options)

        assert req_noapp.relative_uri == '/hello/' + '?' + self.qs
Пример #8
0
    def before(self):
        self.qs = 'marker=deadbeef&limit=10'

        self.headers = {
            'Host': 'falcon.example.com',
            'Content-Type': 'text/plain',
            'Content-Length': '4829',
            'Authorization': ''
        }

        self.app = '/test'
        self.path = '/hello'
        self.relative_uri = self.path + '?' + self.qs
        self.uri = 'http://falcon.example.com' + self.app + self.relative_uri
        self.uri_noqs = 'http://falcon.example.com' + self.app + self.path

        self.req = Request(testing.create_environ(
            app=self.app,
            path='/hello',
            query_string=self.qs,
            headers=self.headers))

        self.req_noqs = Request(testing.create_environ(
            app=self.app,
            path='/hello',
            headers=self.headers))
Пример #9
0
    def test_update_metadata(self):
        # Create
        doc1 = '{"messages": {"ttl": 600}}'
        env = testing.create_environ('/v1/480924/queues/xyz',
                                     method="PUT", body=doc1)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_201)

        # Update
        doc2 = '{"messages": {"ttl": 100}}'
        env = testing.create_environ('/v1/480924/queues/xyz',
                                     method="PUT", body=doc2)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_204)

        # Get
        env = testing.create_environ('/v1/480924/queues/xyz')
        result = self.app(env, self.srmock)
        result_doc = json.loads(result[0])

        self.assertEquals(result_doc, json.loads(doc2))
        self.assertEquals(self.srmock.headers_dict['Content-Location'],
                          env['PATH_INFO'])
Пример #10
0
    def _test_attribute_header(self, name, value, attr, default=None):
        headers = {name: value}
        req = Request(testing.create_environ(headers=headers))
        assert getattr(req, attr) == value

        req = Request(testing.create_environ())
        assert getattr(req, attr) == default
Пример #11
0
    def test_content_length(self):
        headers = {'content-length': '5656'}
        req = Request(testing.create_environ(headers=headers))
        self.assertEqual(req.content_length, 5656)

        headers = {'content-length': ''}
        req = Request(testing.create_environ(headers=headers))
        self.assertEqual(req.content_length, None)
Пример #12
0
    def _test_attribute_header(self, name, value, attr):
        headers = {name: value}
        req = Request(testing.create_environ(headers=headers))
        self.assertEquals(value, getattr(req, attr))

        headers = {name: None}
        req = Request(testing.create_environ(headers=headers))
        self.assertEqual(None, getattr(req, attr))
Пример #13
0
    def test_content_length(self):
        headers = {'content-length': '5656'}
        req = Request(testing.create_environ(headers=headers))
        assert req.content_length == 5656

        headers = {'content-length': ''}
        req = Request(testing.create_environ(headers=headers))
        assert req.content_length is None
Пример #14
0
    def test_unicode_path_in_create_environ(self):
        if six.PY3:
            self.skip('Test does not apply to Py3K')

        env = testing.create_environ(u'/fancy/unícode')
        self.assertEqual(env['PATH_INFO'], '/fancy/un\xc3\xadcode')

        env = testing.create_environ(u'/simple')
        self.assertEqual(env['PATH_INFO'], '/simple')
Пример #15
0
    def test_unicode_path_in_create_environ(self):
        if six.PY3:
            self.skip("Test does not apply to Py3K")

        env = testing.create_environ(u"/fancy/unícode")
        self.assertEqual(env["PATH_INFO"], "/fancy/un\xc3\xadcode")

        env = testing.create_environ(u"/simple")
        self.assertEqual(env["PATH_INFO"], "/simple")
Пример #16
0
    def test_no_uuid(self):
        env = testing.create_environ('/v1/480924/queues/fizbit/messages',
                                     method="POST",
                                     body='[{"body": 0, "ttl": 0}]')

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_400)

        env = testing.create_environ('/v1/480924/queues/fizbit/messages',
                                     method="GET")

        body = self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_400)
Пример #17
0
    def test_bad_metadata(self):
        env = testing.create_environ('/v1/480924/queues/fizbat',
                                     body="{",
                                     method="PUT")

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_400)

        env = testing.create_environ('/v1/480924/queues/fizbat',
                                     body="[]",
                                     method="PUT")

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_400)
Пример #18
0
    def test_simple(self):
        doc = '{"messages": {"ttl": 600}}'
        env = testing.create_environ('/v1/480924/queues/gumshoe',
                                     method="PUT", body=doc)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_201)

        location = ('Location', '/v1/480924/queues/gumshoe')
        self.assertThat(self.srmock.headers, matchers.Contains(location))

        env = testing.create_environ('/v1/480924/queues/gumshoe')
        result = self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_200)
        self.assertEquals(result, [doc])
Пример #19
0
def test_fallback_filename(uri, default, expected, content_type, downloadable,
                           monkeypatch):

    def mockOpen(path, mode):
        if default in path:
            return path
        raise IOError()

    monkeypatch.setattr(io, 'open', mockOpen)
    monkeypatch.setattr('os.path.isfile', lambda file: default in file)

    sr = StaticRoute('/static', '/var/www/statics', downloadable=downloadable,
                     fallback_filename=default)

    req_path = '/static/' + uri

    req = Request(testing.create_environ(
        host='test.com',
        path=req_path,
        app='statics'
    ))
    resp = Response()
    sr(req, resp)

    assert sr.match(req.path)
    assert resp.stream == os.path.join('/var/www/statics', expected)
    assert resp.content_type == content_type

    if downloadable:
        assert os.path.basename(expected) in resp.downloadable_as
    else:
        assert resp.downloadable_as is None
Пример #20
0
def call(method, api_or_module, url, body='', headers=None, params=None, query_string='', scheme='http', **kwargs):
    """Simulates a round-trip call against the given API / URL"""
    api = API(api_or_module).http.server()
    response = StartResponseMock()
    headers = {} if headers is None else headers
    if not isinstance(body, str) and 'json' in headers.get('content-type', 'application/json'):
        body = output_format.json(body)
        headers.setdefault('content-type', 'application/json')

    params = params if params else {}
    params.update(kwargs)
    if params:
        query_string = '{}{}{}'.format(query_string, '&' if query_string else '', urlencode(params, True))
    result = api(create_environ(path=url, method=method, headers=headers, query_string=query_string,
                                body=body, scheme=scheme), response)
    if result:
        try:
            response.data = result[0].decode('utf8')
        except TypeError:
            data = BytesIO()
            for chunk in result:
                data.write(chunk)
            data = data.getvalue()
            try:
                response.data = data.decode('utf8')
            except UnicodeDecodeError:   # pragma: no cover
                response.data = data
        except (UnicodeDecodeError, AttributeError):
            response.data = result[0]
        response.content_type = response.headers_dict['content-type']
        if 'application/json' in response.content_type:
            response.data = json.loads(response.data)

    return response
Пример #21
0
    def test_request_cookie_parsing(self):
        # testing with a github-ish set of cookies
        headers = [
            (
                "Cookie",
                """
                logged_in=no;_gh_sess=eyJzZXXzaW9uX2lkIjoiN2;
                tz=Europe/Berlin; _ga=GA1.2.332347814.1422308165;
                _gat=1;
                _octo=GH1.1.201722077.1422308165""",
            )
        ]

        environ = testing.create_environ(headers=headers)
        req = falcon.Request(environ)

        self.assertEqual("no", req.cookies["logged_in"])
        self.assertEqual("Europe/Berlin", req.cookies["tz"])
        self.assertEqual("GH1.1.201722077.1422308165", req.cookies["_octo"])

        self.assertIn("logged_in", req.cookies)
        self.assertIn("_gh_sess", req.cookies)
        self.assertIn("tz", req.cookies)
        self.assertIn("_ga", req.cookies)
        self.assertIn("_gat", req.cookies)
        self.assertIn("_octo", req.cookies)
Пример #22
0
    def test_non_authenticated(self):
        env = testing.create_environ(self.url_prefix + '/480924/queues/',
                                     method='GET',
                                     headers=self.headers)

        self.app(env, self.srmock)
        self.assertEqual(self.srmock.status, falcon.HTTP_401)
Пример #23
0
    def test_missing_qs(self):
        env = testing.create_environ()
        if 'QUERY_STRING' in env:
            del env['QUERY_STRING']

        # Should not cause an exception when Request is instantiated
        Request(env)
Пример #24
0
def queues_env():
    request_headers = {'Content-Type': 'application/json'}
    path = ('/v1/852809/queues/0fd4c8c6-bd72-11e2-8e47-db5ebd4c8125'
            '/claims/db5ebd4c8125')

    return helpers.create_environ(path, query_string='limit=10&thing=a%20b',
                                  headers=request_headers)
Пример #25
0
    def simulate_request(self, path, project_id=None, **kwargs):
        """Simulate a request.

        Simulates a WSGI request to the API for testing.

        :param path: Request path for the desired resource
        :param project_id: Project ID to use for the X-Project-ID header,
            or None to not set the header
        :param kwargs: Same as falcon.testing.create_environ()

        :returns: standard WSGI iterable response
        """

        # NOTE(flaper87): We create a copy regardless the headers
        # were passed or not. This will prevent modifying `self.headers`
        # in cases where simulate methods are called like:
        # self.simulate_put(path, headers=self.headers)
        headers = kwargs.get('headers', self.headers).copy()
        project_id = ('518b51ea133c4facadae42c328d6b77b' if project_id
                      is None else project_id)
        headers['X-Project-ID'] = headers.get('X-Project-ID', project_id)
        kwargs['headers'] = headers
        try:
            if six.PY3:
                path.encode('latin1').decode('utf-8', 'replace')
        except UnicodeEncodeError:
            self.srmock.status = falcon.HTTP_400
            return

        return self.app(ftest.create_environ(path=path, **kwargs),
                        self.srmock)
Пример #26
0
    def test_custom_metadata(self):
        # Set
        doc = '{"messages": {"ttl": 600}, "padding": "%s"}'
        padding_len = transport.MAX_QUEUE_METADATA_SIZE - (len(doc) - 2)
        doc = doc % ('x' * padding_len)
        env = testing.create_environ('/v1/480924/queues/gumshoe',
                                     method="PUT", body=doc)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_201)

        # Get
        env = testing.create_environ('/v1/480924/queues/gumshoe')
        result = self.app(env, self.srmock)
        result_doc = json.loads(result[0])
        self.assertEquals(result_doc, json.loads(doc))
Пример #27
0
def test_request_cookie_parsing():
    # testing with a github-ish set of cookies
    headers = [
        (
            'Cookie',
            """
            logged_in=no;_gh_sess=eyJzZXXzaW9uX2lkIjoiN2;
            tz=Europe/Berlin; _ga=GA1.2.332347814.1422308165;
            _gat=1;
            _octo=GH1.1.201722077.1422308165
            """
        ),
    ]

    environ = testing.create_environ(headers=headers)
    req = falcon.Request(environ)

    assert req.cookies['logged_in'] == 'no'
    assert req.cookies['tz'] == 'Europe/Berlin'
    assert req.cookies['_octo'] == 'GH1.1.201722077.1422308165'

    assert 'logged_in' in req.cookies
    assert '_gh_sess' in req.cookies
    assert 'tz' in req.cookies
    assert '_ga' in req.cookies
    assert '_gat' in req.cookies
    assert '_octo' in req.cookies
Пример #28
0
    def test_accept_xml(self):
        headers = {'Accept': 'application/xml'}
        req = Request(testing.create_environ(headers=headers))
        self.assertTrue(req.client_accepts_xml)

        headers = {'Accept': '*/*'}
        req = Request(testing.create_environ(headers=headers))
        self.assertTrue(req.client_accepts_xml)

        headers = {'Accept': 'application/json'}
        req = Request(testing.create_environ(headers=headers))
        self.assertFalse(req.client_accepts_xml)

        headers = {'Accept': 'application/xm'}
        req = Request(testing.create_environ(headers=headers))
        self.assertFalse(req.client_accepts_xml)
Пример #29
0
def test_forwarded_multiple_params():
    req = Request(testing.create_environ(
        host='suchproxy02.suchtesting.com',
        path='/languages',
        headers={
            'Forwarded': (
                'host=something.org;proto=hTTps;ignore=me;for=108.166.30.185, '
                'by=203.0.113.43;host=suchproxy01.suchtesting.com;proto=httP'
            )
        }
    ))

    assert req.forwarded is not None

    assert req.forwarded[0].host == 'something.org'
    assert req.forwarded[0].scheme == 'https'
    assert req.forwarded[0].src == '108.166.30.185'
    assert req.forwarded[0].dest is None

    assert req.forwarded[1].host == 'suchproxy01.suchtesting.com'
    assert req.forwarded[1].scheme == 'http'
    assert req.forwarded[1].src is None
    assert req.forwarded[1].dest == '203.0.113.43'

    assert req.forwarded_scheme == 'https'
    assert req.forwarded_host == 'something.org'
    assert req.forwarded_uri != req.uri
    assert req.forwarded_uri == 'https://something.org/languages'
    assert req.forwarded_prefix == 'https://something.org'
Пример #30
0
def test_options(resp):
    """
    Test that options is a json serialized output of resource.describe()

    Args:
        req (falcon.Request): request instance object provided by ``req``
            pytest fixture
        resp (falcon.Response): responce instance provided by ``resp`` pytest
            fixture
    """
    # note: creating request is optional here since we bypass whole falcon
    #       routing and dispatching procedure
    env = create_environ(method="OPTIONS")
    req = Request(env)   # noqa
    resource = Resource()

    resource.on_options(req, resp)

    assert all([
        'OPTIONS' in _retrieve_header(resp, 'allow'),
        'GET' in _retrieve_header(resp, 'allow'),
    ])
    assert resp.status == falcon.HTTP_200
    assert json.loads(resp.body)
    # assert this is obviously the same
    assert resource.describe(req, resp) == json.loads(resp.body)
Пример #31
0
    def _test_header_etag(self, name, value, attr, expected_value):
        headers = {name: value}
        req = Request(testing.create_environ(headers=headers))

        # NOTE(kgriffs): Loop in order to test caching
        for __ in range(3):
            value = getattr(req, attr)

            if expected_value is None:
                assert value is None
                return

            assert value is not None

            for element, expected_element in zip(value, expected_value):
                assert element == expected_element
                if isinstance(expected_element, ETag):
                    assert element.is_weak == expected_element.is_weak
Пример #32
0
def create_req(ctx, body):
    '''creates a falcon request'''
    env = testing.create_environ(
        path='/',
        query_string='',
        protocol='HTTP/1.1',
        scheme='http',
        host='falconframework.org',
        port=None,
        headers={'Content-Type': 'application/json'},
        app='',
        body=body,
        method='POST',
        wsgierrors=None,
        file_wrapper=None)
    req = falcon.Request(env)
    req.context = ctx
    return req
Пример #33
0
    def test_invalid_limit(self):
        req = request.Request(
            testing.create_environ(path='/',
                                   query_string='limit=abc',
                                   headers={
                                       'X_AUTH_TOKEN': '111',
                                       'X_USER_ID': '222',
                                       'X_PROJECT_ID': '333',
                                       'X_ROLES': 'terminator,predator'
                                   }))

        # note(trebskit) assertRaises fails to call property
        # so we need the actual function
        def property_wrapper():
            return req.limit

        self.assertRaises(exceptions.HTTPUnprocessableEntityError,
                          property_wrapper)
Пример #34
0
    def test_validate_context_type(self):
        with mock.patch.object(validation,
                               'validate_content_type') as vc_type, \
                mock.patch.object(validation,
                                  'validate_payload_size') as vp_size, \
                mock.patch.object(validation,
                                  'validate_cross_tenant') as vc_tenant:
            req = request.Request(testing.create_environ())
            vc_type.side_effect = Exception()

            try:
                req.validate(['test'])
            except Exception as ex:
                self.assertEqual(1, vc_type.call_count)
                self.assertEqual(0, vp_size.call_count)
                self.assertEqual(0, vc_tenant.call_count)

                self.assertIsInstance(ex, Exception)
Пример #35
0
def test_invalid_cookies_are_ignored():
    vals = [chr(i) for i in range(0x1F)]
    vals += [chr(i) for i in range(0x7F, 0xFF)]
    vals += '()<>@,;:\\"/[]?={} \x09'.split()

    for c in vals:
        headers = [
            (
                'Cookie',
                'good_cookie=foo;bad' + c + 'cookie=bar'
            ),
        ]

        environ = testing.create_environ(headers=headers)
        req = falcon.Request(environ)

        assert req.cookies['good_cookie'] == 'foo'
        assert 'bad' + c + 'cookie' not in req.cookies
Пример #36
0
    def simulate_request(self, path, project_id=None, **kwargs):
        """Simulate a request.

        Simulates a WSGI request to the API for testing.

        :param path: Request path for the desired resource
        :param project_id: Project ID to use for the X-Project-ID header,
            or None to not set the header
        :param kwargs: Same as falcon.testing.create_environ()

        :returns: standard WSGI iterable response
        """

        if project_id is not None:
            headers = dict(kwargs['headers']) if 'headers' in kwargs else {}
            headers['X-Project-ID'] = project_id
            kwargs['headers'] = headers

        return self.app(ftest.create_environ(path=path, **kwargs), self.srmock)
Пример #37
0
 def test_on_options(self):
     """
     need to check if status of the response is set for 200 and
     """
     env = create_environ(path='/')
     req = Request(env)
     req.context = {'doc': {}}
     resp = Response()
     resource = mongoengine.CollectionResource(objects_class=FakeObjectList,
                                               max_limit=2)
     resource.on_options(req=req, resp=resp)
     self.assertEqual(resp.get_header('Allow'),
                      'GET, HEAD, OPTIONS, POST, PUT')
     self.assertEqual(
         resp.body, {
             'name': 'FakeObjectList',
             'description':
             'Extend list to match interface of List resource',
         })
Пример #38
0
def test_basic_documentation_output_type_accept():
    """Ensure API documentation works with selectable output types"""
    accept_output = hug.output_format.accept(
        {
            'application/json': hug.output_format.json,
            'application/pretty-json': hug.output_format.pretty_json
        },
        default=hug.output_format.json)
    with mock.patch.object(api.http,
                           '_output_format',
                           accept_output,
                           create=True):
        handler = api.http.documentation_404()
        response = StartResponseMock()

        handler(Request(create_environ(path='v1/doc')), response)

    documentation = json.loads(response.data.decode('utf8'))['documentation']
    assert 'handlers' in documentation and 'overview' in documentation
Пример #39
0
    def test_headers_as_list(self, client):
        headers = [
            ('Client-ID', '692ba466-74bb-11e3-bf3f-7567c531c7ca'),
            ('Accept', 'audio/*; q=0.2, audio/basic'),
        ]

        # Unit test
        environ = testing.create_environ(headers=headers)
        req = falcon.Request(environ)

        for name, value in headers:
            assert (name.upper(), value) in req.headers.items()

        # Functional test
        client.app.add_route('/', testing.SimpleTestResource(headers=headers))
        result = client.simulate_get()

        for name, value in headers:
            assert result.headers[name] == value
Пример #40
0
def call(method,
         api_or_module,
         url,
         body="",
         headers=None,
         params=None,
         query_string="",
         scheme="http",
         host=DEFAULT_HOST,
         **kwargs):
    """Simulates a round-trip call against the given API / URL"""
    api = API(api_or_module).http.server()
    response = StartResponseMock()
    headers = {} if headers is None else headers
    if not isinstance(body, str) and "json" in headers.get(
            "content-type", "application/json"):
        body = output_format.json(body)
        headers.setdefault("content-type", "application/json")

    params = params if params else {}
    params.update(kwargs)
    if params:
        query_string = "{}{}{}".format(query_string,
                                       "&" if query_string else "",
                                       urlencode(params, True))
    result = api(
        create_environ(
            path=url,
            method=method,
            headers=headers,
            query_string=query_string,
            body=body,
            scheme=scheme,
            host=host,
        ),
        response,
    )
    if result:
        response.data = _internal_result(result)
        response.content_type = response.headers_dict["content-type"]
        if "application/json" in response.content_type:
            response.data = json.loads(response.data)
    return response
Пример #41
0
def create_bench(name):
    srmock = helpers.StartResponseMock()

    request_headers = {'Content-Type': 'application/json'}
    # env = helpers.create_environ('/hello/584/test', query_string='limit=10',
    #                              headers=request_headers)

    env = helpers.create_environ('/hello',
                                 query_string='limit=10',
                                 headers=request_headers)

    body = helpers.rand_string(0, 10240)  # NOQA
    headers = {'X-Test': 'Funky Chicken'}  # NOQA

    app = eval('create_{0}(body, headers)'.format(name.lower()))

    def bench():
        app(env, srmock)

    return bench
Пример #42
0
    def test_clean_check_error_raising(self):
        """
        Check if clean function returns errors dict when `clean_param_name` raise `ParamException`
        """
        resource = CollectionResource(objects_class=None)
        env = create_environ(path='/')
        req = Request(env)
        req.context = {'doc': {'id': 1, 'name': 'Opentopic'}}
        Response()

        def clean_name_test(self):
            raise ParamException('Test Error Message')

        resource.clean_name = clean_name_test

        data, errors = resource.clean(req.context['doc'])
        self.assertEqual(data, {
            'id': 1,
        })
        self.assertEqual(errors, {'name': ['Test Error Message']})
Пример #43
0
def test_fallback_filename(uri, default, expected, monkeypatch):
    def mockOpen(path, mode):
        if default in path:
            return path
        raise IOError()

    monkeypatch.setattr(io, 'open', mockOpen)
    monkeypatch.setattr('os.path.isfile', lambda file: default in file)

    sr = StaticRoute('/static', '/var/www/statics', fallback_filename=default)

    req_path = '/static/' + uri

    req = Request(
        testing.create_environ(host='test.com', path=req_path, app='statics'))
    resp = Response()
    sr(req, resp)

    assert sr.match(req.path)
    assert resp.stream == os.path.join('/var/www/statics', expected)
Пример #44
0
def test_basic_documentation_output_type_accept():
    """Ensure API documentation works with selectable output types"""
    accept_output = hug.output_format.accept(
        {
            "application/json": hug.output_format.json,
            "application/pretty-json": hug.output_format.pretty_json,
        },
        default=hug.output_format.json,
    )
    with mock.patch.object(api.http,
                           "_output_format",
                           accept_output,
                           create=True):
        handler = api.http.documentation_404()
        response = StartResponseMock()

        handler(Request(create_environ(path="v1/doc")), response)

    documentation = json.loads(response.data.decode("utf8"))["documentation"]
    assert "handlers" in documentation and "overview" in documentation
Пример #45
0
 def test_rfc_forwarded(self):
     req = Request(
         testing.create_environ(
             host='example.com',
             path='/access_route',
             headers={
                 'Forwarded': ('for=192.0.2.43,for=,'
                               'for="[2001:db8:cafe::17]:555",'
                               'for="unknown", by=_hidden,for="\\"\\\\",'
                               'for="_don\\\"t_\\try_this\\\\at_home_\\42",'
                               'for="198\\.51\\.100\\.17\\:1236";'
                               'proto=https;host=example.com')
             }))
     compares = [
         '192.0.2.43', '', '2001:db8:cafe::17', 'unknown', '"\\',
         '_don"t_try_this\\at_home_42', '198.51.100.17'
     ]
     self.assertEqual(req.access_route, compares)
     # test cached
     self.assertEqual(req.access_route, compares)
def test_good_path(uri_prefix, uri_path, expected_path, mtype, monkeypatch):
    monkeypatch.setattr(io, 'open', lambda path, mode: path)

    sr = StaticRoute(uri_prefix, '/var/www/statics')

    req_path = uri_prefix[:-1] if uri_prefix.endswith('/') else uri_prefix
    req_path += uri_path

    req = Request(testing.create_environ(
        host='test.com',
        path=req_path,
        app='statics'
    ))

    resp = Response()

    sr(req, resp)

    assert resp.content_type == mtype
    assert resp.stream == '/var/www/statics' + expected_path
Пример #47
0
    def test_ignore_case_role_check(self):
        lowercase_action = "example:lowercase_monasca_user"
        uppercase_action = "example:uppercase_monasca_user"

        monasca_user_context = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "monasca_user",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "MONASCA_user"
                }
            )
        )
        self.assertTrue(policy.authorize(monasca_user_context.context,
                                         lowercase_action,
                                         {}))
        self.assertTrue(policy.authorize(monasca_user_context.context,
                                         uppercase_action,
                                         {}))
Пример #48
0
def test_forwarded_missing_first_hop_host():
    req = Request(testing.create_environ(
        host='suchproxy02.suchtesting.com',
        path='/languages',
        app='doge',
        headers={
            'Forwarded': 'for=108.166.30.185,host=suchproxy01.suchtesting.com'
        }
    ))

    assert req.forwarded[0].host is None
    assert req.forwarded[0].src == '108.166.30.185'

    assert req.forwarded[1].host == 'suchproxy01.suchtesting.com'
    assert req.forwarded[1].src is None

    assert req.forwarded_scheme == 'http'
    assert req.forwarded_host == 'suchproxy02.suchtesting.com'
    assert req.forwarded_uri == req.uri
    assert req.forwarded_uri == 'http://suchproxy02.suchtesting.com/doge/languages'
    assert req.forwarded_prefix == 'http://suchproxy02.suchtesting.com/doge'
Пример #49
0
class TestWSGIMediaType(base.TestBase):

    config_filename = 'wsgi_sqlite.conf'

    @ddt.data(
        ('GET', '/v1/queues'),
        ('GET', '/v1/queues/nonexistent/metadata'),
        ('GET', '/v1/queues/nonexistent/stats'),
        ('POST', '/v1/queues/nonexistent/messages'),
        ('GET', '/v1/queues/nonexistent/messages/deadbeaf'),
        ('POST', '/v1/queues/nonexistent/claims'),
        ('GET', '/v1/queues/nonexistent/claims/0ad'),
        ('GET', '/v1/health'),
    )
    def test_json_only_endpoints(self, (method, endpoint)):
        headers = {'Client-ID': '30387f00', 'Accept': 'application/xml'}

        env = testing.create_environ(endpoint, method=method, headers=headers)

        self.app(env, self.srmock)
        self.assertEquals(self.srmock.status, falcon.HTTP_406)
Пример #50
0
 def test_on_get(self):
     """
     need to check if status of the response is set for 200 and
     """
     env = create_environ(path='/')
     req = Request(env)
     req.context = {'doc': {}}
     req.params[mongoengine.CollectionResource.PARAM_TOTAL_COUNT] = '1'
     resp = Response()
     resource = mongoengine.CollectionResource(
         objects_class=Mock(return_value=[1, 2, 3]), max_limit=2)
     resource.get_object_list = Mock(return_value=[1, 2])
     resource.get_total_objects = Mock(return_value={'total_count': 3})
     resource.on_get(req=req, resp=resp)
     self.assertEqual(resp.body, {
         'results': [1, 2],
         'total': 3,
         'returned': 2
     })
     self.assertEqual(resp.get_header('x-api-total'), '3')
     self.assertEqual(resp.get_header('x-api-returned'), '2')
Пример #51
0
def test_request_cookie_parsing():
    # testing with a github-ish set of cookies
    headers = [
        (
            'Cookie',
            """
            logged_in=no;_gh_sess=eyJzZXXzaW9uX2lkIjoiN2;
            tz=Europe/Berlin; _ga =GA1.2.332347814.1422308165;
            tz2=Europe/Paris ; _ga2="line1\\012line2";
            tz3=Europe/Madrid ;_ga3= GA3.2.332347814.1422308165;
            _gat=1;
            _octo=GH1.1.201722077.1422308165
            """,
        ),
    ]

    environ = testing.create_environ(headers=headers)
    req = falcon.Request(environ)

    # NOTE(kgriffs): Test case-sensitivity
    assert req.get_cookie_values('TZ') is None
    assert 'TZ' not in req.cookies
    with pytest.raises(KeyError):
        req.cookies['TZ']

    for name, value in [
        ('logged_in', 'no'),
        ('_gh_sess', 'eyJzZXXzaW9uX2lkIjoiN2'),
        ('tz', 'Europe/Berlin'),
        ('tz2', 'Europe/Paris'),
        ('tz3', 'Europe/Madrid'),
        ('_ga', 'GA1.2.332347814.1422308165'),
        ('_ga2', 'line1\nline2'),
        ('_ga3', 'GA3.2.332347814.1422308165'),
        ('_gat', '1'),
        ('_octo', 'GH1.1.201722077.1422308165'),
    ]:
        assert name in req.cookies
        assert req.cookies[name] == value
        assert req.get_cookie_values(name) == [value]
Пример #52
0
def call(method, api_module, url, body='', headers=None, **params):
    '''Simulates a round-trip call against the given api_module / url'''
    api = server(api_module)
    response = StartResponseMock()
    if not isinstance(body, str):
        body = output_format.json(body)
        headers = {} if headers is None else headers
        headers['content-type'] = 'application/json'

    result = api(
        create_environ(path=url,
                       method=method,
                       headers=headers,
                       query_string=urlencode(params),
                       body=body), response)
    if result:
        response.data = result[0].decode('utf8')
        response.content_type = response.headers_dict['content-type']
        if response.content_type == 'application/json':
            response.data = json.loads(response.data)

    return response
Пример #53
0
def test_forwarded_host():
    req = Request(testing.create_environ(
        host='suchproxy02.suchtesting.com',
        path='/languages',
        headers={
            'Forwarded': 'host=something.org , host=suchproxy01.suchtesting.com'
        }
    ))

    assert req.forwarded is not None
    for f in req.forwarded:
        assert f.src is None
        assert f.dest is None
        assert f.scheme is None

    assert req.forwarded[0].host == 'something.org'
    assert req.forwarded[1].host == 'suchproxy01.suchtesting.com'

    assert req.forwarded_host == 'something.org'
    assert req.forwarded_uri != req.uri
    assert req.forwarded_uri == 'http://something.org/languages'
    assert req.forwarded_prefix == 'http://something.org'
Пример #54
0
    def test_request_cookie_parsing(self):
        # testing with a github-ish set of cookies
        headers = [
            ('Cookie', '''
                logged_in=no;_gh_sess=eyJzZXXzaW9uX2lkIjoiN2;
                tz=Europe/Berlin; _ga=GA1.2.332347814.1422308165;
                _gat=1;
                _octo=GH1.1.201722077.1422308165'''),
        ]

        environ = testing.create_environ(headers=headers)
        req = falcon.Request(environ)

        self.assertEqual("no", req.cookies["logged_in"])
        self.assertEqual("Europe/Berlin", req.cookies["tz"])
        self.assertEqual("GH1.1.201722077.1422308165", req.cookies["_octo"])

        self.assertIn("logged_in", req.cookies)
        self.assertIn("_gh_sess", req.cookies)
        self.assertIn("tz", req.cookies)
        self.assertIn("_ga", req.cookies)
        self.assertIn("_gat", req.cookies)
        self.assertIn("_octo", req.cookies)
Пример #55
0
    def test_pep3333(self):
        api = falcon.API()
        mock = testing.StartResponseMock()

        # Simulate a web request (normally done though a WSGI server)
        response = api(testing.create_environ(), mock)

        # Verify that the response is iterable
        assert _is_iterable(response)

        # Make sure start_response was passed a valid status string
        assert mock.call_count == 1
        assert isinstance(mock.status, str)
        assert re.match(r'^\d+[a-zA-Z\s]+$', mock.status)

        # Verify headers is a list of tuples, each containing a pair of strings
        assert isinstance(mock.headers, list)
        if len(mock.headers) != 0:
            header = mock.headers[0]
            assert isinstance(header, tuple)
            assert len(header) == 2
            assert isinstance(header[0], str)
            assert isinstance(header[1], str)
Пример #56
0
    def test_json_only_endpoints(self):
        endpoints = (
            ('GET', self.url_prefix + '/queues'),
            ('GET', self.url_prefix + '/queues/nonexistent/stats'),
            ('POST', self.url_prefix + '/queues/nonexistent/messages'),
            ('GET', self.url_prefix + '/queues/nonexistent/messages/deadbeaf'),
            ('POST', self.url_prefix + '/queues/nonexistent/claims'),
            ('GET', self.url_prefix + '/queues/nonexistent/claims/0ad'),
            ('GET', self.url_prefix + '/health'),
        )

        for method, endpoint in endpoints:
            headers = {
                'Client-ID': str(uuid.uuid4()),
                'Accept': 'application/xml',
            }

            env = testing.create_environ(endpoint,
                                         method=method,
                                         headers=headers)

            self.app(env, self.srmock)
            self.assertEqual(self.srmock.status, falcon.HTTP_406)
Пример #57
0
    def test_request_cookie_parsing(self):
        # testing with a github-ish set of cookies
        headers = [
            ('Cookie', '''
                logged_in=no;_gh_sess=eyJzZXXzaW9uX2lkIjoiN2;
                tz=Europe/Berlin; _ga=GA1.2.332347814.1422308165;
                _gat=1;
                _octo=GH1.1.201722077.1422308165'''),
        ]

        environ = testing.create_environ(headers=headers)
        req = falcon.Request(environ)

        self.assertEqual('no', req.cookies['logged_in'])
        self.assertEqual('Europe/Berlin', req.cookies['tz'])
        self.assertEqual('GH1.1.201722077.1422308165', req.cookies['_octo'])

        self.assertIn('logged_in', req.cookies)
        self.assertIn('_gh_sess', req.cookies)
        self.assertIn('tz', req.cookies)
        self.assertIn('_ga', req.cookies)
        self.assertIn('_gat', req.cookies)
        self.assertIn('_octo', req.cookies)
Пример #58
0
    def test_nonlatin_path(self, test_path):
        # NOTE(kgriffs): When a request comes in, web servers decode
        # the path.  The decoded path may contain UTF-8 characters,
        # but according to the WSGI spec, no strings can contain chars
        # outside ISO-8859-1. Therefore, to reconcile the URI
        # encoding standard that allows UTF-8 with the WSGI spec
        # that does not, WSGI servers tunnel the string via
        # ISO-8859-1. falcon.testing.create_environ() mimics this
        # behavior, e.g.:
        #
        #   tunnelled_path = path.encode('utf-8').decode('iso-8859-1')
        #
        # falcon.Request does the following to reverse the process:
        #
        #   path = tunnelled_path.encode('iso-8859-1').decode('utf-8', 'replace')
        #

        req = Request(testing.create_environ(
            host='com',
            path=test_path,
            headers=self.headers))

        self.assertEqual(req.path, falcon.uri.decode(test_path))
Пример #59
0
    def test_update_params(self):
        """
        Test if param is updated and returned
        """
        resource = SingleResource(objects_class=None)
        env = create_environ(path='/')
        req = Request(env)
        req.context = {
            'doc': {
                'pk': 1,
                'name': 'TestNewName'
            },
        }
        resp = Response()

        resource.objects_class = FakeObjectList()
        resource.serialize = fake_serialize
        resource.on_patch(req, resp)
        self.assertEqual({
            'pk': 1,
            'name': 'TestNewName',
            '_saved': True
        }, resp.body)
Пример #60
0
    def test_pep3333(self):
        api = falcon.API()
        mock = testing.StartResponseMock()

        # Simulate a web request (normally done though a WSGI server)
        response = api(testing.create_environ(), mock)

        # Verify that the response is iterable
        self.assertTrue(_is_iterable(response))

        # Make sure start_response was passed a valid status string
        self.assertIs(mock.call_count, 1)
        self.assertTrue(isinstance(mock.status, str))
        self.assertThat(mock.status, MatchesRegex('^\d+[a-zA-Z\s]+$'))

        # Verify headers is a list of tuples, each containing a pair of strings
        self.assertTrue(isinstance(mock.headers, list))
        if len(mock.headers) != 0:
            header = mock.headers[0]
            self.assertTrue(isinstance(header, tuple))
            self.assertThat(len(header), Equals(2))
            self.assertTrue(isinstance(header[0], str))
            self.assertTrue(isinstance(header[1], str))