Skip to content

Conversation

@anujpundir999
Copy link
Contributor

Proposed change

Improved the test coverage for the slack app by creating,updating some unit tests .

Resolves #1802

Our main aim was to target 80% + test coverage , So I changed 15 files which includes the files whose test coverage was below 80% . Somehow I wasn't able to Target 80% test coverage for 3 files apps/slack/commands/events.py,apps/slack/events/member_joined_channel/catch_all.py and apps/slack/management/commands/slack_sync_messages.py . I have improved the best I can , and for other files test coverage is above 80%.

I have followed all the best practices. If any changes are required , I will be happy to cover them.

Updated Test Coverage-:
image

Overall Test Coverage -> 81.85%

Checklist

  • I've read and followed the contributing guidelines.
  • I've run make check-test locally; all checks and tests passed.

@anujpundir999 anujpundir999 requested a review from arkid15r as a code owner August 3, 2025 18:49
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 3, 2025

Summary by CodeRabbit

  • Tests
    • Added comprehensive unit tests across Slack app components, including admin actions, command handling, event processing, member join events, management commands, models, and views.
    • Tests cover scenarios such as message and member data handling, Slack API interactions, event acknowledgments, and view request handling.
    • Enhanced test coverage improves reliability and ensures correct behavior for Slack integrations.

Walkthrough

This pull request introduces a comprehensive suite of new unit tests targeting the Slack app's backend in the codebase. The tests cover admin actions, command handlers, event processing, model methods, management commands, and views, aiming to significantly improve code coverage and verification of key behaviors.

Changes

Cohort / File(s) Change Summary
Admin Action Tests
backend/tests/apps/slack/admin/member_test.py
Adds tests for the MemberAdmin class, specifically the approve_suggested_users admin action, covering success, multiple, and none scenarios.
Command Handler Tests
backend/tests/apps/slack/commands/command_test.py
Introduces tests for a CommandBase subclass, verifying configuration, template rendering, block parsing, Slack API interactions, and error handling.
User Handler Tests
backend/tests/apps/slack/common/handlers/users_test.py
Adds tests for the get_blocks function, including cases for no results, results present, and pagination logic, with extensive mocking.
Event Base and Handler Tests
backend/tests/apps/slack/events/event_test.py
Provides thorough tests for EventBase and its subclasses, covering template logic, error paths, Slack API exceptions, message sending, and registration.
Member Joined Channel Event Tests
backend/tests/apps/slack/events/member_joined_channel/catch_all_test.py
Adds a test for the catch_all_handler function to ensure correct event acknowledgment.
Management Command Tests: Sync Flags
backend/tests/apps/slack/management/commands/slack_set_conversation_sync_messages_flags_test.py
Adds tests for the handle method of the command, validating ORM update/filter logic for conversation sync flags.
Management Command Tests: Sync Messages
backend/tests/apps/slack/management/commands/slack_sync_messages_test.py
Introduces tests for the Slack message sync management command, covering normal flow, missing token, and Slack API error scenarios.
Member Model Tests
backend/tests/apps/slack/models/member_test.py
Adds tests for the Member model's string representation, from_slack, and update_data methods, including creation and update logic.
Message Model Tests
backend/tests/apps/slack/models/message_test.py
Provides tests for the Message model's string representation, properties (cleaned_text, url, latest_reply), and methods (from_slack, update_data).
Slack Views Tests
backend/tests/apps/slack/views_test.py
Adds a test for the Slack request handler view, ensuring correct invocation and response handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Improve backend/apps/slack test coverage (#1802): Add/expand tests for admin actions, commands, handlers, events, models, management commands, and views
Improve backend/apps/slack test coverage (#1802): Target 80%+ coverage

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Possibly related PRs

Suggested labels

nestbot, backend-tests

Suggested reviewers

  • kasya
  • arkid15r

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0fbe3af and ab54ac8.

📒 Files selected for processing (1)
  • backend/tests/apps/slack/management/commands/slack_sync_messages_test.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/tests/apps/slack/management/commands/slack_sync_messages_test.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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: 2

🧹 Nitpick comments (6)
backend/tests/apps/slack/views_test.py (1)

14-14: Move import to module level.

Importing the view inside the test method is unusual and can make the test harder to understand. Consider moving this import to the top of the file.

+from apps.slack.views import slack_request_handler
 from django.test import RequestFactory


 class TestViews:
     """Tests for the Slack views."""

     def test_slack_request_handler_works(self, mocker):
         """Tests that the view correctly calls the SlackRequestHandler."""
         mock_slack_request_handler = mocker.patch("slack_bolt.adapter.django.SlackRequestHandler")

         mock_handler_instance = mock_slack_request_handler.return_value
         mock_handler_instance.handle.return_value = "mock_http_response"

-        from apps.slack.views import slack_request_handler
-
         request = RequestFactory().post("/slack/events/")
backend/tests/apps/slack/management/commands/slack_set_conversation_sync_messages_flags_test.py (1)

3-6: Consider formatting the long import statement.

The import statement is quite long and could be more readable with better formatting.

-from apps.slack.management.commands.slack_set_conversation_sync_messages_flags import (
-    SYNC_MESSAGES_CONVERSATIONS,
-    Command,
-)
+from apps.slack.management.commands.slack_set_conversation_sync_messages_flags import (
+    Command,
+    SYNC_MESSAGES_CONVERSATIONS,
+)
backend/tests/apps/slack/commands/command_test.py (1)

32-33: Test assertion should use exact string matching.

The test assumes the command name will be "/command" based on the class name "Command". This creates a tight coupling between the test and implementation details.

Consider making the assertion more explicit or testing the transformation logic separately:

-    assert command_instance.command_name == "/command"
+    expected_name = "/command"  # Make expectation explicit
+    assert command_instance.command_name == expected_name
backend/tests/apps/slack/admin/member_test.py (1)

32-34: Remove unnecessary pytest.approx for string comparison.

pytest.approx is designed for floating-point number comparisons, not strings. Using it for string comparison is unnecessary and potentially confusing.

 admin_instance.message_user.assert_called_with(
-    request, pytest.approx(f" assigned user for {mock_member}."), messages.SUCCESS
+    request, f"Successfully assigned user for {mock_member}.", messages.SUCCESS
 )
backend/tests/apps/slack/models/message_test.py (1)

77-86: Consider testing the save parameter behavior.

The test always passes save=True but doesn't verify that save=False would prevent the save call.

Add a test case for the save=False scenario:

def test_update_data_creates_new_message_without_saving(self):
    slack_data = {"ts": "12345.001"}
    conversation = Conversation()

    with (
        patch.object(Message, "save") as mock_save,
        patch.object(Message.objects, "get", side_effect=Message.DoesNotExist),
    ):
        message = Message.update_data(slack_data, conversation, save=False)

    mock_save.assert_not_called()
    assert isinstance(message, Message)
backend/tests/apps/slack/management/commands/slack_sync_messages_test.py (1)

15-16: Remove unused mock variables or use them properly.

The mock_member and mock_message variables are marked with # noqa: F841 but aren't used in the test. Either remove them or integrate them into the test logic.

-    mock_member = mocker.patch(f"{self.target_module}.Member")  # noqa: F841
-    mock_message = mocker.patch(f"{self.target_module}.Message")  # noqa: F841
+    # These models are imported but not directly used in this test
+    mocker.patch(f"{self.target_module}.Member")
+    mocker.patch(f"{self.target_module}.Message")
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d3bc58d and e068364.

📒 Files selected for processing (10)
  • backend/tests/apps/slack/admin/member_test.py (1 hunks)
  • backend/tests/apps/slack/commands/command_test.py (1 hunks)
  • backend/tests/apps/slack/common/handlers/users_test.py (1 hunks)
  • backend/tests/apps/slack/events/event_test.py (1 hunks)
  • backend/tests/apps/slack/events/member_joined_channel/catch_all_test.py (1 hunks)
  • backend/tests/apps/slack/management/commands/slack_set_conversation_sync_messages_flags_test.py (1 hunks)
  • backend/tests/apps/slack/management/commands/slack_sync_messages_test.py (1 hunks)
  • backend/tests/apps/slack/models/member_test.py (1 hunks)
  • backend/tests/apps/slack/models/message_test.py (1 hunks)
  • backend/tests/apps/slack/views_test.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
backend/tests/apps/slack/events/member_joined_channel/catch_all_test.py (1)
backend/apps/slack/events/member_joined_channel/catch_all.py (1)
  • catch_all_handler (13-22)
backend/tests/apps/slack/views_test.py (1)
backend/apps/slack/views.py (1)
  • slack_request_handler (14-24)
backend/tests/apps/slack/management/commands/slack_set_conversation_sync_messages_flags_test.py (1)
backend/apps/slack/models/workspace.py (1)
  • get_default_workspace (27-34)
backend/tests/apps/slack/common/handlers/users_test.py (1)
backend/apps/slack/common/presentation.py (1)
  • EntityPresentation (7-25)
backend/tests/apps/slack/events/event_test.py (1)
backend/apps/slack/events/event.py (3)
  • EventBase (23-265)
  • open_conversation (206-225)
  • configure_events (30-37)
🔇 Additional comments (18)
backend/tests/apps/slack/views_test.py (3)

4-5: LGTM!

The test class structure is appropriate for pytest-style testing.


11-12: LGTM!

The mocking approach correctly isolates the view logic and verifies the integration with the SlackRequestHandler. Using a simple string as the mock response is appropriate for unit testing.

Also applies to: 20-20


1-2: Missing pytest import for mocker fixture.

The test method uses the mocker fixture but pytest is not imported. This will cause a runtime error.

Add the missing import:

+import pytest
 from django.test import RequestFactory

Likely an incorrect or invalid review comment.

backend/tests/apps/slack/common/handlers/users_test.py (5)

7-24: LGTM!

The fixture provides comprehensive and realistic mock user data with all necessary fields for testing the get_blocks function.


28-34: LGTM!

The test properly handles the no results edge case with appropriate mocking and comprehensive assertions.


36-46: LGTM!

The test comprehensively verifies that user data is correctly formatted into Slack message blocks with proper link formatting and user details.


48-54: LGTM!

The parametrized test effectively covers both pagination scenarios with clear test cases and proper assertion logic.

Also applies to: 64-67


63-63: No missing search_query argument in test

The get_blocks function signature in backend/apps/slack/common/handlers/users.py is:

def get_blocks(
    page: int = 1,
    search_query: str = "",
    limit: int = 10,
    presentation: EntityPresentation | None = None,
):
    …

Since search_query has a default value of "", calling get_blocks(presentation=presentation) is perfectly valid and intentionally uses an empty search filter. You can ignore the flagged “missing parameter” suggestion.

Likely an incorrect or invalid review comment.

backend/tests/apps/slack/events/member_joined_channel/catch_all_test.py (1)

9-13: LGTM!

The test effectively verifies the core functionality of the catch_all_handler - ensuring it properly acknowledges the Slack event by calling ack().

backend/tests/apps/slack/management/commands/slack_set_conversation_sync_messages_flags_test.py (1)

10-29: LGTM!

The test comprehensively verifies the management command's ORM operations with proper mocking and assertion of the correct sequence of database updates.

backend/tests/apps/slack/models/member_test.py (4)

10-16: LGTM!

The test effectively covers both named and unnamed member scenarios for the string representation, ensuring proper fallback behavior.


18-33: LGTM!

The test provides comprehensive Slack user data and properly verifies that the from_slack method correctly populates the Member instance fields.


35-47: LGTM!

The test properly simulates the new member creation scenario with appropriate exception mocking and verifies both database interaction and data population.


49-59: LGTM!

The test effectively covers the existing member update scenario with proper mocking and verification of the update workflow.

backend/tests/apps/slack/models/message_test.py (1)

50-71: Excellent comprehensive test for the from_slack method.

This test thoroughly covers all the key transformations and assignments performed by the from_slack method, including timestamp conversion, boolean flag derivation, and object relationships.

backend/tests/apps/slack/events/event_test.py (3)

31-37: Excellent property testing approach.

These tests properly verify the derived template paths and default behaviors, ensuring the property methods work as expected.


64-78: Comprehensive error handling test for SlackApiError.

This test properly verifies that specific Slack API errors are handled gracefully while ensuring the exception handling logic works correctly.


152-170: Well-structured configuration and registration tests.

These tests properly verify the event discovery and registration mechanism, ensuring that the Slack app integration works correctly.

@arkid15r arkid15r enabled auto-merge August 4, 2025 20:37
@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 4, 2025

Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

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

LGTM 👍

@arkid15r arkid15r added this pull request to the merge queue Aug 4, 2025
Merged via the queue into OWASP:main with commit 94566f3 Aug 4, 2025
24 checks passed
trucodd pushed a commit to trucodd/Nest that referenced this pull request Aug 5, 2025
* Improve Slack app test coverage

* improve test for slack admin

* coderabbit suggestions

* Update code

---------

Co-authored-by: Arkadii Yakovets <arkadii.yakovets@owasp.org>
Co-authored-by: Arkadii Yakovets <2201626+arkid15r@users.noreply.github.com>
This was referenced Sep 17, 2025
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.

Improve backend/apps/slack test coverage

2 participants