Skip to content

test: use rational-aware deep comparison#172

Merged
takenagain merged 2 commits intofeat/orderbook-rpc-namespacefrom
codex/refactor-test-for-robust-comparison
Aug 4, 2025
Merged

test: use rational-aware deep comparison#172
takenagain merged 2 commits intofeat/orderbook-rpc-namespacefrom
codex/refactor-test-for-robust-comparison

Conversation

@takenagain
Copy link
Copy Markdown
Contributor

@takenagain takenagain commented Aug 4, 2025

Summary

  • replace brittle trade preimage test fixture tweak with rational-aware deep comparison
  • add helper utilities for tolerant map/list comparison of rational values

Testing

  • dart test packages/komodo_defi_rpc_methods/test/src/swaps/trade_preimage_test.dart (fails: dart not installed)

https://chatgpt.com/codex/tasks/task_e_6890bff815308331ac261d23babbafb3

Summary by CodeRabbit

  • Tests
    • Improved test comparison for trade preimage responses to better handle minor differences in rational and decimal number representations, resulting in more robust and flexible equality checks.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 4, 2025

Walkthrough

A test for TradePreimageResponse was updated to use a new comparison method that tolerates minor differences in rational and decimal number representations. Helper functions were introduced to identify and compare rational lists numerically, replacing manual JSON adjustments with a more robust and flexible equality check.

Changes

Cohort / File(s) Change Summary
Test Rational Tolerant Comparison
packages/komodo_defi_rpc_methods/test/src/swaps/trade_preimage_test.dart
Added deepEqualsWithRationalTolerance, _isRationalList, and _rationalListToDecimal helper functions. Updated the test to use tolerant equality for rational/decimal values.

Sequence Diagram(s)

sequenceDiagram
    participant Test as TradePreimage Test
    participant Helper as Rational Tolerance Helpers

    Test->>Helper: deepEqualsWithRationalTolerance(actual, expected)
    Helper->>Helper: _isRationalList(x)
    Helper->>Helper: _rationalListToDecimal(rat)
    Helper-->>Test: Comparison result (tolerant to rational/decimal differences)
    Test-->>Test: Assert result
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested labels

QA

Poem

A bunny hopped through code so neat,
Comparing numbers, decimal and discrete.
Rational lists or decimals, now both agree,
Thanks to helpers, tests run error-free!
With tolerant checks, the bugs are slight—
The code hops forward, pure delight! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

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

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-test-for-robust-comparison

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.

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.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Aug 4, 2025

Visit the preview URL for this PR (updated for commit 3cd2288):

https://komodo-defi-sdk--pr172-codex-refactor-test-veou7pjq.web.app

(expires Mon, 11 Aug 2025 16:22:53 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 7f9f5ac39928f333b6e8fcefb7138575e24ed347

@takenagain
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@takenagain takenagain requested a review from Copilot August 4, 2025 15:50
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 4, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR replaces a brittle test fixture workaround with a robust rational-aware deep comparison utility to handle decimal/rational value comparisons in trade preimage tests.

  • Removes hardcoded fixture modifications that adjusted rational number format
  • Adds helper functions for comparing rational representations tolerantly
  • Implements recursive deep comparison with numerical equivalence for rational values

Comment thread packages/komodo_defi_rpc_methods/test/src/swaps/trade_preimage_test.dart Outdated
final int numerator = rat[0] as int;
final List<int> denominators = List<int>.from(rat[1] as List);
Decimal value = Decimal.fromInt(numerator);
for (final d in denominators) {
Copy link

Copilot AI Aug 4, 2025

Choose a reason for hiding this comment

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

Division by zero is not handled. If any denominator is 0, this will cause a runtime error. Add validation to check for zero denominators before division.

Suggested change
for (final d in denominators) {
for (final d in denominators) {
if (d == 0) {
throw ArgumentError('Denominator cannot be zero in rational list: $rat');
}

Copilot uses AI. Check for mistakes.
});
}

/// Recursively compares two objects, treating rational/decimal representations as equal if numerically equivalent.
Copy link

Copilot AI Aug 4, 2025

Choose a reason for hiding this comment

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

The documentation should clarify the expected format of rational representations (e.g., [numerator, [denominator1, denominator2, ...]] for chained division) and provide examples of what constitutes a rational list.

Suggested change
/// Recursively compares two objects, treating rational/decimal representations as equal if numerically equivalent.
/// Recursively compares two objects, treating rational/decimal representations as equal if numerically equivalent.
///
/// Rational representations are expected to be lists of the form:
/// [numerator, [denominator1, denominator2, ...]]
/// This format represents chained division, i.e.:
/// numerator / denominator1 / denominator2 / ...
///
/// Examples of rational lists:
/// [1, [2]] // represents 1/2
/// [3, [4, 5]] // represents 3/4/5 = 3/20
/// [7, [1]] // represents 7/1 = 7
///
/// Both compared objects are considered equal if their rational/decimal values are numerically equivalent.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (2)
packages/komodo_defi_rpc_methods/test/src/swaps/trade_preimage_test.dart (2)

108-132: Add null safety and consider circular reference protection.

The core recursive comparison logic is sound, but consider these improvements for robustness:

 bool deepEqualsWithRationalTolerance(dynamic a, dynamic b) {
+  if (a == null || b == null) return a == b;
   if (a is Map && b is Map) {
     if (a.length != b.length) return false;
     for (final key in a.keys) {
-      if (!b.containsKey(key)) return false;
+      if (!b.containsKey(key) || b[key] == null) return false;
       if (!deepEqualsWithRationalTolerance(a[key], b[key])) return false;
     }
     return true;
   }
   if (a is List && b is List) {
     if (a.length != b.length) return false;
     for (int i = 0; i < a.length; i++) {
       if (!deepEqualsWithRationalTolerance(a[i], b[i])) return false;
     }
     return true;
   }

For production use, consider adding circular reference detection using a Set<Object> to track visited objects.


142-150: Add defensive checks for edge cases.

The conversion algorithm is mathematically correct, but consider adding safety checks:

 Decimal _rationalListToDecimal(List<dynamic> rat) {
   final int numerator = rat[0] as int;
   final List<int> denominators = List<int>.from(rat[1] as List);
+  if (denominators.isEmpty) return Decimal.fromInt(numerator);
   Decimal value = Decimal.fromInt(numerator);
   for (final d in denominators) {
+    if (d == 0) throw ArgumentError('Division by zero in rational conversion');
     value = value / Decimal.fromInt(d);
   }
   return value;
 }

This prevents division by zero and handles empty denominator lists gracefully.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be16b9a and 8de2b2f.

📒 Files selected for processing (1)
  • packages/komodo_defi_rpc_methods/test/src/swaps/trade_preimage_test.dart (1 hunks)
🔇 Additional comments (2)
packages/komodo_defi_rpc_methods/test/src/swaps/trade_preimage_test.dart (2)

96-103: LGTM! Excellent improvement to test robustness.

The replacement of brittle fixture manipulation with rational-aware comparison makes the test much more maintainable and provides clearer failure diagnostics.


134-140: LGTM! Robust rational list validation.

The validation logic correctly identifies the rational format [int, [int]] with comprehensive type checking for both numerator and denominators.

@takenagain takenagain marked this pull request as ready for review August 4, 2025 16:19
@takenagain takenagain merged commit 0b1434d into feat/orderbook-rpc-namespace Aug 4, 2025
1 check passed
@takenagain takenagain deleted the codex/refactor-test-for-robust-comparison branch August 4, 2025 16:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants