def setUp(self):
     super(TestKeystoneV2UserUpdate, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.model.tokens.admin_token
     }
     self.tenant_id = self.keystone.model.tenants.add(
         tenant_name='neo',
         description='The One'
     )
     self.user_info = {
         'user': {
             'username': '******',
             'enabled': True,
             'email': '*****@*****.**',
             'OS-KSADM:password': '******'
         }
     }
     self.user_info['user']['userid'] = self.keystone.model.users.add(
         tenant_id=self.tenant_id,
         username=self.user_info['user']['username'],
         email=self.user_info['user']['email'],
         password=self.user_info['user']['OS-KSADM:password'],
         enabled=self.user_info['user']['enabled']
     )
     self.keystone.model.tokens.add(
         tenant_id=self.tenant_id,
         user_id=self.user_info['user']['userid']
     )
     StackInABox.register_service(self.keystone)
Esempio n. 2
0
    def run():
        responses.mock.start()
        StackInABox.register_service(AdvancedService())
        stackinabox.util_responses.responses_registration('localhost')

        res = requests.get('http://localhost/advanced/')
        assert res.status_code == 200
        assert res.text == 'Hello'

        res = requests.get('http://localhost/advanced/h')
        assert res.status_code == 200
        assert res.text == 'Good-Bye'

        expected_result = {
            'bob': 'bob: Good-Bye alice',
            'alice': 'alice: Good-Bye bob',
            'joe': 'joe: Good-Bye jane'
        }
        res = requests.get('http://localhost/advanced/g?bob=alice;'
                           'alice=bob&joe=jane')
        assert res.status_code == 200
        assert res.json() == expected_result

        StackInABox.reset_services()

        responses.mock.stop()
        responses.mock.reset()
Esempio n. 3
0
def registration(uri):
    """Responses handler registration.

    Registers a handler for a given URI with Responses
    so that it can be intercepted and handed to
    Stack-In-A-Box.

    :param uri: URI used for the base of the HTTP requests

    :returns: n/a
    """

    # log the URI that is used to access the Stack-In-A-Box services
    logger.debug(
        'Registering Stack-In-A-Box at {0} under Python Responses'.format(uri))
    # tell Stack-In-A-Box what URI to match with
    StackInABox.update_uri(uri)

    # Build the regex for the URI and register all HTTP verbs
    # with Responses
    regex = re.compile(r'(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I)
    METHODS = [
        responses.DELETE, responses.GET, responses.HEAD, responses.OPTIONS,
        responses.PATCH, responses.POST, responses.PUT
    ]
    for method in METHODS:
        responses.add_callback(method, regex, callback=responses_callback)
Esempio n. 4
0
def httpretty_registration(uri):
    logger.debug(
        'Registering Stack-In-A-Box at {0} under Python HTTPretty'.format(uri))
    StackInABox.update_uri(uri)
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I)
    for method in HttpBaseClass.METHODS:
        register_uri(method, regex, body=httpretty_callback)
Esempio n. 5
0
 def setUp(self):
     super(TestHttprettyKeystone, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.backend.get_admin_token()
     }
     StackInABox.register_service(self.keystone)
 def setUp(self):
     super(TestKeystoneV2UserAddCredentials, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.model.tokens.admin_token
     }
     self.tenant_id = self.keystone.model.tenants.add(
         tenant_name='neo',
         description='The One'
     )
     self.user_info = {
         'user': {
             'username': '******',
             'enabled': True,
             'email': '*****@*****.**',
             'password': '******'
         }
     }
     self.user_info['user']['userid'] = self.keystone.model.users.add(
         tenant_id=self.tenant_id,
         username=self.user_info['user']['username'],
         email=self.user_info['user']['email'],
         password=self.user_info['user']['password'],
         enabled=self.user_info['user']['enabled']
     )
     self.keystone.model.tokens.add(
         tenant_id=self.tenant_id,
         user_id=self.user_info['user']['userid']
     )
     self.keystone.model.roles.add_user_role_by_role_name(
         tenant_id=self.tenant_id,
         user_id=self.user_info['user']['userid'],
         role_name=self.keystone.model.roles.IDENTITY_ADMIN_ROLE
     )
     StackInABox.register_service(self.keystone)
Esempio n. 7
0
def registration(uri):
    """Responses handler registration.

    Registers a handler for a given URI with Responses
    so that it can be intercepted and handed to
    Stack-In-A-Box.

    :param uri: URI used for the base of the HTTP requests

    :returns: n/a
    """

    # log the URI that is used to access the Stack-In-A-Box services
    logger.debug('Registering Stack-In-A-Box at {0} under Python Responses'
                 .format(uri))
    # tell Stack-In-A-Box what URI to match with
    StackInABox.update_uri(uri)

    # Build the regex for the URI and register all HTTP verbs
    # with Responses
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri),
                       re.I)
    METHODS = [
        responses.DELETE,
        responses.GET,
        responses.HEAD,
        responses.OPTIONS,
        responses.PATCH,
        responses.POST,
        responses.PUT
    ]
    for method in METHODS:
        responses.add_callback(method,
                               regex,
                               callback=responses_callback)
Esempio n. 8
0
    def test_double_service_registration(self):
        service1 = HelloService()
        service2 = HelloService()

        StackInABox.register_service(service1)
        with self.assertRaises(ServiceAlreadyRegisteredError):
            StackInABox.register_service(service2)
 def setUp(self):
     super(TestKeystoneV2UserListing, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.model.get_admin_token()
     }
     StackInABox.register_service(self.keystone)
Esempio n. 10
0
 def setUp(self):
     super(TestKeystoneV2UserGet, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.model.tokens.admin_token
     }
     StackInABox.register_service(self.keystone)
Esempio n. 11
0
    def test_double_service_registration(self):
        service1 = HelloService()
        service2 = HelloService()

        StackInABox.register_service(service1)
        with self.assertRaises(ServiceAlreadyRegisteredError):
            StackInABox.register_service(service2)
Esempio n. 12
0
    def test_service_exception(self):
        exceptional = ExceptionalServices()
        StackInABox.register_service(exceptional)

        stackinabox.util_httpretty.httpretty_registration('localhost')

        res = requests.get('http://localhost/except/')
        self.assertEqual(res.status_code, 596)
Esempio n. 13
0
    def run():
        StackInABox.reset_services()
        StackInABox.register_service(HelloService())
        stackinabox.util.responses.registration('localhost')

        res = requests.get('http://localhost/hello/')
        assert res.status_code == 200
        assert res.text == 'Hello'
Esempio n. 14
0
    def run():
        StackInABox.reset_services()
        StackInABox.register_service(HelloService())
        stackinabox.util_responses.responses_registration('localhost')

        res = requests.get('http://localhost/hello/')
        assert res.status_code == 200
        assert res.text == 'Hello'
 def setUp(self):
     super(TestHttprettyKeystone, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.model.tokens.admin_token
     }
     StackInABox.register_service(self.keystone)
     self.session = requests.Session()
Esempio n. 16
0
    def test_service_exception(self):
        exceptional = ExceptionalServices()
        StackInABox.register_service(exceptional)

        stackinabox.util_httpretty.httpretty_registration('localhost')

        res = requests.get('http://localhost/except/')
        self.assertEqual(res.status_code, 596)
Esempio n. 17
0
def responses_registration(uri):
    logger.debug(
        'Registering Stack-In-A-Box at {0} under Python Responses'.format(uri))
    StackInABox.update_uri(uri)
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I)
    METHODS = [
        responses.DELETE, responses.GET, responses.HEAD, responses.OPTIONS,
        responses.PATCH, responses.POST, responses.PUT
    ]
    for method in METHODS:
        responses.add_callback(method, regex, callback=responses_callback)
Esempio n. 18
0
    def test_subservice_registration(self):
        service = AnotherAdvancedService()
        subservice = YetAnotherService()
        service.register_subservice(re.compile('^/french'), subservice)

        StackInABox.register_service(service)

        stackinabox.util_httpretty.httpretty_registration('localhost')

        res = requests.get('http://localhost/aas/french')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.text, 'bonjour')
 def setUp(self):
     super(TestKeystoneV2UserAdd, self).setUp()
     self.keystone = KeystoneV2Service()
     self.headers = {
         'x-auth-token': self.keystone.model.get_admin_token()
     }
     self.user_info = {
         'user': {
             'username': '******',
             'enabled': True,
             'email': '*****@*****.**',
             'OS-KSADM:password': '******'
         }
     }
     StackInABox.register_service(self.keystone)
Esempio n. 20
0
    def test_subservice_registration(self):
        service = AnotherAdvancedService()
        subservice = YetAnotherService()
        service.register_subservice(re.compile('^/french'),
                                    subservice)

        StackInABox.register_service(service)

        stackinabox.util_httpretty.httpretty_registration('localhost')

        res = requests.get('http://localhost/aas/french')
        self.assertEqual(res.status_code,
                         200)
        self.assertEqual(res.text,
                         'bonjour')
Esempio n. 21
0
def httpretty_callback(request, uri, headers):
    """httpretty request handler.

    converts a call intercepted by httpretty to
    the stack-in-a-box infrastructure

    :param request: request object
    :param uri: the uri of the request
    :param headers: headers for the response

    :returns: tuple - (int, dict, string) containing:
                      int - the http response status code
                      dict - the headers for the http response
                      string - http string response

    """
    method = request.method
    response_headers = CaseInsensitiveDict()
    response_headers.update(headers)
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    return StackInABox.call_into(method,
                                 request,
                                 uri,
                                 response_headers)
Esempio n. 22
0
def httpretty_callback(request, uri, headers):
    """httpretty request handler.

    converts a call intercepted by httpretty to
    the stack-in-a-box infrastructure

    :param request: request object
    :param uri: the uri of the request
    :param headers: headers for the response

    :returns: tuple - (int, dict, string) containing:
                      int - the http response status code
                      dict - the headers for the http response
                      string - http string response

    """
    method = request.method
    response_headers = CaseInsensitiveDict()
    response_headers.update(headers)
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    return StackInABox.call_into(method,
                                 request,
                                 uri,
                                 response_headers)
Esempio n. 23
0
def responses_callback(request):
    method = request.method
    headers = CaseInsensitiveDict()
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    uri = request.url
    return StackInABox.call_into(method, request, uri, headers)
Esempio n. 24
0
def httpretty_registration(uri):

    status_data = {
        595: 'StackInABoxService - Unknown Route',
        596: 'StackInABox - Exception in Service Handler',
        597: 'StackInABox - Unknown Service'
    }
    for k, v in six.iteritems(status_data):
        if k not in httpretty.http.STATUSES:
            httpretty.http.STATUSES[k] = v

    logger.debug(
        'Registering Stack-In-A-Box at {0} under Python HTTPretty'.format(uri))
    StackInABox.update_uri(uri)
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I)
    for method in HttpBaseClass.METHODS:
        register_uri(method, regex, body=httpretty_callback)
Esempio n. 25
0
def httpretty_callback(request, uri, headers):
    method = request.method
    response_headers = CaseInsensitiveDict()
    response_headers.update(headers)
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    return StackInABox.call_into(method, request, uri, response_headers)
Esempio n. 26
0
def httpretty_registration(uri):

    status_data = {
        595: 'StackInABoxService - Unknown Route',
        596: 'StackInABox - Exception in Service Handler',
        597: 'StackInABox - Unknown Service'
    }
    for k, v in six.iteritems(status_data):
        if k not in httpretty.http.STATUSES:
            httpretty.http.STATUSES[k] = v

    logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty'
                 .format(uri))
    StackInABox.update_uri(uri)
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri),
                       re.I)
    for method in HttpBaseClass.METHODS:
        register_uri(method, regex, body=httpretty_callback)
def requests_mock_session_registration(uri, session):
    logger.debug('Registering Stack-In-A-Box at {0} under Python Requests-Mock'
                 .format(uri))
    logger.debug('Session has id {0}'.format(id(session)))

    StackInABox.update_uri(uri)
    StackInABox.hold_onto('adapter', requests_mock.Adapter())
    StackInABox.hold_out('adapter').add_matcher(RequestMockCallable(uri))

    session.mount('http://{0}'.format(uri), StackInABox.hold_out('adapter'))
    session.mount('https://{0}'.format(uri), StackInABox.hold_out('adapter'))
Esempio n. 28
0
    def handle(self, request, uri):
        """Request handler interface.

        :param request: Python requests Request object
        :param uri: URI of the request
        """

        # Convert the call over to Stack-In-A-Box
        method = request.method
        headers = CaseInsensitiveDict()
        request_headers = CaseInsensitiveDict()
        request_headers.update(request.headers)
        request.headers = request_headers
        stackinabox_result = StackInABox.call_into(method,
                                                   request,
                                                   uri,
                                                   headers)

        # reformat the result for easier use
        status_code, output_headers, body = stackinabox_result

        json_data = None
        text_data = None
        content_data = None
        body_data = None

        # if the body is a string-type...
        if isinstance(body, six.string_types):
            # Try to convert it to JSON
            text_data = body
            try:
                json_data = json.dumps(text_data)
                text_data = json_data
            except Exception:
                json_data = None
                text_data = body

        # if the body is binary, then it's the content
        elif isinstance(body, six.binary_type):
            content_data = body

        # by default, it's just body data
        else:
            # default to body data
            body_data = body

        # build the Python requests' Response object
        return requests_mock.response.create_response(
            request,
            headers=output_headers,
            status_code=status_code,
            body=body_data,
            json=json_data,
            text=text_data,
            content=content_data
        )
Esempio n. 29
0
    def handle(self, request, uri):
        """Request handler interface.

        :param request: Python requests Request object
        :param uri: URI of the request
        """

        # Convert the call over to Stack-In-A-Box
        method = request.method
        headers = CaseInsensitiveDict()
        request_headers = CaseInsensitiveDict()
        request_headers.update(request.headers)
        request.headers = request_headers
        stackinabox_result = StackInABox.call_into(method,
                                                   request,
                                                   uri,
                                                   headers)

        # reformat the result for easier use
        status_code, output_headers, body = stackinabox_result

        json_data = None
        text_data = None
        content_data = None
        body_data = None

        # if the body is a string-type...
        if isinstance(body, six.string_types):
            # Try to convert it to JSON
            text_data = body
            try:
                json_data = json.dumps(text_data)
                text_data = json_data
            except Exception:
                json_data = None
                text_data = body

        # if the body is binary, then it's the content
        elif isinstance(body, six.binary_type):
            content_data = body

        # by default, it's just body data
        else:
            # default to body data
            body_data = body

        # build the Python requests' Response object
        return requests_mock.response.create_response(
            request,
            headers=output_headers,
            status_code=status_code,
            body=body_data,
            json=json_data,
            text=text_data,
            content=content_data
        )
Esempio n. 30
0
    def run(use_deprecated):
        responses.mock.start()
        StackInABox.register_service(AdvancedService())
        if use_deprecated:
            stackinabox.util.responses.responses_registration('localhost')
        else:
            stackinabox.util.responses.registration('localhost')

        res = requests.get('http://localhost/advanced/')
        assert res.status_code == 200
        assert res.text == 'Hello'

        res = requests.get('http://localhost/advanced/h')
        assert res.status_code == 200
        assert res.text == 'Good-Bye'

        expected_result = {
            'bob': 'bob: Good-Bye alice',
            'alice': 'alice: Good-Bye bob',
            'joe': 'joe: Good-Bye jane'
        }
        res = requests.get('http://localhost/advanced/g?bob=alice;'
                           'alice=bob&joe=jane')
        assert res.status_code == 200
        assert res.json() == expected_result

        res = requests.get('http://localhost/advanced/1234567890')
        assert res.status_code == 200
        assert res.text == 'okay'

        res = requests.get('http://localhost/advanced/_234567890')
        assert res.status_code == 595

        res = requests.put('http://localhost/advanced/h')
        assert res.status_code == 405

        res = requests.put('http://localhost/advanced2/i')
        assert res.status_code == 597

        StackInABox.reset_services()

        responses.mock.stop()
        responses.mock.reset()
Esempio n. 31
0
def responses_registration(uri):
    logger.debug('Registering Stack-In-A-Box at {0} under Python Responses'
                 .format(uri))
    StackInABox.update_uri(uri)
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri),
                       re.I)
    METHODS = [
        responses.DELETE,
        responses.GET,
        responses.HEAD,
        responses.OPTIONS,
        responses.PATCH,
        responses.POST,
        responses.PUT
    ]
    for method in METHODS:
        responses.add_callback(method,
                               regex,
                               callback=responses_callback)
Esempio n. 32
0
def httpretty_callback(request, uri, headers):
    method = request.method
    response_headers = CaseInsensitiveDict()
    response_headers.update(headers)
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    return StackInABox.call_into(method,
                                 request,
                                 uri,
                                 response_headers)
Esempio n. 33
0
def responses_callback(request):
    method = request.method
    headers = CaseInsensitiveDict()
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    uri = request.url
    return StackInABox.call_into(method,
                                 request,
                                 uri,
                                 headers)
Esempio n. 34
0
    def run():
        responses.mock.start()
        StackInABox.register_service(AdvancedService())
        stackinabox.util.responses.registration('localhost')

        res = requests.get('http://localhost/advanced/')
        assert res.status_code == 200
        assert res.text == 'Hello'

        res = requests.get('http://localhost/advanced/h')
        assert res.status_code == 200
        assert res.text == 'Good-Bye'

        expected_result = {
            'bob': 'bob: Good-Bye alice',
            'alice': 'alice: Good-Bye bob',
            'joe': 'joe: Good-Bye jane'
        }
        res = requests.get('http://localhost/advanced/g?bob=alice;'
                           'alice=bob&joe=jane')
        assert res.status_code == 200
        assert res.json() == expected_result

        res = requests.get('http://localhost/advanced/1234567890')
        assert res.status_code == 200
        assert res.text == 'okay'

        res = requests.get('http://localhost/advanced/_234567890')
        assert res.status_code == 595

        res = requests.put('http://localhost/advanced/h')
        assert res.status_code == 405

        res = requests.put('http://localhost/advanced2/i')
        assert res.status_code == 597

        StackInABox.reset_services()

        responses.mock.stop()
        responses.mock.reset()
Esempio n. 35
0
    def setUp(self):
        super(TestKeystoneV2AuthBase, self).setUp()

        self.tenantname = self.make_tenant_name()
        self.keystone = KeystoneV2Service()
        self.username = '******'.format(str(uuid.uuid4()))
        self.password = '******'.format(
            str(uuid.uuid4()).replace('-', '')
        )
        self.apikey = str(uuid.uuid4())
        self.email = '{0}@stackinabox.mock'.format(self.username)
        self.keystone.model.tenants.add(
            tenant_name=self.tenantname,
            description="test tenant"
        )
        tenant_data = self.keystone.model.tenants.get_by_name(
            tenant_name=self.tenantname
        )
        self.tenantid = tenant_data['id']

        self.keystone.model.users.add(
            tenant_id=self.tenantid,
            username=self.username,
            password=self.password,
            apikey=self.apikey,
            email=self.email
        )
        user_data = self.keystone.model.users.get_by_name(
            tenant_id=self.tenantid,
            username=self.username
        )
        self.userid = user_data['user_id']
        self.token = self.keystone.model.tokens.make_token()
        self.keystone.model.tokens.add(
            tenant_id=self.tenantid,
            user_id=self.userid,
            token=self.token
        )

        StackInABox.register_service(self.keystone)
Esempio n. 36
0
    def handle(self, request, uri):
        """Request handler interface.

        :param request: Python requests Request object
        :param uri: URI of the request
        """

        # Convert the call over to Stack-In-A-Box
        method = request.method
        headers = CaseInsensitiveDict()
        request_headers = CaseInsensitiveDict()
        request_headers.update(request.headers)
        request.headers = request_headers
        stackinabox_result = StackInABox.call_into(method,
                                                   request,
                                                   uri,
                                                   headers)

        # reformat the result for easier use
        status_code, output_headers, body = stackinabox_result

        text_data = None
        content_data = None
        body_data = None

        # if the body is a string-type...
        if isinstance(body, six.string_types):
            logger.debug('running text result')
            # Try to convert it to JSON
            text_data = body

        # if the body is binary, then it's the content
        elif isinstance(body, six.binary_type):
            logger.debug('running binary result')
            content_data = body

        # by default, it's just body data
        else:
            # default to body data
            logger.debug('running default result')
            body_data = body

        # build the Python requests' Response object
        # `raw` and `json` parameters shouldn't be used
        return requests_mock.response.create_response(
            request,
            headers=output_headers,
            status_code=status_code,
            body=body_data,
            text=text_data,
            content=content_data
        )
Esempio n. 37
0
    def test_user_listing(self):
        stackinabox.util_httpretty.httpretty_registration('localhost')

        neo_tenant_id = self.keystone.backend.add_tenant(tenantname='neo',
                                                         description='The One')
        tom = self.keystone.backend.add_user(neo_tenant_id,
                                             'tom',
                                             '*****@*****.**',
                                             'bluepill',
                                             'iamnottheone',
                                             enabled=True)
        self.keystone.backend.add_user_role_by_rolename(
            neo_tenant_id, tom, 'identity:user-admin')

        self.keystone.backend.add_token(neo_tenant_id, tom)
        user_data = self.keystone.backend.get_token_by_userid(tom)
        self.headers['x-auth-token'] = user_data['token']
        res = requests.get('http://localhost/keystone/v2.0/users',
                           headers=self.headers)
        print(res.text)
        self.assertEqual(res.status_code, 200)
        user_data = res.json()

        self.assertEqual(len(user_data['users']), 1)

        self.keystone.backend.add_user(neo_tenant_id,
                                       'neo',
                                       '*****@*****.**',
                                       'redpill',
                                       'iamtheone',
                                       enabled=True)

        res = requests.get('http://localhost/keystone/v2.0/users',
                           headers=self.headers)
        self.assertEqual(res.status_code, 200)
        user_data = res.json()

        self.assertEqual(len(user_data['users']), 2)
        StackInABox.reset_services()
Esempio n. 38
0
        def wrapped(*args, **kwargs):
            args_copy = list(args)
            for arg in self.args:
                args_copy.append(arg)
            args_finalized = tuple(args_copy)
            kwargs.update(self.kwargs)

            if self.enable_service_access is not None:
                kwargs[self.enable_service_access] = self.services

            httpretty.reset()
            httpretty.enable()

            for service in self.services.values():
                StackInABox.register_service(service)
            httpretty_registration(self.uri)
            return_value = fn(*args_finalized, **kwargs)
            StackInABox.reset_services()

            httpretty.disable()
            httpretty.reset()

            return return_value
Esempio n. 39
0
        def wrapped(*args, **kwargs):
            args_copy = list(args)
            for arg in self.args:
                args_copy.append(arg)
            args_finalized = tuple(args_copy)
            kwargs.update(self.kwargs)

            if self.enable_service_access is not None:
                kwargs[self.enable_service_access] = self.services

            httpretty.reset()
            httpretty.enable()

            for service in self.services.values():
                StackInABox.register_service(service)
            httpretty_registration(self.uri)
            return_value = fn(*args_finalized, **kwargs)
            StackInABox.reset_services()

            httpretty.disable()
            httpretty.reset()

            return return_value
Esempio n. 40
0
    def __init__(self, services=None):
        """
        Create the WSGI Application

        :param list services: list of :obj:`StackInABoxService`s to load into
            StackInABox.
        """
        self.stackinabox = StackInABox()
        self.stack_service = StackInAWsgiSessionManager()
        self.admin_service = StackInAWsgiAdmin(
            self.stack_service,
            'http://localhost/stackinabox/'
        )
        self.stackinabox.register(self.admin_service)
        self.stackinabox.register(self.stack_service)

        def __check_service(service_object):
            """
            Simple wrapper to check whether an object provide by the caller is
            a StackInABoxService by creating an instance
            """
            svc = service_object()
            if not isinstance(svc, StackInABoxService):
                raise TypeError(
                    "Service is not a Stack-In-A-Box Service"
                )

        # if the caller does not provide any services then just log it
        # to keep from user confusion
        if services is not None:

            # Allow the caller to provide either an iterable of services to
            # to provide to the session or to provide a single service object
            if isinstance(services, Iterable):
                # for each service verify it is a StackInABoxService
                for service in services:
                    __check_service(service)
                    self.RegisterWithStackInABox(service)

            else:
                # if it's not an iterable - e.g a single object - then
                # just check the variable itself
                __check_service(services)
                self.RegisterWithStackInABox(services)

        else:
            logger.debug(
                "No services registered on initialization"
            )
Esempio n. 41
0
def registration(uri):
    """httpretty handler registration.

    registers a handler for a given uri with httpretty
    so that it can be intercepted and handed to
    stack-in-a-box.

    :param uri: uri used for the base of the http requests

    :returns: n/a

    """

    # add the stack-in-a-box specific response codes to
    # http's status information
    status_data = {
        595: 'StackInABoxService - Unknown Route',
        596: 'StackInABox - Exception in Service Handler',
        597: 'StackInABox - Unknown Service'
    }
    for k, v in six.iteritems(status_data):
        if k not in httpretty.http.STATUSES:
            httpretty.http.STATUSES[k] = v

    # log the uri that is used to access the stack-in-a-box services
    logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty'
                 .format(uri))
    # tell stack-in-a-box what uri to match with
    StackInABox.update_uri(uri)

    # build the regex for the uri and register all http verbs
    # with httpretty
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri),
                       re.I)
    for method in HttpBaseClass.METHODS:
        register_uri(method, regex, body=httpretty_callback)
Esempio n. 42
0
def registration(uri):
    """httpretty handler registration.

    registers a handler for a given uri with httpretty
    so that it can be intercepted and handed to
    stack-in-a-box.

    :param uri: uri used for the base of the http requests

    :returns: n/a

    """

    # add the stack-in-a-box specific response codes to
    # http's status information
    status_data = {
        595: 'StackInABoxService - Unknown Route',
        596: 'StackInABox - Exception in Service Handler',
        597: 'StackInABox - Unknown Service'
    }
    for k, v in six.iteritems(status_data):
        if k not in httpretty.http.STATUSES:
            httpretty.http.STATUSES[k] = v

    # log the uri that is used to access the stack-in-a-box services
    logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty'
                 .format(uri))
    # tell stack-in-a-box what uri to match with
    StackInABox.update_uri(uri)

    # build the regex for the uri and register all http verbs
    # with httpretty
    regex = re.compile(r'(http)?s?(://)?{0}:?(\d+)?/'.format(uri),
                       re.I)
    for method in HttpBaseClass.METHODS:
        register_uri(method, regex, body=httpretty_callback)
Esempio n. 43
0
            def run():
                responses.mock.start()

                StackInABox.reset_services()
                for service in self.services.values():
                    StackInABox.register_service(service)
                responses_registration(self.uri)
                return_value = fn(*args_finalized, **kwargs)
                StackInABox.reset_services()

                responses.mock.stop()
                responses.mock.reset()
Esempio n. 44
0
            def run():
                responses.mock.start()

                StackInABox.reset_services()
                for service in self.services.values():
                    StackInABox.register_service(service)
                responses_registration(self.uri)
                return_value = fn(*args_finalized, **kwargs)
                StackInABox.reset_services()

                responses.mock.stop()
                responses.mock.reset()
    def handle(self, request, uri):
        method = request.method
        headers = CaseInsensitiveDict()
        request_headers = CaseInsensitiveDict()
        request_headers.update(request.headers)
        request.headers = request_headers
        stackinabox_result = StackInABox.call_into(method,
                                                   request,
                                                   uri,
                                                   headers)

        status_code, output_headers, body = stackinabox_result

        json_data = None
        text_data = None
        content_data = None
        body_data = None

        if isinstance(body, six.string_types):
            text_data = body
            try:
                json_data = json.dumps(text_data)
                text_data = json_data
            except:
                json_data = None
                text_data = body

        elif isinstance(body, six.binary_type):
            content_data = body

        else:
            # default to body data
            body_data = body

        return requests_mock.response.create_response(
            request,
            headers=output_headers,
            status_code=status_code,
            body=body_data,
            json=json_data,
            text=text_data,
            content=content_data
        )
Esempio n. 46
0
def responses_callback(request):
    """Responses Request Handler.

    Converts a call intercepted by Responses to
    the Stack-In-A-Box infrastructure

    :param request: request object

    :returns: tuple - (int, dict, string) containing:
                      int - the HTTP response status code
                      dict - the headers for the HTTP response
                      string - HTTP string response
    """
    method = request.method
    headers = CaseInsensitiveDict()
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    uri = request.url
    return StackInABox.call_into(method, request, uri, headers)
Esempio n. 47
0
def session_registration(uri, session):
    """Requests-mock registration with a specific Session.

    :param uri: base URI to match against
    :param session: Python requests' Session object

    :returns: n/a
    """
    # log the URI that is used to access the Stack-In-A-Box services
    logger.debug('Registering Stack-In-A-Box at {0} under Python Requests-Mock'
                 .format(uri))
    logger.debug('Session has id {0}'.format(id(session)))

    # tell Stack-In-A-Box what URI to match with
    StackInABox.update_uri(uri)

    # Create a Python Requests Adapter object for handling the session
    StackInABox.hold_onto('adapter', requests_mock.Adapter())
    # Add the Request handler object for the URI
    StackInABox.hold_out('adapter').add_matcher(RequestMockCallable(uri))

    # Tell the session about the adapter and the URI
    session.mount('http://{0}'.format(uri), StackInABox.hold_out('adapter'))
    session.mount('https://{0}'.format(uri), StackInABox.hold_out('adapter'))
Esempio n. 48
0
def session_registration(uri, session):
    """Requests-mock registration with a specific Session.

    :param uri: base URI to match against
    :param session: Python requests' Session object

    :returns: n/a
    """
    # log the URI that is used to access the Stack-In-A-Box services
    logger.debug('Registering Stack-In-A-Box at {0} under Python Requests-Mock'
                 .format(uri))
    logger.debug('Session has id {0}'.format(id(session)))

    # tell Stack-In-A-Box what URI to match with
    StackInABox.update_uri(uri)

    # Create a Python Requests Adapter object for handling the session
    StackInABox.hold_onto('adapter', requests_mock.Adapter())
    # Add the Request handler object for the URI
    StackInABox.hold_out('adapter').add_matcher(RequestMockCallable(uri))

    # Tell the session about the adapter and the URI
    session.mount('http://{0}'.format(uri), StackInABox.hold_out('adapter'))
    session.mount('https://{0}'.format(uri), StackInABox.hold_out('adapter'))
Esempio n. 49
0
def responses_callback(request):
    """Responses Request Handler.

    Converts a call intercepted by Responses to
    the Stack-In-A-Box infrastructure

    :param request: request object

    :returns: tuple - (int, dict, string) containing:
                      int - the HTTP response status code
                      dict - the headers for the HTTP response
                      string - HTTP string response
    """
    method = request.method
    headers = CaseInsensitiveDict()
    request_headers = CaseInsensitiveDict()
    request_headers.update(request.headers)
    request.headers = request_headers
    uri = request.url
    return StackInABox.call_into(method,
                                 request,
                                 uri,
                                 headers)
Esempio n. 50
0
 def tearDown(self):
     super(TestRequestsMockBasic, self).tearDown()
     StackInABox.reset_services()
     self.session.close()
Esempio n. 51
0
 def tearDown(self):
     super(TestServiceRouteRegistration, self).tearDown()
     StackInABox.reset_services()
Esempio n. 52
0
 def setUp(self):
     super(TestRequestMockAdapter, self).setUp()
     StackInABox.register_service(self.hello_service)
     self.session = requests.Session()
 def tearDown(self):
     super(TestKeystoneV2UserAddCredentials, self).tearDown()
     StackInABox.reset_services()
Esempio n. 54
0
 def setUp(self):
     super(TestMetrics, self).setUp()
     self.service = HttpStatsdService()
     StackInABox.register_service(self.service)
     self.statsd_client = HttpStatsdClient('http://localhost/statsd/')
Esempio n. 55
0
        def wrapped(*args, **kwargs):
            args_copy = list(args)
            for arg in self.args:
                args_copy.append(arg)
            args_finalized = tuple(args_copy)
            kwargs.update(self.kwargs)

            if self.enable_service_access is not None:
                kwargs[self.enable_service_access] = self.services

            with requests_mock_activate():
                if self.session is not None:
                    kwargs[self.session] = requests.Session()

                    StackInABox.reset_services()
                    for service in self.services.values():
                        StackInABox.register_service(service)
                    requests_mock_session_registration(self.uri,
                                                       kwargs[self.session])
                    return_value = fn(*args_finalized, **kwargs)
                    StackInABox.reset_services()

                else:
                    StackInABox.reset_services()
                    for service in self.services.values():
                        StackInABox.register_service(service)
                    requests_mock_registration(self.uri)
                    return_value = fn(*args_finalized, **kwargs)
                    StackInABox.reset_services()

            return return_value
Esempio n. 56
0
 def tearDown(self):
     super(TestMetrics, self).tearDown()
     StackInABox.reset_services()
 def tearDown(self):
     super(TestKeystoneV2UserListing, self).tearDown()
     StackInABox.reset_services()
Esempio n. 58
0
 def tearDown(self):
     super(TestKeystoneV2AuthBase, self).tearDown()
     StackInABox.reset_services()