Ejemplo n.º 1
0
def test_cookie_header_is_missing():
    environ = testing.create_environ(headers={})

    req = falcon.Request(environ)
    assert req.cookies == {}
    assert req.get_cookie_values('x') is None

    # NOTE(kgriffs): Test again with a new object to cover calling in the
    #   opposite order.
    req = falcon.Request(environ)
    assert req.get_cookie_values('x') is None
    assert req.cookies == {}
    def test_authenticate_with_invalid_user(self):
        """
        Verify authenticate denies with a proper JSON in Etcd, Authorization header, and no matching user.
        """
        with mock.patch('cherrypy.engine.publish') as _publish:
            # Mock the return of the Etcd get result
            return_value = mock.MagicMock(etcd.EtcdResult)
            with open(self.user_config, 'r') as users_file:
                return_value.value = users_file.read()

            manager = mock.MagicMock(StoreHandlerManager)
            _publish.return_value = [manager]

            manager.get.return_value = return_value

            # Reload with the data from the mock'd Etcd
            http_basic_auth = httpbasicauth.HTTPBasicAuth()

            # Test the call
            req = falcon.Request(
                create_environ(headers={'Authorization': 'basic Yjpi'}))
            resp = falcon.Response()
            self.assertRaises(
                falcon.HTTPForbidden,
                http_basic_auth.authenticate,
                req, resp)
Ejemplo n.º 3
0
 def test_decode_basic_auth_with_no_header(self):
     """
     Verify returns no user with no authorization header.
     """
     req = falcon.Request(create_environ(headers={}))
     self.assertEquals((None, None),
                       self.http_basic_auth._decode_basic_auth(req))
Ejemplo n.º 4
0
 def test_authenticator_process_request(self):
     """
     Verify Authenticator's process_request calls authenticate.
     """
     self.assertRaises(falcon.HTTPForbidden,
                       self.authenticator.process_request,
                       falcon.Request(create_environ()), falcon.Response())
Ejemplo n.º 5
0
    def test_on_get_response_networksv2_list(self):
        """Test list function"""

        client, env = get_client_env(query_string='name=123321')
        client['Account'].getNetworkVlans.return_value = [{
            'id':
            '123321',
            'name':
            'Public Network',
            'subnets': [{
                'id': 1
            }, {
                'id': 3
            }, {
                'id': 5
            }],
            'vlanNumber':
            999,
            'networkSpace':
            'PRIVATE'
        }]

        req = falcon.Request(env)
        resp = falcon.Response()

        networks.NetworksV2().on_get(req, resp)
        self.assertEqual(resp.status, 200)
        self.check_response_body(resp.body['networks'][0])
Ejemplo n.º 6
0
def _set_up_req_resp_body(**kwargs):
    env = helpers.create_environ(**kwargs)
    req = falcon.Request(env)
    resp = falcon.Response()
    client = mock.MagicMock()
    env['sl_client'] = client
    return client, env, req, resp
Ejemplo n.º 7
0
def test_request_adapter(mocker):
    env = testing.create_environ(
        query_string='page=1',
        headers={
            'X-API-Key': 'secret-key',
            'Cookie': str('session=secret'),
            'Content-Type': 'application/json',
        },
        body='{"foo": "bar"}',
        method='GET',
    )
    falcon_req = falcon.Request(env)
    falcon_req.uri_template = '/users/{id}'
    falcon_req.context['x'] = 42
    req = _RequestAdapter(falcon_req, {'id': '42'})

    assert req.uri_template == '/users/{id}'
    assert req.method == 'get'
    assert req.context['x'] == 42
    assert req.path == {'id': '42'}
    assert req.query == {'page': '1'}
    assert req.header['x-api-key'] == 'secret-key'
    assert req.cookie == {'session': 'secret'}
    assert req.content_length == len('{"foo": "bar"}')
    assert req.media_type == 'application/json'
    assert req.media == {'foo': 'bar'}

    with pytest.raises(KeyError):
        req.header['unknown']

    with pytest.raises(falcon.HTTPBadRequest):
        falcon_req = mocker.MagicMock()
        type(falcon_req).media = mocker.PropertyMock(side_effect=ValueError)
        req = _RequestAdapter(falcon_req, {})
        req.media
Ejemplo n.º 8
0
 def perform_flavor_detail(self, q_str, tenant_id, flavor_list):
     env = get_client_env(query_string=q_str)
     self.req = falcon.Request(env)
     self.resp = falcon.Response()
     self.app = mock.MagicMock()
     instance = flavors.FlavorsDetailV2(app=self.app, flavors=flavor_list)
     instance.on_get(self.req, self.resp, tenant_id)
Ejemplo n.º 9
0
 def test_on_post_invalid_create(self, create_instance_mock):
     create_instance_mock.side_effect = Exception('badrequest')
     client, env = get_client_env(body=self.body_string)
     req = falcon.Request(env)
     resp = falcon.Response()
     self.instance.on_post(req, resp, 'tenant_id')
     self.assertEqual(resp.status, 400)
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
Ejemplo n.º 11
0
    def test_on_get_response_networkv2_private(self):
        """Test working path of NetworkV2()"""

        client, env = get_client_env(query_string='name=123321')
        net_vlan = client['Network_Vlan']
        net_vlan.getObject.return_value = {
            'id': 11,
            'name': 'Public Network',
            'subnets': [{
                'id': 1
            }, {
                'id': 3
            }, {
                'id': 5
            }],
            'vlanNumber': 999,
            'networkSpace': 'PRIVATE'
        }
        req = falcon.Request(env)
        resp = falcon.Response()

        networks.NetworkV2().on_get(req, resp, 11)

        self.check_response_body(resp.body['network'])
        self.assertEqual(resp.status, 200)
        self.assertEqual(resp.body['network']['provider:physical_network'],
                         True)
Ejemplo n.º 12
0
def test_http_error_handler():
    http_error = falcon.HTTPBadRequest()
    req = falcon.Request(testing.create_environ())
    resp = falcon.Response()
    params = {}

    with pytest.raises(Problem):
        http_error_handler(http_error, req, resp, params)
Ejemplo n.º 13
0
 def perform_extra_detail_key(self, tenant_id, flavor_id, key_id):
     env = get_client_env()
     self.req = falcon.Request(env)
     self.resp = falcon.Response()
     flavors = flavor_list_loader.Flavors.get_flavors(app=mock.MagicMock())
     instance = extra_specs.ExtraSpecsFlavorKeyV2(app=mock.MagicMock(),
                                                  flavors=flavors)
     instance.on_get(self.req, self.resp, tenant_id, flavor_id, key_id)
Ejemplo n.º 14
0
 def perform_server_action(self, body_str, tenant_id, instance_id, flavors):
     self.client, self.env = get_client_env(body=body_str)
     self.vg_clientMock = self.client['Virtual_Guest']
     self.req = falcon.Request(self.env)
     self.resp = falcon.Response()
     instance = servers.ServerActionV2(app=mock.MagicMock(),
                                       flavors=flavors)
     instance.on_post(self.req, self.resp, tenant_id, instance_id)
Ejemplo n.º 15
0
 def perform_get_vol_details(self, tenant_id, instance_id, volume_id):
     self.client, self.env = get_client_env()
     self.vg_clientMock = self.client['Virtual_Guest']
     self.vdi_clientMock = self.client['Virtual_Disk_Image']
     self.req = falcon.Request(self.env)
     self.resp = falcon.Response()
     instance = volumes.OSVolumeAttachmentV2()
     instance.on_get(self.req, self.resp, tenant_id, instance_id, volume_id)
Ejemplo n.º 16
0
 def perform_attach_action(self, body_str, tenant_id, instance_id):
     self.client, self.env = get_client_env(body=body_str)
     self.vg_clientMock = self.client['Virtual_Guest']
     self.vdi_clientMock = self.client['Virtual_Disk_Image']
     self.req = falcon.Request(self.env)
     self.resp = falcon.Response()
     instance = volumes.OSVolumeAttachmentsV2()
     instance.on_post(self.req, self.resp, tenant_id, instance_id)
Ejemplo n.º 17
0
    def test_on_get_response_subnetv2_invalid_id(self):
        """Test invalid id"""
        client, env = get_client_env()
        req = falcon.Request(env)
        resp = falcon.Response()

        subnets.SubnetV2().on_get(req, resp, 'BAD_ID')
        self.assertEquals(resp.status, 400)
Ejemplo n.º 18
0
 def test_decode_basic_auth_with_bad_data_in_header(self):
     """
     Verify decoding returns no user with bad base64 data in the header.
     """
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic BADDATA'}))
     self.assertEquals((None, None),
                       self.http_basic_auth._decode_basic_auth(req))
Ejemplo n.º 19
0
def test_serialize_problem_accept_html():
    environ = testing.create_environ(headers={'Accept': 'text/html'})
    req = falcon.Request(environ)
    resp = falcon.Response()
    problem = Problem.from_http_error(falcon.HTTPBadRequest())

    serialize_problem(req, resp, problem)

    assert resp.content_type == 'application/json'
Ejemplo n.º 20
0
 def test_process_response_without_resource(self):
     with self.assertRaises(AssertionError):
         with self.assertLogs("", level="INFO"):
             self.middleware.process_response(
                 req=falcon.Request(env=self.mock_wsgi_env),
                 res=None,
                 resource=None,
                 req_succeeded=None,
             )
Ejemplo n.º 21
0
    def test_get_raw_headers(self):
        headers = [('Client-ID', '692ba466-74bb-11e3-bf3f-7567c531c7ca'),
                   ('Accept', 'audio/*; q=0.2, audio/basic')]

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

        for name, value in headers:
            self.assertIn((name.upper(), value), req.headers.items())
Ejemplo n.º 22
0
 def test_on_post_invalid(self):
     self.body['server']['networks'][0]['uuid'] = 'invalid'
     client, env = get_client_env(
         body='{"server": {"name": "testserver", '
         '"imageRef": "a1783280-6b1f", "flavorRef": "invalid"}}')
     req = falcon.Request(env)
     resp = falcon.Response()
     self.instance.on_post(req, resp, 'tenant_id')
     self.assertEqual(resp.status, 400)
Ejemplo n.º 23
0
    def test_on_get_response_networkv2_invalid_id(self):
        """Test invalid id"""
        client, env = get_client_env()

        req = falcon.Request(env)
        resp = falcon.Response()

        networks.NetworkV2().on_get(req, resp, 'BAD_ID')
        self.assertEqual(resp.status, 400)
    def test_valid_certs(self):
        """
        Verify authenticate succeeds when cn matches, fails when it doesn't
        """
        self.expect_forbidden(data=self.cert, cn="other-cn")

        auth = httpauthclientcert.HTTPClientCertAuth(cn="system:master-proxy")
        req = falcon.Request(create_environ())
        req.env[SSL_CLIENT_VERIFY] = self.cert
        resp = falcon.Response()
        self.assertEqual(None, auth.authenticate(req, resp))

        # With no cn any is valid
        auth = httpauthclientcert.HTTPClientCertAuth()
        req = falcon.Request(create_environ())
        req.env[SSL_CLIENT_VERIFY] = self.cert
        resp = falcon.Response()
        self.assertEqual(None, auth.authenticate(req, resp))
Ejemplo n.º 25
0
 def test_process_resource_with_resource(self):
     with self.assertLogs("", level="INFO") as cm:
         self.middleware.process_resource(
             req=falcon.Request(env=self.mock_wsgi_env),
             res=None,
             resource="A resource",
             params=None,
         )
         self.assertEqual(cm.output,
                          ["INFO:root:INCOMING REQUEST GET / 0.0.0.0 None"])
Ejemplo n.º 26
0
def test_duplicate_cookie():
    headers = [
        ('Cookie', 'x=1;bad{cookie=bar; x=2;x=3 ; x=4;'),
    ]

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

    assert req.cookies['x'] == '1'
    assert req.get_cookie_values('x') == ['1', '2', '3', '4']
Ejemplo n.º 27
0
 def test_authenticate_with_header(self):
     """
     Verify authenticate uses the submitted token and forbids without the header.
     """
     self._container_mgr.__getitem__()._get = mock.MagicMock(
         return_value=mock.MagicMock(status_code=409))
     req = falcon.Request(create_environ(headers={}))
     resp = falcon.Response()
     self.assertRaises(falcon.errors.HTTPForbidden,
                       self.kubernetes_auth.authenticate, req, resp)
Ejemplo n.º 28
0
    def test_on_get_subnetsv2_response_list(self):
        """Test list function"""
        client, env = get_client_env(query_string='name=10')
        SUBNET_DICT['id'] = 10
        client['Account'].getSubnets.return_value = [SUBNET_DICT]
        req = falcon.Request(env)
        resp = falcon.Response()

        subnets.SubnetsV2().on_get(req, resp)
        self.check_body_response(resp.body['subnets'][0])
Ejemplo n.º 29
0
    def test_on_get_response(self):
        """Test working path of NetworkV2()"""
        client, env = get_client_env(query_string='name=123321')

        req = falcon.Request(env)
        resp = falcon.Response()

        index.Index(client).on_get(req, resp)

        self.check_response_body(resp.body['versions'])
        self.assertEqual(resp.status, '200 OK')
Ejemplo n.º 30
0
 def test_authenticate_with_valid_user(self):
     """
     Verify authenticate works with a proper JSON file, Authorization header, and a matching user.
     """
     self.http_basic_auth_by_file = httpauth.HTTPBasicAuthByFile(
         './conf/users.json')
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic YTph'}))
     resp = falcon.Response()
     self.assertEquals(None,
                       self.http_basic_auth_by_file.authenticate(req, resp))