From c347ff742e06253786ad50a12e607b2d925f2a39 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Thu, 9 Jul 2020 14:52:58 +0300 Subject: [PATCH] Add app.test_mode which is set on testing calls --- sanic/app.py | 1 + sanic/testing.py | 2 ++ tests/test_app.py | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/sanic/app.py b/sanic/app.py index 5c805874..25139e1b 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -90,6 +90,7 @@ class Sanic: self.named_response_middleware = {} # Register alternative method names self.go_fast = self.run + self.test_mode = False @property def loop(self): diff --git a/sanic/testing.py b/sanic/testing.py index 36233e70..c92a5d31 100644 --- a/sanic/testing.py +++ b/sanic/testing.py @@ -21,6 +21,7 @@ class SanicTestClient: self.app = app self.port = port self.host = host + self.app.test_mode = True def get_new_session(self): return httpx.AsyncClient(verify=False) @@ -200,6 +201,7 @@ class SanicASGITestClient(httpx.AsyncClient): app.asgi = True self.app = app + self.app.test_mode = True dispatch = SanicASGIDispatch(app=app, client=(ASGI_HOST, PORT or 0)) super().__init__(dispatch=dispatch, base_url=base_url) diff --git a/tests/test_app.py b/tests/test_app.py index ab7da76d..e49fb72e 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -222,3 +222,24 @@ def test_handle_request_with_nested_sanic_exception(app, monkeypatch, caplog): def test_app_name_required(): with pytest.deprecated_call(): Sanic() + + +def test_app_has_test_mode_sync(app): + @app.get("/") + def handler(request): + assert request.app.test_mode + return text("test") + + _, response = app.test_client.get("/") + assert response.status == 200 + + +@pytest.mark.asyncio +async def test_app_has_test_mode_async(app): + @app.get("/") + async def handler(request): + assert request.app.test_mode + return text("test") + + _, response = await app.asgi_client.get("/") + assert response.status == 200