fix: применить ruff format к 7 файлам

ruff format --check падает на 7 файлах (не 5 как было указано).
Изменения — чистое форматирование: line wrapping, trailing commas, blank lines.
Никаких логических изменений.

Файлы: bot.py, tests/test_commands_news.py, tests/test_commands_pg.py,
tests/test_fetch_weather.py, tests/test_help_command.py,
tests/test_morning_runner.py, utils/pogoda.py
This commit is contained in:
deadzilla 2026-07-22 21:58:55 +05:00
parent 0f3ec2f9bc
commit 1a6b7043ad
8 changed files with 38 additions and 18 deletions

View File

@ -75,7 +75,7 @@
### Высокий приоритет ### Высокий приоритет
- [ ] **`ruff format --check` падает на 5 файлах** — `bot.py`, `utils/__init__.py`, `tests/test_commands_news.py`, `tests/test_help_command.py`, `tests/test_morning_runner.py` требуют применения форматирования - [x] ~~**`ruff format --check` падает на 5 файлах**~~ — применён `ruff format` к 7 файлам (`bot.py`, `tests/test_commands_news.py`, `tests/test_commands_pg.py`, `tests/test_fetch_weather.py`, `tests/test_help_command.py`, `tests/test_morning_runner.py`, `utils/pogoda.py`)
### Средний приоритет ### Средний приоритет

12
bot.py
View File

@ -34,7 +34,8 @@ class TextHelpCommand(commands.HelpCommand):
return f"!{command.qualified_name} {command.signature}" return f"!{command.qualified_name} {command.signature}"
async def send_bot_help( async def send_bot_help(
self, mapping: dict[discord.ext.commands.Command, list[discord.ext.commands.Command]] self,
mapping: dict[discord.ext.commands.Command, list[discord.ext.commands.Command]],
) -> None: ) -> None:
lines: list[str] = ["Доступные команды:"] lines: list[str] = ["Доступные команды:"]
@ -54,9 +55,7 @@ class TextHelpCommand(commands.HelpCommand):
lines.append("\nВведите !<название команды> для использования.") lines.append("\nВведите !<название команды> для использования.")
await self.get_destination().send("\n".join(lines)) await self.get_destination().send("\n".join(lines))
async def send_cog_help( async def send_cog_help(self, cog: discord.ext.commands.Cog) -> None:
self, cog: discord.ext.commands.Cog
) -> None:
commands_with_desc = cog.get_commands() commands_with_desc = cog.get_commands()
lines: list[str] = [f"Команды [{cog.qualified_name}]:"] lines: list[str] = [f"Команды [{cog.qualified_name}]:"]
for command in commands_with_desc: for command in commands_with_desc:
@ -75,9 +74,7 @@ class TextHelpCommand(commands.HelpCommand):
await self.get_destination().send("\n".join(lines)) await self.get_destination().send("\n".join(lines))
async def send_group_help( async def send_group_help(self, group: commands.Group) -> None:
self, group: commands.Group
) -> None:
lines: list[str] = [f"!{group.qualified_name} {group.signature}"] lines: list[str] = [f"!{group.qualified_name} {group.signature}"]
if group.doc: if group.doc:
lines.append(group.short_doc or group.help) lines.append(group.short_doc or group.help)
@ -92,6 +89,7 @@ class TextHelpCommand(commands.HelpCommand):
async def send_error_message(self, error: str) -> None: async def send_error_message(self, error: str) -> None:
await self.get_destination().send(error) await self.get_destination().send(error)
load_dotenv() load_dotenv()
intents = discord.Intents.default() intents = discord.Intents.default()

View File

@ -41,7 +41,13 @@ class TestNewsCommand:
def _make_articles(self, count: int = 3) -> list[dict]: def _make_articles(self, count: int = 3) -> list[dict]:
return [ return [
{"title": f"Статья {i}", "link": f"https://habr.com/article/{i}", "pub_date": f"Mon, 28 May 2026 10:00:00 +0000", "creator": "author", "tags": []} {
"title": f"Статья {i}",
"link": f"https://habr.com/article/{i}",
"pub_date": f"Mon, 28 May 2026 10:00:00 +0000",
"creator": "author",
"tags": [],
}
for i in range(1, count + 1) for i in range(1, count + 1)
] ]

View File

@ -109,7 +109,9 @@ class TestPgCommand:
"""wind_speed_mps — не число — показываются порывы ветра (gust fallback).""" """wind_speed_mps — не число — показываются порывы ветра (gust fallback)."""
cog = self._make_cog() cog = self._make_cog()
ctx = self._make_ctx() ctx = self._make_ctx()
weather = self._make_weather_data(wind_speed_mps="abc") # gust=8.0, dir=n по умолчанию weather = self._make_weather_data(
wind_speed_mps="abc"
) # gust=8.0, dir=n по умолчанию
with patch("commands.pg.fetch_weather", new=AsyncMock(return_value=weather)): with patch("commands.pg.fetch_weather", new=AsyncMock(return_value=weather)):
await cog.pg.callback(cog, ctx) await cog.pg.callback(cog, ctx)
@ -138,7 +140,9 @@ class TestPgCommand:
"""wind_speed_mps = 0 — 0.0 + порывы + направление.""" """wind_speed_mps = 0 — 0.0 + порывы + направление."""
cog = self._make_cog() cog = self._make_cog()
ctx = self._make_ctx() ctx = self._make_ctx()
weather = self._make_weather_data(wind_speed_mps=0) # gust=8.0, dir=n по умолчанию weather = self._make_weather_data(
wind_speed_mps=0
) # gust=8.0, dir=n по умолчанию
with patch("commands.pg.fetch_weather", new=AsyncMock(return_value=weather)): with patch("commands.pg.fetch_weather", new=AsyncMock(return_value=weather)):
await cog.pg.callback(cog, ctx) await cog.pg.callback(cog, ctx)

View File

@ -88,7 +88,9 @@ class TestFetchWeather:
result = await fetch_weather() result = await fetch_weather()
assert result is not None assert result is not None
assert result["current_condition"][0]["weatherDesc"] == [{"value": "Неизвестно"}] assert result["current_condition"][0]["weatherDesc"] == [
{"value": "Неизвестно"}
]
@patch("utils.pogoda._session.get") @patch("utils.pogoda._session.get")
async def test_fetch_weather_ssl_error_retry(self, mock_get) -> None: async def test_fetch_weather_ssl_error_retry(self, mock_get) -> None:
@ -261,7 +263,9 @@ class TestFetchWeather:
assert result is not None assert result is not None
assert result["current_condition"][0]["temp_C"] == -15 assert result["current_condition"][0]["temp_C"] == -15
assert result["current_condition"][0]["weatherDesc"] == [{"value": "Сильный снег"}] assert result["current_condition"][0]["weatherDesc"] == [
{"value": "Сильный снег"}
]
@patch("utils.pogoda._session.get") @patch("utils.pogoda._session.get")
async def test_fetch_weather_includes_headers(self, mock_get) -> None: async def test_fetch_weather_includes_headers(self, mock_get) -> None:

View File

@ -14,6 +14,7 @@ sys.path.insert(0, str(ROOT_DIR))
def help_command() -> "bot.TextHelpCommand": def help_command() -> "bot.TextHelpCommand":
"""Создать экземпляр TextHelpCommand.""" """Создать экземпляр TextHelpCommand."""
import bot import bot
return bot.TextHelpCommand() return bot.TextHelpCommand()

View File

@ -243,6 +243,4 @@ class TestRunMorningWithFallback:
# Проверяем, что в тексте есть погода и нет fallback сообщения # Проверяем, что в тексте есть погода и нет fallback сообщения
assert "Погода в Магнитогорске" in message_text assert "Погода в Магнитогорске" in message_text
assert ( assert "Не удалось получить данные из внешних источников" not in message_text
"Не удалось получить данные из внешних источников" not in message_text
)

View File

@ -71,7 +71,10 @@ async def fetch_weather(
async with _weather_cache_lock: async with _weather_cache_lock:
cached_data, cached_time = _weather_cache cached_data, cached_time = _weather_cache
if time.monotonic() - cached_time < _WEATHER_CACHE_TTL: if time.monotonic() - cached_time < _WEATHER_CACHE_TTL:
logger.debug("Погода: возвращены данные из кэша (TTL %.0f сек)", _WEATHER_CACHE_TTL) logger.debug(
"Погода: возвращены данные из кэша (TTL %.0f сек)",
_WEATHER_CACHE_TTL,
)
return cached_data return cached_data
await yandex_weather_limiter.acquire() await yandex_weather_limiter.acquire()
@ -92,7 +95,13 @@ async def fetch_weather(
{ {
"temp_C": fact.get("temp"), "temp_C": fact.get("temp"),
"FeelsLikeC": fact.get("feels_like"), "FeelsLikeC": fact.get("feels_like"),
"weatherDesc": [{"value": yandex_condition_to_russian(fact.get("condition"))}], "weatherDesc": [
{
"value": yandex_condition_to_russian(
fact.get("condition")
)
}
],
"humidity": fact.get("humidity"), "humidity": fact.get("humidity"),
"wind_speed_mps": fact.get("wind_speed"), "wind_speed_mps": fact.get("wind_speed"),
"wind_gust": fact.get("wind_gust"), "wind_gust": fact.get("wind_gust"),