def test_bogus_method(self, client, resource_things): client.app.add_route('/things', resource_things) client.app.add_route('/things/{id}/stuff/{sid}', resource_things) response = client.simulate_request(path='/things', method=testing.rand_string(3, 4)) assert not resource_things.called assert response.status == falcon.HTTP_400
class HelloResource: sample_status = '200 OK' sample_unicode = (u'Hello World! \x80' + six.text_type(testing.rand_string(0, 0))) sample_utf8 = sample_unicode.encode('utf-8') def __init__(self, mode): self.called = False self.mode = mode def on_get(self, req, resp): self.called = True self.req, self.resp = req, resp resp.status = falcon.HTTP_200 if 'stream' in self.mode: resp.stream = io.BytesIO(self.sample_utf8) if 'stream_len' in self.mode: resp.stream_len = len(self.sample_utf8) if 'body' in self.mode: if 'bytes' in self.mode: resp.body = self.sample_utf8 else: resp.body = self.sample_unicode if 'data' in self.mode: resp.data = self.sample_utf8 def on_head(self, req, resp): self.on_get(req, resp)
def test_post_read_bounded_stream(self, server_base_url): body = testing.rand_string(_SIZE_1_KB / 2, _SIZE_1_KB) resp = requests.post(server_base_url + 'bucket', data=body, timeout=_REQUEST_TIMEOUT) assert resp.status_code == 200 assert resp.text == body
def test_should_fail_too_long_name(self): name = testing.rand_string(256, 260) dimensions = {name: 1} err = self.assertRaises(exceptions.HTTPUnprocessableEntity, validation.validate_dimensions, dimensions) msg = 'Dimension name %s must be 255 characters or less' % name self.assertEqual(err.description, msg)
def __init__(self): self.sample_utf8 = testing.rand_string(8 * SIZE_1_KB, 16 * SIZE_1_KB).encode() fh, self.tempfile_name = tempfile.mkstemp() with open(fh, 'wb') as f: f.write(self.sample_utf8) self._aiofiles = None
def test_should_fail_too_long_name(self): name = testing.rand_string(256, 260) dimensions = {name: 1} with self.assertRaises(exceptions.HTTPUnprocessableEntity) as context: common_service.Validations.validate_dimensions(dimensions) msg = 'Dimension name %s must be 255 characters or less' % name self.assertEqual(context.exception.description, msg)
def test_body_stream_wrapper(self): data = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) expected_body = data.encode('utf-8') expected_len = len(expected_body) # NOTE(kgriffs): Append newline char to each line # to match readlines behavior expected_lines = [(line + '\n').encode('utf-8') for line in data.split('\n')] # NOTE(kgriffs): Remove trailing newline to simulate # what readlines does expected_lines[-1] = expected_lines[-1][:-1] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.read(), expected_body) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.read(2), expected_body[0:2]) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.read(expected_len + 1), expected_body) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.readline(), expected_lines[0]) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.readline(-1), expected_lines[0]) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.readline(expected_len + 1), expected_lines[0]) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.readlines(), expected_lines) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.readlines(-1), expected_lines) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(body.readlines(expected_len + 1), expected_lines) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) self.assertEqual(next(body), expected_lines[0]) stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) for i, line in enumerate(body): self.assertEqual(line, expected_lines[i])
class StatusTestResource: sample_body = testing.rand_string(0, 128 * 1024) def __init__(self, status): self.status = status def on_get(self, req, resp): resp.status = self.status resp.body = self.sample_body
def test_should_fail_ok_name_too_long_value(self): name = 'monasca' value = testing.rand_string(256, 300) dimensions = {name: value} with self.assertRaises(exceptions.HTTPUnprocessableEntity) as context: validation.validate_dimensions(dimensions) msg = 'Dimension value %s must be 255 characters or less' % value self.assertEqual(context.exception.description, msg)
def test_should_fail_ok_name_too_long_value(self): name = 'monasca' value = testing.rand_string(256, 300) dimensions = {name: value} err = self.assertRaises(exceptions.HTTPUnprocessableEntity, validation.validate_dimensions, dimensions) msg = 'Dimension value %s must be 255 characters or less' % value self.assertEqual(err.description, msg)
def test_should_fail_for_invalid_length(self): r_app_type = testing.rand_string(300, 600) with self.assertRaises(exceptions.HTTPUnprocessableEntity) as context: validation.validate_application_type(r_app_type) length = validation.APPLICATION_TYPE_CONSTRAINTS['MAX_LENGTH'] msg = ('Application type {type} must be ' '{length} characters or less'.format(type=r_app_type, length=length)) self.assertEqual(context.exception.description, msg)
def test_should_fail_for_invalid_length(self): r_app_type = testing.rand_string(300, 600) with self.assertRaises(exceptions.HTTPUnprocessableEntity) as context: common_service.Validations.validate_application_type(r_app_type) length = common_service.APPLICATION_TYPE_CONSTRAINTS['MAX_LENGTH'] msg = ('Application type {type} must be ' '{length} characters or less'.format(type=r_app_type, length=length)) self.assertEqual(context.exception.description, msg)
def test_post_multiple(self, server_base_url): body = testing.rand_string(_SIZE_1_KB // 2, _SIZE_1_KB) resp = requests.post(server_base_url, data=body, timeout=_REQUEST_TIMEOUT) assert resp.status_code == 200 assert resp.text == body assert resp.headers['X-Counter'] == '0' time.sleep(1) resp = requests.post(server_base_url, data=body, timeout=_REQUEST_TIMEOUT) assert resp.headers['X-Counter'] == '2002'
def create_bench(name): srmock = helpers.StartResponseMock() env = helpers.create_environ('/hello/584/test', query_string='limit=10') 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
class HelloResource: sample_status = '200 OK' sample_unicode = 'Hello World! \x80 - ' + testing.rand_string(0, 5) sample_utf8 = sample_unicode.encode('utf-8') def __init__(self, mode): self.called = False self.mode = mode async def on_get(self, req, resp): self.called = True self.req, self.resp = req, resp resp.status = falcon.HTTP_200 if 'stream' in self.mode: if 'filelike' in self.mode: stream = DataReader(self.sample_utf8) else: async def data_emitter(): for b in self.sample_utf8: yield bytes([b]) if 'stream_genfunc' in self.mode: stream = data_emitter elif 'stream_nongenfunc' in self.mode: stream = 42 else: stream = data_emitter() if 'stream_len' in self.mode: stream_len = len(self.sample_utf8) else: stream_len = None if 'use_helper' in self.mode: resp.set_stream(stream, stream_len) else: resp.stream = stream resp.content_length = stream_len if 'body' in self.mode: if 'bytes' in self.mode: resp.text = self.sample_utf8 else: resp.text = self.sample_unicode if 'data' in self.mode: resp.data = self.sample_utf8 async def on_head(self, req, resp): await self.on_get(req, resp)
class ClosingFilelikeHelloResource: sample_status = '200 OK' sample_unicode = 'Hello World! \x80' + testing.rand_string(0, 0) sample_utf8 = sample_unicode.encode('utf-8') def __init__(self, stream_factory): self.called = False self.stream = stream_factory(self.sample_utf8) self.stream_len = len(self.sample_utf8) def on_get(self, req, resp): self.called = True self.req, self.resp = req, resp resp.status = falcon.HTTP_200 resp.set_stream(self.stream, self.stream_len)
class HelloResource(object): sample_status = '200 OK' sample_unicode = (u'Hello World! \x80' + compat.text_type(testing.rand_string(0, 0))) sample_utf8 = sample_unicode.encode('utf-8') def __init__(self, mode): self.called = False self.mode = mode def on_get(self, req, resp): self.called = True self.req, self.resp = req, resp resp.status = falcon.HTTP_200 if 'stream' in self.mode: if 'filelike' in self.mode: stream = io.BytesIO(self.sample_utf8) else: stream = [self.sample_utf8] if 'stream_len' in self.mode: stream_len = len(self.sample_utf8) else: stream_len = None if 'use_helper' in self.mode: resp.set_stream(stream, stream_len) else: resp.stream = stream resp.stream_len = stream_len if 'body' in self.mode: if 'bytes' in self.mode: resp.body = self.sample_utf8 else: resp.body = self.sample_unicode if 'data' in self.mode: resp.data = self.sample_utf8 def on_head(self, req, resp): self.on_get(req, resp)
def test_read_body(self, client, resource): client.app.add_route('/', resource) expected_body = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) expected_len = len(expected_body) headers = { 'Content-Length': str(expected_len), 'Capture-Req-Body-Bytes': '-1', } client.simulate_request(path='/', body=expected_body, headers=headers) content_len = resource.captured_req.get_header('content-length') assert content_len == str(expected_len) stream = resource.captured_req.stream assert resource.captured_req_body == expected_body.encode('utf-8') assert stream.tell() == expected_len
def test_read_body(self): expected_body = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) expected_len = len(expected_body) headers = {'Content-Length': str(expected_len)} self.simulate_request('', body=expected_body, headers=headers) content_len = self.resource.req.get_header('content-length') self.assertEqual(content_len, str(expected_len)) stream = self.resource.req.stream actual_body = stream.read() self.assertEqual(actual_body, expected_body.encode('utf-8')) stream.seek(0, 2) self.assertEqual(stream.tell(), expected_len) self.assertEqual(stream.tell(), expected_len)
def test_read_body(self): expected_body = testing.rand_string(2, 1 * 1024 * 1024) expected_len = len(expected_body) headers = {'Content-Length': str(expected_len)} self.simulate_request('', body=expected_body, headers=headers) content_len = self.resource.req.get_header('content-length') self.assertEqual(content_len, str(expected_len)) stream = self.resource.req.stream actual_body = stream.read() self.assertEquals(actual_body, expected_body.encode('utf-8')) stream.seek(0, 2) self.assertEquals(stream.tell(), expected_len) self.assertEquals(stream.tell(), expected_len)
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
def test_read_body(self, client, resource): client.app.add_route('/', resource) expected_body = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) expected_len = len(expected_body) headers = {'Content-Length': str(expected_len)} client.simulate_request(path='/', body=expected_body, headers=headers) content_len = resource.captured_req.get_header('content-length') assert content_len == str(expected_len) stream = self._get_wrapped_stream(resource.captured_req) actual_body = stream.read() assert actual_body == expected_body.encode('utf-8') stream.seek(0, 2) assert stream.tell() == expected_len assert stream.tell() == expected_len
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
def test_iteration_already_started(): body = testing.rand_string(1, 2048).encode() s = _stream(body) async def t(): stream_iter = s.__aiter__() chunks = [await stream_iter.__anext__()] with pytest.raises(ValueError): stream_iter2 = s.__aiter__() await stream_iter2.__anext__() while True: try: chunks.append(await stream_iter.__anext__()) except StopAsyncIteration: break assert b''.join(chunks) == body falcon.invoke_coroutine_sync(t)
def test_read_socket_body(self): expected_body = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) def server(): class Echo(object): def on_post(self, req, resp): # wsgiref socket._fileobject blocks when len not given, # but Falcon is smarter than that. :D body = req.stream.read() resp.body = body def on_put(self, req, resp): # wsgiref socket._fileobject blocks when len too long, # but Falcon should work around that for me. body = req.stream.read(req.content_length + 1) resp.body = body api = falcon.API() api.add_route('/echo', Echo()) httpd = simple_server.make_server('127.0.0.1', 8989, api) httpd.serve_forever() process = multiprocessing.Process(target=server) process.daemon = True process.start() # Let it boot process.join(1) url = 'http://127.0.0.1:8989/echo' resp = requests.post(url, data=expected_body) self.assertEquals(resp.text, expected_body) resp = requests.put(url, data=expected_body) self.assertEquals(resp.text, expected_body) process.terminate()
def test_read_socket_body(self): expected_body = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) def server(): class Echo(object): def on_post(self, req, resp): # wsgiref socket._fileobject blocks when len not given, # but Falcon is smarter than that. :D body = req.stream.read() resp.body = body def on_put(self, req, resp): # wsgiref socket._fileobject blocks when len too long, # but Falcon should work around that for me. body = req.stream.read(req.content_length + 1) resp.body = body api = falcon.API() api.add_route('/echo', Echo()) httpd = simple_server.make_server('127.0.0.1', 8989, api) httpd.serve_forever() process = multiprocessing.Process(target=server) process.daemon = True process.start() # Let it boot process.join(1) url = 'http://127.0.0.1:8989/echo' resp = requests.post(url, data=expected_body) self.assertEqual(resp.text, expected_body) resp = requests.put(url, data=expected_body) self.assertEqual(resp.text, expected_body) process.terminate()
def setUp(self): super(TestHeaders, self).setUp() self.sample_body = testing.rand_string(0, 128 * 1024) self.resource = testing.SimpleTestResource(body=self.sample_body) self.api.add_route('/', self.resource)
import os import pytest import falcon from falcon import asgi, testing @pytest.mark.parametrize('body', [ b'', b'\x00', b'\x00\xFF', b'catsup', b'\xDE\xAD\xBE\xEF' * 512, testing.rand_string(1, 2048), os.urandom(100 * 2**20), ], ids=[ 'empty', 'null', 'null-ff', 'normal', 'long', 'random', 'random-large' ]) @pytest.mark.parametrize('extra_body', [True, False]) @pytest.mark.parametrize('set_content_length', [True, False]) def test_read_all(body, extra_body, set_content_length): if extra_body and not set_content_length: pytest.skip( 'extra_body ignores set_content_length so we only need to test ' 'one of the parameter permutations') expected_body = body if isinstance(body, bytes) else body.encode()
# NOTE(kgriffs): Based on testing, these values provide a ceiling that's # several times higher than fast x86 hardware can achieve today. ITER_DETECTION_MAX_ATTEMPTS = 27 ITER_DETECTION_MULTIPLIER = 1.7 ITER_DETECTION_STARTING = 3000 # NOTE(kgriffs): Benchmark duration range, in seconds, to target ITER_DETECTION_DURATION_MIN = 1.0 ITER_DETECTION_DURATION_MAX = 6.0 JIT_WARMING_MULTIPLIER = 30 PYPY = platform.python_implementation() == 'PyPy' BODY = helpers.rand_string(10240, 10240).encode('utf-8') # NOQA HEADERS = {'X-Test': 'Funky Chicken'} # NOQA class StartResponseMockLite(object): """Mock object representing a WSGI `start_response` callable.""" def __init__(self): self._called = 0 self.status = None self.headers = None self.exc_info = None def __call__(self, status, headers, exc_info=None): """Implements the PEP-3333 `start_response` protocol."""
if verbose: if pprofile is None: print('pprofile not found. Please install pprofile and try again.') return pprofile.runctx(code, locals(), globals(), filename=filename) else: cProfile.runctx(code, locals(), globals(), sort='tottime', filename=filename) BODY = helpers.rand_string(10240, 10240) # NOQA HEADERS = {'X-Test': 'Funky Chicken'} # NOQA 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
from collections import defaultdict from datetime import datetime import pytest import falcon from falcon import testing SAMPLE_BODY = testing.rand_string(0, 128 * 1024) @pytest.fixture def client(): app = falcon.API() return testing.TestClient(app) class XmlResource: def __init__(self, content_type): self.content_type = content_type def on_get(self, req, resp): resp.set_header('content-type', self.content_type) class HeaderHelpersResource: def __init__(self, last_modified=None): if last_modified is not None: self.last_modified = last_modified
def test_post(self): body = testing.rand_string(_SIZE_1_KB // 2, _SIZE_1_KB) resp = requests.post(_SERVER_BASE_URL, data=body) assert resp.status_code == 200 assert resp.text == body
from falcon.constants import PYPY import falcon.testing as helpers # NOTE(kgriffs): Based on testing, these values provide a ceiling that's # several times higher than fast x86 hardware can achieve today. ITER_DETECTION_MAX_ATTEMPTS = 27 ITER_DETECTION_MULTIPLIER = 1.7 ITER_DETECTION_STARTING = 3000 # NOTE(kgriffs): Benchmark duration range, in seconds, to target ITER_DETECTION_DURATION_MIN = 1.0 ITER_DETECTION_DURATION_MAX = 6.0 JIT_WARMING_MULTIPLIER = 30 BODY = helpers.rand_string(10240, 10240).encode('utf-8') # NOQA HEADERS = {'X-Test': 'Funky Chicken'} # NOQA class StartResponseMockLite: """Mock object representing a WSGI `start_response` callable.""" def __init__(self): self._called = 0 self.status = None self.headers = None self.exc_info = None def __call__(self, status, headers, exc_info=None): """Implement the PEP-3333 `start_response` protocol.""" self._called += 1
from collections import defaultdict from datetime import datetime import pytest import falcon from falcon import testing from falcon.util import compat SAMPLE_BODY = testing.rand_string(0, 128 * 1024) @pytest.fixture def client(): app = falcon.API() return testing.TestClient(app) class XmlResource(object): def __init__(self, content_type): self.content_type = content_type def on_get(self, req, resp): resp.set_header('content-type', self.content_type) class HeaderHelpersResource(object): def __init__(self, last_modified=None): if last_modified is not None: self.last_modified = last_modified else:
def test_post_read_bounded_stream(self): body = testing.rand_string(_SIZE_1_KB / 2, _SIZE_1_KB) resp = requests.post(_SERVER_BASE_URL + 'bucket', data=body) assert resp.status_code == 200 assert resp.text == body
gc.collect() code = 'for x in range(10000): func()' if verbose: if pprofile is None: print('pprofile not found. Please install pprofile and try again.') return pprofile.runctx(code, locals(), globals(), filename=filename) else: cProfile.runctx(code, locals(), globals(), sort='tottime', filename=filename) BODY = helpers.rand_string(10240, 10240) # NOQA HEADERS = {'X-Test': 'Funky Chicken'} # NOQA 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 test_body_stream_wrapper(self): data = testing.rand_string(SIZE_1_KB / 2, SIZE_1_KB) expected_body = data.encode('utf-8') expected_len = len(expected_body) # NOTE(kgriffs): Append newline char to each line # to match readlines behavior expected_lines = [(line + '\n').encode('utf-8') for line in data.split('\n')] # NOTE(kgriffs): Remove trailing newline to simulate # what readlines does expected_lines[-1] = expected_lines[-1][:-1] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.read() == expected_body stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.read(2) == expected_body[0:2] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.read(expected_len + 1) == expected_body # NOTE(kgriffs): Test that reading past the end does not # hang, but returns the empty string. stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) for i in range(expected_len + 1): expected_value = expected_body[i:i + 1] if i < expected_len else b'' assert body.read(1) == expected_value stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.readline() == expected_lines[0] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.readline(-1) == expected_lines[0] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.readline(expected_len + 1) == expected_lines[0] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.readlines() == expected_lines stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.readlines(-1) == expected_lines stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert body.readlines(expected_len + 1) == expected_lines stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) assert next(body) == expected_lines[0] stream = io.BytesIO(expected_body) body = request_helpers.Body(stream, expected_len) for i, line in enumerate(body): assert line == expected_lines[i]