From de2dce003854175f26c111e71c8ef21af29081f4 Mon Sep 17 00:00:00 2001 From: Paulo Vital Date: Thu, 19 Nov 2026 10:04:43 +0100 Subject: [PATCH] refactor: use match-case for dispatch chains Replace if/elif chains that dispatch on a single subject with structural pattern matching (PEP 634) in secrets, registered spans, span exception recording, and the FastAPI, Starlette and Django middleware instrumentation. Convert the equivalent chains in the related tests. Branch order and behavior are unchanged. Signed-off-by: Paulo Vital --- .../instrumentation/django/middleware.py | 42 ++-- src/instana/instrumentation/fastapi.py | 17 +- src/instana/instrumentation/starlette.py | 9 +- src/instana/span/registered_span.py | 222 ++++++++---------- src/instana/span/span.py | 51 ++-- src/instana/util/secrets.py | 118 +++++----- tests/clients/kafka/test_kafka_python.py | 37 +-- tests/clients/test_aio_pika.py | 23 +- tests/clients/test_httpx.py | 43 ++-- tests/frameworks/test_werkzeug.py | 27 ++- tests/span/test_registered_span.py | 48 ++-- 11 files changed, 318 insertions(+), 319 deletions(-) diff --git a/src/instana/instrumentation/django/middleware.py b/src/instana/instrumentation/django/middleware.py index 3037581a..8b5d0422 100644 --- a/src/instana/instrumentation/django/middleware.py +++ b/src/instana/instrumentation/django/middleware.py @@ -202,12 +202,19 @@ def load_middleware_wrapper( if DJ_INSTANA_MIDDLEWARE in settings.MIDDLEWARE: return wrapped(*args, **kwargs) - if isinstance(settings.MIDDLEWARE, tuple): - settings.MIDDLEWARE = (DJ_INSTANA_MIDDLEWARE,) + settings.MIDDLEWARE - elif isinstance(settings.MIDDLEWARE, list): - settings.MIDDLEWARE = [DJ_INSTANA_MIDDLEWARE] + settings.MIDDLEWARE - else: - logger.warning("Instana: Couldn't add InstanaMiddleware to Django") + match settings.MIDDLEWARE: + case tuple(): + settings.MIDDLEWARE = ( + DJ_INSTANA_MIDDLEWARE, + ) + settings.MIDDLEWARE + case list(): + settings.MIDDLEWARE = [ + DJ_INSTANA_MIDDLEWARE + ] + settings.MIDDLEWARE + case _: + logger.warning( + "Instana: Couldn't add InstanaMiddleware to Django" + ) elif ( hasattr(settings, "MIDDLEWARE_CLASSES") @@ -216,16 +223,19 @@ def load_middleware_wrapper( if DJ_INSTANA_MIDDLEWARE in settings.MIDDLEWARE_CLASSES: return wrapped(*args, **kwargs) - if isinstance(settings.MIDDLEWARE_CLASSES, tuple): - settings.MIDDLEWARE_CLASSES = ( - DJ_INSTANA_MIDDLEWARE, - ) + settings.MIDDLEWARE_CLASSES - elif isinstance(settings.MIDDLEWARE_CLASSES, list): - settings.MIDDLEWARE_CLASSES = [ - DJ_INSTANA_MIDDLEWARE - ] + settings.MIDDLEWARE_CLASSES - else: - logger.warning("Instana: Couldn't add InstanaMiddleware to Django") + match settings.MIDDLEWARE_CLASSES: + case tuple(): + settings.MIDDLEWARE_CLASSES = ( + DJ_INSTANA_MIDDLEWARE, + ) + settings.MIDDLEWARE_CLASSES + case list(): + settings.MIDDLEWARE_CLASSES = [ + DJ_INSTANA_MIDDLEWARE + ] + settings.MIDDLEWARE_CLASSES + case _: + logger.warning( + "Instana: Couldn't add InstanaMiddleware to Django" + ) else: # pragma: no cover logger.warning("Instana: Couldn't find middleware settings") diff --git a/src/instana/instrumentation/fastapi.py b/src/instana/instrumentation/fastapi.py index bb163129..f890813d 100644 --- a/src/instana/instrumentation/fastapi.py +++ b/src/instana/instrumentation/fastapi.py @@ -65,14 +65,15 @@ def init_with_instana( kwargs: Dict[str, Any], ) -> None: middleware = kwargs.get("middleware") - if middleware is None: - kwargs["middleware"] = [Middleware(InstanaASGIMiddleware)] - elif isinstance(middleware, list): - middleware.append(Middleware(InstanaASGIMiddleware)) - elif isinstance(middleware, tuple): - kwargs["middleware"] = (*middleware, Middleware(InstanaASGIMiddleware)) - else: - logger.warning("Unsupported FastAPI middleware sequence type.") + match middleware: + case None: + kwargs["middleware"] = [Middleware(InstanaASGIMiddleware)] + case list(): + middleware.append(Middleware(InstanaASGIMiddleware)) + case tuple(): + kwargs["middleware"] = (*middleware, Middleware(InstanaASGIMiddleware)) + case _: + logger.warning("Unsupported FastAPI middleware sequence type.") exception_handlers = kwargs.get("exception_handlers") if exception_handlers is None: diff --git a/src/instana/instrumentation/starlette.py b/src/instana/instrumentation/starlette.py index df9224d7..e2d3a4b3 100644 --- a/src/instana/instrumentation/starlette.py +++ b/src/instana/instrumentation/starlette.py @@ -25,10 +25,11 @@ def init_with_instana( kwargs: Dict[str, Any], ) -> None: middleware = kwargs.get("middleware") - if middleware is None: - kwargs["middleware"] = [Middleware(InstanaASGIMiddleware)] - elif isinstance(middleware, list): - middleware.append(Middleware(InstanaASGIMiddleware)) + match middleware: + case None: + kwargs["middleware"] = [Middleware(InstanaASGIMiddleware)] + case list(): + middleware.append(Middleware(InstanaASGIMiddleware)) return wrapped(*args, **kwargs) diff --git a/src/instana/span/registered_span.py b/src/instana/span/registered_span.py index 8234169a..a1c34b3f 100644 --- a/src/instana/span/registered_span.py +++ b/src/instana/span/registered_span.py @@ -68,32 +68,25 @@ def __init__( ) def _populate_entry_span_data(self, span: "InstanaSpan") -> None: - if span.name in HTTP_SPANS: - self._collect_http_attributes(span) - - elif span.name == "aioamqp-consumer": - self._collect_aioamqp_attributes(span) - - elif span.name == "aws.lambda.entry": - self._collect_lambda_attributes(span) - - elif span.name == "celery-worker": - self._collect_celery_attributes(span) - - elif span.name == "gcps-consumer": - self._collect_gcps_consumer_attributes(span) - - elif span.name == "rabbitmq": - self._collect_rabbitmq_attributes(span) - - elif span.name == "rpc-server": - self._collect_rpc_attributes(span) - - elif span.name.startswith("kafka"): - self._collect_kafka_attributes(span) - - else: - logger.debug(f"SpanRecorder: Unknown entry span: {span.name}") + match span.name: + case name if name in HTTP_SPANS: + self._collect_http_attributes(span) + case "aioamqp-consumer": + self._collect_aioamqp_attributes(span) + case "aws.lambda.entry": + self._collect_lambda_attributes(span) + case "celery-worker": + self._collect_celery_attributes(span) + case "gcps-consumer": + self._collect_gcps_consumer_attributes(span) + case "rabbitmq": + self._collect_rabbitmq_attributes(span) + case "rpc-server": + self._collect_rpc_attributes(span) + case name if name.startswith("kafka"): + self._collect_kafka_attributes(span) + case _: + logger.debug(f"SpanRecorder: Unknown entry span: {span.name}") def _populate_local_span_data(self, span: "InstanaSpan") -> None: if span.name == "render": @@ -105,71 +98,51 @@ def _populate_local_span_data(self, span: "InstanaSpan") -> None: logger.debug(f"SpanRecorder: Unknown local span: {span.name}") def _populate_exit_span_data(self, span: "InstanaSpan") -> None: - if span.name in HTTP_SPANS: - self._collect_http_attributes(span) - - elif span.name == "aioamqp-publisher": - self._collect_aioamqp_attributes(span) - - elif span.name == "boto3": - self._collect_boto3_attributes(span) - - elif span.name == "cassandra": - self._collect_cassandra_attributes(span) - - elif span.name == "celery-client": - self._collect_celery_attributes(span) - - elif span.name == "couchbase": - self._collect_couchbase_attributes(span) - - elif span.name == "dynamodb": - self._collect_dynamodb_attributes(span) - - elif span.name == "elasticsearch": - self._collect_elasticsearch_attributes(span) - - elif span.name == "rabbitmq": - self._collect_rabbitmq_attributes(span) - - elif span.name == "redis": - self._collect_redis_attributes(span) - - elif span.name == "rpc-client": - self._collect_rpc_attributes(span) - - elif span.name == "s3": - self._collect_s3_attributes(span) - - elif span.name == "sqlalchemy": - self._collect_sqlalchemy_attributes(span) - - elif span.name == "mysql": - self._collect_mysql_attributes(span) - - elif span.name == "mssql": - self._collect_mssql_attributes(span) - - elif span.name == "postgres": - self._collect_postgres_attributes(span) - - elif span.name == "mongo": - self._collect_mongo_attributes(span) - - elif span.name == "gcs": - self._collect_gcs_attributes(span) - - elif span.name == "gcps-producer": - self._collect_gcps_producer_attributes(span) - - elif span.name == "log": - self._collect_log_attributes(span) - - elif span.name.startswith("kafka"): - self._collect_kafka_attributes(span) - - else: - logger.debug(f"SpanRecorder: Unknown exit span: {span.name}") + match span.name: + case name if name in HTTP_SPANS: + self._collect_http_attributes(span) + case "aioamqp-publisher": + self._collect_aioamqp_attributes(span) + case "boto3": + self._collect_boto3_attributes(span) + case "cassandra": + self._collect_cassandra_attributes(span) + case "celery-client": + self._collect_celery_attributes(span) + case "couchbase": + self._collect_couchbase_attributes(span) + case "dynamodb": + self._collect_dynamodb_attributes(span) + case "elasticsearch": + self._collect_elasticsearch_attributes(span) + case "rabbitmq": + self._collect_rabbitmq_attributes(span) + case "redis": + self._collect_redis_attributes(span) + case "rpc-client": + self._collect_rpc_attributes(span) + case "s3": + self._collect_s3_attributes(span) + case "sqlalchemy": + self._collect_sqlalchemy_attributes(span) + case "mysql": + self._collect_mysql_attributes(span) + case "mssql": + self._collect_mssql_attributes(span) + case "postgres": + self._collect_postgres_attributes(span) + case "mongo": + self._collect_mongo_attributes(span) + case "gcs": + self._collect_gcs_attributes(span) + case "gcps-producer": + self._collect_gcps_producer_attributes(span) + case "log": + self._collect_log_attributes(span) + case name if name.startswith("kafka"): + self._collect_kafka_attributes(span) + case _: + logger.debug(f"SpanRecorder: Unknown exit span: {span.name}") def _collect_http_attributes(self, span: "InstanaSpan") -> None: self.data["http"]["host"] = span.attributes.pop("http.host", None) @@ -446,39 +419,40 @@ def _collect_lambda_attributes(self, span: "InstanaSpan") -> None: trigger_type = self.data["lambda"]["trigger"] - if trigger_type in ["aws:api.gateway", "aws:application.load.balancer"]: - self._collect_http_attributes(span) - elif trigger_type == "aws:cloudwatch.events": - self.data["lambda"]["cw"]["events"]["id"] = span.attributes.pop( - "data.lambda.cw.events.id", None - ) - self.data["lambda"]["cw"]["events"]["more"] = span.attributes.pop( - "lambda.cw.events.more", False - ) - self.data["lambda"]["cw"]["events"]["resources"] = span.attributes.pop( - "lambda.cw.events.resources", None - ) - elif trigger_type == "aws:cloudwatch.logs": - self.data["lambda"]["cw"]["logs"]["group"] = span.attributes.pop( - "lambda.cw.logs.group", None - ) - self.data["lambda"]["cw"]["logs"]["stream"] = span.attributes.pop( - "lambda.cw.logs.stream", None - ) - self.data["lambda"]["cw"]["logs"]["more"] = span.attributes.pop( - "lambda.cw.logs.more", None - ) - self.data["lambda"]["cw"]["logs"]["events"] = span.attributes.pop( - "lambda.cw.logs.events", None - ) - elif trigger_type == "aws:s3": - self.data["lambda"]["s3"]["events"] = span.attributes.pop( - "lambda.s3.events", None - ) - elif trigger_type == "aws:sqs": - self.data["lambda"]["sqs"]["messages"] = span.attributes.pop( - "lambda.sqs.messages", None - ) + match trigger_type: + case "aws:api.gateway" | "aws:application.load.balancer": + self._collect_http_attributes(span) + case "aws:cloudwatch.events": + self.data["lambda"]["cw"]["events"]["id"] = span.attributes.pop( + "data.lambda.cw.events.id", None + ) + self.data["lambda"]["cw"]["events"]["more"] = span.attributes.pop( + "lambda.cw.events.more", False + ) + self.data["lambda"]["cw"]["events"]["resources"] = span.attributes.pop( + "lambda.cw.events.resources", None + ) + case "aws:cloudwatch.logs": + self.data["lambda"]["cw"]["logs"]["group"] = span.attributes.pop( + "lambda.cw.logs.group", None + ) + self.data["lambda"]["cw"]["logs"]["stream"] = span.attributes.pop( + "lambda.cw.logs.stream", None + ) + self.data["lambda"]["cw"]["logs"]["more"] = span.attributes.pop( + "lambda.cw.logs.more", None + ) + self.data["lambda"]["cw"]["logs"]["events"] = span.attributes.pop( + "lambda.cw.logs.events", None + ) + case "aws:s3": + self.data["lambda"]["s3"]["events"] = span.attributes.pop( + "lambda.s3.events", None + ) + case "aws:sqs": + self.data["lambda"]["sqs"]["messages"] = span.attributes.pop( + "lambda.sqs.messages", None + ) def _collect_log_attributes(self, span: "InstanaSpan") -> None: # use last special key values diff --git a/src/instana/span/span.py b/src/instana/span/span.py index 4ba9291b..2570005d 100644 --- a/src/instana/span/span.py +++ b/src/instana/span/span.py @@ -154,31 +154,32 @@ def record_exception( else: message = repr(exception) - if self.name in ["rpc-server", "rpc-client"]: - self.set_attribute("rpc.error", message) - elif self.name == "mysql": - self.set_attribute("mysql.error", message) - elif self.name == "postgres": - self.set_attribute("pg.error", message) - elif self.name in HTTP_SPANS: - self.set_attribute("http.error", message) - elif self.name in ["celery-client", "celery-worker"]: - self.set_attribute("error", message) - elif self.name == "sqlalchemy": - self.set_attribute("sqlalchemy.err", message) - elif self.name == "aws.lambda.entry": - self.set_attribute("lambda.error", message) - elif self.name.startswith("kafka"): - self.set_attribute("kafka.error", message) - elif self.name == "mssql": - self.set_attribute("mssql.error", message) - else: - _attributes = {"message": message} - if attributes: - _attributes.update(attributes) - self.add_event( - name="exception", attributes=_attributes, timestamp=timestamp - ) + match self.name: + case "rpc-server" | "rpc-client": + self.set_attribute("rpc.error", message) + case "mysql": + self.set_attribute("mysql.error", message) + case "postgres": + self.set_attribute("pg.error", message) + case name if name in HTTP_SPANS: + self.set_attribute("http.error", message) + case "celery-client" | "celery-worker": + self.set_attribute("error", message) + case "sqlalchemy": + self.set_attribute("sqlalchemy.err", message) + case "aws.lambda.entry": + self.set_attribute("lambda.error", message) + case name if name.startswith("kafka"): + self.set_attribute("kafka.error", message) + case "mssql": + self.set_attribute("mssql.error", message) + case _: + _attributes = {"message": message} + if attributes: + _attributes.update(attributes) + self.add_event( + name="exception", attributes=_attributes, timestamp=timestamp + ) except Exception: logger.debug("span.record_exception", exc_info=True) raise diff --git a/src/instana/util/secrets.py b/src/instana/util/secrets.py index c5a01281..fe52a296 100644 --- a/src/instana/util/secrets.py +++ b/src/instana/util/secrets.py @@ -25,29 +25,30 @@ def contains_secret(candidate, matcher, kwlist): logger.debug("contains_secret: bad keyword list") return False - if matcher == 'equals-ignore-case': - for keyword in kwlist: - if candidate.lower() == keyword.lower(): - return True - elif matcher == 'equals': - for keyword in kwlist: - if candidate == keyword: - return True - elif matcher == 'contains-ignore-case': - for keyword in kwlist: - if keyword.lower() in candidate: - return True - elif matcher == 'contains': - for keyword in kwlist: - if keyword in candidate: - return True - elif matcher == 'regex': - for regexp in kwlist: - if re.match(regexp, candidate): - return True - else: - logger.debug("contains_secret: unknown matcher") - return False + match matcher: + case "equals-ignore-case": + for keyword in kwlist: + if candidate.lower() == keyword.lower(): + return True + case "equals": + for keyword in kwlist: + if candidate == keyword: + return True + case "contains-ignore-case": + for keyword in kwlist: + if keyword.lower() in candidate: + return True + case "contains": + for keyword in kwlist: + if keyword in candidate: + return True + case "regex": + for regexp in kwlist: + if re.match(regexp, candidate): + return True + case _: + logger.debug("contains_secret: unknown matcher") + return False except Exception: logger.debug("contains_secret", exc_info=True) @@ -72,58 +73,59 @@ def strip_secrets_from_query(qp, matcher, kwlist): try: if qp is None: - return '' + return "" if not isinstance(kwlist, list): logger.debug("strip_secrets_from_query: bad keyword list") return qp # If there are no key=values, then just return - if '=' not in qp: + if "=" not in qp: return qp - if '?' in qp: - path, query = qp.split('?') + if "?" in qp: + path, query = qp.split("?") else: query = qp params = parse.parse_qsl(query, keep_blank_values=True) - redacted = [''] - - if matcher == 'equals-ignore-case': - for keyword in kwlist: - for index, kv in enumerate(params): - if kv[0].lower() == keyword.lower(): - params[index] = (kv[0], redacted) - elif matcher == 'equals': - for keyword in kwlist: - for index, kv in enumerate(params): - if kv[0] == keyword: - params[index] = (kv[0], redacted) - elif matcher == 'contains-ignore-case': - for keyword in kwlist: - for index, kv in enumerate(params): - if keyword.lower() in kv[0].lower(): - params[index] = (kv[0], redacted) - elif matcher == 'contains': - for keyword in kwlist: - for index, kv in enumerate(params): - if keyword in kv[0]: - params[index] = (kv[0], redacted) - elif matcher == 'regex': - for regexp in kwlist: - for index, kv in enumerate(params): - if re.match(regexp, kv[0]): - params[index] = (kv[0], redacted) - else: - logger.debug("strip_secrets_from_query: unknown matcher") - return qp + redacted = [""] + + match matcher: + case "equals-ignore-case": + for keyword in kwlist: + for index, kv in enumerate(params): + if kv[0].lower() == keyword.lower(): + params[index] = (kv[0], redacted) + case "equals": + for keyword in kwlist: + for index, kv in enumerate(params): + if kv[0] == keyword: + params[index] = (kv[0], redacted) + case "contains-ignore-case": + for keyword in kwlist: + for index, kv in enumerate(params): + if keyword.lower() in kv[0].lower(): + params[index] = (kv[0], redacted) + case "contains": + for keyword in kwlist: + for index, kv in enumerate(params): + if keyword in kv[0]: + params[index] = (kv[0], redacted) + case "regex": + for regexp in kwlist: + for index, kv in enumerate(params): + if re.match(regexp, kv[0]): + params[index] = (kv[0], redacted) + case _: + logger.debug("strip_secrets_from_query: unknown matcher") + return qp result = parse.urlencode(params, doseq=True) query = parse.unquote(result) if path: - query = path + '?' + query + query = path + "?" + query return query except Exception: diff --git a/tests/clients/kafka/test_kafka_python.py b/tests/clients/kafka/test_kafka_python.py index f3228481..21cd7ab0 100644 --- a/tests/clients/kafka/test_kafka_python.py +++ b/tests/clients/kafka/test_kafka_python.py @@ -498,13 +498,13 @@ def test_kafka_consumer_root_exit(self) -> None: producer_span = get_first_span_by_filter( spans, - lambda span: span.n == "kafka" - and span.data["kafka"]["access"] == "send", + lambda span: span.n == "kafka" and span.data["kafka"]["access"] == "send", ) consumer_span = get_first_span_by_filter( spans, - lambda span: span.n == "kafka" - and span.data["kafka"]["access"] == "consume", + lambda span: ( + span.n == "kafka" and span.data["kafka"]["access"] == "consume" + ), ) assert producer_span.s @@ -877,20 +877,21 @@ def test_kafka_downstream_suppression(self) -> None: for topic_partition, partition_messages in messages.items(): for message in partition_messages: - if message.topic == "span-topic_1": - assert message.headers == [("x_instana_l_s", b"0")] - elif message.topic == "span-topic_2": - assert message.headers == [ - ("x_instana_l_s", b"1"), - ( - "x_instana_t", - format_span_id(producer_span_2.t).encode("utf-8"), - ), - ( - "x_instana_s", - format_span_id(producer_span_2.s).encode("utf-8"), - ), - ] + match message.topic: + case "span-topic_1": + assert message.headers == [("x_instana_l_s", b"0")] + case "span-topic_2": + assert message.headers == [ + ("x_instana_l_s", b"1"), + ( + "x_instana_t", + format_span_id(producer_span_2.t).encode("utf-8"), + ), + ( + "x_instana_s", + format_span_id(producer_span_2.s).encode("utf-8"), + ), + ] def test_save_consumer_span_into_context(self, span: "InstanaSpan") -> None: """Test save_consumer_span_into_context function.""" diff --git a/tests/clients/test_aio_pika.py b/tests/clients/test_aio_pika.py index 6d2102c6..98a306ce 100644 --- a/tests/clients/test_aio_pika.py +++ b/tests/clients/test_aio_pika.py @@ -52,17 +52,18 @@ async def publish_message(self, params_combination: str = "both_args") -> None: args = () kwargs = {} - if params_combination == "both_kwargs": - kwargs = {"message": message, "routing_key": queue_name} - elif params_combination == "arg_kwarg": - args = (message,) - kwargs = {"routing_key": queue_name} - elif params_combination == "arg_kwarg_empty_key": - args = (message,) - kwargs = {"routing_key": ""} - else: - # params_combination == "both_args" - args = (message, queue_name) + match params_combination: + case "both_kwargs": + kwargs = {"message": message, "routing_key": queue_name} + case "arg_kwarg": + args = (message,) + kwargs = {"routing_key": queue_name} + case "arg_kwarg_empty_key": + args = (message,) + kwargs = {"routing_key": ""} + case _: + # params_combination == "both_args" + args = (message, queue_name) # Sending the message await exchange.publish(*args, **kwargs) diff --git a/tests/clients/test_httpx.py b/tests/clients/test_httpx.py index bfc15389..458ae833 100644 --- a/tests/clients/test_httpx.py +++ b/tests/clients/test_httpx.py @@ -42,34 +42,41 @@ def _resource(self, request_mode) -> Generator[None, None, None]: async def get_async_response(self, path, request_method, headers) -> httpx.Response: """Asynchronous request function""" async with httpx.AsyncClient() as client: - if request_method == "GET": - response = await client.get( - testenv["flask_server"] + path, headers=headers - ) - elif request_method == "POST": - response = await client.post( - testenv["flask_server"] + path, headers=headers - ) + match request_method: + case "GET": + response = await client.get( + testenv["flask_server"] + path, headers=headers + ) + case "POST": + response = await client.post( + testenv["flask_server"] + path, headers=headers + ) return response # Synchronous request function def get_sync_response(self, path, request_method, headers) -> httpx.Response: """Synchronous request function""" - if request_method == "GET": - response = self.client.get(testenv["flask_server"] + path, headers=headers) - elif request_method == "POST": - response = self.client.post(testenv["flask_server"] + path, headers=headers) + match request_method: + case "GET": + response = self.client.get( + testenv["flask_server"] + path, headers=headers + ) + case "POST": + response = self.client.post( + testenv["flask_server"] + path, headers=headers + ) return response def execute_request( self, request_mode, path, request_method="GET", headers=None ) -> httpx.Response: - if request_mode == "async": - res = self.loop.run_until_complete( - self.get_async_response(path, request_method, headers) - ) - elif request_mode == "sync": - res = self.get_sync_response(path, request_method, headers) + match request_mode: + case "async": + res = self.loop.run_until_complete( + self.get_async_response(path, request_method, headers) + ) + case "sync": + res = self.get_sync_response(path, request_method, headers) return res def test_get_request(self, request_mode) -> None: diff --git a/tests/frameworks/test_werkzeug.py b/tests/frameworks/test_werkzeug.py index de9b6250..9d535790 100644 --- a/tests/frameworks/test_werkzeug.py +++ b/tests/frameworks/test_werkzeug.py @@ -28,19 +28,20 @@ def simple_wsgi_app(environ: dict[str, Any], start_response: Callable) -> list: request = Request(environ) path = request.path - if path == "/": - response = Response("Hello World") - elif path == "/error": - response = Response("Internal Server Error", status=500) - elif path == "/exception": - raise RuntimeError("Test exception") - elif path.startswith("/hello/"): - name = path.split("/")[-1] - response = Response(f"Hello, {name}!") - elif path == "/query": - response = Response(f"Query: {request.query_string.decode()}") - else: - response = Response("Not Found", status=404) + match path: + case "/": + response = Response("Hello World") + case "/error": + response = Response("Internal Server Error", status=500) + case "/exception": + raise RuntimeError("Test exception") + case _ if path.startswith("/hello/"): + name = path.split("/")[-1] + response = Response(f"Hello, {name}!") + case "/query": + response = Response(f"Query: {request.query_string.decode()}") + case _: + response = Response("Not Found", status=404) return response(environ, start_response) diff --git a/tests/span/test_registered_span.py b/tests/span/test_registered_span.py index 71006ee0..eeaf06fc 100644 --- a/tests/span/test_registered_span.py +++ b/tests/span/test_registered_span.py @@ -231,30 +231,30 @@ def test_populate_entry_span_data_AWSlambda( assert reg_span.data["lambda"]["arn"] == "test" assert expected_result["lambda.trigger"] == reg_span.data["lambda"]["trigger"] - if expected_result["lambda.trigger"] == "aws:api.gateway": - assert expected_result["http.host"] == reg_span.data["http"]["host"] - assert expected_result["http.url"] == reg_span.data["http"]["url"] - - elif expected_result["lambda.trigger"] == "aws:cloudwatch.events": - assert ( - expected_result["lambda.cw.events.resources"] - == reg_span.data["lambda"]["cw"]["events"]["resources"] - ) - elif expected_result["lambda.trigger"] == "aws:cloudwatch.logs": - assert ( - expected_result["lambda.cw.logs.group"] - == reg_span.data["lambda"]["cw"]["logs"]["group"] - ) - elif expected_result["lambda.trigger"] == "aws:s3": - assert ( - expected_result["lambda.s3.events"] - == reg_span.data["lambda"]["s3"]["events"] - ) - elif expected_result["lambda.trigger"] == "aws:sqs": - assert ( - expected_result["lambda.sqs.messages"] - == reg_span.data["lambda"]["sqs"]["messages"] - ) + match expected_result["lambda.trigger"]: + case "aws:api.gateway": + assert expected_result["http.host"] == reg_span.data["http"]["host"] + assert expected_result["http.url"] == reg_span.data["http"]["url"] + case "aws:cloudwatch.events": + assert ( + expected_result["lambda.cw.events.resources"] + == reg_span.data["lambda"]["cw"]["events"]["resources"] + ) + case "aws:cloudwatch.logs": + assert ( + expected_result["lambda.cw.logs.group"] + == reg_span.data["lambda"]["cw"]["logs"]["group"] + ) + case "aws:s3": + assert ( + expected_result["lambda.s3.events"] + == reg_span.data["lambda"]["s3"]["events"] + ) + case "aws:sqs": + assert ( + expected_result["lambda.sqs.messages"] + == reg_span.data["lambda"]["sqs"]["messages"] + ) @pytest.mark.parametrize( "span_name, service_name, attributes",