Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add UP and FA rules to ruff #3155

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

import logging
import re
from collections import defaultdict
from itertools import chain
from typing import Dict, Mapping, Sequence
from typing import Mapping, Sequence

import requests
import snappy
Expand Down Expand Up @@ -71,14 +72,14 @@ class PrometheusRemoteWriteMetricsExporter(MetricExporter):
def __init__(
self,
endpoint: str,
basic_auth: Dict = None,
headers: Dict = None,
basic_auth: dict = None,
headers: dict = None,
timeout: int = 30,
tls_config: Dict = None,
proxies: Dict = None,
tls_config: dict = None,
proxies: dict = None,
resources_as_labels: bool = True,
preferred_temporality: Dict[type, AggregationTemporality] = None,
preferred_aggregation: Dict = None,
preferred_temporality: dict[type, AggregationTemporality] = None,
preferred_aggregation: dict = None,
):
self.endpoint = endpoint
self.basic_auth = basic_auth
Expand Down Expand Up @@ -115,7 +116,7 @@ def basic_auth(self):
return self._basic_auth

@basic_auth.setter
def basic_auth(self, basic_auth: Dict):
def basic_auth(self, basic_auth: dict):
if basic_auth:
if "username" not in basic_auth:
raise ValueError("username required in basic_auth")
Expand Down Expand Up @@ -147,7 +148,7 @@ def tls_config(self):
return self._tls_config

@tls_config.setter
def tls_config(self, tls_config: Dict):
def tls_config(self, tls_config: dict):
if tls_config:
new_config = {}
if "ca_file" in tls_config:
Expand All @@ -170,15 +171,15 @@ def proxies(self):
return self._proxies

@proxies.setter
def proxies(self, proxies: Dict):
def proxies(self, proxies: dict):
self._proxies = proxies

@property
def headers(self):
return self._headers

@headers.setter
def headers(self, headers: Dict):
def headers(self, headers: dict):
self._headers = headers

def export(
Expand Down Expand Up @@ -355,7 +356,7 @@ def _build_message(timeseries: Sequence[TimeSeries]) -> bytes:
serialized_message = write_request.SerializeToString()
return snappy.compress(serialized_message)

def _build_headers(self) -> Dict:
def _build_headers(self) -> dict:
headers = {
"Content-Encoding": "snappy",
"Content-Type": "application/x-protobuf",
Expand All @@ -367,7 +368,7 @@ def _build_headers(self) -> Dict:
return headers

def _send_message(
self, message: bytes, headers: Dict
self, message: bytes, headers: dict
) -> MetricExportResult:
auth = None
if self.basic_auth:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,18 +314,18 @@ def test_invalid_export(prom_rw):
@patch("requests.post")
def test_valid_send_message(mock_post, prom_rw):
mock_post.return_value.configure_mock(**{"ok": True})
result = prom_rw._send_message(bytes(), {})
result = prom_rw._send_message(b"", {})
assert mock_post.call_count == 1
assert result == MetricExportResult.SUCCESS


def test_invalid_send_message(prom_rw):
result = prom_rw._send_message(bytes(), {})
result = prom_rw._send_message(b"", {})
assert result == MetricExportResult.FAILURE


# Verifies that build_message calls snappy.compress and returns SerializedString
@patch("snappy.compress", return_value=bytes())
@patch("snappy.compress", return_value=b"")
def test_build_message(mock_compress, prom_rw):
message = prom_rw._build_message([TimeSeries()])
assert mock_compress.call_count == 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@
.. _Rich: https://rich.readthedocs.io/
.. _OpenTelemetry: https://github.com/open-telemetry/opentelemetry-python/
"""

# pylint: disable=import-error
from __future__ import annotations

import datetime
import typing
from typing import Dict, Optional

from rich.console import Console
from rich.syntax import Syntax
Expand Down Expand Up @@ -150,7 +151,7 @@ class RichConsoleSpanExporter(SpanExporter):

def __init__(
self,
service_name: Optional[str] = None,
service_name: str | None = None,
):
self.service_name = service_name
self.console = Console()
Expand All @@ -165,7 +166,7 @@ def export(self, spans: typing.Sequence[ReadableSpan]) -> SpanExportResult:
return SpanExportResult.SUCCESS

@staticmethod
def spans_to_tree(spans: typing.Sequence[ReadableSpan]) -> Dict[str, Tree]:
def spans_to_tree(spans: typing.Sequence[ReadableSpan]) -> dict[str, Tree]:
trees = {}
parents = {}
spans = list(spans)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from typing import Optional
from __future__ import annotations

from openai import Stream

Expand Down Expand Up @@ -201,12 +199,12 @@ def append_tool_call(self, tool_call):

class StreamWrapper:
span: Span
response_id: Optional[str] = None
response_model: Optional[str] = None
service_tier: Optional[str] = None
response_id: str | None = None
response_model: str | None = None
service_tier: str | None = None
finish_reasons: list = []
prompt_tokens: Optional[int] = 0
completion_tokens: Optional[int] = 0
prompt_tokens: int | None = 0
completion_tokens: int | None = 0

def __init__(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

from os import environ
from typing import Mapping, Optional, Union
from typing import Mapping
from urllib.parse import urlparse

from httpx import URL
Expand Down Expand Up @@ -179,7 +180,7 @@ def is_streaming(kwargs):
return non_numerical_value_is_set(kwargs.get("stream"))


def non_numerical_value_is_set(value: Optional[Union[bool, str]]):
def non_numerical_value_is_set(value: bool | str | None):
return bool(value) and value != NOT_GIVEN


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-locals

from typing import Optional
from __future__ import annotations

import pytest
from openai import APIConnectionError, AsyncOpenAI, NotFoundError
Expand Down Expand Up @@ -802,8 +801,8 @@ def assert_all_attributes(
request_model: str,
response_id: str = None,
response_model: str = None,
input_tokens: Optional[int] = None,
output_tokens: Optional[int] = None,
input_tokens: int | None = None,
output_tokens: int | None = None,
operation_name: str = "chat",
server_address: str = "api.openai.com",
):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-locals

from typing import Optional
from __future__ import annotations

import pytest
from openai import APIConnectionError, NotFoundError, OpenAI
Expand Down Expand Up @@ -779,8 +778,8 @@ def assert_all_attributes(
request_model: str,
response_id: str = None,
response_model: str = None,
input_tokens: Optional[int] = None,
output_tokens: Optional[int] = None,
input_tokens: int | None = None,
output_tokens: int | None = None,
operation_name: str = "chat",
server_address: str = "api.openai.com",
):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any, Callable, Optional
from __future__ import annotations

from typing import Any, Callable

from aio_pika import Queue
from aio_pika.abc import AbstractIncomingMessage
Expand All @@ -28,7 +30,7 @@ def __init__(self, tracer: Tracer, queue: Queue):
self._tracer = tracer
self._queue = queue

def _get_span(self, message: AbstractIncomingMessage) -> Optional[Span]:
def _get_span(self, message: AbstractIncomingMessage) -> Span | None:
builder = SpanBuilder(self._tracer)
builder.set_as_consumer()
builder.set_operation(MessagingOperationValues.RECEIVE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Callable, Optional
from __future__ import annotations

from typing import Callable

import aiormq
from aio_pika import Exchange
Expand All @@ -29,7 +31,7 @@ def __init__(self, tracer: Tracer, exchange: Exchange):

def _get_publish_span(
self, message: AbstractMessage, routing_key: str
) -> Optional[Span]:
) -> Span | None:
builder = SpanBuilder(self._tracer)
builder.set_as_producer()
builder.set_destination(f"{self._exchange.name},{routing_key}")
Expand All @@ -40,7 +42,7 @@ def _get_publish_span(
def decorate(self, publish: Callable) -> Callable:
async def decorated_publish(
message: AbstractMessage, routing_key: str, **kwargs
) -> Optional[aiormq.abc.ConfirmationFrameType]:
) -> aiormq.abc.ConfirmationFrameType | None:
span = self._get_publish_span(message, routing_key)
if not span:
return await publish(message, routing_key, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
from __future__ import annotations

from aio_pika.abc import AbstractChannel, AbstractMessage

Expand Down Expand Up @@ -77,7 +77,7 @@ def set_message(self, message: AbstractMessage):
properties.correlation_id
)

def build(self) -> Optional[Span]:
def build(self) -> Span | None:
if not is_instrumentation_enabled():
return None
if self._operation:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

import asyncio
from typing import Type
from unittest import TestCase, mock, skipIf
from unittest.mock import MagicMock

Expand Down Expand Up @@ -70,7 +71,7 @@ def test_get_publish_span(self):
attributes=self.EXPECTED_ATTRIBUTES,
)

def _test_publish(self, exchange_type: Type[Exchange]):
def _test_publish(self, exchange_type: type[Exchange]):
exchange = exchange_type(CONNECTION_7, CHANNEL_7, EXCHANGE_NAME)
with mock.patch.object(
PublishDecorator, "_get_publish_span"
Expand Down Expand Up @@ -149,7 +150,7 @@ def test_get_publish_span(self):
attributes=self.EXPECTED_ATTRIBUTES,
)

def _test_publish(self, exchange_type: Type[Exchange]):
def _test_publish(self, exchange_type: type[Exchange]):
exchange = exchange_type(CONNECTION_8, CHANNEL_8, EXCHANGE_NAME)
with mock.patch.object(
PublishDecorator, "_get_publish_span"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ def response_hook(span: Span, params: typing.Union[
---
"""

from __future__ import annotations

import types
import typing
from typing import Collection
Expand Down Expand Up @@ -323,9 +325,7 @@ def _instrument(
url_filter: _UrlFilterT = None,
request_hook: _RequestHookT = None,
response_hook: _ResponseHookT = None,
trace_configs: typing.Optional[
typing.Sequence[aiohttp.TraceConfig]
] = None,
trace_configs: typing.Sequence[aiohttp.TraceConfig] | None = None,
sem_conv_opt_in_mode: _StabilityMode = _StabilityMode.DEFAULT,
):
"""Enables tracing of all ClientSessions
Expand Down
Loading
Loading