Python starlette.testclient.TestClient() Examples
The following are 30
code examples of starlette.testclient.TestClient().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
starlette.testclient
, or try the search function
.
Example #1
Source File: test_exception_handlers.py From fastapi_contrib with MIT License | 7 votes |
def pydantic_exception_invalid_query(q: int = Query(...)): return {"q": q} # def test_exception_handler_invalid_query(): # with TestClient(app) as client: # response = client.get( # "/pydantic/exception/invalidquery/", params={"q": "$"} # ) # assert response.status_code == 400 # response = response.json() # assert response["error_codes"] == [400] # assert response["message"] == "Validation error." # assert response["fields"] == [ # { # "name": "q", # "message": "Value is not a valid integer.", # "error_code": 400, # } # ]
Example #2
Source File: test_forwards.py From mergify-engine with Apache License 2.0 | 7 votes |
def test_app_event_forward(_, __, httpserver): with open( os.path.join(os.path.dirname(__file__), "events", "push_event.json") ) as f: data = f.read() headers = { "X-GitHub-Delivery": str(uuid.uuid4()), "X-GitHub-Event": "push", "X-Hub-Signature": "sha1=%s" % utils.compute_hmac(data.encode()), "User-Agent": "GitHub-Hookshot/044aadd", "Content-Type": "application/json", } httpserver.expect_request( "/", method="POST", data=data, headers=headers ).respond_with_data("") with mock.patch( "mergify_engine.config.WEBHOOK_APP_FORWARD_URL", httpserver.url_for("/"), ): with testclient.TestClient(web.app) as client: client.post("/event", data=data, headers=headers) httpserver.check_assertions()
Example #3
Source File: test_pagination.py From fastapi_contrib with MIT License | 6 votes |
def test_custom_pagination_correct_filters(): class CustomPagination2(Pagination): default_offset = 90 default_limit = 1 max_offset = 100 max_limit = 2000 @app.get("/hallo3/pagination3/") async def hallo3_pagination3(pagination: CustomPagination2 = Depends()): resp = await pagination.paginate(serializer_class=TestSerializer) return resp with TestClient(app) as client: response = client.get("/hallo3/pagination3/?limit=1001") assert response.status_code == 200 response = client.get("/hallo3/pagination3/?offset=99") assert response.status_code == 200 response = client.get("/hallo3/pagination3/?offset=99&limit=1001") assert response.status_code == 200
Example #4
Source File: test_webgear.py From vidgear with Apache License 2.0 | 6 votes |
def test_webgear_class(source, stabilize, colorspace, time_delay): """ Test for various WebGear API parameters """ try: web = WebGear( source=source, stabilize=stabilize, colorspace=colorspace, time_delay=time_delay, logging=True, ) client = TestClient(web(), raise_server_exceptions=True) response = client.get("/") assert response.status_code == 200 response_404 = client.get("/test") assert response_404.status_code == 404 web.shutdown() except Exception as e: pytest.fail(str(e))
Example #5
Source File: test_webgear.py From vidgear with Apache License 2.0 | 6 votes |
def test_webgear_options(options): """ Test for various WebGear API internal options """ try: web = WebGear(source=return_testvideo_path(), logging=True, **options) client = TestClient(web(), raise_server_exceptions=True) response = client.get("/") assert response.status_code == 200 response_video = client.get("/video") assert response_video.status_code == 200 web.shutdown() except Exception as e: if isinstance(e, AssertionError): logger.exception(str(e)) elif isinstance(e, requests.exceptions.Timeout): logger.exceptions(str(e)) else: pytest.fail(str(e))
Example #6
Source File: models.py From schemathesis with MIT License | 6 votes |
def call_asgi( self, app: Any = None, base_url: Optional[str] = "http://testserver", headers: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> requests.Response: application = app or self.app if application is None: raise RuntimeError( "ASGI application instance is required. " "Please, set `app` argument in the schema constructor or pass it to `call_asgi`" ) client = ASGIClient(application) return self.call(base_url=base_url, session=client, headers=headers, **kwargs)
Example #7
Source File: test_badges.py From mergify-engine with Apache License 2.0 | 6 votes |
def test_badge_redirect(): with testclient.TestClient(web.app) as client: reply = client.get( "/badges/mergifyio/mergify-engine.png", allow_redirects=False ) assert reply.status_code == 302 assert reply.headers["Location"] == ( "https://img.shields.io/endpoint.png" "?url=https://dashboard.mergify.io/badges/mergifyio/mergify-engine&style=flat" ) with testclient.TestClient(web.app) as client: reply = client.get( "/badges/mergifyio/mergify-engine.svg", allow_redirects=False ) assert reply.status_code == 302 assert reply.headers["Location"] == ( "https://img.shields.io/endpoint.svg" "?url=https://dashboard.mergify.io/badges/mergifyio/mergify-engine&style=flat" )
Example #8
Source File: test_exception_handlers.py From fastapi_contrib with MIT License | 6 votes |
def test_exception_handler_with_list_str_instead_of_ints(): with TestClient(app) as client: response = client.post( "/pydantic/exception/multipleint/", json={"integers": ["d"]} ) assert response.status_code == 400 response = response.json() assert response == { "error_codes": [400], "message": "Validation error.", "fields": [ { "name": "integers", "message": "Value is not a valid integer.", "error_code": 400, } ], }
Example #9
Source File: test_configuration.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_custom_root_value_is_passed_to_subscription_resolvers(schema): app = GraphQL(schema, root_value={"test": "TEST-ROOT"}) client = TestClient(app) with client.websocket_connect("/", "graphql-ws") as ws: ws.send_json({"type": GQL_CONNECTION_INIT}) ws.send_json( { "type": GQL_START, "id": "test1", "payload": {"query": "subscription { testRoot }"}, } ) response = ws.receive_json() assert response["type"] == GQL_CONNECTION_ACK response = ws.receive_json() assert response["type"] == GQL_DATA assert response["payload"] == {"data": {"testRoot": "TEST-ROOT"}}
Example #10
Source File: test_exception_handlers.py From fastapi_contrib with MIT License | 6 votes |
def test_exception_handler_when_one_of_multi_choice_invalid(): with TestClient(app) as client: response = client.post( "/pydantic/exception/multiplechoice/", json={"multi": ["d", "a"]} ) assert response.status_code == 400 response = response.json() assert response["error_codes"] == [400] assert response["message"] == "Validation error." assert response["fields"] == [ { "message": "One or more values provided are not valid.", "name": "multi", "error_code": 400, } ]
Example #11
Source File: test_configuration.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_custom_root_value_function_is_called_by_subscription(schema): get_root_value = Mock(return_value=True) app = GraphQL(schema, root_value=get_root_value) client = TestClient(app) with client.websocket_connect("/", "graphql-ws") as ws: ws.send_json({"type": GQL_CONNECTION_INIT}) ws.send_json( { "type": GQL_START, "id": "test1", "payload": {"query": "subscription { ping }"}, } ) response = ws.receive_json() assert response["type"] == GQL_CONNECTION_ACK response = ws.receive_json() assert response["type"] == GQL_DATA get_root_value.assert_called_once()
Example #12
Source File: test_exception_handlers.py From fastapi_contrib with MIT License | 6 votes |
def test_exception_handler_when_choice_invalid(): with TestClient(app) as client: response = client.post( "/pydantic/exception/choice/", json={"kind": "d"} ) assert response.status_code == 400 response = response.json() assert response["error_codes"] == [400] assert response["message"] == "Validation error." assert response["fields"] == [ { "message": "One or more values provided are not valid.", "name": "kind", "error_code": 400, } ]
Example #13
Source File: test_exception_handlers.py From fastapi_contrib with MIT License | 6 votes |
def test_exception_handler_when_regex_invalid(): with TestClient(app) as client: response = client.post( "/pydantic/exception/regexp/", json={"name": "$$$"} ) assert response.status_code == 400 response = response.json() assert response["error_codes"] == [400] assert response["message"] == "Validation error." assert response["fields"] == [ { "message": "Provided value doesn't match valid format.", "name": "name", "error_code": 400, } ]
Example #14
Source File: test_configuration.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_custom_logger_is_used_to_log_subscription_source_error(schema, mocker): logging_mock = mocker.patch("ariadne.logger.logging") app = GraphQL(schema, logger="custom") client = TestClient(app) with client.websocket_connect("/", "graphql-ws") as ws: ws.send_json({"type": GQL_CONNECTION_INIT}) ws.send_json( { "type": GQL_START, "id": "test1", "payload": {"query": "subscription { sourceError }"}, } ) response = ws.receive_json() assert response["type"] == GQL_CONNECTION_ACK response = ws.receive_json() assert response["type"] == GQL_DATA logging_mock.getLogger.assert_called_once_with("custom")
Example #15
Source File: test_configuration.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_custom_logger_is_used_to_log_subscription_resolver_error(schema, mocker): logging_mock = mocker.patch("ariadne.logger.logging") app = GraphQL(schema, logger="custom") client = TestClient(app) with client.websocket_connect("/", "graphql-ws") as ws: ws.send_json({"type": GQL_CONNECTION_INIT}) ws.send_json( { "type": GQL_START, "id": "test1", "payload": {"query": "subscription { resolverError }"}, } ) response = ws.receive_json() assert response["type"] == GQL_CONNECTION_ACK response = ws.receive_json() assert response["type"] == GQL_DATA logging_mock.getLogger.assert_called_once_with("custom")
Example #16
Source File: test_configuration.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_custom_error_formatter_is_used_to_format_subscription_resolver_error(schema): error_formatter = Mock(return_value=True) app = GraphQL(schema, error_formatter=error_formatter) client = TestClient(app) with client.websocket_connect("/", "graphql-ws") as ws: ws.send_json({"type": GQL_CONNECTION_INIT}) ws.send_json( { "type": GQL_START, "id": "test1", "payload": {"query": "subscription { resolverError }"}, } ) response = ws.receive_json() assert response["type"] == GQL_CONNECTION_ACK response = ws.receive_json() assert response["type"] == GQL_DATA assert response["id"] == "test1" error_formatter.assert_called_once()
Example #17
Source File: test_pagination.py From fastapi_contrib with MIT License | 6 votes |
def test_custom_pagination_invalid_offset_and_limit(): class CustomPagination(Pagination): default_offset = 90 default_limit = 1 max_offset = 100 max_limit = 2000 @app.get("/hallo2/pagination2/") async def hallo2_pagination2(pagination: CustomPagination = Depends()): resp = await pagination.paginate(serializer_class=TestSerializer) return resp with TestClient(app) as client: response = client.get("/hallo2/pagination2/?limit=2001") assert response.status_code == 422 response = client.get("/hallo2/pagination2/?offset=101") assert response.status_code == 422 response = client.get("/hallo2/pagination2/?offset=101&limit=2001") assert response.status_code == 422
Example #18
Source File: test_middlewares.py From fastapi_contrib with MIT License | 5 votes |
def test_request_id_not_in_state(): with TestClient(app) as client: response = client.get("/") assert response.status_code == 200 response = response.json() assert response["request_id"] is None
Example #19
Source File: test_middlewares.py From fastapi_contrib with MIT License | 5 votes |
def test_tracer_defined(): app = FastAPI() mock_tracer = MagicMock(spec=Tracer) mock_tracer.return_value.__enter__.return_value = mock_tracer app.tracer = mock_tracer app.add_middleware(OpentracingMiddleware) @app.get("/") async def index(): ... with TestClient(app) as client: response = client.get("/") assert response.status_code == 200
Example #20
Source File: test_backends.py From fastapi_contrib with MIT License | 5 votes |
def test_user_logged_in(): with TestClient(app) as client: response = client.get( "/me/", headers={"Authorization": f"Token t"} ) assert response.status_code == 200 response = response.json() assert response["username"] == "u"
Example #21
Source File: test_permissions.py From fastapi_contrib with MIT License | 5 votes |
def test_doesnt_have_auth_permission(): with TestClient(app) as client: response = client.get( "/authed/", headers={"Authorization": f"Token t"} ) assert response.status_code == 401 response = response.json() assert response == { "error_codes": [401], "message": "Not authenticated.", "fields": [], }
Example #22
Source File: test_permissions.py From fastapi_contrib with MIT License | 5 votes |
def test_has_auth_permission(): with TestClient(app) as client: response = client.get( "/authed/", headers={"Authorization": f"Token t"} ) assert response.status_code == 200 response = response.json() assert response["username"] == "u"
Example #23
Source File: test_forwards.py From mergify-engine with Apache License 2.0 | 5 votes |
def test_market_event_forward(_, __, httpserver): with open( os.path.join(os.path.dirname(__file__), "events", "market_event.json") ) as f: data = f.read() headers = { "X-GitHub-Delivery": str(uuid.uuid4()), "X-GitHub-Event": "purchased", "X-Hub-Signature": "sha1=%s" % utils.compute_hmac(data.encode()), "User-Agent": "GitHub-Hookshot/044aadd", "Content-Type": "application/json", } httpserver.expect_request( "/", method="POST", data=data, headers=headers ).respond_with_data("") with mock.patch( "mergify_engine.config.WEBHOOK_MARKETPLACE_FORWARD_URL", httpserver.url_for("/"), ): with testclient.TestClient(web.app) as client: client.post("/marketplace", data=data, headers=headers) httpserver.check_assertions()
Example #24
Source File: test_serializers.py From fastapi_contrib with MIT License | 5 votes |
def test_model_serializer_in_route(): from fastapi_contrib.db.client import MongoDBClient MongoDBClient.__instance = None MongoDBClient._MongoDBClient__instance = None test_client = TestClient(app) response = test_client.post("/test/", json={"c": "cc", "id": 123}) assert response.status_code == 200 response = response.json() assert response["id"] == 3 assert "c" not in response.keys()
Example #25
Source File: test_pagination.py From fastapi_contrib with MIT License | 5 votes |
def test_paginate_no_filters(): with TestClient(app) as client: response = client.get("/hallo/pagination/") assert response.status_code == 200 response = response.json() assert response["count"] == 1
Example #26
Source File: test_pagination.py From fastapi_contrib with MIT License | 5 votes |
def test_paginate_zero_offset_zero_limit2(): with TestClient(app) as client: response = client.get("/hallo/pagination/?limit=0&offset=0") assert response.status_code == 422
Example #27
Source File: starlette_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_post(app, elasticapm_client): client = TestClient(app) response = client.post( "/", headers={ constants.TRACEPARENT_HEADER_NAME: "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-03", constants.TRACESTATE_HEADER_NAME: "foo=bar,bar=baz", "REMOTE_ADDR": "127.0.0.1", }, data={"foo": "bar"}, ) assert response.status_code == 200 assert len(elasticapm_client.events[constants.TRANSACTION]) == 1 transaction = elasticapm_client.events[constants.TRANSACTION][0] spans = elasticapm_client.spans_for_transaction(transaction) assert len(spans) == 1 span = spans[0] assert transaction["name"] == "POST /" assert transaction["result"] == "HTTP 2xx" assert transaction["type"] == "request" assert transaction["span_count"]["started"] == 1 request = transaction["context"]["request"] assert request["method"] == "POST" assert request["socket"] == {"remote_address": "127.0.0.1", "encrypted": False} assert request["body"]["foo"] == "bar" assert span["name"] == "test"
Example #28
Source File: test_plugin_starlette.py From spectree with Apache License 2.0 | 5 votes |
def client(): with TestClient(app) as client: yield client
Example #29
Source File: starlette_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(app, elasticapm_client): client = TestClient(app) response = client.get( "/", headers={ constants.TRACEPARENT_HEADER_NAME: "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-03", constants.TRACESTATE_HEADER_NAME: "foo=bar,bar=baz", "REMOTE_ADDR": "127.0.0.1", }, ) assert response.status_code == 200 assert len(elasticapm_client.events[constants.TRANSACTION]) == 1 transaction = elasticapm_client.events[constants.TRANSACTION][0] spans = elasticapm_client.spans_for_transaction(transaction) assert len(spans) == 1 span = spans[0] assert transaction["name"] == "GET /" assert transaction["result"] == "HTTP 2xx" assert transaction["type"] == "request" assert transaction["span_count"]["started"] == 1 request = transaction["context"]["request"] assert request["method"] == "GET" assert request["socket"] == {"remote_address": "127.0.0.1", "encrypted": False} assert span["name"] == "test"
Example #30
Source File: test_middlewares.py From fastapi_contrib with MIT License | 5 votes |
def test_request_id_in_state(): with TestClient(app) as client: request_id = str(uuid.uuid4()) response = client.get( "/", headers={settings.request_id_header: request_id} ) assert response.status_code == 200 response = response.json() assert response["request_id"] == request_id