diff --git a/docs/sanic/testing.md b/docs/sanic/testing.md index 79c719e8..8ea4a2b7 100644 --- a/docs/sanic/testing.md +++ b/docs/sanic/testing.md @@ -1,51 +1,73 @@ # Testing -Sanic endpoints can be tested locally using the `sanic.utils` module, which +Sanic endpoints can be tested locally using the `test_client` object, which depends on the additional [aiohttp](https://aiohttp.readthedocs.io/en/stable/) -library. The `sanic_endpoint_test` function runs a local server, issues a -configurable request to an endpoint, and returns the result. It takes the -following arguments: +library. -- `app` An instance of a Sanic app. -- `method` *(default `'get'`)* A string representing the HTTP method to use. -- `uri` *(default `'/'`)* A string representing the endpoint to test. +The `test_client` exposes `get`, `post`, `put`, `delete`, `patch`, `head` and `options` methods +for you to run against your application. A simple example (using pytest) is like follows: + +```python +# Import the Sanic app, usually created with Sanic(__name__) +from external_server import app + +def test_index_returns_200(): + request, response = app.test_client.get('/') + assert response.status == 200 + +def test_index_put_not_allowed(): + request, response = app.test_client.put('/') + assert response.status == 405 +``` + +Internally, each time you call one of the `test_client` methods, the Sanic app is run at `127.0.01:42101` and +your test request is executed against your application, using `aiohttp`. + +The `test_client` methods accept the following arguments and keyword arguments: + +- `uri` *(default `'/'`)* A string representing the URI to test. - `gather_request` *(default `True`)* A boolean which determines whether the original request will be returned by the function. If set to `True`, the return value is a tuple of `(request, response)`, if `False` only the response is returned. -- `loop` *(default `None`)* The event loop to use. -- `debug` *(default `False`)* A boolean which determines whether to run the - server in debug mode. +- `server_kwargs` *(default `{}`) a dict of additional arguments to pass into `app.run` before the test request is run. +- `debug` *(default `False`)* A boolean which determines whether to run the server in debug mode. -The function further takes the `*request_args` and `**request_kwargs`, which -are passed directly to the aiohttp ClientSession request. For example, to -supply data with a GET request, `method` would be `get` and the keyword -argument `params={'value', 'key'}` would be supplied. More information about +The function further takes the `*request_args` and `**request_kwargs`, which are passed directly to the aiohttp ClientSession request. + +For example, to supply data to a GET request, you would do the following: + +```python +def test_get_request_includes_data(): + params = {'key1': 'value1', 'key2': 'value2'} + request, response = app.test_client.get('/', params=params) + assert request.args.get('key1') == 'value1' +``` + +And to supply data to a JSON POST request: + +```python +def test_post_json_request_includes_data(): + data = {'key1': 'value1', 'key2': 'value2'} + request, response = app.test_client.post('/', data=json.dumps(data)) + assert request.json.get('key1') == 'value1' +``` + + +More information about the available arguments to aiohttp can be found [in the documentation for ClientSession](https://aiohttp.readthedocs.io/en/stable/client_reference.html#client-session). -Below is a complete example of an endpoint test, -using [pytest](http://doc.pytest.org/en/latest/). The test checks that the -`/challenge` endpoint responds to a GET request with a supplied challenge -string. -```python -import pytest -import aiohttp +### Deprecated: `sanic_endpoint_test` + +Prior to version 0.3.2, testing was provided through the `sanic_endpoint_test` method. This method will be deprecated in the next major version after 0.4.0; please use the `test_client` instead. + +``` from sanic.utils import sanic_endpoint_test -# Import the Sanic app, usually created with Sanic(__name__) -from external_server import app - -def test_endpoint_challenge(): - # Create the challenge data - request_data = {'challenge': 'dummy_challenge'} - - # Send the request to the endpoint, using the default `get` method - request, response = sanic_endpoint_test(app, - uri='/challenge', - params=request_data) - - # Assert that the server responds with the challenge string - assert response.text == request_data['challenge'] +def test_index_returns_200(): + request, response = sanic_endpoint_test(app) + assert response.status == 200 ``` + diff --git a/sanic/sanic.py b/sanic/sanic.py index 45bf0653..e92aab07 100644 --- a/sanic/sanic.py +++ b/sanic/sanic.py @@ -17,6 +17,7 @@ from .response import HTTPResponse from .router import Router from .server import serve, serve_multiple, HttpProtocol from .static import register as static_register +from .testing import TestClient from .views import CompositionView @@ -409,6 +410,14 @@ class Sanic: response_callback(response) + # -------------------------------------------------------------------- # + # Testing + # -------------------------------------------------------------------- # + + @property + def test_client(self): + return TestClient(self) + # -------------------------------------------------------------------- # # Execution # -------------------------------------------------------------------- # diff --git a/sanic/testing.py b/sanic/testing.py new file mode 100644 index 00000000..52e70f5a --- /dev/null +++ b/sanic/testing.py @@ -0,0 +1,91 @@ +from sanic.log import log + +HOST = '127.0.0.1' +PORT = 42101 + + +class TestClient: + def __init__(self, app): + self.app = app + + async def _local_request(self, method, uri, cookies=None, *args, **kwargs): + import aiohttp + if uri.startswith(('http:', 'https:', 'ftp:', 'ftps://' '//')): + url = uri + else: + url = 'http://{host}:{port}{uri}'.format( + host=HOST, port=PORT, uri=uri) + + log.info(url) + async with aiohttp.ClientSession(cookies=cookies) as session: + async with getattr( + session, method.lower())(url, *args, **kwargs) as response: + response.text = await response.text() + response.body = await response.read() + return response + + def _sanic_endpoint_test( + self, method='get', uri='/', gather_request=True, + debug=False, server_kwargs={}, + *request_args, **request_kwargs): + results = [None, None] + exceptions = [] + + if gather_request: + def _collect_request(request): + if results[0] is None: + results[0] = request + self.app.request_middleware.appendleft(_collect_request) + + @self.app.listener('after_server_start') + async def _collect_response(sanic, loop): + try: + response = await self._local_request( + method, uri, *request_args, + **request_kwargs) + results[-1] = response + except Exception as e: + exceptions.self.append(e) + self.app.stop() + + self.app.run(host=HOST, debug=debug, port=PORT, **server_kwargs) + self.app.listeners['after_server_start'].pop() + + if exceptions: + raise ValueError("Exception during request: {}".format(exceptions)) + + if gather_request: + try: + request, response = results + return request, response + except: + raise ValueError( + "Request and response object expected, got ({})".format( + results)) + else: + try: + return results[-1] + except: + raise ValueError( + "Request object expected, got ({})".format(results)) + + def get(self, *args, **kwargs): + return self._sanic_endpoint_test('get', *args, **kwargs) + + def post(self, *args, **kwargs): + return self._sanic_endpoint_test('post', *args, **kwargs) + + def put(self, *args, **kwargs): + return self._sanic_endpoint_test('put', *args, **kwargs) + + def delete(self, *args, **kwargs): + return self._sanic_endpoint_test('delete', *args, **kwargs) + + def patch(self, *args, **kwargs): + return self._sanic_endpoint_test('patch', *args, **kwargs) + + def options(self, *args, **kwargs): + return self._sanic_endpoint_test('options', *args, **kwargs) + + def head(self, *args, **kwargs): + return self._sanic_endpoint_test('head', *args, **kwargs) diff --git a/sanic/utils.py b/sanic/utils.py index 890a2af5..0aa4b33c 100644 --- a/sanic/utils.py +++ b/sanic/utils.py @@ -1,64 +1,16 @@ -import aiohttp -from sanic.log import log - -HOST = '127.0.0.1' -PORT = 42101 - - -async def local_request(method, uri, cookies=None, *args, **kwargs): - if uri.startswith(('http:', 'https:', 'ftp:', 'ftps://' '//')): - url = uri - else: - url = 'http://{host}:{port}{uri}'.format(host=HOST, port=PORT, uri=uri) - - log.info(url) - async with aiohttp.ClientSession(cookies=cookies) as session: - async with getattr( - session, method.lower())(url, *args, **kwargs) as response: - response.text = await response.text() - response.body = await response.read() - return response +import warnings +from sanic.testing import TestClient def sanic_endpoint_test(app, method='get', uri='/', gather_request=True, - debug=False, server_kwargs={}, *request_args, - **request_kwargs): - results = [None, None] - exceptions = [] + debug=False, server_kwargs={}, + *request_args, **request_kwargs): + warnings.warn( + "Use of sanic_endpoint_test will be deprecated in" + "the next major version after 0.4.0. Please use the `test_client` " + "available on the app object.", DeprecationWarning) - if gather_request: - def _collect_request(request): - if results[0] is None: - results[0] = request - app.request_middleware.appendleft(_collect_request) - - @app.listener('after_server_start') - async def _collect_response(sanic, loop): - try: - response = await local_request(method, uri, *request_args, - **request_kwargs) - results[-1] = response - except Exception as e: - exceptions.append(e) - app.stop() - - app.run(host=HOST, debug=debug, port=PORT, **server_kwargs) - app.listeners['after_server_start'].pop() - - if exceptions: - raise ValueError("Exception during request: {}".format(exceptions)) - - if gather_request: - try: - request, response = results - return request, response - except: - raise ValueError( - "Request and response object expected, got ({})".format( - results)) - else: - try: - return results[-1] - except: - raise ValueError( - "Request object expected, got ({})".format(results)) + test_client = TestClient(app) + return test_client._sanic_endpoint_test( + method, uri, gather_request, debug, server_kwargs, + *request_args, **request_kwargs) diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index aebb7429..69d52737 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -3,7 +3,6 @@ import inspect from sanic import Sanic from sanic.blueprints import Blueprint from sanic.response import json, text -from sanic.utils import sanic_endpoint_test from sanic.exceptions import NotFound, ServerError, InvalidUsage @@ -20,7 +19,7 @@ def test_bp(): return text('Hello') app.blueprint(bp) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'Hello' @@ -33,7 +32,7 @@ def test_bp_with_url_prefix(): return text('Hello') app.blueprint(bp) - request, response = sanic_endpoint_test(app, uri='/test1/') + request, response = app.test_client.get('/test1/') assert response.text == 'Hello' @@ -53,10 +52,10 @@ def test_several_bp_with_url_prefix(): app.blueprint(bp) app.blueprint(bp2) - request, response = sanic_endpoint_test(app, uri='/test1/') + request, response = app.test_client.get('/test1/') assert response.text == 'Hello' - request, response = sanic_endpoint_test(app, uri='/test2/') + request, response = app.test_client.get('/test2/') assert response.text == 'Hello2' def test_bp_with_host(): @@ -73,13 +72,15 @@ def test_bp_with_host(): app.blueprint(bp) headers = {"Host": "example.com"} - request, response = sanic_endpoint_test(app, uri='/test1/', - headers=headers) + request, response = app.test_client.get( + '/test1/', + headers=headers) assert response.text == 'Hello' headers = {"Host": "sub.example.com"} - request, response = sanic_endpoint_test(app, uri='/test1/', - headers=headers) + request, response = app.test_client.get( + '/test1/', + headers=headers) assert response.text == 'Hello subdomain!' @@ -111,18 +112,21 @@ def test_several_bp_with_host(): assert bp.host == "example.com" headers = {"Host": "example.com"} - request, response = sanic_endpoint_test(app, uri='/test/', - headers=headers) + request, response = app.test_client.get( + '/test/', + headers=headers) assert response.text == 'Hello' assert bp2.host == "sub.example.com" headers = {"Host": "sub.example.com"} - request, response = sanic_endpoint_test(app, uri='/test/', - headers=headers) + request, response = app.test_client.get( + '/test/', + headers=headers) assert response.text == 'Hello2' - request, response = sanic_endpoint_test(app, uri='/test/other/', - headers=headers) + request, response = app.test_client.get( + '/test/other/', + headers=headers) assert response.text == 'Hello3' def test_bp_middleware(): @@ -139,7 +143,7 @@ def test_bp_middleware(): app.blueprint(blueprint) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.status == 200 assert response.text == 'OK' @@ -166,15 +170,15 @@ def test_bp_exception_handler(): app.blueprint(blueprint) - request, response = sanic_endpoint_test(app, uri='/1') + request, response = app.test_client.get('/1') assert response.status == 400 - request, response = sanic_endpoint_test(app, uri='/2') + request, response = app.test_client.get('/2') assert response.status == 200 assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/3') + request, response = app.test_client.get('/3') assert response.status == 200 def test_bp_listeners(): @@ -209,7 +213,7 @@ def test_bp_listeners(): app.blueprint(blueprint) - request, response = sanic_endpoint_test(app, uri='/') + request, response = app.test_client.get('/') assert order == [1,2,3,4,5,6] @@ -225,7 +229,7 @@ def test_bp_static(): app.blueprint(blueprint) - request, response = sanic_endpoint_test(app, uri='/testing.file') + request, response = app.test_client.get('/testing.file') assert response.status == 200 assert response.body == current_file_contents @@ -263,44 +267,44 @@ def test_bp_shorthand(): app.blueprint(blueprint) - request, response = sanic_endpoint_test(app, uri='/get', method='get') + request, response = app.test_client.get('/get') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/get', method='post') + request, response = app.test_client.post('/get') assert response.status == 405 - request, response = sanic_endpoint_test(app, uri='/put', method='put') + request, response = app.test_client.put('/put') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/put', method='get') + request, response = app.test_client.get('/post') assert response.status == 405 - request, response = sanic_endpoint_test(app, uri='/post', method='post') + request, response = app.test_client.post('/post') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/post', method='get') + request, response = app.test_client.get('/post') assert response.status == 405 - request, response = sanic_endpoint_test(app, uri='/head', method='head') + request, response = app.test_client.head('/head') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/head', method='get') + request, response = app.test_client.get('/head') assert response.status == 405 - request, response = sanic_endpoint_test(app, uri='/options', method='options') + request, response = app.test_client.options('/options') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/options', method='get') + request, response = app.test_client.get('/options') assert response.status == 405 - request, response = sanic_endpoint_test(app, uri='/patch', method='patch') + request, response = app.test_client.patch('/patch') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/patch', method='get') + request, response = app.test_client.get('/patch') assert response.status == 405 - request, response = sanic_endpoint_test(app, uri='/delete', method='delete') + request, response = app.test_client.delete('/delete') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/delete', method='get') + request, response = app.test_client.get('/delete') assert response.status == 405 diff --git a/tests/test_cookies.py b/tests/test_cookies.py index 19351fde..d88288ee 100644 --- a/tests/test_cookies.py +++ b/tests/test_cookies.py @@ -2,7 +2,6 @@ from datetime import datetime, timedelta from http.cookies import SimpleCookie from sanic import Sanic from sanic.response import json, text -from sanic.utils import sanic_endpoint_test import pytest @@ -19,7 +18,7 @@ def test_cookies(): response.cookies['right_back'] = 'at you' return response - request, response = sanic_endpoint_test(app, cookies={"test": "working!"}) + request, response = app.test_client.get('/', cookies={"test": "working!"}) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) @@ -40,7 +39,7 @@ def test_false_cookies(httponly, expected): response.cookies['right_back']['httponly'] = httponly return response - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) @@ -55,7 +54,7 @@ def test_http2_cookies(): return response headers = {'cookie': 'test=working!'} - request, response = sanic_endpoint_test(app, headers=headers) + request, response = app.test_client.get('/', headers=headers) assert response.text == 'Cookies are: working!' @@ -70,7 +69,7 @@ def test_cookie_options(): response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10) return response - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) @@ -88,7 +87,7 @@ def test_cookie_deletion(): del response.cookies['i_never_existed'] return response - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) diff --git a/tests/test_custom_protocol.py b/tests/test_custom_protocol.py index 88202428..74564012 100644 --- a/tests/test_custom_protocol.py +++ b/tests/test_custom_protocol.py @@ -1,7 +1,6 @@ from sanic import Sanic from sanic.server import HttpProtocol from sanic.response import text -from sanic.utils import sanic_endpoint_test app = Sanic('test_custom_porotocol') @@ -26,7 +25,7 @@ def test_use_custom_protocol(): server_kwargs = { 'protocol': CustomHttpProtocol } - request, response = sanic_endpoint_test(app, uri='/1', - server_kwargs=server_kwargs) + request, response = app.test_client.get( + '/1', server_kwargs=server_kwargs) assert response.status == 200 assert response.text == 'OK' diff --git a/tests/test_dynamic_routes.py b/tests/test_dynamic_routes.py index 24ba79b5..950584a8 100644 --- a/tests/test_dynamic_routes.py +++ b/tests/test_dynamic_routes.py @@ -1,6 +1,5 @@ from sanic import Sanic from sanic.response import text -from sanic.utils import sanic_endpoint_test from sanic.router import RouteExists import pytest @@ -22,8 +21,7 @@ def test_overload_dynamic_routes(method, attr, expected): async def handler2(request, param): return text('OK2 ' + param) - request, response = sanic_endpoint_test( - app, method, uri='/overload/test') + request, response = getattr(app.test_client, method)('/overload/test') assert getattr(response, attr) == expected diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 819d39f2..968369f8 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -4,7 +4,6 @@ from bs4 import BeautifulSoup from sanic import Sanic from sanic.response import text from sanic.exceptions import InvalidUsage, ServerError, NotFound -from sanic.utils import sanic_endpoint_test class SanicExceptionTestException(Exception): @@ -48,33 +47,32 @@ def exception_app(): def test_no_exception(exception_app): """Test that a route works without an exception""" - request, response = sanic_endpoint_test(exception_app) + request, response = exception_app.test_client.get('/') assert response.status == 200 assert response.text == 'OK' def test_server_error_exception(exception_app): """Test the built-in ServerError exception works""" - request, response = sanic_endpoint_test(exception_app, uri='/error') + request, response = exception_app.test_client.get('/error') assert response.status == 500 def test_invalid_usage_exception(exception_app): """Test the built-in InvalidUsage exception works""" - request, response = sanic_endpoint_test(exception_app, uri='/invalid') + request, response = exception_app.test_client.get('/invalid') assert response.status == 400 def test_not_found_exception(exception_app): """Test the built-in NotFound exception works""" - request, response = sanic_endpoint_test(exception_app, uri='/404') + request, response = exception_app.test_client.get('/404') assert response.status == 404 def test_handled_unhandled_exception(exception_app): """Test that an exception not built into sanic is handled""" - request, response = sanic_endpoint_test( - exception_app, uri='/divide_by_zero') + request, response = exception_app.test_client.get('/divide_by_zero') assert response.status == 500 soup = BeautifulSoup(response.body, 'html.parser') assert soup.h1.text == 'Internal Server Error' @@ -86,17 +84,16 @@ def test_handled_unhandled_exception(exception_app): def test_exception_in_exception_handler(exception_app): """Test that an exception thrown in an error handler is handled""" - request, response = sanic_endpoint_test( - exception_app, uri='/error_in_error_handler_handler') + request, response = exception_app.test_client.get( + '/error_in_error_handler_handler') assert response.status == 500 assert response.body == b'An error occurred while handling an error' def test_exception_in_exception_handler_debug_off(exception_app): """Test that an exception thrown in an error handler is handled""" - request, response = sanic_endpoint_test( - exception_app, - uri='/error_in_error_handler_handler', + request, response = exception_app.test_client.get( + '/error_in_error_handler_handler', debug=False) assert response.status == 500 assert response.body == b'An error occurred while handling an error' @@ -104,9 +101,8 @@ def test_exception_in_exception_handler_debug_off(exception_app): def test_exception_in_exception_handler_debug_off(exception_app): """Test that an exception thrown in an error handler is handled""" - request, response = sanic_endpoint_test( - exception_app, - uri='/error_in_error_handler_handler', + request, response = exception_app.test_client.get( + '/error_in_error_handler_handler', debug=True) assert response.status == 500 assert response.body.startswith(b'Exception raised in exception ') diff --git a/tests/test_exceptions_handler.py b/tests/test_exceptions_handler.py index e252d3e6..fac8ea85 100644 --- a/tests/test_exceptions_handler.py +++ b/tests/test_exceptions_handler.py @@ -1,7 +1,6 @@ from sanic import Sanic from sanic.response import text from sanic.exceptions import InvalidUsage, ServerError, NotFound -from sanic.utils import sanic_endpoint_test from bs4 import BeautifulSoup exception_handler_app = Sanic('test_exception_handler') @@ -41,31 +40,30 @@ def handler_exception(request, exception): def test_invalid_usage_exception_handler(): - request, response = sanic_endpoint_test(exception_handler_app, uri='/1') + request, response = exception_handler_app.test_client.get('/1') assert response.status == 400 def test_server_error_exception_handler(): - request, response = sanic_endpoint_test(exception_handler_app, uri='/2') + request, response = exception_handler_app.test_client.get('/2') assert response.status == 200 assert response.text == 'OK' def test_not_found_exception_handler(): - request, response = sanic_endpoint_test(exception_handler_app, uri='/3') + request, response = exception_handler_app.test_client.get('/3') assert response.status == 200 def test_text_exception__handler(): - request, response = sanic_endpoint_test( - exception_handler_app, uri='/random') + request, response = exception_handler_app.test_client.get('/random') assert response.status == 200 assert response.text == 'OK' def test_html_traceback_output_in_debug_mode(): - request, response = sanic_endpoint_test( - exception_handler_app, uri='/4', debug=True) + request, response = exception_handler_app.test_client.get( + '/4', debug=True) assert response.status == 500 soup = BeautifulSoup(response.body, 'html.parser') html = str(soup) @@ -81,5 +79,5 @@ def test_html_traceback_output_in_debug_mode(): def test_inherited_exception_handler(): - request, response = sanic_endpoint_test(exception_handler_app, uri='/5') + request, response = exception_handler_app.test_client.get('/5') assert response.status == 200 diff --git a/tests/test_logging.py b/tests/test_logging.py index ec326276..fc26ca93 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -3,7 +3,6 @@ import uuid from sanic.response import text from sanic import Sanic from io import StringIO -from sanic.utils import sanic_endpoint_test import logging logging_format = '''module: %(module)s; \ @@ -29,7 +28,7 @@ def test_log(): log.info(rand_string) return text('hello') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') log_text = log_stream.getvalue() assert rand_string in log_text diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 95580e1d..f84d7151 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -2,7 +2,6 @@ from json import loads as json_loads, dumps as json_dumps from sanic import Sanic from sanic.request import Request from sanic.response import json, text, HTTPResponse -from sanic.utils import sanic_endpoint_test # ------------------------------------------------------------ # @@ -22,7 +21,7 @@ def test_middleware_request(): async def handler(request): return text('OK') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'OK' assert type(results[0]) is Request @@ -46,7 +45,7 @@ def test_middleware_response(): async def handler(request): return text('OK') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'OK' assert type(results[0]) is Request @@ -65,7 +64,7 @@ def test_middleware_override_request(): async def handler(request): return text('FAIL') - response = sanic_endpoint_test(app, gather_request=False) + response = app.test_client.get('/', gather_request=False) assert response.status == 200 assert response.text == 'OK' @@ -82,7 +81,7 @@ def test_middleware_override_response(): async def handler(request): return text('FAIL') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.status == 200 assert response.text == 'OK' @@ -122,7 +121,7 @@ def test_middleware_order(): async def handler(request): return text('OK') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.status == 200 assert order == [1,2,3,4,5,6] diff --git a/tests/test_multiprocessing.py b/tests/test_multiprocessing.py index 7f68c1b6..1342c6d3 100644 --- a/tests/test_multiprocessing.py +++ b/tests/test_multiprocessing.py @@ -3,7 +3,7 @@ import random import signal from sanic import Sanic -from sanic.utils import HOST, PORT +from sanic.testing import HOST, PORT def test_multiprocessing(): diff --git a/tests/test_payload_too_large.py b/tests/test_payload_too_large.py index e8eec09e..a1a58d3d 100644 --- a/tests/test_payload_too_large.py +++ b/tests/test_payload_too_large.py @@ -1,7 +1,6 @@ from sanic import Sanic from sanic.response import text from sanic.exceptions import PayloadTooLarge -from sanic.utils import sanic_endpoint_test data_received_app = Sanic('data_received') data_received_app.config.REQUEST_MAX_SIZE = 1 @@ -22,8 +21,7 @@ def handler_exception(request, exception): def test_payload_too_large_from_error_handler(): - response = sanic_endpoint_test( - data_received_app, uri='/1', gather_request=False) + response = data_received_app.test_client.get('/1', gather_request=False) assert response.status == 413 assert response.text == 'Payload Too Large from error_handler.' @@ -34,8 +32,8 @@ async def handler2(request): def test_payload_too_large_at_data_received_default(): - response = sanic_endpoint_test( - data_received_default_app, uri='/1', gather_request=False) + response = data_received_default_app.test_client.get( + '/1', gather_request=False) assert response.status == 413 assert response.text == 'Error: Payload Too Large' @@ -47,8 +45,7 @@ async def handler3(request): def test_payload_too_large_at_on_header_default(): data = 'a' * 1000 - response = sanic_endpoint_test( - on_header_default_app, method='post', uri='/1', - gather_request=False, data=data) + response = on_header_default_app.test_client.post( + '/1', gather_request=False, data=data) assert response.status == 413 assert response.text == 'Error: Payload Too Large' diff --git a/tests/test_redirect.py b/tests/test_redirect.py index b2b72c35..421ee1cf 100644 --- a/tests/test_redirect.py +++ b/tests/test_redirect.py @@ -2,7 +2,6 @@ import pytest from sanic import Sanic from sanic.response import text, redirect -from sanic.utils import sanic_endpoint_test @pytest.fixture @@ -40,9 +39,8 @@ def test_redirect_default_302(redirect_app): """ We expect a 302 default status code and the headers to be set. """ - request, response = sanic_endpoint_test( - redirect_app, method="get", - uri="/redirect_init", + request, response = redirect_app.test_client.get( + '/redirect_init', allow_redirects=False) assert response.status == 302 @@ -51,8 +49,7 @@ def test_redirect_default_302(redirect_app): def test_redirect_headers_none(redirect_app): - request, response = sanic_endpoint_test( - redirect_app, method="get", + request, response = redirect_app.test_client.get( uri="/redirect_init", headers=None, allow_redirects=False) @@ -65,9 +62,8 @@ def test_redirect_with_301(redirect_app): """ Test redirection with a different status code. """ - request, response = sanic_endpoint_test( - redirect_app, method="get", - uri="/redirect_init_with_301", + request, response = redirect_app.test_client.get( + "/redirect_init_with_301", allow_redirects=False) assert response.status == 301 @@ -78,9 +74,8 @@ def test_get_then_redirect_follow_redirect(redirect_app): """ With `allow_redirects` we expect a 200. """ - response = sanic_endpoint_test( - redirect_app, method="get", - uri="/redirect_init", gather_request=False, + request, response = redirect_app.test_client.get( + "/redirect_init", allow_redirects=True) assert response.status == 200 @@ -88,8 +83,8 @@ def test_get_then_redirect_follow_redirect(redirect_app): def test_chained_redirect(redirect_app): - """Test sanic_endpoint_test is working for redirection""" - request, response = sanic_endpoint_test(redirect_app, uri='/1') + """Test test_client is working for redirection""" + request, response = redirect_app.test_client.get('/1') assert request.url.endswith('/1') assert response.status == 200 assert response.text == 'OK' diff --git a/tests/test_request_data.py b/tests/test_request_data.py index 098878e7..1d0a3795 100644 --- a/tests/test_request_data.py +++ b/tests/test_request_data.py @@ -1,6 +1,5 @@ from sanic import Sanic from sanic.response import json -from sanic.utils import sanic_endpoint_test from ujson import loads @@ -17,7 +16,7 @@ def test_storage(): def handler(request): return json({ 'user': request.get('user'), 'sidekick': request.get('sidekick') }) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') response_json = loads(response.text) assert response_json['user'] == 'sanic' diff --git a/tests/test_request_timeout.py b/tests/test_request_timeout.py index 8cf3a680..404aec12 100644 --- a/tests/test_request_timeout.py +++ b/tests/test_request_timeout.py @@ -2,7 +2,6 @@ from sanic import Sanic import asyncio from sanic.response import text from sanic.exceptions import RequestTimeout -from sanic.utils import sanic_endpoint_test from sanic.config import Config Config.REQUEST_TIMEOUT = 1 @@ -22,7 +21,7 @@ def handler_exception(request, exception): def test_server_error_request_timeout(): - request, response = sanic_endpoint_test(request_timeout_app, uri='/1') + request, response = request_timeout_app.test_client.get('/1') assert response.status == 408 assert response.text == 'Request Timeout from error_handler.' @@ -34,7 +33,6 @@ async def handler_2(request): def test_default_server_error_request_timeout(): - request, response = sanic_endpoint_test( - request_timeout_default_app, uri='/1') + request, response = request_timeout_default_app.test_client.get('/1') assert response.status == 408 assert response.text == 'Error: Request Timeout' diff --git a/tests/test_requests.py b/tests/test_requests.py index 6fabbd34..c1736030 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -5,7 +5,6 @@ import pytest from sanic import Sanic from sanic.exceptions import ServerError from sanic.response import json, text, redirect -from sanic.utils import sanic_endpoint_test # ------------------------------------------------------------ # @@ -19,7 +18,7 @@ def test_sync(): def handler(request): return text('Hello') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'Hello' @@ -31,7 +30,7 @@ def test_text(): async def handler(request): return text('Hello') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'Hello' @@ -44,7 +43,7 @@ def test_headers(): headers = {"spam": "great"} return text('Hello', headers=headers) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.headers.get('spam') == 'great' @@ -57,7 +56,7 @@ def test_non_str_headers(): headers = {"answer": 42} return text('Hello', headers=headers) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.headers.get('answer') == '42' @@ -72,7 +71,7 @@ def test_invalid_response(): async def handler(request): return 'This should fail' - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.status == 500 assert response.text == "Internal Server Error." @@ -84,7 +83,7 @@ def test_json(): async def handler(request): return json({"test": True}) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') try: results = json_loads(response.text) @@ -102,7 +101,7 @@ def test_invalid_json(): return json(request.json()) data = "I am not json" - request, response = sanic_endpoint_test(app, data=data) + request, response = app.test_client.get('/', data=data) assert response.status == 400 @@ -114,8 +113,8 @@ def test_query_string(): async def handler(request): return text('OK') - request, response = sanic_endpoint_test( - app, params=[("test1", "1"), ("test2", "false"), ("test2", "true")]) + request, response = app.test_client.get( + '/', params=[("test1", "1"), ("test2", "false"), ("test2", "true")]) assert request.args.get('test1') == '1' assert request.args.get('test2') == 'false' @@ -135,7 +134,7 @@ def test_token(): 'Authorization': 'Token {}'.format(token) } - request, response = sanic_endpoint_test(app, headers=headers) + request, response = app.test_client.get('/', headers=headers) assert request.token == token @@ -153,8 +152,8 @@ def test_post_json(): payload = {'test': 'OK'} headers = {'content-type': 'application/json'} - request, response = sanic_endpoint_test( - app, data=json_dumps(payload), headers=headers) + request, response = app.test_client.get( + '/', data=json_dumps(payload), headers=headers) assert request.json.get('test') == 'OK' assert response.text == 'OK' @@ -170,7 +169,7 @@ def test_post_form_urlencoded(): payload = 'test=OK' headers = {'content-type': 'application/x-www-form-urlencoded'} - request, response = sanic_endpoint_test(app, data=payload, headers=headers) + request, response = app.test_client.get('/', data=payload, headers=headers) assert request.form.get('test') == 'OK' @@ -190,6 +189,6 @@ def test_post_form_multipart_form_data(): headers = {'content-type': 'multipart/form-data; boundary=----sanic'} - request, response = sanic_endpoint_test(app, data=payload, headers=headers) + request, response = app.test_client.get(data=payload, headers=headers) assert request.form.get('test') == 'OK' diff --git a/tests/test_response.py b/tests/test_response.py index f35f10e9..9639e076 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -2,7 +2,6 @@ from random import choice from sanic import Sanic from sanic.response import HTTPResponse -from sanic.utils import sanic_endpoint_test def test_response_body_not_a_string(): @@ -14,5 +13,5 @@ def test_response_body_not_a_string(): async def hello_route(request): return HTTPResponse(body=random_num) - request, response = sanic_endpoint_test(app, uri='/hello') + request, response = app.test_client.get('/hello') assert response.text == str(random_num) diff --git a/tests/test_routes.py b/tests/test_routes.py index 525f87cb..12371e57 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -3,7 +3,6 @@ import pytest from sanic import Sanic from sanic.response import text from sanic.router import RouteExists, RouteDoesNotExist -from sanic.utils import sanic_endpoint_test # ------------------------------------------------------------ # @@ -17,10 +16,10 @@ def test_shorthand_routes_get(): def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/get', method='get') + request, response = app.test_client.get('/get') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/get', method='post') + request, response = app.test_client.post('/get') assert response.status == 405 def test_shorthand_routes_post(): @@ -30,10 +29,10 @@ def test_shorthand_routes_post(): def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/post', method='post') + request, response = app.test_client.post('/post') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/post', method='get') + request, response = app.test_client.get('/post') assert response.status == 405 def test_shorthand_routes_put(): @@ -43,10 +42,10 @@ def test_shorthand_routes_put(): def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/put', method='put') + request, response = app.test_client.put('/put') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/put', method='get') + request, response = app.test_client.get('/put') assert response.status == 405 def test_shorthand_routes_patch(): @@ -56,10 +55,10 @@ def test_shorthand_routes_patch(): def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/patch', method='patch') + request, response = app.test_client.patch('/patch') assert response.text == 'OK' - request, response = sanic_endpoint_test(app, uri='/patch', method='get') + request, response = app.test_client.get('/patch') assert response.status == 405 def test_shorthand_routes_head(): @@ -69,10 +68,10 @@ def test_shorthand_routes_head(): def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/head', method='head') + request, response = app.test_client.head('/head') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/head', method='get') + request, response = app.test_client.get('/head') assert response.status == 405 def test_shorthand_routes_options(): @@ -82,10 +81,10 @@ def test_shorthand_routes_options(): def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/options', method='options') + request, response = app.test_client.options('/options') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/options', method='get') + request, response = app.test_client.get('/options') assert response.status == 405 def test_static_routes(): @@ -99,10 +98,10 @@ def test_static_routes(): async def handler2(request): return text('OK2') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.text == 'OK1' - request, response = sanic_endpoint_test(app, uri='/pizazz') + request, response = app.test_client.get('/pizazz') assert response.text == 'OK2' @@ -116,7 +115,7 @@ def test_dynamic_route(): results.append(name) return text('OK') - request, response = sanic_endpoint_test(app, uri='/folder/test123') + request, response = app.test_client.get('/folder/test123') assert response.text == 'OK' assert results[0] == 'test123' @@ -132,12 +131,12 @@ def test_dynamic_route_string(): results.append(name) return text('OK') - request, response = sanic_endpoint_test(app, uri='/folder/test123') + request, response = app.test_client.get('/folder/test123') assert response.text == 'OK' assert results[0] == 'test123' - request, response = sanic_endpoint_test(app, uri='/folder/favicon.ico') + request, response = app.test_client.get('/folder/favicon.ico') assert response.text == 'OK' assert results[1] == 'favicon.ico' @@ -153,11 +152,11 @@ def test_dynamic_route_int(): results.append(folder_id) return text('OK') - request, response = sanic_endpoint_test(app, uri='/folder/12345') + request, response = app.test_client.get('/folder/12345') assert response.text == 'OK' assert type(results[0]) is int - request, response = sanic_endpoint_test(app, uri='/folder/asdf') + request, response = app.test_client.get('/folder/asdf') assert response.status == 404 @@ -171,14 +170,14 @@ def test_dynamic_route_number(): results.append(weight) return text('OK') - request, response = sanic_endpoint_test(app, uri='/weight/12345') + request, response = app.test_client.get('/weight/12345') assert response.text == 'OK' assert type(results[0]) is float - request, response = sanic_endpoint_test(app, uri='/weight/1234.56') + request, response = app.test_client.get('/weight/1234.56') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/weight/1234-56') + request, response = app.test_client.get('/weight/1234-56') assert response.status == 404 @@ -189,16 +188,16 @@ def test_dynamic_route_regex(): async def handler(request, folder_id): return text('OK') - request, response = sanic_endpoint_test(app, uri='/folder/test') + request, response = app.test_client.get('/folder/test') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test1') + request, response = app.test_client.get('/folder/test1') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/folder/test-123') + request, response = app.test_client.get('/folder/test-123') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/folder/') + request, response = app.test_client.get('/folder/') assert response.status == 200 @@ -209,16 +208,16 @@ def test_dynamic_route_unhashable(): async def handler(request, unhashable): return text('OK') - request, response = sanic_endpoint_test(app, uri='/folder/test/asdf/end/') + request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test///////end/') + request, response = app.test_client.get('/folder/test///////end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test/end/') + request, response = app.test_client.get('/folder/test/end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test/nope/') + request, response = app.test_client.get('/folder/test/nope/') assert response.status == 404 @@ -251,10 +250,10 @@ def test_method_not_allowed(): async def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 200 - request, response = sanic_endpoint_test(app, method='post', uri='/test') + request, response = app.test_client.post('/test') assert response.status == 405 @@ -270,10 +269,10 @@ def test_static_add_route(): app.add_route(handler1, '/test') app.add_route(handler2, '/test2') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.text == 'OK1' - request, response = sanic_endpoint_test(app, uri='/test2') + request, response = app.test_client.get('/test2') assert response.text == 'OK2' @@ -287,7 +286,7 @@ def test_dynamic_add_route(): return text('OK') app.add_route(handler, '/folder/') - request, response = sanic_endpoint_test(app, uri='/folder/test123') + request, response = app.test_client.get('/folder/test123') assert response.text == 'OK' assert results[0] == 'test123' @@ -303,12 +302,12 @@ def test_dynamic_add_route_string(): return text('OK') app.add_route(handler, '/folder/') - request, response = sanic_endpoint_test(app, uri='/folder/test123') + request, response = app.test_client.get('/folder/test123') assert response.text == 'OK' assert results[0] == 'test123' - request, response = sanic_endpoint_test(app, uri='/folder/favicon.ico') + request, response = app.test_client.get('/folder/favicon.ico') assert response.text == 'OK' assert results[1] == 'favicon.ico' @@ -325,11 +324,11 @@ def test_dynamic_add_route_int(): app.add_route(handler, '/folder/') - request, response = sanic_endpoint_test(app, uri='/folder/12345') + request, response = app.test_client.get('/folder/12345') assert response.text == 'OK' assert type(results[0]) is int - request, response = sanic_endpoint_test(app, uri='/folder/asdf') + request, response = app.test_client.get('/folder/asdf') assert response.status == 404 @@ -344,14 +343,14 @@ def test_dynamic_add_route_number(): app.add_route(handler, '/weight/') - request, response = sanic_endpoint_test(app, uri='/weight/12345') + request, response = app.test_client.get('/weight/12345') assert response.text == 'OK' assert type(results[0]) is float - request, response = sanic_endpoint_test(app, uri='/weight/1234.56') + request, response = app.test_client.get('/weight/1234.56') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/weight/1234-56') + request, response = app.test_client.get('/weight/1234-56') assert response.status == 404 @@ -363,16 +362,16 @@ def test_dynamic_add_route_regex(): app.add_route(handler, '/folder/') - request, response = sanic_endpoint_test(app, uri='/folder/test') + request, response = app.test_client.get('/folder/test') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test1') + request, response = app.test_client.get('/folder/test1') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/folder/test-123') + request, response = app.test_client.get('/folder/test-123') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/folder/') + request, response = app.test_client.get('/folder/') assert response.status == 200 @@ -384,16 +383,16 @@ def test_dynamic_add_route_unhashable(): app.add_route(handler, '/folder//end/') - request, response = sanic_endpoint_test(app, uri='/folder/test/asdf/end/') + request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test///////end/') + request, response = app.test_client.get('/folder/test///////end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test/end/') + request, response = app.test_client.get('/folder/test/end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test/nope/') + request, response = app.test_client.get('/folder/test/nope/') assert response.status == 404 @@ -429,10 +428,10 @@ def test_add_route_method_not_allowed(): app.add_route(handler, '/test', methods=['GET']) - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 200 - request, response = sanic_endpoint_test(app, method='post', uri='/test') + request, response = app.test_client.post('/test') assert response.status == 405 @@ -448,19 +447,19 @@ def test_remove_static_route(): app.add_route(handler1, '/test') app.add_route(handler2, '/test2') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/test2') + request, response = app.test_client.get('/test2') assert response.status == 200 app.remove_route('/test') app.remove_route('/test2') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/test2') + request, response = app.test_client.get('/test2') assert response.status == 404 @@ -472,11 +471,11 @@ def test_remove_dynamic_route(): app.add_route(handler, '/folder/') - request, response = sanic_endpoint_test(app, uri='/folder/test123') + request, response = app.test_client.get('/folder/test123') assert response.status == 200 app.remove_route('/folder/') - request, response = sanic_endpoint_test(app, uri='/folder/test123') + request, response = app.test_client.get('/folder/test123') assert response.status == 404 @@ -495,24 +494,24 @@ def test_remove_unhashable_route(): app.add_route(handler, '/folder//end/') - request, response = sanic_endpoint_test(app, uri='/folder/test/asdf/end/') + request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test///////end/') + request, response = app.test_client.get('/folder/test///////end/') assert response.status == 200 - request, response = sanic_endpoint_test(app, uri='/folder/test/end/') + request, response = app.test_client.get('/folder/test/end/') assert response.status == 200 app.remove_route('/folder//end/') - request, response = sanic_endpoint_test(app, uri='/folder/test/asdf/end/') + request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/folder/test///////end/') + request, response = app.test_client.get('/folder/test///////end/') assert response.status == 404 - request, response = sanic_endpoint_test(app, uri='/folder/test/end/') + request, response = app.test_client.get('/folder/test/end/') assert response.status == 404 @@ -524,22 +523,22 @@ def test_remove_route_without_clean_cache(): app.add_route(handler, '/test') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 200 app.remove_route('/test', clean_cache=True) - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 404 app.add_route(handler, '/test') - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 200 app.remove_route('/test', clean_cache=False) - request, response = sanic_endpoint_test(app, uri='/test') + request, response = app.test_client.get('/test') assert response.status == 200 @@ -554,16 +553,16 @@ def test_overload_routes(): async def handler2(request): return text('OK2') - request, response = sanic_endpoint_test(app, 'get', uri='/overload') + request, response = app.test_client.get('/overload') assert response.text == 'OK1' - request, response = sanic_endpoint_test(app, 'post', uri='/overload') + request, response = app.test_client.post('/overload') assert response.text == 'OK2' - request, response = sanic_endpoint_test(app, 'put', uri='/overload') + request, response = app.test_client.put('/overload') assert response.text == 'OK2' - request, response = sanic_endpoint_test(app, 'delete', uri='/overload') + request, response = app.test_client.delete('/overload') assert response.status == 405 with pytest.raises(RouteExists): @@ -584,10 +583,10 @@ def test_unmergeable_overload_routes(): async def handler2(request): return text('Duplicated') - request, response = sanic_endpoint_test(app, 'get', uri='/overload_whole') + request, response = app.test_client.get('/overload_whole') assert response.text == 'OK1' - request, response = sanic_endpoint_test(app, 'post', uri='/overload_whole') + request, response = app.test_client.post('/overload_whole') assert response.text == 'OK1' @@ -600,8 +599,8 @@ def test_unmergeable_overload_routes(): async def handler2(request): return text('Duplicated') - request, response = sanic_endpoint_test(app, 'get', uri='/overload_part') + request, response = app.test_client.get('/overload_part') assert response.text == 'OK1' - request, response = sanic_endpoint_test(app, 'post', uri='/overload_part') + request, response = app.test_client.post('/overload_part') assert response.status == 405 diff --git a/tests/test_server_events.py b/tests/test_server_events.py index 3335489e..0dcaba1c 100644 --- a/tests/test_server_events.py +++ b/tests/test_server_events.py @@ -6,7 +6,7 @@ import signal import pytest from sanic import Sanic -from sanic.utils import HOST, PORT +from sanic.testing import HOST, PORT AVAILABLE_LISTENERS = [ 'before_server_start', diff --git a/tests/test_signal_handlers.py b/tests/test_signal_handlers.py index 3654e57c..c4cca92b 100644 --- a/tests/test_signal_handlers.py +++ b/tests/test_signal_handlers.py @@ -1,6 +1,6 @@ from sanic import Sanic from sanic.response import HTTPResponse -from sanic.utils import HOST, PORT +from sanic.testing import HOST, PORT from unittest.mock import MagicMock import pytest import asyncio diff --git a/tests/test_static.py b/tests/test_static.py index 4d6c0ee2..783a56c7 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -4,7 +4,6 @@ import os import pytest from sanic import Sanic -from sanic.utils import sanic_endpoint_test @pytest.fixture(scope='module') @@ -32,7 +31,7 @@ def test_static_file(static_file_directory, file_name): app.static( '/testing.file', get_file_path(static_file_directory, file_name)) - request, response = sanic_endpoint_test(app, uri='/testing.file') + request, response = app.test_client.get('/testing.file') assert response.status == 200 assert response.body == get_file_content(static_file_directory, file_name) @@ -44,8 +43,8 @@ def test_static_directory(file_name, base_uri, static_file_directory): app = Sanic('test_static') app.static(base_uri, static_file_directory) - request, response = sanic_endpoint_test( - app, uri='{}/{}'.format(base_uri, file_name)) + request, response = app.test_client.get( + uri='{}/{}'.format(base_uri, file_name)) assert response.status == 200 assert response.body == get_file_content(static_file_directory, file_name) @@ -57,8 +56,7 @@ def test_static_head_request(file_name, static_file_directory): '/testing.file', get_file_path(static_file_directory, file_name), use_content_range=True) - request, response = sanic_endpoint_test( - app, uri='/testing.file', method='head') + request, response = app.test_client.head('/testing.file') assert response.status == 200 assert 'Accept-Ranges' in response.headers assert 'Content-Length' in response.headers @@ -77,8 +75,7 @@ def test_static_content_range_correct(file_name, static_file_directory): headers = { 'Range': 'bytes=12-19' } - request, response = sanic_endpoint_test( - app, uri='/testing.file', headers=headers) + request, response = app.test_client.get('/testing.file', headers=headers) assert response.status == 200 assert 'Content-Length' in response.headers assert 'Content-Range' in response.headers @@ -99,8 +96,7 @@ def test_static_content_range_front(file_name, static_file_directory): headers = { 'Range': 'bytes=12-' } - request, response = sanic_endpoint_test( - app, uri='/testing.file', headers=headers) + request, response = app.test_client.get('/testing.file', headers=headers) assert response.status == 200 assert 'Content-Length' in response.headers assert 'Content-Range' in response.headers @@ -121,8 +117,7 @@ def test_static_content_range_back(file_name, static_file_directory): headers = { 'Range': 'bytes=-12' } - request, response = sanic_endpoint_test( - app, uri='/testing.file', headers=headers) + request, response = app.test_client.get('/testing.file', headers=headers) assert response.status == 200 assert 'Content-Length' in response.headers assert 'Content-Range' in response.headers @@ -140,7 +135,7 @@ def test_static_content_range_empty(file_name, static_file_directory): '/testing.file', get_file_path(static_file_directory, file_name), use_content_range=True) - request, response = sanic_endpoint_test(app, uri='/testing.file') + request, response = app.test_client.get('/testing.file') assert response.status == 200 assert 'Content-Length' in response.headers assert 'Content-Range' not in response.headers @@ -160,8 +155,7 @@ def test_static_content_range_error(file_name, static_file_directory): headers = { 'Range': 'bytes=1-0' } - request, response = sanic_endpoint_test( - app, uri='/testing.file', headers=headers) + request, response = app.test_client.get('/testing.file', headers=headers) assert response.status == 416 assert 'Content-Length' in response.headers assert 'Content-Range' in response.headers diff --git a/tests/test_url_building.py b/tests/test_url_building.py index 02cbce31..f234efda 100644 --- a/tests/test_url_building.py +++ b/tests/test_url_building.py @@ -5,7 +5,7 @@ from sanic import Sanic from sanic.response import text from sanic.views import HTTPMethodView from sanic.blueprints import Blueprint -from sanic.utils import sanic_endpoint_test, PORT as test_port +from sanic.testing import PORT as test_port from sanic.exceptions import URLBuildError import string @@ -41,8 +41,7 @@ def test_simple_url_for_getting(simple_app): url = simple_app.url_for(letter) assert url == '/{}'.format(letter) - request, response = sanic_endpoint_test( - simple_app, uri=url) + request, response = simple_app.test_client.get(url) assert response.status == 200 assert response.text == letter @@ -59,7 +58,7 @@ def test_simple_url_for_getting_with_more_params(args, url): return text('this should pass') assert url == app.url_for('passes', **args) - request, response = sanic_endpoint_test(app, uri=url) + request, response = app.test_client.get(url) assert response.status == 200 assert response.text == 'this should pass' diff --git a/tests/test_utf8.py b/tests/test_utf8.py index 8530aeac..e1602958 100644 --- a/tests/test_utf8.py +++ b/tests/test_utf8.py @@ -1,7 +1,6 @@ from json import loads as json_loads, dumps as json_dumps from sanic import Sanic from sanic.response import json, text -from sanic.utils import sanic_endpoint_test # ------------------------------------------------------------ # @@ -15,7 +14,7 @@ def test_utf8_query_string(): async def handler(request): return text('OK') - request, response = sanic_endpoint_test(app, params=[("utf8", '✓')]) + request, response = app.test_client.get('/', params=[("utf8", '✓')]) assert request.args.get('utf8') == '✓' @@ -26,7 +25,7 @@ def test_utf8_response(): async def handler(request): return text('✓') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == '✓' @@ -38,7 +37,7 @@ def skip_test_utf8_route(): return text('OK') # UTF-8 Paths are not supported - request, response = sanic_endpoint_test(app, route='/✓', uri='/✓') + request, response = app.test_client.get('/✓') assert response.text == 'OK' @@ -52,7 +51,9 @@ def test_utf8_post_json(): payload = {'test': '✓'} headers = {'content-type': 'application/json'} - request, response = sanic_endpoint_test(app, data=json_dumps(payload), headers=headers) + request, response = app.test_client.get( + '/', + data=json_dumps(payload), headers=headers) assert request.json.get('test') == '✓' assert response.text == 'OK' diff --git a/tests/test_vhosts.py b/tests/test_vhosts.py index 660ebb5f..53fdf53f 100644 --- a/tests/test_vhosts.py +++ b/tests/test_vhosts.py @@ -1,6 +1,5 @@ from sanic import Sanic from sanic.response import json, text -from sanic.utils import sanic_endpoint_test def test_vhosts(): @@ -15,11 +14,11 @@ def test_vhosts(): return text("You're at subdomain.example.com!") headers = {"Host": "example.com"} - request, response = sanic_endpoint_test(app, headers=headers) + request, response = app.test_client.get('/', headers=headers) assert response.text == "You're at example.com!" headers = {"Host": "subdomain.example.com"} - request, response = sanic_endpoint_test(app, headers=headers) + request, response = app.test_client.get('/', headers=headers) assert response.text == "You're at subdomain.example.com!" @@ -31,9 +30,9 @@ def test_vhosts_with_list(): return text("Hello, world!") headers = {"Host": "hello.com"} - request, response = sanic_endpoint_test(app, headers=headers) + request, response = app.test_client.get('/', headers=headers) assert response.text == "Hello, world!" headers = {"Host": "world.com"} - request, response = sanic_endpoint_test(app, headers=headers) + request, response = app.test_client.get('/', headers=headers) assert response.text == "Hello, world!" diff --git a/tests/test_views.py b/tests/test_views.py index ec0b91b8..627a3b6c 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -6,7 +6,6 @@ from sanic.response import text, HTTPResponse from sanic.views import HTTPMethodView, CompositionView from sanic.blueprints import Blueprint from sanic.request import Request -from sanic.utils import sanic_endpoint_test from sanic.constants import HTTP_METHODS @@ -39,7 +38,7 @@ def test_methods(method): app.add_route(DummyView.as_view(), '/') - request, response = sanic_endpoint_test(app, method=method) + request, response = getattr(app.test_client, method.lower())('/') assert response.headers['method'] == method @@ -52,9 +51,9 @@ def test_unexisting_methods(): return text('I am get method') app.add_route(DummyView.as_view(), '/') - request, response = sanic_endpoint_test(app, method="get") + request, response = app.test_client.get('/') assert response.text == 'I am get method' - request, response = sanic_endpoint_test(app, method="post") + request, response = app.test_client.post('/') assert response.text == 'Error: Method POST not allowed for URL /' @@ -68,7 +67,7 @@ def test_argument_methods(): app.add_route(DummyView.as_view(), '/') - request, response = sanic_endpoint_test(app, uri='/test123') + request, response = app.test_client.get('/test123') assert response.text == 'I am get method with test123' @@ -85,7 +84,7 @@ def test_with_bp(): bp.add_route(DummyView.as_view(), '/') app.blueprint(bp) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'I am get method' @@ -102,7 +101,7 @@ def test_with_bp_with_url_prefix(): bp.add_route(DummyView.as_view(), '/') app.blueprint(bp) - request, response = sanic_endpoint_test(app, uri='/test1/') + request, response = app.test_client.get('/test1/') assert response.text == 'I am get method' @@ -123,7 +122,7 @@ def test_with_middleware(): async def handler(request): results.append(request) - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'I am get method' assert type(results[0]) is Request @@ -150,7 +149,7 @@ def test_with_middleware_response(): app.add_route(DummyView.as_view(), '/') - request, response = sanic_endpoint_test(app) + request, response = app.test_client.get('/') assert response.text == 'I am get method' assert type(results[0]) is Request @@ -172,7 +171,7 @@ def test_with_custom_class_methods(): return text('I am get method and global var is {}'.format(self.global_var)) app.add_route(DummyView.as_view(), '/') - request, response = sanic_endpoint_test(app, method="get") + request, response = app.test_client.get('/') assert response.text == 'I am get method and global var is 10' @@ -194,7 +193,7 @@ def test_with_decorator(): return text('I am get method') app.add_route(DummyView.as_view(), '/') - request, response = sanic_endpoint_test(app, method="get") + request, response = app.test_client.get('/') assert response.text == 'I am get method' assert results[0] == 1 @@ -234,11 +233,11 @@ def test_composition_view_runs_methods_as_expected(method): app.add_route(view, '/') if method in ['GET', 'POST', 'PUT']: - request, response = sanic_endpoint_test(app, uri='/', method=method) + request, response = getattr(app.test_client, method.lower())('/') assert response.text == 'first method' if method in ['DELETE', 'PATCH']: - request, response = sanic_endpoint_test(app, uri='/', method=method) + request, response = getattr(app.test_client, method.lower())('/') assert response.text == 'second method' @@ -252,10 +251,10 @@ def test_composition_view_rejects_invalid_methods(method): app.add_route(view, '/') if method in ['GET', 'POST', 'PUT']: - request, response = sanic_endpoint_test(app, uri='/', method=method) + request, response = getattr(app.test_client, method.lower())('/') assert response.status == 200 assert response.text == 'first method' if method in ['DELETE', 'PATCH']: - request, response = sanic_endpoint_test(app, uri='/', method=method) + request, response = getattr(app.test_client, method.lower())('/') assert response.status == 405