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 2 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 @@ -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 @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import asyncio
import contextlib
import typing
Expand Down Expand Up @@ -51,7 +53,7 @@

def run_with_test_server(
runnable: typing.Callable, url: str, handler: typing.Callable
) -> typing.Tuple[str, int]:
) -> str | int:
async def do_request():
app = aiohttp.web.Application()
parsed_url = urllib.parse.urlparse(url)
Expand Down Expand Up @@ -107,7 +109,7 @@ def _http_request(
status_code: int = HTTPStatus.OK,
request_handler: typing.Callable = None,
**kwargs,
) -> typing.Tuple[str, int]:
) -> tuple[str, int]:
"""Helper to start an aiohttp test server and send an actual HTTP request to it."""

async def default_handler(request):
Expand Down Expand Up @@ -269,10 +271,8 @@ def request_hook(span: Span, params: aiohttp.TraceRequestStartParams):

def response_hook(
span: Span,
params: typing.Union[
aiohttp.TraceRequestEndParams,
aiohttp.TraceRequestExceptionParams,
],
params: aiohttp.TraceRequestEndParams
| aiohttp.TraceRequestExceptionParams,
):
span.set_attribute("response_hook_attr", "value")

Expand Down Expand Up @@ -646,7 +646,7 @@ def tearDown(self):
@staticmethod
# pylint:disable=unused-argument
async def default_handler(request):
return aiohttp.web.Response(status=int(200))
return aiohttp.web.Response(status=200)

@staticmethod
def get_default_request(url: str = URL):
Expand Down Expand Up @@ -861,10 +861,8 @@ def request_hook(span: Span, params: aiohttp.TraceRequestStartParams):

def response_hook(
span: Span,
params: typing.Union[
aiohttp.TraceRequestEndParams,
aiohttp.TraceRequestExceptionParams,
],
params: aiohttp.TraceRequestEndParams
| aiohttp.TraceRequestExceptionParams,
):
span.set_attribute("response_hook_attr", "value")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def test_context_setter(self) -> None:

carrier_list = [("key1", b"val1")]
context_setter.set(carrier_list, "key2", "val2")
self.assertTrue(("key2", "val2".encode()) in carrier_list)
self.assertTrue(("key2", b"val2") in carrier_list)

def test_context_getter(self) -> None:
context_setter = AIOKafkaContextSetter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ def test_context_setter(self) -> None:
carrier_dict = {"key1": "val1"}
context_setter.set(carrier_dict, "key2", "val2")
self.assertGreaterEqual(
carrier_dict.items(), {"key2": "val2".encode()}.items()
carrier_dict.items(), {"key2": b"val2"}.items()
)

carrier_list = [("key1", "val1")]
context_setter.set(carrier_list, "key2", "val2")
self.assertTrue(("key2", "val2".encode()) in carrier_list)
self.assertTrue(("key2", b"val2") in carrier_list)

def test_context_getter(self) -> None:
context_setter = KafkaContextSetter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,17 +253,15 @@ class RequestInfo(typing.NamedTuple):
method: bytes
url: httpx.URL
headers: httpx.Headers | None
stream: typing.Optional[
typing.Union[httpx.SyncByteStream, httpx.AsyncByteStream]
]
extensions: typing.Optional[dict]
stream: httpx.SyncByteStream | httpx.AsyncByteStream | None
extensions: dict | None


class ResponseInfo(typing.NamedTuple):
status_code: int
headers: httpx.Headers | None
stream: typing.Iterable[bytes]
extensions: typing.Optional[dict]
extensions: dict | None


def _get_default_span_name(method: str) -> str:
Expand All @@ -274,7 +272,7 @@ def _get_default_span_name(method: str) -> str:
return method


def _prepare_headers(headers: typing.Optional[Headers]) -> httpx.Headers:
def _prepare_headers(headers: Headers | None) -> httpx.Headers:
return httpx.Headers(headers)


Expand Down Expand Up @@ -311,10 +309,8 @@ def _inject_propagation_headers(headers, args, kwargs):


def _extract_response(
response: typing.Union[
httpx.Response, typing.Tuple[int, Headers, httpx.SyncByteStream, dict]
],
) -> typing.Tuple[int, Headers, httpx.SyncByteStream, dict, str]:
response: httpx.Response | tuple[int, Headers, httpx.SyncByteStream, dict],
) -> tuple[int, Headers, httpx.SyncByteStream, dict, str]:
if isinstance(response, httpx.Response):
status_code = response.status_code
headers = response.headers
Expand All @@ -332,7 +328,7 @@ def _extract_response(

def _apply_request_client_attributes_to_span(
span_attributes: dict,
url: typing.Union[str, URL, httpx.URL],
url: str | URL | httpx.URL,
method_original: str,
semconv: _StabilityMode,
):
Expand Down Expand Up @@ -407,9 +403,9 @@ class SyncOpenTelemetryTransport(httpx.BaseTransport):
def __init__(
self,
transport: httpx.BaseTransport,
tracer_provider: typing.Optional[TracerProvider] = None,
request_hook: typing.Optional[RequestHook] = None,
response_hook: typing.Optional[ResponseHook] = None,
tracer_provider: TracerProvider | None = None,
request_hook: RequestHook | None = None,
response_hook: ResponseHook | None = None,
):
_OpenTelemetrySemanticConventionStability._initialize()
self._sem_conv_opt_in_mode = _OpenTelemetrySemanticConventionStability._get_opentelemetry_stability_opt_in_mode(
Expand All @@ -426,15 +422,15 @@ def __init__(
self._request_hook = request_hook
self._response_hook = response_hook

def __enter__(self) -> "SyncOpenTelemetryTransport":
def __enter__(self) -> SyncOpenTelemetryTransport:
self._transport.__enter__()
return self

def __exit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]] = None,
exc_value: typing.Optional[BaseException] = None,
traceback: typing.Optional[TracebackType] = None,
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: TracebackType | None = None,
) -> None:
self._transport.__exit__(exc_type, exc_value, traceback)

Expand All @@ -443,10 +439,7 @@ def handle_request(
self,
*args,
**kwargs,
) -> typing.Union[
typing.Tuple[int, "Headers", httpx.SyncByteStream, dict],
httpx.Response,
]:
) -> tuple[int, Headers, httpx.SyncByteStream, dict] | httpx.Response:
"""Add request info to span."""
if not is_http_instrumentation_enabled():
return self._transport.handle_request(*args, **kwargs)
Expand Down Expand Up @@ -532,9 +525,9 @@ class AsyncOpenTelemetryTransport(httpx.AsyncBaseTransport):
def __init__(
self,
transport: httpx.AsyncBaseTransport,
tracer_provider: typing.Optional[TracerProvider] = None,
request_hook: typing.Optional[AsyncRequestHook] = None,
response_hook: typing.Optional[AsyncResponseHook] = None,
tracer_provider: TracerProvider | None = None,
request_hook: AsyncRequestHook | None = None,
response_hook: AsyncResponseHook | None = None,
):
_OpenTelemetrySemanticConventionStability._initialize()
self._sem_conv_opt_in_mode = _OpenTelemetrySemanticConventionStability._get_opentelemetry_stability_opt_in_mode(
Expand All @@ -551,25 +544,22 @@ def __init__(
self._request_hook = request_hook
self._response_hook = response_hook

async def __aenter__(self) -> "AsyncOpenTelemetryTransport":
async def __aenter__(self) -> AsyncOpenTelemetryTransport:
await self._transport.__aenter__()
return self

async def __aexit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]] = None,
exc_value: typing.Optional[BaseException] = None,
traceback: typing.Optional[TracebackType] = None,
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: TracebackType | None = None,
) -> None:
await self._transport.__aexit__(exc_type, exc_value, traceback)

# pylint: disable=R0914
async def handle_async_request(
self, *args, **kwargs
) -> typing.Union[
typing.Tuple[int, "Headers", httpx.AsyncByteStream, dict],
httpx.Response,
]:
) -> tuple[int, Headers, httpx.AsyncByteStream, dict] | httpx.Response:
"""Add request info to span."""
if not is_http_instrumentation_enabled():
return await self._transport.handle_async_request(*args, **kwargs)
Expand Down Expand Up @@ -872,14 +862,10 @@ async def _handle_async_request_wrapper( # pylint: disable=too-many-locals
@classmethod
def instrument_client(
cls,
client: typing.Union[httpx.Client, httpx.AsyncClient],
client: httpx.Client | httpx.AsyncClient,
tracer_provider: TracerProvider = None,
request_hook: typing.Union[
typing.Optional[RequestHook], typing.Optional[AsyncRequestHook]
] = None,
response_hook: typing.Union[
typing.Optional[ResponseHook], typing.Optional[AsyncResponseHook]
] = None,
request_hook: RequestHook | AsyncRequestHook | None = None,
response_hook: ResponseHook | AsyncResponseHook | None = None,
) -> None:
"""Instrument httpx Client or AsyncClient

Expand Down Expand Up @@ -978,7 +964,7 @@ def instrument_client(

@staticmethod
def uninstrument_client(
client: typing.Union[httpx.Client, httpx.AsyncClient],
client: httpx.Client | httpx.AsyncClient,
):
"""Disables instrumentation for the given client instance

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
DEFAULT_LOGGING_FORMAT = "%(asctime)s %(levelname)s [%(name)s] [%(filename)s:%(lineno)d] [trace_id=%(otelTraceID)s span_id=%(otelSpanID)s resource.service.name=%(otelServiceName)s trace_sampled=%(otelTraceSampled)s] - %(message)s"


_MODULE_DOC = """
_MODULE_DOC = f"""
The OpenTelemetry ``logging`` integration automatically injects tracing context into log statements.

The integration registers a custom log record factory with the the standard library logging module that automatically inject
Expand All @@ -33,7 +33,7 @@

.. code-block::

{default_logging_format}
{DEFAULT_LOGGING_FORMAT}

Enable trace context injection
------------------------------
Expand Down Expand Up @@ -77,7 +77,7 @@

.. code-block::

{default_logging_format}
{DEFAULT_LOGGING_FORMAT}

.. envvar:: OTEL_PYTHON_LOG_LEVEL

Expand Down Expand Up @@ -136,4 +136,4 @@
are not injected into the log record objects. This means any attempted log statements made after setting the logging format and before enabling this integration
will result in KeyError exceptions. Such exceptions are automatically swallowed by the logging module and do not result in crashes but you may still lose out
on important log messages.
""".format(default_logging_format=DEFAULT_LOGGING_FORMAT)
"""
Original file line number Diff line number Diff line change
Expand Up @@ -406,12 +406,10 @@ def test_metric_uninstrument(self):
with request.urlopen(self.URL):
self.assertEqual(
len(
(
self.memory_metrics_reader.get_metrics_data()
.resource_metrics[0]
.scope_metrics[0]
.metrics
)
self.memory_metrics_reader.get_metrics_data()
.resource_metrics[0]
.scope_metrics[0]
.metrics
),
3,
)
Expand Down Expand Up @@ -453,12 +451,10 @@ def test_metric_uninstrument(self):
with request.urlopen(self.URL):
self.assertEqual(
len(
(
self.memory_metrics_reader.get_metrics_data()
.resource_metrics[0]
.scope_metrics[0]
.metrics
)
self.memory_metrics_reader.get_metrics_data()
.resource_metrics[0]
.scope_metrics[0]
.metrics
),
3,
)
Expand Down Expand Up @@ -502,12 +498,10 @@ def test_metric_uninstrument(self):
with request.urlopen(self.URL):
self.assertEqual(
len(
(
self.memory_metrics_reader.get_metrics_data()
.resource_metrics[0]
.scope_metrics[0]
.metrics
)
self.memory_metrics_reader.get_metrics_data()
.resource_metrics[0]
.scope_metrics[0]
.metrics
),
3,
)
Expand Down
18 changes: 10 additions & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ output-format = "concise"
# https://docs.astral.sh/ruff/linter/#rule-selection
# pylint: https://github.com/astral-sh/ruff/issues/970
select = [
"I", # isort
"F", # pyflakes
"E", # pycodestyle errors
"W", # pycodestyle warnings
"PLC", # pylint convention
"PLE", # pylint error
"Q", # flake8-quotes
"A", # flake8-builtins
"I", # https://docs.astral.sh/ruff/rules/#isort-i
"F", # https://docs.astral.sh/ruff/rules/#pyflakes-f
"E", # https://docs.astral.sh/ruff/rules/#error-e
"W", # https://docs.astral.sh/ruff/rules/#warning-w
"PLC", # https://docs.astral.sh/ruff/rules/#convention-c
"PLE", # https://docs.astral.sh/ruff/rules/#error-e_1
"Q", # https://docs.astral.sh/ruff/rules/#flake8-quotes-q
"A", # https://docs.astral.sh/ruff/rules/#flake8-builtins-a
"UP", # https://docs.astral.sh/ruff/rules/#pyupgrade-up
"FA" # https://docs.astral.sh/ruff/rules/#flake8-future-annotations-fa
Comment on lines +23 to +24
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those two are the additions from this PR.

]
ignore = [
"E501", # line-too-long
Expand Down
4 changes: 2 additions & 2 deletions scripts/eachdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,11 +588,11 @@ def update_changelog(path, version, new_entry):

def update_changelogs(version):
today = datetime.now().strftime("%Y-%m-%d")
new_entry = """## [Unreleased](https://github.com/open-telemetry/opentelemetry-python/compare/v{version}...HEAD)
new_entry = f"""## [Unreleased](https://github.com/open-telemetry/opentelemetry-python/compare/v{version}...HEAD)

## [{version}](https://github.com/open-telemetry/opentelemetry-python/releases/tag/v{version}) - {today}

""".format(version=version, today=today)
"""
errors = False
try:
update_changelog("./CHANGELOG.md", version, new_entry)
Expand Down
Loading
Loading