def test_srmock(self):
        mock = testing.StartResponseMock()
        mock(falcon.HTTP_200, ())

        assert mock.status == falcon.HTTP_200
        assert mock.exc_info is None

        mock = testing.StartResponseMock()
        exc_info = sys.exc_info()
        mock(falcon.HTTP_200, (), exc_info)

        assert mock.exc_info == exc_info
Esempio n. 2
0
    def test_srmock(self):
        mock = testing.StartResponseMock()
        mock(falcon.HTTP_200, ())

        self.assertEqual(falcon.HTTP_200, mock.status)
        self.assertEqual(None, mock.exc_info)

        mock = testing.StartResponseMock()
        exc_info = sys.exc_info()
        mock(falcon.HTTP_200, (), exc_info)

        self.assertEqual(exc_info, mock.exc_info)
Esempio n. 3
0
    def setUp(self):
        super(TestBase, self).setUp()

        if not self.config_file:
            self.skipTest("No config specified")

        self.conf.register_opts(configs._GENERAL_OPTIONS)
        self.conf.register_opts(validation._TRANSPORT_LIMITS_OPTIONS,
                                group=validation._TRANSPORT_LIMITS_GROUP)
        self.transport_cfg = self.conf[validation._TRANSPORT_LIMITS_GROUP]

        self.conf.register_opts(driver._WSGI_OPTIONS, group=driver._WSGI_GROUP)
        self.wsgi_cfg = self.conf[driver._WSGI_GROUP]

        self.conf.unreliable = True
        self.conf.admin_mode = True
        self.boot = bootstrap.Bootstrap(self.conf)
        self.addCleanup(self.boot.storage.close)
        self.addCleanup(self.boot.control.close)

        self.app = self.boot.transport.app

        self.srmock = ftest.StartResponseMock()

        self.headers = {
            'Client-ID': uuidutils.generate_uuid(),
            'X-ROLES': 'admin',
            'X-USER-ID': 'a12d157c7d0d41999096639078fd11fc',
            'X-TENANT-ID': 'abb69142168841fcaa2785791b92467f',
        }
Esempio n. 4
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = batch.RestaurantCollection()
        self.api.add_route('/batch/restaurants', self.resource)
        self.srmock = testing.StartResponseMock()

        restaurants = [{
            'name': 'a',
            'description': 'desc A',
            'email': '*****@*****.**',
            'address': 'tokyo',
        }, {
            'name': 'b',
            'description': 'desc B',
            'email': '*****@*****.**',
            'address': 'kyoto',
        }]
        self.restaurants = []
        for r in restaurants:
            rest = Restaurant(**r)
            rest.save()
            self.restaurants.append(rest)
Esempio n. 5
0
    def setUp(self):
        super(TestBase, self).setUp()

        if not self.config_file:
            self.skipTest("No config specified")

        self.conf.register_opts(default.ALL_OPTS)
        self.conf.register_opts(transport.ALL_OPTS,
                                group=transport.GROUP_NAME)
        self.transport_cfg = self.conf[transport.GROUP_NAME]

        self.conf.register_opts(drivers_transport_wsgi.ALL_OPTS,
                                group=drivers_transport_wsgi.GROUP_NAME)
        self.wsgi_cfg = self.conf[drivers_transport_wsgi.GROUP_NAME]

        self.conf.unreliable = True
        self.conf.admin_mode = True
        self.boot = bootstrap.Bootstrap(self.conf)
        self.addCleanup(self.boot.storage.close)
        self.addCleanup(self.boot.control.close)

        self.app = self.boot.transport.app

        self.srmock = ftest.StartResponseMock()

        self.headers = {
            'Client-ID': uuidutils.generate_uuid(),
            'X-ROLES': 'admin',
            'X-USER-ID': 'a12d157c7d0d41999096639078fd11fc',
            'X-TENANT-ID': 'abb69142168841fcaa2785791b92467f',
        }
Esempio n. 6
0
    def setUp(self):
        super(TestBase, self).setUp()

        if not self.config_file:
            self.skipTest("No config specified")

        self.conf.register_opts(bootstrap._GENERAL_OPTIONS)
        self.conf.register_opts(validation._TRANSPORT_LIMITS_OPTIONS,
                                group=validation._TRANSPORT_LIMITS_GROUP)
        self.transport_cfg = self.conf[validation._TRANSPORT_LIMITS_GROUP]

        self.conf.register_opts(driver._WSGI_OPTIONS, group=driver._WSGI_GROUP)
        self.wsgi_cfg = self.conf[driver._WSGI_GROUP]

        self.conf.unreliable = True
        self.conf.admin_mode = True
        self.boot = bootstrap.Bootstrap(self.conf)

        self.app = self.boot.transport.app

        self.srmock = ftest.StartResponseMock()

        self.headers = {
            'Client-ID': str(uuid.uuid4()),
        }
Esempio n. 7
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware', return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = menu.Collection()
        self.api.add_route('/restaurants', self.resource)
        self.srmock = testing.StartResponseMock()
        self.restaurants = [
            Restaurant(name='a', description='a', email='*****@*****.**',
                       address='Roppongi Hills, Mori Tower, Minato-ku, Tokyo',
                       geolocation=[139.729183, 35.660429]),  # exactly at Roppongi Hills Mori Tower
            Restaurant(name='z', description='z', email='*****@*****.**',
                       address='Nishi-Azabu, Minato-ku, Tokyo',
                       geolocation=[139.727553, 35.659599]),  # slightly away from Roppongi
        ]
        for r in self.restaurants:
            r.save()

        self.menus = [
            Menu(name='curry chicken', price=550, currency='JPY', images=[], tags=['chicken', 'curry'], restaurant=self.restaurants[0]),
            Menu(name='keema curry', price=700, currency='JPY', images=[], tags=['indian', 'curry'], restaurant=self.restaurants[0]),
            Menu(name='tempura don', price=600, currency='JPY', images=[], tags=['japanese', 'fried'], restaurant=self.restaurants[1]),
            Menu(name='chahan set', price=900, currency='JPY', images=[], tags=['fried', 'rice'], restaurant=self.restaurants[1]),
            Menu(name='yakisoba', price=400, currency='JPY', images=[], tags=['noodles'], restaurant=self.restaurants[1])
        ]
        for m in self.menus:
            m.save()
Esempio n. 8
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = restaurant.Collection()
        self.api.add_route('/restaurants', self.resource)
        self.srmock = testing.StartResponseMock()
 def simulate_request(self, method, path, **kwargs):
     self.srmock = ftest.StartResponseMock()
     headers = kwargs.get('headers', self.headers).copy()
     kwargs['method'] = method
     kwargs['headers'] = headers
     return self.app(
         ftest.create_environ(path=path, protocol='HTTP/1.1', **kwargs),
         self.srmock)
Esempio n. 10
0
    def setUp(self):
        super(TestCreateQueue, self).setUp()

        conf_file = self.conf_path('wsgi_reference.conf')
        boot = marconi.Bootstrap(conf_file)

        self.app = boot.transport.app
        self.srmock = testing.StartResponseMock()
    def setUp(self):
        super(TestBase, self).setUp()

        import dynamicNetworkConfig
        dynamicNetworkConfig.context = DummyContext()

        self.app = Driver().app
        self.srmock = ftest.StartResponseMock()
        self.headers = {}
Esempio n. 12
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = rating.Item()
        self.api.add_route('/ratings/menus/{id}', self.resource)
        self.srmock = testing.StartResponseMock()

        self.setup_common_resources_DB()
Esempio n. 13
0
 def app_setup(self, hooks):
     endpoints = [
         ('/v1.0', v1_0.public_endpoints()),
     ]
     self.app = falcon.API(before=hooks)
     for version_path, endpoints in endpoints:
         for route, resource in endpoints:
             self.app.add_route(version_path + route, resource)
     self.srmock = ftest.StartResponseMock()
     self.headers = {}
Esempio n. 14
0
    def _simulate_request(self,
                          url,
                          method='GET',
                          data=None,
                          headers=None,
                          params=None):
        """Simulate a request.

        Simulates a WSGI request to the API for testing.

        :param url: Request path for the desired resource
        :param method: (Default 'GET') The HTTP method to send
        :param data: (Default None) A dict that will be serialized
            to JSON and submitted as the body of the request. May
            also be a pre-serialized string.
        :param headers: (Default None) A dict containing
            extra HTTP headers to send.
        :param params: (Default None) A dict of parameters
            to use in the query string for the request.

        :returns: a requests response instance
        """

        if headers is None:
            headers = self.headers

        headers = self._sanitize_headers(headers)

        if data is None:
            body = ''
        elif isinstance(data, str) or isinstance(data, six.text_type):
            body = data
        else:
            body = json.dumps(data, ensure_ascii=False)

        parsed_url = six.moves.urllib_parse.urlparse(url)

        query = parsed_url.query

        if params is not None:
            extra = '&'.join(
                [key + '=' + str(value) for key, value in params.items()])

            query += '&' + extra

        environ = ftest.create_environ(method=method,
                                       path=parsed_url.path,
                                       query_string=query,
                                       headers=headers,
                                       body=body)

        srmock = ftest.StartResponseMock()
        wsgi_result = self.app(environ, srmock)

        return ResponseMock(srmock, wsgi_result)
Esempio n. 15
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware', return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = menu.Collection()
        self.api.add_route('/restaurants', self.resource)
        self.srmock = testing.StartResponseMock()
        self.restaurant = Restaurant(name='a', description='a', email='*****@*****.**',
                                     address='Roppongi Hills, Mori Tower, Minato-ku, Tokyo',
                                     geolocation=[139.729183, 35.660429])
        self.restaurant.save()
Esempio n. 16
0
    def setUp(self):
        super(TestBase, self).setUp()

        if self.config_filename is None:
            self.skipTest('No config specified')

        conf_file = self.conf_path(self.config_filename)
        boot = marconi.Bootstrap(conf_file)

        self.app = boot.transport.app
        self.srmock = testing.StartResponseMock()
Esempio n. 17
0
def create_bench(name, env):
    srmock = helpers.StartResponseMock()

    function = name.lower().replace('-', '_')
    app = eval('create.{0}(BODY, HEADERS)'.format(function))

    def bench():
        app(env, srmock)
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    return bench
    def simulate(protocol, headers=None):
        env = testing.create_environ(
            method='GET',
            scheme=protocol,
            path=_TEST_PATH,
            query_string='',
            headers=headers,
        )

        srmock = testing.StartResponseMock()
        iterable = app(env, srmock)

        return testing.Result(iterable, srmock.status, srmock.headers)
Esempio n. 19
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware', return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = menu.Item()
        self.api.add_route('/menus/{id}', self.resource)
        self.srmock = testing.StartResponseMock()

        self.menus = [
            Menu(name='curry chicken', price=550, currency='JPY', images=[], tags=['chicken', 'curry']),
            Menu(name='keema curry', price=700, currency='JPY', images=[], tags=['indian', 'curry'])
        ]
        for m in self.menus:
            m.save()
Esempio n. 20
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = restaurant.Item()
        self.api.add_route('/restaurants/{id}', self.resource)
        self.srmock = testing.StartResponseMock()
        self.restaurant = None
        rst = Restaurant(name='a',
                         description='desc',
                         email='*****@*****.**',
                         address='Asakusa, Taito-ku, Tokyo',
                         geolocation=[139.79843, 35.712074])

        self.restaurant = rst.save()
Esempio n. 21
0
    def setUp(self):
        self.api = get_test_snakebite().app
        self.resource = status.Status()
        self.api.add_route('/status', self.resource)
        self.srmock = testing.StartResponseMock()

        users = [
            User(first_name='Clarke',
                 last_name='Kent',
                 display_name='Clarke Kent',
                 email='*****@*****.**',
                 role=Role.USER)
        ]
        self.users = []
        for user in users:
            user.save()
            self.users.append(user)
Esempio n. 22
0
    def simulate_request(self, path, **kwargs):
        """Simulate a request.

        Simulates a WSGI request to the API for testing.

        :param path: Request path for the desired resource
        :param kwargs: Same as falcon.testing.create_environ()

        :returns: standard WSGI iterable response
        """

        self.srmock = ftest.StartResponseMock()
        headers = kwargs.get('headers', self.headers).copy()
        kwargs['headers'] = headers
        return self.app(
            ftest.create_environ(path=path, protocol='HTTP/1.0', **kwargs),
            self.srmock)
Esempio n. 23
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware', return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = menu.Item()
        self.api.add_route('/menus/{id}', self.resource)
        self.srmock = testing.StartResponseMock()
        self.menu = None
        mnu = Menu(
            name='menu1',
            price=500,
            currency='JPY',
            tags=['chicken', 'curry'],
            images=[]
        )

        self.menu = mnu.save()
Esempio n. 24
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = rating.Collection()
        self.api.add_route('/rating/menus', self.resource)
        self.srmock = testing.StartResponseMock()

        self.setup_common_resources_DB()

        self.ratings = [
            MenuRating(user=self.users[0], menu=self.menus[0], rating=4.0),
            MenuRating(user=self.users[1], menu=self.menus[1], rating=2.0),
            MenuRating(user=self.users[0], menu=self.menus[1], rating=5.0)
        ]
        for r in self.ratings:
            r.save()
Esempio n. 25
0
def create_bench(name, env):
    srmock = helpers.StartResponseMock()

    function = name.lower().replace('-', '_')
    app = eval('create.{0}(BODY, HEADERS)'.format(function))

    def bench():
        app(env, srmock)
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    def bench_generator():
        exhaust(app(env, srmock))
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    if inspect.isgeneratorfunction(app):
        return bench_generator
    else:
        return bench
Esempio n. 26
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
Esempio n. 27
0
    def setUp(self):
        super(TestBase, self).setUp()

        import deuce
        deuce.context = DummyContextObject()
        deuce.context.project_id = self.create_project_id()
        deuce.context.openstack = DummyContextObject()
        deuce.context.openstack.auth_token = self.create_auth_token()
        deuce.context.openstack.swift = DummyContextObject()
        deuce.context.openstack.swift.storage_url = 'storage.url'

        # Override the storage locations
        # This is required for environments that run multiple tests
        # at the same time, e.g. tox -e py34 in one shell and
        # tox -e py33 in another shell simultaneously, f.e Jenkins
        deuce.conf.block_storage_driver.disk.path = \
            test_disk_storage_location

        self.app = Driver().app
        self.srmock = ftest.StartResponseMock()
        self.headers = {}
Esempio n. 28
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = tag.Collection()
        self.api.add_route('/tags', self.resource)
        self.srmock = testing.StartResponseMock()
        self.tags = [
            'buzzword', 'hipster', 'trending', 'barely trending', 'classic',
            'safe', 'weird', 'regrettable'
        ]

        for i in range(len(self.tags)):
            r = Menu(name='Menu #{}'.format(i),
                     price=200.00,
                     currency='JPY',
                     images=['http://example.com/1.jpg'],
                     tags=[])
            r.tags = self.tags[:-i] if i else self.tags  # first restaurant has more tags than the next
            r.save()
Esempio n. 29
0
    def setUp(self):
        with mock.patch('snakebite.JWTAuthMiddleware',
                        return_value=get_mock_auth_middleware()):
            self.api = get_test_snakebite().app

        self.resource = restaurant.Collection()
        self.api.add_route('/restaurants', self.resource)
        self.srmock = testing.StartResponseMock()
        self.restaurants = [
            Restaurant(name='a',
                       description='desc',
                       email='*****@*****.**',
                       address='Asakusa, Taito-ku, Tokyo',
                       geolocation=[139.79843, 35.712074]),
            Restaurant(name='b',
                       description='description',
                       email='*****@*****.**',
                       address='Roppongi, Minato-ku, Tokyo',
                       geolocation=[139.731443, 35.662836])
        ]
        for r in self.restaurants:
            r.save()
Esempio n. 30
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)