Skip to content

Conversation

@erickod
Copy link
Owner

@erickod erickod commented Oct 15, 2025

Summary by CodeRabbit

  • New Features

    • Added a method to retrieve a built notification from the factory caller.
    • Added len() support to the factory caller to get the count of registered factories.
  • Refactor/Style

    • Standardized single-quote string literals and reformatted imports/call sites across the codebase.
    • Aligned default argument literals for consistency without changing behavior.
  • Tests

    • Updated tests to match quoting/style conventions and adjusted a test helper signature; test behavior remains unchanged.

Este Pull Request implementa melhorias de formatação e consistência no código. As principais alterações incluem:

  • Padronização de Aspas: Todas as strings literais foram alteradas de aspas duplas ("...") para aspas simples ('...') em todo o projeto.
  • Reformatação de Imports: Imports que ocupavam múltiplas linhas foram reestruturados para melhorar a legibilidade, utilizando parênteses para agrupamento.
  • Consistência na Formatação de Código: Ajustes na formatação de chamadas de função, declarações de métodos e dicionários para aderir a um estilo de código mais uniforme e legível.

Essas mudanças não introduzem novas funcionalidades nem alteram o comportamento existente do sistema, focando exclusivamente na melhoria da manutenibilidade e legibilidade do código.

@kody-ai
Copy link

kody-ai bot commented Oct 15, 2025

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration

@reviewOptions

Access your configuration settings here.

@coderabbitai
Copy link

coderabbitai bot commented Oct 15, 2025

Walkthrough

The changes primarily standardize string quoting and import formatting across modules and tests. One class, NotificationFactoryCaller, adds two public methods: get_notification(...) and len(). Several signatures reflect quote-style default updates. No control flow or behavior changes are introduced outside the new NotificationFactoryCaller methods.

Changes

Cohort / File(s) Summary
Application bootstrap
app.py
Reformatted imports and call layout; standardized single quotes; no behavioral change.
Testing configuration
conftest.py
Switched double to single quotes in string operations; no behavior change.
Use case
system_notification/application/send_notification_usecase/send_notification_usecase.py
Import reformatting; quote normalization; dataclass defaults re-quoted; constructed payloads reformatted; no logic change.
Config
system_notification/config/config.py
Quote standardization in env/config reads; no behavior change.
Auth decorator
system_notification/domain/decorators/jwt_auth_controller_decorator.py
Import and quote formatting; unchanged control flow.
Factory caller (feature)
system_notification/domain/notification_factory_caller.py
Added get_notification(...) and len(); minor formatting; error payload quote changes.
Notifications base & Slack factory
system_notification/domain/notifications/base_notification.py, system_notification/domain/notifications/factories/slack_notification_factory.py
Quote/style normalization; defaults re-quoted; no semantic change.
Notification target
system_notification/domain/notifications/notification_target.py
str f-string re-quoted; same output.
Domain protocols
system_notification/domain/protocols/controller_protocol.py, .../factory_caller_protocol.py, .../jwt_adapter_protocol.py, .../notification_factory_protocol.py, .../notification_sender.py
Import and annotation quote/style tweaks; signatures unchanged in meaning.
HTTP client (aiohttp)
system_notification/infra/http/client/aiohttp_adapter/aiohttp_adapter.py, .../protocols.py
Quote normalization; minor signature formatting; same APIs.
HTTP servers
system_notification/infra/http/server/fastapi_http_server.py, .../flask_http_server.py
Quote/style adjustments; Flask make_func default re-quoted; no behavior change.
JWT adapter
system_notification/infra/jwt/jose_jwt_adapter.py
Quote normalization; unchanged behavior.
HTTP controllers
system_notification/infra/http/controller/health_check_controller.py, .../send_notification_controller.py
Import and quote standardization; same routes and handling.
Application test
tests/application/test_send_notification_usecase.py
Quote/style changes; FakeTestingFactory.make_notificaton now includes self.
Decorator tests
tests/domain/decorators/test_auth_decorator.py
Style-only updates.
Notification tests
tests/domain/notifications/test_base_notification.py, tests/domain/notifications/test_notification_target.py
Quote/style updates; semantics unchanged.
Factory caller tests
tests/domain/test_factory_caller.py
Import and quote formatting; no logic changes.
HTTP client tests
tests/infra/http/client/test_aiohttp_adapter.py
Import formatting; quote updates; type annotation quotes updated.
Controller serializer (tests)
tests/infra/http/controller/api_notification_serializer.py
Default icon re-quoted; method signatures reformatted; no logic change.
Send controller tests
tests/infra/http/controller/test_send_notification_controller.py
Quote/style normalization; no behavior changes.
JWT adapter tests
tests/infra/jwt/test_jose_jw_adapter.py
Quote changes only.
FastAPI server tests
tests/infra/server/test_fastapi_http_server.py
Quote/style updates; default argument literals re-quoted.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant FC as NotificationFactoryCaller
  participant F as Matching Factory
  participant N as Notification

  Note over C,FC: New method: get_notification(...)
  C->>FC: get_notification(title, content, destin, priority)
  FC->>F: resolve factory by destin.type
  alt factory found
    F->>N: make_notification(title, content, destin, priority)
    F-->>FC: Notification
    FC-->>C: Notification
  else factory not found
    FC-->>C: None
  end

  Note over C,FC: __len__() returns number of registered factories
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A hare taps keys with tidy delight,
Swapping quotes in gentle, silent night.
Two new tricks in the factory’s warren—how neat!
Count the burrows, craft a note complete.
Hippity-hop, tests still pass bright,
Carrots for style, and functions just right. 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The title “format” is overly generic and does not clearly convey the scope or specific nature of the changes, such as standardizing string quotes and import formatting across multiple modules. While it hints at formatting work, it lacks meaningful context and clarity for reviewers. Please update the pull request title to something more descriptive, for example “chore: standardize code formatting (string quotes and import grouping)” to clearly summarize the scope of the changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/format

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

@erickod
Copy link
Owner Author

erickod commented Oct 15, 2025

@Copilot

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
system_notification/domain/notification_factory_caller.py (1)

45-53: Pass the target through when creating a notification.

Factory.make_notificaton expects the destination information before the priority. By only passing (title, content, priority), the factory receives the priority value as the target and silently falls back to the default priority (0). That breaks priority handling and any factory logic that relies on the real target. Forward the target explicitly (and keep priority in the correct slot) to restore the intended behavior.

Apply this diff:

-        return factory.make_notificaton(title, content, priority)
+        return factory.make_notificaton(
+            title,
+            content,
+            destin.target,
+            priority,
+        )
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ef19d6 and 394f1e3.

📒 Files selected for processing (33)
  • app.py (2 hunks)
  • conftest.py (1 hunks)
  • system_notification/application/send_notification_usecase/send_notification_usecase.py (4 hunks)
  • system_notification/config/config.py (1 hunks)
  • system_notification/domain/decorators/jwt_auth_controller_decorator.py (2 hunks)
  • system_notification/domain/notification_factory_caller.py (2 hunks)
  • system_notification/domain/notifications/base_notification.py (2 hunks)
  • system_notification/domain/notifications/factories/slack_notification_factory.py (1 hunks)
  • system_notification/domain/notifications/notification_target.py (1 hunks)
  • system_notification/domain/protocols/controller_protocol.py (1 hunks)
  • system_notification/domain/protocols/factory_caller_protocol.py (1 hunks)
  • system_notification/domain/protocols/jwt_adapter_protocol.py (1 hunks)
  • system_notification/domain/protocols/notification_factory_protocol.py (1 hunks)
  • system_notification/domain/protocols/notification_sender.py (1 hunks)
  • system_notification/infra/http/client/aiohttp_adapter/aiohttp_adapter.py (3 hunks)
  • system_notification/infra/http/client/aiohttp_adapter/protocols.py (1 hunks)
  • system_notification/infra/http/controller/health_check_controller.py (2 hunks)
  • system_notification/infra/http/controller/send_notification_controller.py (3 hunks)
  • system_notification/infra/http/server/fastapi_http_server.py (3 hunks)
  • system_notification/infra/http/server/flask_http_server.py (4 hunks)
  • system_notification/infra/jwt/jose_jwt_adapter.py (1 hunks)
  • system_notification/infra/notification_handlers/slack_notification_handler.py (1 hunks)
  • tests/application/test_send_notification_usecase.py (2 hunks)
  • tests/domain/decorators/test_auth_decorator.py (3 hunks)
  • tests/domain/notifications/test_base_notification.py (4 hunks)
  • tests/domain/notifications/test_notification_target.py (1 hunks)
  • tests/domain/test_factory_caller.py (2 hunks)
  • tests/infra/http/client/test_aiohttp_adapter.py (8 hunks)
  • tests/infra/http/controller/api_notification_serializer.py (2 hunks)
  • tests/infra/http/controller/test_send_notification_controller.py (4 hunks)
  • tests/infra/jwt/test_jose_jw_adapter.py (1 hunks)
  • tests/infra/notifications_handlers/test_slack_notification_handler.py (3 hunks)
  • tests/infra/server/test_fastapi_http_server.py (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (28)
tests/infra/jwt/test_jose_jw_adapter.py (2)
system_notification/infra/jwt/jose_jwt_adapter.py (4)
  • JoseJWTAdapter (9-30)
  • encode (16-17)
  • decode (19-24)
  • is_valid (26-30)
system_notification/domain/protocols/jwt_adapter_protocol.py (3)
  • encode (7-8)
  • decode (10-13)
  • is_valid (15-16)
tests/infra/notifications_handlers/test_slack_notification_handler.py (4)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notifications/base_notification.py (2)
  • BaseNotification (14-82)
  • add_target (40-41)
system_notification/domain/notifications/notification_target.py (1)
  • NotificationTarget (5-18)
system_notification/infra/notification_handlers/slack_notification_handler.py (1)
  • SlackNotificationHandler (12-44)
tests/domain/notifications/test_notification_target.py (2)
system_notification/domain/notifications/notification_target.py (2)
  • NotificationTarget (5-18)
  • target (14-15)
system_notification/domain/notifications/base_notification.py (1)
  • target (54-55)
system_notification/infra/http/controller/health_check_controller.py (5)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/infra/http/server/helpers/http_response.py (1)
  • HttpResponse (6-9)
system_notification/domain/protocols/controller_protocol.py (2)
  • on (15-16)
  • handle (25-26)
system_notification/infra/http/server/fastapi_http_server.py (1)
  • on (34-58)
system_notification/infra/http/server/flask_http_server.py (1)
  • on (47-73)
system_notification/application/send_notification_usecase/send_notification_usecase.py (5)
system_notification/domain/protocols/factory_caller_protocol.py (1)
  • FactoryCaller (17-33)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notifications/base_notification.py (3)
  • status (44-45)
  • status (48-51)
  • target (54-55)
system_notification/domain/notifications/notification_target.py (1)
  • target (14-15)
app.py (5)
system_notification/infra/http/server/fastapi_http_server.py (1)
  • FastApiHttpServer (26-64)
system_notification/infra/http/server/flask_http_server.py (1)
  • FlaskHttpServer (39-73)
tests/infra/http/controller/api_notification_serializer.py (1)
  • ApiNotificationSerializer (25-60)
system_notification/domain/notification_factory_caller.py (2)
  • NotificationFactoryCaller (21-56)
  • add_factory (25-26)
system_notification/domain/notifications/factories/slack_notification_factory.py (1)
  • SlackNotificationFactory (17-31)
tests/domain/test_factory_caller.py (6)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notification_factory_caller.py (4)
  • NotificationFactoryCaller (21-56)
  • add_factory (25-26)
  • get_sender (28-43)
  • get_notification (45-53)
system_notification/domain/notifications/base_notification.py (1)
  • BaseNotification (14-82)
system_notification/domain/notifications/factories/slack_notification_factory.py (1)
  • SlackNotificationFactory (17-31)
system_notification/domain/notifications/notification_target.py (1)
  • NotificationTarget (5-18)
system_notification/infra/notification_handlers/slack_notification_handler.py (1)
  • SlackNotificationHandler (12-44)
system_notification/infra/http/server/fastapi_http_server.py (2)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/infra/http/server/flask_http_server.py (1)
  • get_query_params_as_dict (14-22)
system_notification/domain/protocols/controller_protocol.py (2)
system_notification/infra/http/server/fastapi_http_server.py (2)
  • serve (31-32)
  • on (34-58)
system_notification/infra/http/server/flask_http_server.py (2)
  • serve (44-45)
  • on (47-73)
system_notification/infra/jwt/jose_jwt_adapter.py (1)
system_notification/domain/protocols/jwt_adapter_protocol.py (2)
  • encode (7-8)
  • decode (10-13)
system_notification/domain/notifications/notification_target.py (1)
system_notification/domain/notifications/base_notification.py (1)
  • target (54-55)
system_notification/infra/http/client/aiohttp_adapter/aiohttp_adapter.py (2)
system_notification/infra/http/client/aiohttp_adapter/protocols.py (1)
  • ClientSession (4-15)
tests/infra/http/client/test_aiohttp_adapter.py (1)
  • json (17-19)
tests/domain/decorators/test_auth_decorator.py (4)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/infra/http/server/helpers/http_response.py (1)
  • HttpResponse (6-9)
system_notification/infra/jwt/jose_jwt_adapter.py (2)
  • JoseJWTAdapter (9-30)
  • encode (16-17)
system_notification/domain/decorators/jwt_auth_controller_decorator.py (1)
  • authenticated (22-23)
system_notification/domain/notifications/factories/slack_notification_factory.py (6)
system_notification/domain/notifications/base_notification.py (1)
  • BaseNotification (14-82)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
system_notification/domain/protocols/notification_sender.py (1)
  • NotificationSender (9-13)
system_notification/infra/notification_handlers/slack_notification_handler.py (1)
  • SlackNotificationHandler (12-44)
system_notification/domain/protocols/notification_factory_protocol.py (1)
  • make_notificaton (14-17)
tests/application/test_send_notification_usecase.py (1)
  • make_notificaton (46-55)
tests/infra/http/client/test_aiohttp_adapter.py (1)
system_notification/infra/http/client/aiohttp_adapter/aiohttp_adapter.py (6)
  • AioHttpAdapter (11-68)
  • get (55-56)
  • post (58-59)
  • put (61-62)
  • patch (64-65)
  • delete (67-68)
system_notification/domain/notifications/base_notification.py (1)
system_notification/domain/notifications/notification_target.py (1)
  • NotificationTarget (5-18)
system_notification/domain/protocols/notification_sender.py (1)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
tests/infra/http/controller/test_send_notification_controller.py (4)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notifications/notification_target.py (2)
  • NotificationTarget (5-18)
  • target (14-15)
system_notification/domain/protocols/controller_protocol.py (2)
  • Controller (19-26)
  • handle (25-26)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/domain/protocols/factory_caller_protocol.py (6)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
system_notification/domain/protocols/notification_sender.py (1)
  • NotificationSender (9-13)
system_notification/domain/notification_factory_caller.py (2)
  • add_factory (25-26)
  • get_sender (28-43)
system_notification/domain/protocols/notification_factory_protocol.py (1)
  • NotificationFactory (11-20)
system_notification/domain/notifications/base_notification.py (1)
  • target (54-55)
system_notification/domain/notifications/notification_target.py (2)
  • target (14-15)
  • NotificationTarget (5-18)
system_notification/domain/decorators/jwt_auth_controller_decorator.py (4)
system_notification/domain/protocols/jwt_adapter_protocol.py (2)
  • JWTAdapter (6-16)
  • is_valid (15-16)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/infra/http/server/helpers/http_response.py (1)
  • HttpResponse (6-9)
system_notification/infra/jwt/jose_jwt_adapter.py (1)
  • is_valid (26-30)
system_notification/domain/protocols/notification_factory_protocol.py (2)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
system_notification/domain/protocols/notification_sender.py (1)
  • NotificationSender (9-13)
tests/domain/notifications/test_base_notification.py (2)
system_notification/domain/notifications/base_notification.py (5)
  • vars (78-79)
  • status (44-45)
  • status (48-51)
  • is_scheduled (62-63)
  • target (54-55)
system_notification/domain/notifications/notification_target.py (2)
  • target (14-15)
  • NotificationTarget (5-18)
system_notification/infra/http/controller/send_notification_controller.py (9)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notifications/notification_target.py (2)
  • NotificationTarget (5-18)
  • target (14-15)
system_notification/domain/protocols/controller_protocol.py (2)
  • HttpServer (11-16)
  • on (15-16)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/infra/http/server/helpers/http_response.py (1)
  • HttpResponse (6-9)
system_notification/infra/http/server/fastapi_http_server.py (1)
  • on (34-58)
system_notification/infra/http/server/flask_http_server.py (1)
  • on (47-73)
system_notification/application/send_notification_usecase/send_notification_usecase.py (2)
  • SendNotificationInput (20-26)
  • execute (39-68)
tests/infra/http/controller/test_send_notification_controller.py (1)
  • execute (108-109)
tests/infra/server/test_fastapi_http_server.py (3)
system_notification/infra/http/server/fastapi_http_server.py (2)
  • FastApiHttpServer (26-64)
  • on (34-58)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
system_notification/infra/http/server/helpers/http_response.py (1)
  • HttpResponse (6-9)
system_notification/infra/http/server/flask_http_server.py (1)
system_notification/infra/http/server/helpers/http_request.py (1)
  • HttpRequest (19-25)
tests/application/test_send_notification_usecase.py (5)
system_notification/domain/notifications/base_notification.py (2)
  • BaseNotification (14-82)
  • target (54-55)
system_notification/domain/notifications/notification_target.py (2)
  • NotificationTarget (5-18)
  • target (14-15)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
system_notification/domain/protocols/notification_sender.py (1)
  • NotificationSender (9-13)
system_notification/application/send_notification_usecase/send_notification_usecase.py (1)
  • SendNotificationInput (20-26)
system_notification/domain/notification_factory_caller.py (6)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notifications/notification_target.py (2)
  • NotificationTarget (5-18)
  • target (14-15)
system_notification/domain/protocols/notification_factory_protocol.py (2)
  • NotificationFactory (11-20)
  • make_sender (19-20)
system_notification/domain/protocols/notification_protocol.py (1)
  • Notification (6-35)
system_notification/domain/protocols/notification_sender.py (1)
  • NotificationSender (9-13)
system_notification/domain/protocols/factory_caller_protocol.py (1)
  • get_sender (21-24)
system_notification/infra/notification_handlers/slack_notification_handler.py (4)
system_notification/domain/exceptions/notification_error.py (1)
  • TargetNotFound (1-2)
system_notification/domain/notifications/base_notification.py (5)
  • BaseNotification (14-82)
  • target (54-55)
  • get_text (35-38)
  • status (44-45)
  • status (48-51)
system_notification/domain/notifications/notification_target.py (1)
  • target (14-15)
tests/infra/notifications_handlers/test_slack_notification_handler.py (1)
  • chat_postMessage (34-40)
🪛 Ruff (0.14.0)
tests/infra/jwt/test_jose_jw_adapter.py

5-5: Possible hardcoded password assigned to: "secret"

(S105)


11-11: Possible hardcoded password assigned to: "secret"

(S105)


19-19: Possible hardcoded password assigned to: "secret"

(S105)


27-27: Possible hardcoded password assigned to: "secret"

(S105)

tests/infra/notifications_handlers/test_slack_notification_handler.py

17-17: Possible hardcoded password assigned to: "token"

(S105)

system_notification/infra/http/controller/health_check_controller.py

20-20: Unused method argument: request

(ARG002)

tests/domain/test_factory_caller.py

30-30: Possible hardcoded password assigned to argument: "slack_token"

(S106)


36-36: Possible hardcoded password assigned to argument: "slack_token"

(S106)


46-46: Possible hardcoded password assigned to argument: "slack_token"

(S106)


55-55: Possible hardcoded password assigned to argument: "slack_token"

(S106)

system_notification/infra/http/server/fastapi_http_server.py

37-37: Do not perform function call Depends in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

system_notification/infra/http/client/aiohttp_adapter/aiohttp_adapter.py

16-16: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)

tests/domain/decorators/test_auth_decorator.py

10-10: Possible hardcoded password assigned to argument: "secret"

(S106)


52-52: f-string without any placeholders

Remove extraneous f prefix

(F541)


55-55: Avoid equality comparisons to False; use not jwt_auth_validation.authenticated: for false checks

Replace with not jwt_auth_validation.authenticated

(E712)

tests/infra/http/controller/test_send_notification_controller.py

31-31: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)


32-32: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)

tests/domain/notifications/test_base_notification.py

32-32: Avoid equality comparisons to False; use not sut.is_scheduled: for false checks

Replace with not sut.is_scheduled

(E712)

system_notification/infra/http/server/flask_http_server.py

45-45: Possible binding to all interfaces

(S104)

tests/application/test_send_notification_usecase.py

50-50: Unused method argument: target

(ARG002)

system_notification/infra/notification_handlers/slack_notification_handler.py

33-42: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Comment on lines +50 to 51
def asdf(name: str = 'any valid name') -> str:
return name
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Remove unused nested helper.

The new asdf function is never invoked and just adds dead code inside on(). Please drop it to keep the handler clean.

Apply this diff to remove it:

-        def asdf(name: str = 'any valid name') -> str:
-            return name
-
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def asdf(name: str = 'any valid name') -> str:
return name
🤖 Prompt for AI Agents
In system_notification/infra/http/server/fastapi_http_server.py around lines
50-51 there is an unused nested helper function `asdf(name: str = 'any valid
name') -> str:` that is never called; remove the entire nested function
definition from inside the `on()` handler so the handler contains only active
logic and no dead code, then run tests/lint to ensure no references remain and
adjust surrounding indentation if needed.

)


class JWTAuthControllerDecorator:
Copy link

Choose a reason for hiding this comment

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

kody code-review Bug high

class JWTAuthControllerDecorator:
    def __init__(self, jwt_adapter: JWTAdapter) -> None:
        self._jwt_adapter = jwt_adapter

    def __call__(self, controller: Callable, *args, **kwargs) -> Callable:
        self._undecorated_callable = controller

        @functools.wraps(controller)
        async def wrapper(
            controller_instance: Callable, request: HttpRequest
        ) -> Any:
            authorization_list = request.headers.get(
                'authorization', ''
            ).split(' ')
            if len(authorization_list) <= 1 or not self._jwt_adapter.is_valid(
                data=authorization_list[1]
            ):
                return HttpResponse(
                    status_code=401,
                    body={
                        'message': 'Not Authorized',
                        'detail': 'invalid API token',
                    },
                )
            # O estado de autenticação não deve ser armazenado na instância do decorator.
            # Se necessário, ele deve ser anexado ao objeto 'request'.
            return await controller(controller_instance, request=request)

Problema de estado compartilhado em ambientes concorrentes, onde uma única instância de classe é usada para múltiplos requests, causando condições de corrida e corrupção de estado.

This issue appears in multiple locations:

  • system_notification/domain/decorators/jwt_auth_controller_decorator.py: Lines 16-46
  • tests/domain/decorators/test_auth_decorator.py: Lines 41-60
    Remova o estado compartilhado da instância da classe e armazene o estado de autenticação no objeto 'request' ou em um contexto específico de cada request.

Fale com o Kody mencionando @kody

Essa sugestão foi útil? Reaja com 👍 ou 👎 para ajudar o Kody a aprender com essa interação.

Comment on lines 48 to 51
def status(self, status: str) -> None:
if status.lower() in ("queued", "sent"):
if status.lower() in ('queued', 'sent'):
self._is_sent = True
self._status = status
Copy link

Choose a reason for hiding this comment

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

kody code-review Bug high

    @status.setter
    def status(self, status: str) -> None:
        if status.lower() in ('queued', 'sent'):
            self._is_sent = True
        else:
            self._is_sent = False
        self._status = status

Problemas de validação e tratamento de erros inconsistentes, onde exceções não são capturadas corretamente ou estados inconsistentes são mantidos.

This issue appears in multiple locations:

  • system_notification/domain/notifications/base_notification.py: Lines 48-51
  • system_notification/infra/notification_handlers/slack_notification_handler.py: Lines 25-32
  • tests/infra/http/controller/api_notification_serializer.py: Lines 47-54
  • tests/infra/http/controller/test_send_notification_controller.py: Lines 111-129
    Implemente validações consistentes e tratamento de erros adequado, garantindo que todas as exceções sejam capturadas e tratadas de acordo com o fluxo esperado da aplicação.

Fale com o Kody mencionando @kody

Essa sugestão foi útil? Reaja com 👍 ou 👎 para ajudar o Kody a aprender com essa interação.

self._factories[factory.target_type] = factory

async def get_sender(self, target: NotificationTarget) -> Optional[NotificationSender]:
async def get_sender(
Copy link

Choose a reason for hiding this comment

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

kody code-review Cross File high

async def get_sender(self, target: NotificationTarget) -> Optional[NotificationSender]:
    ...
    raise TargetNotFound({
        'is_sent': False,
        'destin': {
            'target_type': target.type,
            'target': target.target,
        },
        'detail': 'unknown_handler',
    })

Unificar a lógica de tratamento de erros entre NotificationFactoryCaller e FactoryCaller, que atualmente tratam erros de forma inconsistente.

Fale com o Kody mencionando @kody

Essa sugestão foi útil? Reaja com 👍 ou 👎 para ajudar o Kody a aprender com essa interação.

Comment on lines 66 to 72
view.__name__ = controller.__class__.__name__
self._app.add_url_rule(url, None, view, methods=[method.upper()])
self._app.add_url_rule(
url + "/",
url + '/',
None,
view,
methods=[method.upper()],
Copy link

Choose a reason for hiding this comment

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

kody code-review Bug critical

        view_name = controller.__class__.__name__
        view.__name__ = view_name
        # Cada regra de URL precisa de um endpoint único. Ao fornecer 'None',
        # o Flask usa o nome da função. Para registrar a mesma função para duas
        # rotas, devemos fornecer endpoints únicos explicitamente.
        self._app.add_url_rule(url, f'{view_name}', view, methods=[method.upper()])
        self._app.add_url_rule(
            url + '/',
            f'{view_name}_slash',
            view,
            methods=[method.upper()],
        )

O código tenta registrar duas regras de URL (uma com e outra sem a barra final /) para a mesma função view. O Flask utiliza o nome da função (view.__name__) como um identificador de 'endpoint' único por padrão quando nenhum é fornecido explicitamente. Como a mesma função view é usada para ambas as chamadas add_url_rule, o mesmo nome de endpoint implícito é usado duas vezes. Isso causa um AssertionError durante a inicialização do Flask, pois os nomes dos endpoints devem ser únicos, impedindo o servidor de iniciar.

Cenário de Falha:

  1. O método on é chamado para registrar uma rota, por exemplo: server.on('GET', '/health', HealthController()).
  2. A primeira chamada self._app.add_url_rule('/health', ...) registra a rota com o endpoint implícito 'HealthController'.
  3. A segunda chamada self._app.add_url_rule('/health/', ...) tenta registrar a rota com o mesmo endpoint implícito 'HealthController'.
  4. O Flask lança um AssertionError: View function mapping is overwriting an existing endpoint function..., e a aplicação falha ao iniciar.

Fale com o Kody mencionando @kody

Essa sugestão foi útil? Reaja com 👍 ou 👎 para ajudar o Kody a aprender com essa interação.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants