Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete slot mapping fix #1602

Merged
merged 1 commit into from
Nov 22, 2024

Conversation

maheshsattala
Copy link
Contributor

@maheshsattala maheshsattala commented Nov 21, 2024

Fix Delete Slot Mapping api and added related test cases

Summary by CodeRabbit

  • New Features

    • Simplified the deletion process for slot mappings by removing unnecessary parameters.
  • Bug Fixes

    • Enhanced error handling for deletion attempts of non-existent slot mappings.
  • Tests

    • Added new tests for adding and deleting slot mappings, including validation for successful and erroneous scenarios.

Copy link

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes involve a modification to the delete_slot_mapping function in the kairon/api/app/routers/bot/bot.py file, simplifying its implementation by removing the user parameter from the function call. Additionally, new test functions have been introduced in tests/integration_test/services_test.py to enhance test coverage for slot mapping functionalities, including tests for adding, successfully deleting, and handling the deletion of non-existent slot mappings.

Changes

File Path Change Summary
kairon/api/app/routers/bot/bot.py Updated delete_slot_mapping method signature to remove user parameter.
tests/integration_test/services_test.py Added new test functions: test_add_slot_mapping_1, test_delete_slot_mapping_1, and test_delete_slot_mapping_does_not_exist.

Poem

In the burrow deep, where the code does play,
A slot mapping's gone, in a simpler way.
With tests now added, to catch every fall,
The rabbit hops high, for the changes are small! 🐇✨
Hooray for the code, and the paths that we weave,
In the garden of logic, we joyfully believe!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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

🧹 Outside diff range and nitpick comments (3)
tests/integration_test/services_test.py (3)

21441-21464: Enhance test coverage and maintainability

While the test covers the basic flow, consider these improvements:

  1. Rename test to be more descriptive (e.g., test_add_slot_mapping_success)
  2. Add validation of the actual mapping structure in the response
  3. Add cleanup in a teardown to ensure test isolation
  4. Consider parameterizing the test for different slot types and mapping configurations
-def test_add_slot_mapping_1():
+def test_add_slot_mapping_success():
     response = client.post(
         f"/api/bot/{pytest.bot}/slots",
         json={"name": "name_slot", "type": "text"},
         headers={"Authorization": pytest.token_type + " " + pytest.access_token},
     )
 
     actual = response.json()
     assert actual["message"] == "Slot added successfully!"
     assert actual["success"]
     assert actual["error_code"] == 0
+    
     response = client.post(
         f"/api/bot/{pytest.bot}/slots/mapping",
         json={
             "slot": "name_slot",
             "mapping": {"type": "from_text", "value": "user", "entity": "name_slot"},
         },
         headers={"Authorization": pytest.token_type + " " + pytest.access_token},
     )
     actual = response.json()
     assert actual["message"] == "Slot mapping added"
     assert actual["success"]
     assert actual["error_code"] == 0
+    # Validate mapping structure
+    response = client.get(
+        f"/api/bot/{pytest.bot}/slots/mapping",
+        headers={"Authorization": pytest.token_type + " " + pytest.access_token},
+    )
+    actual = response.json()
+    assert any(
+        mapping["slot"] == "name_slot" and 
+        mapping["mapping"][0]["type"] == "from_text" and
+        mapping["mapping"][0]["value"] == "user" and
+        mapping["mapping"][0]["entity"] == "name_slot"
+        for mapping in actual["data"]
+    )

21499-21508: Improve error case testing

The test could be improved for better clarity and reliability:

  1. Use a clearly invalid mapping ID (e.g., "non_existent_id") instead of reusing bot ID
  2. Add verification that the mapping truly doesn't exist before attempting deletion
  3. Consider testing other error scenarios (e.g., invalid format, empty ID)
 def test_delete_slot_mapping_does_not_exist():
+    # Verify mapping doesn't exist
+    response = client.get(
+        f"/api/bot/{pytest.bot}/slots/mapping",
+        headers={"Authorization": pytest.token_type + " " + pytest.access_token},
+    )
+    actual = response.json()
+    assert actual["success"]
+    assert not any(
+        any(m["_id"] == "non_existent_id" for m in mapping["mapping"])
+        for mapping in actual["data"]
+    )
+
     response = client.delete(
-        f"/api/bot/{pytest.bot}/slots/mapping_id/{pytest.bot}",
+        f"/api/bot/{pytest.bot}/slots/mapping_id/non_existent_id",
         headers={"Authorization": pytest.token_type + " " + pytest.access_token},
     )
     actual = response.json()

21441-21508: Consider improving test architecture

The test implementation could benefit from:

  1. Creating shared fixtures for common setup/teardown operations
  2. Extracting API calls into helper methods to reduce duplication
  3. Using a base test class with common utilities
  4. Adding test data factories for consistent test data creation

This would improve maintainability and reduce code duplication across tests.

Example helper method structure:

class SlotMappingTestBase:
    def create_slot(self, name: str, slot_type: str) -> dict:
        response = client.post(
            f"/api/bot/{pytest.bot}/slots",
            json={"name": name, "type": slot_type},
            headers=self.get_headers(),
        )
        return response.json()

    def add_slot_mapping(self, slot: str, mapping: dict) -> dict:
        response = client.post(
            f"/api/bot/{pytest.bot}/slots/mapping",
            json={"slot": slot, "mapping": mapping},
            headers=self.get_headers(),
        )
        return response.json()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d9901a and 91615b4.

📒 Files selected for processing (2)
  • kairon/api/app/routers/bot/bot.py (1 hunks)
  • tests/integration_test/services_test.py (1 hunks)
🔇 Additional comments (1)
kairon/api/app/routers/bot/bot.py (1)

1387-1387: 🛠️ Refactor suggestion

Verify the impact of removing user parameter from slot mapping deletion.

The change from delete_slot_mapping to delete_singular_slot_mapping and removal of user parameter has the following implications:

  1. The new function name better reflects its single-record deletion behavior
  2. The removal of user parameter might affect audit logging capabilities

Let's verify the consistency of this change across the codebase:

Consider adding a comment explaining why user tracking was removed from this operation, or if audit logging is handled within the mongo processor implementation.

✅ Verification successful

Based on the analysis of the shell script results, I can now provide a final response:

Removal of user parameter is consistent with audit logging implementation

The change from delete_slot_mapping to delete_singular_slot_mapping is safe because:

  1. The new function is properly integrated with the audit logging system through the SlotMapping model which inherits from Auditlog and is decorated with @auditlogger.log
  2. The user information is automatically captured through the FastAPI security dependency current_user in the route handler
  3. The audit logging is handled at the model level through MongoDB signals, not requiring explicit user parameter in method calls
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other usages of slot mapping deletion functions
# and verify audit logging implementation

# Check for other usages of the old and new functions
echo "Checking function usages:"
rg "delete_slot_mapping|delete_singular_slot_mapping" -A 5

# Check if audit logging is handled within the mongo processor
echo "Checking audit logging implementation:"
ast-grep --pattern 'def delete_singular_slot_mapping($$$)'

Length of output: 8496


Script:

#!/bin/bash
# Let's check the implementation of delete_singular_slot_mapping to understand how it handles audit logging
echo "Checking delete_singular_slot_mapping implementation:"
rg -A 10 "def delete_singular_slot_mapping" kairon/shared/data/processor.py

# Also check if there's any audit logging mechanism in the codebase
echo "Checking audit logging mechanism:"
rg "audit|log.*activity" -A 3

Length of output: 72637

Comment on lines +21466 to +21497
def test_delete_slot_mapping_1():
response = client.get(
f"/api/bot/{pytest.bot}/slots/mapping",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
for slot_mapping in actual["data"]:
if slot_mapping['slot'] == "name_slot":
mapping_id = slot_mapping['mapping'][0]['_id']
break
assert len(actual["data"]) == 12

response = client.delete(
f"/api/bot/{pytest.bot}/slots/mapping_id/{mapping_id}",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
assert actual["message"] == "Slot mapping deleted"
assert actual["error_code"] == 0
assert not actual["data"]

response = client.get(
f"/api/bot/{pytest.bot}/slots/mapping",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
assert actual["error_code"] == 0
assert len(actual["data"]) == 11

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix brittle test implementation

The test has several issues that could lead to flaky behavior:

  1. Hardcoded assertions for total mappings (12 -> 11) make the test brittle
  2. Missing error handling if mapping_id is not found
  3. Implicit dependency on test data state
-def test_delete_slot_mapping_1():
+def test_delete_slot_mapping_success():
     response = client.get(
         f"/api/bot/{pytest.bot}/slots/mapping",
         headers={"Authorization": pytest.token_type + " " + pytest.access_token},
     )
     actual = response.json()
     assert actual["success"]
+    initial_mapping_count = len(actual["data"])
+    mapping_id = None
     for slot_mapping in actual["data"]:
         if slot_mapping['slot'] == "name_slot":
             mapping_id = slot_mapping['mapping'][0]['_id']
             break
-    assert len(actual["data"]) == 12
+    assert mapping_id is not None, "Required test mapping 'name_slot' not found"

     response = client.delete(
         f"/api/bot/{pytest.bot}/slots/mapping_id/{mapping_id}",
         headers={"Authorization": pytest.token_type + " " + pytest.access_token},
     )
     actual = response.json()
     assert actual["success"]
     assert actual["message"] == "Slot mapping deleted"
     assert actual["error_code"] == 0
     assert not actual["data"]

     response = client.get(
         f"/api/bot/{pytest.bot}/slots/mapping",
         headers={"Authorization": pytest.token_type + " " + pytest.access_token},
     )
     actual = response.json()
     assert actual["success"]
     assert actual["error_code"] == 0
-    assert len(actual["data"]) == 11
+    assert len(actual["data"]) == initial_mapping_count - 1
📝 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 test_delete_slot_mapping_1():
response = client.get(
f"/api/bot/{pytest.bot}/slots/mapping",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
for slot_mapping in actual["data"]:
if slot_mapping['slot'] == "name_slot":
mapping_id = slot_mapping['mapping'][0]['_id']
break
assert len(actual["data"]) == 12
response = client.delete(
f"/api/bot/{pytest.bot}/slots/mapping_id/{mapping_id}",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
assert actual["message"] == "Slot mapping deleted"
assert actual["error_code"] == 0
assert not actual["data"]
response = client.get(
f"/api/bot/{pytest.bot}/slots/mapping",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
assert actual["error_code"] == 0
assert len(actual["data"]) == 11
def test_delete_slot_mapping_success():
response = client.get(
f"/api/bot/{pytest.bot}/slots/mapping",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
initial_mapping_count = len(actual["data"])
mapping_id = None
for slot_mapping in actual["data"]:
if slot_mapping['slot'] == "name_slot":
mapping_id = slot_mapping['mapping'][0]['_id']
break
assert mapping_id is not None, "Required test mapping 'name_slot' not found"
response = client.delete(
f"/api/bot/{pytest.bot}/slots/mapping_id/{mapping_id}",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
assert actual["message"] == "Slot mapping deleted"
assert actual["error_code"] == 0
assert not actual["data"]
response = client.get(
f"/api/bot/{pytest.bot}/slots/mapping",
headers={"Authorization": pytest.token_type + " " + pytest.access_token},
)
actual = response.json()
assert actual["success"]
assert actual["error_code"] == 0
assert len(actual["data"]) == initial_mapping_count - 1

Copy link
Collaborator

@sushantpatade sushantpatade left a comment

Choose a reason for hiding this comment

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

approved

@sushantpatade sushantpatade merged commit 82e9497 into digiteinfotech:master Nov 22, 2024
8 checks passed
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