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

fix: failing tests due to change in incident name #2550

Merged
merged 3 commits into from
Nov 20, 2024

Conversation

talboren
Copy link
Member

@talboren talboren commented Nov 20, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced JSON handling with improved parsing flexibility and error management.
    • Introduced a new method for consistent alert formatting in the PagerdutyProvider.
  • Bug Fixes

    • Improved error handling for invalid JSON inputs in alert functions.
    • Enhanced logging detail for exceptions in data pulling functions.
  • Tests

    • Refined organization of import statements and enhanced readability of assertions in test cases.

@talboren talboren linked an issue Nov 20, 2024 that may be closed by this pull request
Copy link

vercel bot commented Nov 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
keep ⬜️ Ignored (Inspect) Visit Preview Nov 20, 2024 10:34am

@dosubot dosubot bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Nov 20, 2024
Copy link

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes in this pull request involve modifications across multiple files, including keep/functions/__init__.py, tests/test_rules_engine.py, keep/api/routes/preset.py, and keep/providers/pagerduty_provider/pagerduty_provider.py. The __init__.py file updates JSON handling by switching from the standard json module to json5, enhancing error handling and input processing. The test file refines import organization and simplifies assertions for clarity. Additionally, error logging in the API routes is improved, and a new static method for alert formatting is introduced in the Pagerduty provider.

Changes

File Change Summary
keep/functions/init.py - Changed import from json to json5.
- Updated json_dumps and json_loads function signatures.
- Enhanced json_loads with a nested parse_bad_json function for cleaning input.
- Improved error handling in get_firing_time and is_first_time functions.
tests/test_rules_engine.py - Restructured import statements for clarity.
- Simplified assertions related to user_generated_name.
- Enhanced readability of assertions for last_seen_time.
- Minor adjustments in alert message formatting in test_incident_resolution_on_all.
- Reformatted parameters in test_incident_resolution_on_edge.
keep/api/routes/preset.py - Changed logging from logger.error() to logger.exception() for improved error reporting in pull_data_from_providers.
keep/providers/pagerduty_provider/pagerduty_provider.py - Added static method _format_alert for alert formatting.
- Updated _get_incidents to use _format_alert.
- Minor adjustments in _format_incident method for consistency.

Poem

In the land of code where rabbits play,
JSON's now flexible, hip-hip-hooray!
With functions refined, and tests all neat,
Our code hops along, a joyful feat!
So let’s celebrate, with a twitch of our nose,
For clarity blooms where the code garden grows! 🐇✨


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.

@dosubot dosubot bot added the Bug Something isn't working label Nov 20, 2024
@talboren talboren enabled auto-merge (squash) November 20, 2024 10:09
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: 2

🧹 Outside diff range and nitpick comments (2)
keep/functions/__init__.py (1)

Line range hint 279-281: Enhance error messages for incident-related validation

Given that this PR aims to fix failing tests due to incident name changes, consider improving the error messages in get_firing_time and is_first_time to be more specific about incident name validation requirements. For example:

- raise ValueError("fingerprint is required")
+ raise ValueError("Invalid or missing incident fingerprint. Please ensure the incident name follows the required format.")

This would make it easier to diagnose and fix test failures related to incident names.

Also applies to: 323-324

tests/test_rules_engine.py (1)

Line range hint 573-587: Consider tracking TODOs in issue tracker

The TODO comments provide valuable guidance for future test coverage. Consider creating GitHub issues to track these test cases properly.

Would you like me to help create GitHub issues for tracking these test cases?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dae291b and 1713e8d.

📒 Files selected for processing (2)
  • keep/functions/__init__.py (2 hunks)
  • tests/test_rules_engine.py (9 hunks)
🔇 Additional comments (5)
keep/functions/__init__.py (1)

Line range hint 1-350: Verify test coverage for JSON parsing changes

While the changes might fix the immediate test failures, please ensure:

  1. Test cases cover both successful and error scenarios with the new json5 parsing
  2. Integration tests verify the interaction between functions using different JSON parsing methods
  3. Edge cases with malformed incident names are properly tested

This will help prevent future issues from the mixed use of JSON parsing methods.

tests/test_rules_engine.py (4)

9-19: LGTM! Import organization improves readability

The grouping of related imports enhances code organization and maintainability.


272-277: Verify incident name changes across the codebase

The assertion now expects the incident name to match the rule name directly, removing any prefix. This change aligns with the PR objective of fixing failing tests due to incident name changes.

The last_seen_time assertion has been reformatted for better readability.


Line range hint 364-374: LGTM! More descriptive alert messages

The alert messages are now more descriptive, making the test cases clearer and easier to understand.

Also applies to: 398-402, 426-430


455-459: LGTM! Improved test parameterization formatting

The test parameterization is now more readable with parameters spread across multiple lines.

keep/functions/__init__.py Show resolved Hide resolved
keep/functions/__init__.py Show resolved Hide resolved
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: 0

🧹 Outside diff range and nitpick comments (3)
keep/api/routes/preset.py (2)

140-143: Consider catching specific exceptions instead of bare Exception

While the change to logger.exception() is good for including stack traces, catching a bare Exception might mask specific errors. Consider catching and handling specific exceptions that could occur during incident pulling (e.g., ConnectionError, TimeoutError, etc.).

-                except Exception:
+                except (ConnectionError, TimeoutError) as e:
                     logger.exception(
                         f"Unknown error pulling incidents from provider {provider.type} ({provider.id})",
                         extra={**extra, "trace_id": trace_id},
                     )
+                except Exception as e:
+                    logger.exception(
+                        f"Unexpected error pulling incidents from provider {provider.type} ({provider.id})",
+                        extra={**extra, "trace_id": trace_id, "error_type": type(e).__name__},
+                    )

168-171: Enhance error handling and maintain logging consistency

Similar to the incident pulling section, consider:

  1. Catching specific exceptions instead of bare Exception
  2. Adding trace_id to the extra context for consistency with other error logs
-            except Exception:
+            except (ConnectionError, TimeoutError) as e:
                 logger.exception(
                     f"Unknown error pulling topology from provider {provider.type} ({provider.id})",
-                    extra={**extra},
+                    extra={**extra, "trace_id": trace_id},
                 )
+            except Exception as e:
+                logger.exception(
+                    f"Unexpected error pulling topology from provider {provider.type} ({provider.id})",
+                    extra={**extra, "trace_id": trace_id, "error_type": type(e).__name__},
+                )
keep/providers/pagerduty_provider/pagerduty_provider.py (1)

Line range hint 578-603: LGTM! Consider adding error handling for missing fields.

The implementation is well-structured and handles both new and old format events correctly. The code is clean and follows good practices.

Consider adding defensive programming for potential missing fields:

-        status = PagerdutyProvider.ALERT_STATUS_MAP.get(event.get("status", "firing"))
+        status = PagerdutyProvider.ALERT_STATUS_MAP.get(event.get("status", "firing"), AlertStatus.FIRING)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1713e8d and ef38adb.

📒 Files selected for processing (2)
  • keep/api/routes/preset.py (2 hunks)
  • keep/providers/pagerduty_provider/pagerduty_provider.py (2 hunks)
🔇 Additional comments (1)
keep/providers/pagerduty_provider/pagerduty_provider.py (1)

795-803: LGTM! Clean implementation of incident and alert formatting.

The changes properly integrate the new static formatting methods while maintaining the relationship between incidents and their alerts.

@talboren talboren disabled auto-merge November 20, 2024 10:42
Copy link
Contributor

@Kiryous Kiryous left a comment

Choose a reason for hiding this comment

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

LGTM!

@talboren talboren merged commit 57df5a1 into main Nov 20, 2024
14 checks passed
@talboren talboren deleted the 2549-bug-failing-tests branch November 20, 2024 10:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working size:M This PR changes 30-99 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[🐛 Bug]: Failing tests
2 participants