Add Redmine API token authentication

This commit is contained in:
Кокос Артем Николаевич
2026-05-22 17:18:30 +07:00
parent 7bc6e024c0
commit 8bc8181ce3
14 changed files with 190 additions and 43 deletions

View File

@@ -1,5 +1,4 @@
import sys
import pytest
from io import StringIO
from unittest import mock
from redmine_reporter.cli import main
@@ -14,6 +13,7 @@ from redmine_reporter.config import Config
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="x",
REDMINE_PASSWORD="y",
)
@@ -34,6 +34,7 @@ def test_cli_smoke_empty(mock_fetch):
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="x",
REDMINE_PASSWORD="y",
)
@@ -48,6 +49,7 @@ def test_cli_returns_zero_on_no_entries(mock_fetch):
@mock.patch.multiple(
Config,
REDMINE_URL="",
REDMINE_API_KEY=None,
REDMINE_USER=None,
REDMINE_PASSWORD=None,
)
@@ -66,6 +68,7 @@ def test_cli_invalid_date_format():
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="x",
REDMINE_PASSWORD="y",
)
@@ -81,6 +84,7 @@ def test_cli_unknown_output_extension(mock_fetch, tmp_path):
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="x",
REDMINE_PASSWORD="y",
)

View File

@@ -1,8 +1,15 @@
import pytest
from unittest import mock
from redmine_reporter.client import fetch_issues_with_spent_time
from redmine_reporter.config import Config
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="user",
REDMINE_PASSWORD="password",
)
@mock.patch("redmine_reporter.client.Redmine")
def test_fetch_aggregates_hours_per_issue(mock_redmine_class):
"""Два time entry на одну задачу -- часы суммируются."""
@@ -34,6 +41,13 @@ def test_fetch_aggregates_hours_per_issue(mock_redmine_class):
assert total_hours == 3.5
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="user",
REDMINE_PASSWORD="password",
)
@mock.patch("redmine_reporter.client.Redmine")
def test_fetch_returns_none_when_no_entries(mock_redmine_class):
"""Нет time entries -- возвращается None."""
@@ -47,6 +61,13 @@ def test_fetch_returns_none_when_no_entries(mock_redmine_class):
assert result is None
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="user",
REDMINE_PASSWORD="password",
)
@mock.patch("redmine_reporter.client.Redmine")
def test_fetch_skips_entries_without_issue(mock_redmine_class):
"""Time entry без привязки к задаче игнорируется."""
@@ -65,6 +86,13 @@ def test_fetch_skips_entries_without_issue(mock_redmine_class):
assert result is None
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="user",
REDMINE_PASSWORD="password",
)
@mock.patch("redmine_reporter.client.Redmine")
def test_fetch_multiple_issues(mock_redmine_class):
"""Несколько задач -- каждая с правильным суммарным временем."""
@@ -100,3 +128,51 @@ def test_fetch_multiple_issues(mock_redmine_class):
hours_by_id = {issue.id: hours for issue, hours in result}
assert hours_by_id[1] == 1.5
assert hours_by_id[2] == 2.0
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY="api-token",
REDMINE_USER="user",
REDMINE_PASSWORD="password",
)
@mock.patch("redmine_reporter.client.Redmine")
def test_fetch_uses_api_key_when_present(mock_redmine_class):
"""Если задан API key, он используется вместо логина/пароля."""
mock_redmine = mock_redmine_class.return_value
mock_user = mock.MagicMock()
mock_user.id = 1
mock_redmine.user.get.return_value = mock_user
mock_redmine.time_entry.filter.return_value = []
fetch_issues_with_spent_time("2026-01-01", "2026-01-31")
_, kwargs = mock_redmine_class.call_args
assert kwargs["key"] == "api-token"
assert "username" not in kwargs
assert "password" not in kwargs
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="user",
REDMINE_PASSWORD="password",
)
@mock.patch("redmine_reporter.client.Redmine")
def test_fetch_uses_username_password_when_no_api_key(mock_redmine_class):
"""Если API key не задан, остаётся старая схема логин/пароль."""
mock_redmine = mock_redmine_class.return_value
mock_user = mock.MagicMock()
mock_user.id = 1
mock_redmine.user.get.return_value = mock_user
mock_redmine.time_entry.filter.return_value = []
fetch_issues_with_spent_time("2026-01-01", "2026-01-31")
_, kwargs = mock_redmine_class.call_args
assert kwargs["username"] == "user"
assert kwargs["password"] == "password"
assert "key" not in kwargs

View File

@@ -1,4 +1,3 @@
import os
import pytest
from unittest import mock
from redmine_reporter.config import Config
@@ -11,24 +10,49 @@ from redmine_reporter.config import Config
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER="test",
REDMINE_PASSWORD="secret",
)
def test_config_valid():
def test_config_valid_with_password_fallback():
Config.validate() # не должно быть исключения
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY="token",
REDMINE_USER=None,
REDMINE_PASSWORD=None,
)
def test_config_valid_with_api_key():
Config.validate() # не должно быть исключения
@mock.patch.multiple(
Config,
REDMINE_URL="",
REDMINE_API_KEY=None,
REDMINE_USER=None,
REDMINE_PASSWORD=None,
)
def test_config_missing():
def test_config_missing_url():
with pytest.raises(ValueError, match="REDMINE_URL"):
Config.validate()
@mock.patch.multiple(
Config,
REDMINE_URL="https://red.eltex.loc",
REDMINE_API_KEY=None,
REDMINE_USER=None,
REDMINE_PASSWORD=None,
)
def test_config_missing_auth():
with pytest.raises(ValueError, match="REDMINE_API_KEY"):
Config.validate()
@mock.patch.multiple(Config, REDMINE_AUTHOR="Иванов И.И.")
def test_get_author():
assert Config.get_author("") == "Иванов И.И."

View File

@@ -7,12 +7,12 @@ from redmine_reporter.formatters.console import TableFormatter, CompactFormatter
from redmine_reporter.formatters.csv import CSVFormatter
from redmine_reporter.formatters.markdown import MarkdownFormatter
from redmine_reporter.formatters.odt import ODTFormatter
from odf.opendocument import OpenDocument, newdoc
from odf.opendocument import OpenDocument, OpenDocumentText
def _make_empty_odt_bytes() -> bytes:
"""Создаёт минимальный валидный ODT-документ в памяти."""
doc = newdoc(doctype="odt")
doc = OpenDocumentText()
buf = io.BytesIO()
doc.save(buf)
return buf.getvalue()
@@ -122,7 +122,9 @@ def odt_formatter():
)
),
):
yield ODTFormatter(author="Тест Автор", from_date="2026-01-01", to_date="2026-01-31")
yield ODTFormatter(
author="Тест Автор", from_date="2026-01-01", to_date="2026-01-31"
)
# -- Параметризованные тесты текстовых форматтеров --
@@ -206,7 +208,9 @@ def test_odt_formatter_save_creates_valid_file(fake_rows, tmp_path):
)
),
):
formatter = ODTFormatter(author="Тест", from_date="2026-01-01", to_date="2026-01-31")
formatter = ODTFormatter(
author="Тест", from_date="2026-01-01", to_date="2026-01-31"
)
output_file = tmp_path / "report.odt"
formatter.save(fake_rows, str(output_file))

View File

@@ -1,6 +1,4 @@
import pytest
from redmine_reporter.report_builder import build_grouped_report, STATUS_TRANSLATION
from redmine_reporter.utils import get_version
class MockIssue:

View File

@@ -1,5 +1,8 @@
import pytest
from redmine_reporter.utils import hours_to_human, get_month_name_from_range, get_version
from redmine_reporter.utils import (
hours_to_human,
get_month_name_from_range,
get_version,
)
def test_hours_to_human_zero():