Skip to content

Commit

Permalink
Update pyproject setting, remove pytest.ini and fix ruff findings (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpbede authored Jan 24, 2024
1 parent e382c4d commit c066c97
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 34 deletions.
2 changes: 1 addition & 1 deletion aioelectricitymaps/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


def retry_legacy(
func: Callable[_P, Coroutine[Any, Any, _R]]
func: Callable[_P, Coroutine[Any, Any, _R]],
) -> Callable[_P, Coroutine[Any, Any, _R]]:
"""Decorator to retry a function with the legacy API if SwitchedToLegacyAPI is raised."""

Check failure on line 16 in aioelectricitymaps/decorators.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (D401)

aioelectricitymaps/decorators.py:16:5: D401 First line of docstring should be in imperative mood: "Decorator to retry a function with the legacy API if SwitchedToLegacyAPI is raised."

Check failure on line 16 in aioelectricitymaps/decorators.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (E501)

aioelectricitymaps/decorators.py:16:89: E501 Line too long (93 > 88)

Expand Down
29 changes: 18 additions & 11 deletions aioelectricitymaps/electricitymaps.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Async Python client for electricitymaps.com."""
from __future__ import annotations

from dataclasses import dataclass
import json
import logging
from dataclasses import dataclass
from typing import Any

from aiohttp import ClientSession
Expand Down Expand Up @@ -32,7 +32,6 @@ class ElectricityMaps:

async def _get(self, url: str, params: dict[str, Any] | None = None) -> Any:
"""Execute a GET request against the API."""

if self.session is None:
self.session = ClientSession()
self._close_session = True
Expand All @@ -44,16 +43,18 @@ async def _get(self, url: str, params: dict[str, Any] | None = None) -> Any:

try:
async with self.session.get(
url, headers=headers, params=params
url,
headers=headers,
params=params,
) as response:
parsed = await response.json()
except json.JSONDecodeError as exception:
raise ElectricityMapsDecodeError(
f"JSON decoding failed: {exception}"
f"JSON decoding failed: {exception}",

Check failure on line 53 in aioelectricitymaps/electricitymaps.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (EM102)

aioelectricitymaps/electricitymaps.py:53:17: EM102 Exception must not use an f-string literal, assign to variable first
) from exception

Check failure on line 54 in aioelectricitymaps/electricitymaps.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (TRY003)

aioelectricitymaps/electricitymaps.py:52:19: TRY003 Avoid specifying long messages outside the exception class
except Exception as exc:

Check failure on line 55 in aioelectricitymaps/electricitymaps.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (BLE001)

aioelectricitymaps/electricitymaps.py:55:16: BLE001 Do not catch blind exception: `Exception`
raise ElectricityMapsError(
f"Unknown error occurred while fetching data: {exc}"
f"Unknown error occurred while fetching data: {exc}",

Check failure on line 57 in aioelectricitymaps/electricitymaps.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (EM102)

aioelectricitymaps/electricitymaps.py:57:17: EM102 Exception must not use an f-string literal, assign to variable first
) from exc

Check failure on line 58 in aioelectricitymaps/electricitymaps.py

View workflow job for this annotation

GitHub Actions / Ruff

Ruff (TRY003)

aioelectricitymaps/electricitymaps.py:56:19: TRY003 Avoid specifying long messages outside the exception class
else:
_LOGGER.debug(
Expand All @@ -74,7 +75,7 @@ async def _get(self, url: str, params: dict[str, Any] | None = None) -> Any:
# enable legacy mode and let the function recalled by the decorator
if not self._is_legacy_token:
_LOGGER.debug(
"Detected invalid token on new API, retrying on legacy API."
"Detected invalid token on new API, retrying on legacy API.",
)
self._is_legacy_token = True
raise SwitchedToLegacyAPI
Expand All @@ -85,27 +86,33 @@ async def _get(self, url: str, params: dict[str, Any] | None = None) -> Any:

@retry_legacy
async def latest_carbon_intensity_by_coordinates(
self, lat: str, lon: str
self,
lat: str,
lon: str,
) -> CarbonIntensityResponse:
"""Get carbon intensity by coordinates."""
if self._is_legacy_token:
result = await self._get(
ApiEndpoints.LEGACY_CARBON_INTENSITY, {"lat": lat, "lon": lon}
ApiEndpoints.LEGACY_CARBON_INTENSITY,
{"lat": lat, "lon": lon},
)
else:
result = await self._get(
ApiEndpoints.CARBON_INTENSITY, {"lat": lat, "lon": lon}
ApiEndpoints.CARBON_INTENSITY,
{"lat": lat, "lon": lon},
)
return CarbonIntensityResponse.from_dict(result)

@retry_legacy
async def latest_carbon_intensity_by_country_code(
self, code: str
self,
code: str,
) -> CarbonIntensityResponse:
"""Get carbon intensity by country code."""
if self._is_legacy_token:
result = await self._get(
ApiEndpoints.LEGACY_CARBON_INTENSITY, {"countryCode": code}
ApiEndpoints.LEGACY_CARBON_INTENSITY,
{"countryCode": code},
)
else:
result = await self._get(ApiEndpoints.CARBON_INTENSITY, {"zone": code})
Expand Down
4 changes: 2 additions & 2 deletions aioelectricitymaps/marshmallow.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ class ZoneList(dict[str, Zone], DataClassJsonMixin):
mm_field=fields.Dict(
keys=fields.String(),
values=fields.Nested(Zone.schema()),
)
)
),
),
)
3 changes: 2 additions & 1 deletion aioelectricitymaps/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@ class Zone(DataClassJsonMixin):

zone_name: str = field(metadata=config(letter_case=LetterCase.CAMEL))
country_name: str | None = field(
metadata=config(letter_case=LetterCase.CAMEL), default=None
metadata=config(letter_case=LetterCase.CAMEL),
default=None,
)
33 changes: 19 additions & 14 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,17 @@ aresponses = "^3.0.0"
syrupy = "4.6.0"
yamllint = "^1.33.0"

[tool.coverage.run]
plugins = ["covdefaults"]
source = ["aioelectricitymaps"]
[tool.poetry.urls]
"Bug Tracker" = "https://github.com/jpbede/aioelectricitymaps/issues"
Changelog = "https://github.com/jpbede/aioelectricitymaps/releases"

[tool.coverage.report]
show_missing = true
fail_under = 50

[tool.coverage.run]
plugins = ["covdefaults"]
source = ["aioelectricitymaps"]

[tool.mypy]
# Specify the target platform details in config, so your developers are
Expand All @@ -60,7 +65,6 @@ disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
no_implicit_optional = true
no_implicit_reexport = true
strict_optional = true
warn_incomplete_stub = true
warn_no_return = true
Expand All @@ -70,9 +74,6 @@ warn_unused_configs = true
warn_unused_ignores = true

[tool.pylint.MASTER]
#extension-pkg-whitelist = [
# "orjson",
#]
ignore = [
"tests",
]
Expand All @@ -99,6 +100,10 @@ disable = [
"duplicate-code",
"format",
"unsubscriptable-object",
"too-many-instance-attributes",
"too-many-arguments",
"too-many-public-methods",
"wrong-import-order",
]

[tool.pylint.SIMILARITIES]
Expand All @@ -114,15 +119,15 @@ asyncio_mode = "auto"
[tool.ruff]
ignore = [
"ANN101", # Self... explanatory
"ANN102", # cls... just as useless
"ANN401", # Opinioated warning on disallowing dynamically typed expressions
"D203", # Conflicts with other rules
"D213", # Conflicts with other rules
"D417", # False positives in some occasions
"PLR2004", # Just annoying, not really useful

# Conflicts with the Ruff formatter
"COM812",
"ISC001",
"PLR0913", # Too many arguments
"TCH001",
"TCH003",
]
select = ["ALL"]

Expand All @@ -132,9 +137,9 @@ mark-parentheses = false

[tool.ruff.isort]
known-first-party = ["aioelectricitymaps"]

[tool.ruff.lint.flake8-type-checking]
#runtime-evaluated-base-classes = ["mashumaro.mixins.orjson.DataClassORJSONMixin"]
force-sort-within-sections = true
split-on-trailing-comma = false
combine-as-imports = true

[tool.ruff.mccabe]
max-complexity = 25
Expand Down
2 changes: 0 additions & 2 deletions pytest.ini

This file was deleted.

2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pytest
from aresponses import ResponsesMockServer
import pytest

from . import load_fixture

Expand Down
5 changes: 3 additions & 2 deletions tests/test_electricitymaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from unittest.mock import patch

import aiohttp
import pytest
from aresponses import ResponsesMockServer
import pytest

from aioelectricitymaps import ElectricityMaps
from aioelectricitymaps.exceptions import (
Expand Down Expand Up @@ -42,7 +42,8 @@ async def test_carbon_intensity_by_coordinates(mock_response, snapshot) -> None:
em = ElectricityMaps(token="abc123", session=session)
assert (
await em.latest_carbon_intensity_by_coordinates(
lat="53.1357012", lon="8.2024685"
lat="53.1357012",
lon="8.2024685",
)
== snapshot
)
Expand Down

0 comments on commit c066c97

Please sign in to comment.