Skip to content

feat: add debug logging for auth token expiry and renewal decisions#102

Merged
Veldkornet merged 2 commits into
HiDiHo01:mainfrom
Veldkornet:feat/auth-token-expiry-debug-logging
Jun 17, 2026
Merged

feat: add debug logging for auth token expiry and renewal decisions#102
Veldkornet merged 2 commits into
HiDiHo01:mainfrom
Veldkornet:feat/auth-token-expiry-debug-logging

Conversation

@Veldkornet

@Veldkornet Veldkornet commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds detailed debug logging around authentication token lifetime, renewal thresholds, and token update decisions to facilitate easier troubleshooting and observability of the authentication lifecycle.

Key Changes

  1. Defined class constant TOKEN_RENEWAL_MARGIN = timedelta(minutes=5) on FrankEnergie class to match the client's token renewal buffer.
  2. Implemented debug logging for token expiry checks (exposing now, expires_at, and remaining time) during validate_authentication and _requires_token_refresh.
  3. Implemented debug logging for renewal triggers when a token's lifetime falls within the renewal margin.
  4. Implemented debug logging for successful token updates on login and renew_token, including fallback handling for mock/test tokens.
  5. Added unit test test_renew_token_logging in tests/test_renew_token.py to assert that all logging paths are correctly executed and verify output formatting.

Why this is needed

Resolves #93. This logging provides visibility into token expiry times, timezone alignments, and client renewal actions, which is essential for diagnosing authentication failures in production environments.

Summary by Sourcery

Voeg observability toe aan de authenticatie‑levenscyclus door het loggen van token-vervalcontroles, beslissingen over vernieuwing en tokenupdates, en verifieer dit gedrag met tests.

Nieuwe features:

  • Log controles op tokenverval en resterende levensduur tijdens authenticatievalidatie en evaluatie van tokenvernieuwing.
  • Log wanneer tokenvernieuwing vereist is op basis van een gedefinieerde vernieuwingsmarge en de vervaltijd van het token.
  • Log succesvolle updates van authenticatietokens tijdens login en tokenvernieuwing, inclusief de afhandeling van tokens zonder expliciete vervalmetagegevens.

Tests:

  • Voeg een test voor vernieuwingslogging toe om te controleren dat validatie- en vernieuwingspaden voor authenticatie de verwachte debuglogberichten en -formaten genereren.
Original summary in English

Summary by Sourcery

Add observability to the authentication lifecycle by logging token expiry checks, renewal decisions, and token updates, and verify this behavior with tests.

New Features:

  • Log token expiry checks and remaining lifetime during authentication validation and token refresh evaluation.
  • Log when token renewal is required based on a defined renewal margin and token expiry time.
  • Log successful authentication token updates during login and token renewal, including handling of tokens without explicit expiry metadata.

Tests:

  • Add a renewal logging test to assert that authentication validation and renewal paths emit the expected debug log messages and formats.

Summary by CodeRabbit

  • Bug Fixes

    • Strengthened token renewal logic with improved authentication expiry validation and explicit decision branching.
    • Enhanced debug logging during authentication checks and token renewal to better diagnose authentication issues.
  • Tests

    • Added test coverage for token renewal logging behavior and authentication validation flow.

@sourcery-ai

sourcery-ai Bot commented Jun 17, 2026

Copy link
Copy Markdown

Gids voor reviewers

Voegt debug-level logging toe rond de evaluatie van token-verval en beslissingen over vernieuwing in FrankEnergie, plus tests om het loggedrag en de formattering te verifiëren.

Sequentiediagram voor bijgewerkte auth-token-vervalcontroles en logging

sequenceDiagram
    actor Client
    participant FrankEnergie
    participant Auth
    participant Logger

    Client->>FrankEnergie: validate_authentication()
    FrankEnergie->>FrankEnergie: is_authenticated
    alt authenticated and auth with expires_at
        FrankEnergie->>FrankEnergie: datetime.now(UTC)
        FrankEnergie->>Logger: debug(Token expiry check...)
    end
    FrankEnergie->>FrankEnergie: acquire _renew_lock
    alt auth.is_expired
        FrankEnergie->>Logger: debug(Token renewal required...)
        FrankEnergie->>FrankEnergie: renew_token()
        FrankEnergie->>FrankEnergie: _query(query)
        FrankEnergie->>Auth: Authentication.from_dict(response)
        Auth-->>FrankEnergie: auth
        FrankEnergie->>Logger: debug(Authentication token updated, expires_at=...)
    end
    FrankEnergie-->>Client: bool

    Client->>FrankEnergie: _requires_token_refresh(operation_name)
    alt operation_name == RENEW_TOKEN_OPERATIONNAME or _auth is None
        FrankEnergie-->>Client: False
    else check expiry
        FrankEnergie->>FrankEnergie: datetime.now(UTC)
        FrankEnergie->>Logger: debug(Token expiry check...)
        FrankEnergie->>FrankEnergie: is_expired = _auth.is_expired
        alt is_expired and expires_at
            FrankEnergie->>Logger: debug(Token renewal required...)
        end
        FrankEnergie-->>Client: is_expired
    end
Loading

Wijzigingen per bestand

Wijziging Details Bestanden
Introduceer expliciete marge voor tokenvernieuwing en gedetailleerde debug-logging voor verval/vernieuwing in de authenticatiestroom.
  • Voeg de constante TOKEN_RENEWAL_MARGIN toe op FrankEnergie om een vernieuwingbuffer van 5 minuten te definiëren.
  • Log huidige tijd, token-vervaltijd en resterende levensduur telkens wanneer authenticatie wordt gevalideerd of tokenvernieuwing wordt overwogen.
  • Log wanneer een token als vernieuwing-verplicht wordt beschouwd, inclusief de vernieuwingdrempel in minuten.
python_frank_energie/frank_energie.py
Verbeter paden voor tokenupdates om nieuwe vervalmetadata te loggen na login en tokenvernieuwing.
  • Log na een geslaagde login dat het authenticatietoken is bijgewerkt en voeg de bijbehorende expires_at of een onbekende/mock-placeholder toe.
  • Log na een geslaagde tokenvernieuwing dat het authenticatietoken is bijgewerkt en voeg de bijbehorende expires_at of een onbekende/mock-placeholder toe.
python_frank_energie/frank_energie.py
Voeg unittests toe voor het nieuwe loggedrag in de tokenvernieuwingsstroom.
  • Voeg een asynchrone test toe die validate_authentication door niet-verlopen en verlopen paden stuurt terwijl logs worden vastgelegd.
  • Controleer dat logberichten voor vervalcontrole, vernieuwing vereist en token bijgewerkt aanwezig zijn en correct geformatteerd zijn.
tests/test_renew_token.py

Beoordeling ten opzichte van gelinkte issues

Issue Doelstelling Afgedekt Uitleg
#93 Debug-logging toevoegen van token-vervalinformatie (inclusief huidige tijd, vervaltijd en resterende levensduur) rond authenticatievalidatie en beslissingen over tokenvernieuwing.
#93 Debug-logging toevoegen wanneer tokenvernieuwing vereist/geactiveerd is, inclusief de token-vervaltijd en de vernieuwingdrempel/-marge.
#93 Debug-logging toevoegen na geslaagde updates van het authenticatietoken (login en tokenvernieuwing), inclusief de nieuwe token-vervaltijd.

Mogelijk gerelateerde issues


Tips en commando's

Interactie met Sourcery

  • Een nieuwe review starten: Plaats de comment @sourcery-ai review op de pull request.
  • Discussies voortzetten: Reageer direct op de reviewcomments van Sourcery.
  • Een GitHub-issue genereren vanuit een reviewcomment: Vraag Sourcery om een issue te maken van een reviewcomment door erop te reageren. Je kunt ook reageren op een reviewcomment met @sourcery-ai issue om er een issue van te maken.
  • Een titel voor de pull request genereren: Schrijf @sourcery-ai ergens in de titel van de pull request om op elk moment een titel te genereren. Je kunt ook @sourcery-ai title in een comment op de pull request plaatsen om de titel op elk moment (opnieuw) te genereren.
  • Een samenvatting van de pull request genereren: Schrijf @sourcery-ai summary ergens in de body van de pull request om op elk moment precies daar een PR-samenvatting te genereren waar je die wilt hebben. Je kunt ook @sourcery-ai summary in een comment op de pull request plaatsen om de samenvatting op elk moment (opnieuw) te genereren.
  • Gids voor reviewers genereren: Plaats de comment @sourcery-ai guide op de pull request om de gids voor reviewers op elk moment (opnieuw) te genereren.
  • Alle Sourcery-comments oplossen: Plaats de comment @sourcery-ai resolve op de pull request om alle Sourcery-comments op te lossen. Handig als je alle comments al hebt verwerkt en ze niet meer wilt zien.
  • Alle Sourcery-reviews verwerpen: Plaats de comment @sourcery-ai dismiss op de pull request om alle bestaande Sourcery-reviews te verwerpen. Vooral nuttig als je met een schone lei een nieuwe review wilt starten – vergeet niet @sourcery-ai review te plaatsen om een nieuwe review te starten!

Je ervaring aanpassen

Ga naar je dashboard om:

  • Reviewfuncties zoals de door Sourcery gegenereerde samenvatting van de pull request, de gids voor reviewers en andere functies in of uit te schakelen.
  • De reviewtaal te wijzigen.
  • Aangepaste reviewinstructies toe te voegen, verwijderen of te bewerken.
  • Andere reviewinstellingen aan te passen.

Hulp krijgen

Original review guide in English

Reviewer's Guide

Adds debug-level logging around token expiry evaluation and renewal decisions in FrankEnergie, plus tests to verify the logging behavior and formatting.

Sequence diagram for updated auth token expiry checks and logging

sequenceDiagram
    actor Client
    participant FrankEnergie
    participant Auth
    participant Logger

    Client->>FrankEnergie: validate_authentication()
    FrankEnergie->>FrankEnergie: is_authenticated
    alt authenticated and auth with expires_at
        FrankEnergie->>FrankEnergie: datetime.now(UTC)
        FrankEnergie->>Logger: debug(Token expiry check...)
    end
    FrankEnergie->>FrankEnergie: acquire _renew_lock
    alt auth.is_expired
        FrankEnergie->>Logger: debug(Token renewal required...)
        FrankEnergie->>FrankEnergie: renew_token()
        FrankEnergie->>FrankEnergie: _query(query)
        FrankEnergie->>Auth: Authentication.from_dict(response)
        Auth-->>FrankEnergie: auth
        FrankEnergie->>Logger: debug(Authentication token updated, expires_at=...)
    end
    FrankEnergie-->>Client: bool

    Client->>FrankEnergie: _requires_token_refresh(operation_name)
    alt operation_name == RENEW_TOKEN_OPERATIONNAME or _auth is None
        FrankEnergie-->>Client: False
    else check expiry
        FrankEnergie->>FrankEnergie: datetime.now(UTC)
        FrankEnergie->>Logger: debug(Token expiry check...)
        FrankEnergie->>FrankEnergie: is_expired = _auth.is_expired
        alt is_expired and expires_at
            FrankEnergie->>Logger: debug(Token renewal required...)
        end
        FrankEnergie-->>Client: is_expired
    end
Loading

File-Level Changes

Change Details Files
Introduce explicit token renewal margin and detailed expiry/renewal debug logging in authentication flow.
  • Add TOKEN_RENEWAL_MARGIN constant on FrankEnergie to define a 5-minute renewal buffer.
  • Log current time, token expiry, and remaining lifetime whenever authentication is validated or token refresh is considered.
  • Log when a token is considered renewal-required, including the renewal threshold in minutes.
python_frank_energie/frank_energie.py
Enhance token update paths to log new expiry metadata after login and token renewal.
  • After successful login, log that the authentication token was updated and include its expires_at or an unknown/mock placeholder.
  • After successful token renewal, log that the authentication token was updated and include its expires_at or an unknown/mock placeholder.
python_frank_energie/frank_energie.py
Add unit coverage for the new logging behavior in the token renewal flow.
  • Add async test that drives validate_authentication through non-expired and expired paths while capturing logs.
  • Assert that expiry check, renewal-required, and token-updated log messages are present and correctly formatted.
tests/test_renew_token.py

Assessment against linked issues

Issue Objective Addressed Explanation
#93 Add debug logging of token expiry information (including current time, expiry time, and remaining lifetime) around authentication validation and token refresh decisions.
#93 Add debug logging when a token renewal is required/triggered, including the token expiry time and the renewal threshold/margin.
#93 Add debug logging after successful authentication token updates (login and token renewal), including the new token expiry time.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Veldkornet, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 52 minutes and 56 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e2bd7063-2059-4677-a1c3-03e5cd5200f0

📥 Commits

Reviewing files that changed from the base of the PR and between e5d4f39 and a662dc9.

📒 Files selected for processing (4)
  • python_frank_energie/authentication.py
  • python_frank_energie/frank_energie.py
  • python_frank_energie/models.py
  • tests/test_renew_token.py
📝 Walkthrough

Walkthrough

Adds a TOKEN_RENEWAL_MARGIN = timedelta(minutes=5) class attribute to FrankEnergie and enriches validate_authentication(), _requires_token_refresh(), login(), and renew_token() with debug log statements that record token expiry timestamps, remaining time, and renewal threshold context. A new async test verifies the expected log output across both the non-renewal and renewal paths.

Token Renewal Debug Logging

Layer / File(s) Summary
TOKEN_RENEWAL_MARGIN constant and expiry/renewal logging
python_frank_energie/frank_energie.py
Adds TOKEN_RENEWAL_MARGIN class attribute; expands validate_authentication() to log current UTC time, expires_at, and remaining time before the renewal lock; rewrites _requires_token_refresh() with explicit early-exit branches and per-branch debug logging; adds expires_at log lines to login() and renew_token() after auth state is updated.
test_renew_token_logging
tests/test_renew_token.py
New async test mocks the renewal HTTP POST, drives validate_authentication() through the non-renewal path (future expires_at) then the renewal path (past expires_at), and asserts specific DEBUG messages for expiry check, renewal required, and token update.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • HiDiHo01/python-frank-energie#101: Modifies Authentication.is_expired semantics (e.g., None expires_at behavior), which directly affects when _requires_token_refresh() returns True and therefore which log branches are exercised by the new logging added in this PR.

Suggested labels

authentication, tests

🐇 A token grows old, the clock ticks away,
I log each expiry to brighten the day.
Five minutes the margin, the threshold is set,
No silent renewals — debug, don't forget!
Hop, hop — the logs tell all! 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding debug logging for authentication token expiry and renewal decisions, which aligns with the core modifications in the codebase.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from issue #93: TOKEN_RENEWAL_MARGIN constant, token expiry logging with UTC time/expiration/remaining duration, renewal trigger logging with threshold context, and successful token update logging with fallback handling.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #93's requirements: token expiry logging, renewal decision logging, successful update logging, and a test to verify the logging paths.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - ik heb 1 issue gevonden en wat high-level feedback achtergelaten:

  • De nieuwe constante TOKEN_RENEWAL_MARGIN wordt momenteel alleen gebruikt voor logging en niet in de daadwerkelijke logica voor vernieuwing/verval; overweeg om deze óf te koppelen aan de is_expired-/vernieuwingslogica, óf om te verduidelijken waarom deze puur informatief is om toekomstige verwarring te voorkomen.
  • De debuglogging voor tokenverval en -vernieuwing is gedupliceerd tussen validate_authentication en _requires_token_refresh; overweeg een kleine helper te extraheren om dit gedrag te centraliseren en toekomstige wijzigingen consistent te houden.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new TOKEN_RENEWAL_MARGIN constant is currently only used for logging and not in any actual renewal/expiry decision logic; consider either wiring it into the `is_expired`/renewal logic or clarifying why it’s purely informational to avoid future confusion.
- The token expiry and renewal debug logging logic is duplicated between `validate_authentication` and `_requires_token_refresh`; consider extracting a small helper to centralize this behavior and keep future changes consistent.

## Individual Comments

### Comment 1
<location path="tests/test_renew_token.py" line_range="123-124" />
<code_context>
         await api.close()
+
+
+@pytest.mark.asyncio
+async def test_renew_token_logging(aresponses, caplog):
+    """Test that authentication and renewal decisions generate debug log statements."""
+    import logging
</code_context>
<issue_to_address>
**issue (testing):** De nieuwe test valideert alleen logging via `validate_authentication`, maar dekt niet de `_requires_token_refresh`-, `login`- of `renew_token`-loggingpaden die in de PR-beschrijving worden genoemd.

Gezien het doel om alle nieuwe loggingpaden te valideren, dekt deze test alleen de `validate_authentication`-flow. Voeg alsjeblieft gerichte tests toe voor:

- `_requires_token_refresh` met zowel verlopen als niet-verlopende tokens om de vervalcontrole en de "Token renewal required"-logs te testen.
- `login` happy path om de log "Authentication token updated; expires_at=..." te asserten.
- `renew_token` happy path om dezelfde log voor een vernieuwd token te asserten.

Dit zorgt ervoor dat elke nieuwe loggingbranch expliciet wordt getest en beschermd is tegen regressies.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Original comment in English

Hey - I've found 1 issue, and left some high level feedback:

  • The new TOKEN_RENEWAL_MARGIN constant is currently only used for logging and not in any actual renewal/expiry decision logic; consider either wiring it into the is_expired/renewal logic or clarifying why it’s purely informational to avoid future confusion.
  • The token expiry and renewal debug logging logic is duplicated between validate_authentication and _requires_token_refresh; consider extracting a small helper to centralize this behavior and keep future changes consistent.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new TOKEN_RENEWAL_MARGIN constant is currently only used for logging and not in any actual renewal/expiry decision logic; consider either wiring it into the `is_expired`/renewal logic or clarifying why it’s purely informational to avoid future confusion.
- The token expiry and renewal debug logging logic is duplicated between `validate_authentication` and `_requires_token_refresh`; consider extracting a small helper to centralize this behavior and keep future changes consistent.

## Individual Comments

### Comment 1
<location path="tests/test_renew_token.py" line_range="123-124" />
<code_context>
         await api.close()
+
+
+@pytest.mark.asyncio
+async def test_renew_token_logging(aresponses, caplog):
+    """Test that authentication and renewal decisions generate debug log statements."""
+    import logging
</code_context>
<issue_to_address>
**issue (testing):** The new test only validates logging via `validate_authentication`, but does not cover the `_requires_token_refresh`, `login`, or `renew_token` logging paths mentioned in the PR description.

Given the goal of validating all new logging paths, this test only covers the `validate_authentication` flow. Please add targeted tests for:

- `_requires_token_refresh` with both expiring and non-expiring tokens to exercise the expiry check and "Token renewal required" logs.
- `login` happy path to assert the "Authentication token updated; expires_at=..." log.
- `renew_token` happy path to assert the same log for a renewed token.

This will ensure each new logging branch is explicitly tested and protected against regressions.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/test_renew_token.py
Comment on lines +123 to +124
@pytest.mark.asyncio
async def test_renew_token_logging(aresponses, caplog):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (testing): De nieuwe test valideert alleen logging via validate_authentication, maar dekt niet de _requires_token_refresh-, login- of renew_token-loggingpaden die in de PR-beschrijving worden genoemd.

Gezien het doel om alle nieuwe loggingpaden te valideren, dekt deze test alleen de validate_authentication-flow. Voeg alsjeblieft gerichte tests toe voor:

  • _requires_token_refresh met zowel verlopen als niet-verlopende tokens om de vervalcontrole en de "Token renewal required"-logs te testen.
  • login happy path om de log "Authentication token updated; expires_at=..." te asserten.
  • renew_token happy path om dezelfde log voor een vernieuwd token te asserten.

Dit zorgt ervoor dat elke nieuwe loggingbranch expliciet wordt getest en beschermd is tegen regressies.

Original comment in English

issue (testing): The new test only validates logging via validate_authentication, but does not cover the _requires_token_refresh, login, or renew_token logging paths mentioned in the PR description.

Given the goal of validating all new logging paths, this test only covers the validate_authentication flow. Please add targeted tests for:

  • _requires_token_refresh with both expiring and non-expiring tokens to exercise the expiry check and "Token renewal required" logs.
  • login happy path to assert the "Authentication token updated; expires_at=..." log.
  • renew_token happy path to assert the same log for a renewed token.

This will ensure each new logging branch is explicitly tested and protected against regressions.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
python_frank_energie/frank_energie.py (1)

100-100: 🏗️ Heavy lift

Unify renewal threshold source of truth for decision + logs.

At Line 205 the refresh decision still comes from self._auth.is_expired (hardcoded 5-minute margin in python_frank_energie/models.py:323-331), while Line 210 logs TOKEN_RENEWAL_MARGIN. This can silently desync behavior vs logs if either value changes.

Suggested direction
-        is_expired = self._auth.is_expired
+        is_expired = (
+            self._auth.expires_at is None
+            and bool(self._auth.authToken and len(self._auth.authToken.split(".")) >= 3)
+        ) or (
+            self._auth.expires_at is not None
+            and now_utc >= (self._auth.expires_at - self.TOKEN_RENEWAL_MARGIN)
+        )

If you prefer keeping expiry logic in Authentication, expose a margin-aware method there and call it from here so both paths share one implementation.

Also applies to: 205-212

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@python_frank_energie/frank_energie.py` at line 100, The token renewal
decision at line 205 uses `self._auth.is_expired` which contains a hardcoded
5-minute margin embedded in the Authentication class, while the logging at line
210 references `TOKEN_RENEWAL_MARGIN` from the current file. To unify the source
of truth, expose a margin-aware method in the Authentication class that accepts
or references the `TOKEN_RENEWAL_MARGIN` constant, then replace the
`self._auth.is_expired` call at line 205 with a call to this new method,
ensuring both the renewal decision logic and the logging statement use the same
margin value from a single source.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/test_renew_token.py`:
- Around line 154-172: The test currently aggregates logs from both
validate_authentication() calls (when token is not expired and when it is
expired), making it impossible to verify that the non-renewal case does not log
"Token renewal required" while the renewal case does. Insert caplog.clear()
between the two validate_authentication() calls to separate the logged output by
phase, then add explicit assertions after the first call to verify that "Token
renewal required" is NOT present (use assert not any(...)), and keep the
existing assertions after the second call to verify it IS present.

---

Nitpick comments:
In `@python_frank_energie/frank_energie.py`:
- Line 100: The token renewal decision at line 205 uses `self._auth.is_expired`
which contains a hardcoded 5-minute margin embedded in the Authentication class,
while the logging at line 210 references `TOKEN_RENEWAL_MARGIN` from the current
file. To unify the source of truth, expose a margin-aware method in the
Authentication class that accepts or references the `TOKEN_RENEWAL_MARGIN`
constant, then replace the `self._auth.is_expired` call at line 205 with a call
to this new method, ensuring both the renewal decision logic and the logging
statement use the same margin value from a single source.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4dd92e1c-630e-4e0a-93aa-40e597139d90

📥 Commits

Reviewing files that changed from the base of the PR and between 3f044f4 and e5d4f39.

📒 Files selected for processing (2)
  • python_frank_energie/frank_energie.py
  • tests/test_renew_token.py

Comment thread tests/test_renew_token.py
@Veldkornet Veldkornet merged commit a662dc9 into HiDiHo01:main Jun 17, 2026
5 of 6 checks passed
@github-actions github-actions Bot added size/l and removed size/m labels Jun 17, 2026
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add debug logging for authentication token expiry and renewal decisions

1 participant