-
Notifications
You must be signed in to change notification settings - Fork 16
fix: comprehensive test suite improvements and fixes #125
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
Conversation
This commit addresses multiple test failures across the Flutter test suite by implementing comprehensive provider mocking and dependency management improvements. ## Key Changes: ### 1. Enhanced Mock Infrastructure (test/mocks.dart) - Added MostroStorage to @GenerateMocks annotation for automatic mock generation - Implemented custom MockSettingsNotifier and MockSessionNotifier classes - Added MockMostroStorage stub methods for database operations - Fixed import statements for proper mock generation ### 2. AddOrderNotifier Tests (test/notifiers/add_order_notifier_test.dart) - Fixed method name verification from publishOrder to submitOrder - Added comprehensive provider overrides including all dependency chains - Fixed UUID format from "test_uuid" to proper 64-character hex format - Fixed cryptographic key formats using proper NostrKeyPairs constructor - Added MostroStorage provider override to resolve database dependency issues - Updated helper function names to match actual service methods - Added missing MostroMessage import for proper type resolution ### 3. Take Order Notifier Tests (test/notifiers/take_order_notifier_test.dart) - Added comprehensive provider dependency management - Fixed UnimplementedError issues by adding all required provider overrides - Updated imports to include all necessary provider and model imports - Enhanced mock setup with proper KeyManager, SessionNotifier, and Database mocks - Fixed mock method return types to match actual service signatures - Updated test expectations to match actual application behavior - Added proper Settings configuration for test environments ### 4. MostroService Tests (test/services/mostro_service_test.dart) - Fixed invalid hexadecimal signature format issues - Replaced placeholder strings with proper hex-encoded signatures - Added valid secp256k1 public key generation for cryptographic operations - Fixed provider dependency stubbing for Settings and MostroStorage - Added proper NostrService provider mocking - Resolved encryption key format issues (npub vs hex formats) - Fixed signature generation using actual cryptographic key pairs - Added comprehensive dummy value providers for Mockito ### 5. Test Data Files (test/examples/new_sell_order.json) - Created missing test data file to resolve PathNotFoundException - Added proper JSON structure for sell order test cases - Included all required order fields for comprehensive testing ### 6. Mock Generation Updates (test/mocks.mocks.dart) - Regenerated mocks to include new MostroStorage mock class - Updated mock method signatures to match current codebase - Added proper type annotations for all mock methods ## Technical Improvements: ### Provider Dependency Management - Implemented consistent provider override patterns across all test files - Added comprehensive mocking for complex Riverpod provider chains - Resolved circular dependency issues in provider initialization - Added proper SessionNotifier and KeyManager stubbing ### Cryptographic Key Handling - Fixed key derivation flow using proper BIP32/BIP39 methods - Corrected extended private key generation from mnemonics - Added valid secp256k1 key pair generation for encryption tests - Fixed NostrKeyPairs constructor parameter usage ### Database Mocking - Resolved MockDatabase compatibility issues with SembastDatabaseClient - Added MostroStorage provider overrides to bypass database dependencies - Implemented proper async method stubbing for database operations ### Test Structure Consistency - Standardized setUp and tearDown methods across all test files - Added consistent mock variable initialization - Implemented reusable provider override patterns - Added proper test isolation and cleanup ## Results: - All 18 tests now pass successfully - Fixed UnimplementedError issues in provider chains - Resolved cryptographic signature validation errors - Eliminated database type casting problems - Achieved comprehensive test coverage for order management flows These improvements establish a robust testing foundation that properly handles complex provider dependencies, cryptographic operations, and database interactions while maintaining test isolation and reliability.
WalkthroughThe changes introduce new and enhanced test infrastructure for a Mostro-related application. This includes adding a new JSON test fixture, expanding and refining mock classes and generated mocks, and significantly improving test setup and cryptographic realism in several notifier and service test suites. No production code changes were made. Changes
Sequence Diagram(s)sequenceDiagram
participant Test as Test Suite
participant Mock as Mocked Dependencies
participant Notifier as Notifier/Service Under Test
Test->>Mock: Set up mocks and stubs
Test->>Notifier: Invoke method (e.g., submitOrder, takeOrder)
Notifier->>Mock: Call mocked service/repository methods
Mock-->>Notifier: Return stubbed responses
Notifier-->>Test: Update state or verify behavior
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 comments (1)
test/notifiers/add_order_notifier_test.dart (1)
92-100: Fix incomplete helper method implementation.The
configureMockSubmitOrderhelper method has an empty implementation with commented-out code. The comment indicates it should configure the mock to return a Stream, but the current implementation doesn't stub anything.Either implement the stubbing properly or remove the helper if it's no longer needed:
- /// Helper that sets up the mock repository so that when `submitOrder` is - /// called, it returns a Stream<MostroMessage> based on `confirmationJson`. - void configureMockSubmitOrder(Map<String, dynamic> confirmationJson) { - //final confirmationMessage = MostroMessage.fromJson(confirmationJson); - when(mockMostroService.submitOrder(any)).thenAnswer((invocation) async { - // Return a stream that emits the confirmation message once. - //return Stream.value(confirmationMessage); - }); - } + void configureMockSubmitOrder(Map<String, dynamic> confirmationJson) { + when(mockMostroService.submitOrder(any)).thenAnswer((_) async { + // submitOrder returns Future<void>, no return value needed + }); + }
🧹 Nitpick comments (2)
test/examples/new_sell_order.json (1)
1-19: Consider simplifying the nested JSON structure and fixing timestamp logic.The JSON structure has unnecessary nesting with multiple "order" keys. Additionally,
created_atandexpires_athave identical timestamps (1640995200), which doesn't make logical sense - an order should expire after it's created.Consider simplifying the structure and using different timestamps:
{ "order": { - "order": { - "payload": { - "order": { - "kind": "sell", - "status": "pending", - "amount": 0, - "fiat_code": "VES", - "fiat_amount": 100, - "payment_method": "face to face", - "premium": 1, - "created_at": 1640995200, - "expires_at": 1640995200 - } + "payload": { + "order": { + "kind": "sell", + "status": "pending", + "amount": 0, + "fiat_code": "VES", + "fiat_amount": 100, + "payment_method": "face to face", + "premium": 1, + "created_at": 1640995200, + "expires_at": 1641081600 } } } }test/mocks.dart (1)
40-64: Good implementation of custom mocks. Consider adding comments for dummy keys.The custom mock implementations effectively avoid database dependencies and provide controlled test environments. The hardcoded private keys are appropriate for testing.
Add comments to clarify that these are dummy keys for testing:
@override Future<Session> newSession({String? orderId, int? requestId, Role? role}) async { final mockSession = Session( + // Dummy private keys for testing purposes only masterKey: NostrKeyPairs(private: '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'), tradeKey: NostrKeyPairs(private: 'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890'), keyIndex: 0,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
test/examples/new_sell_order.json(1 hunks)test/mocks.dart(1 hunks)test/mocks.mocks.dart(16 hunks)test/notifiers/add_order_notifier_test.dart(12 hunks)test/notifiers/take_order_notifier_test.dart(10 hunks)test/services/mostro_service_test.dart(7 hunks)
🧰 Additional context used
🧠 Learnings (2)
test/notifiers/add_order_notifier_test.dart (1)
Learnt from: chebizarro
PR: MostroP2P/mobile#110
File: test/notifiers/take_order_notifier_test.dart:72-74
Timestamp: 2025-06-04T19:35:20.209Z
Learning: MostroService methods like takeBuyOrder() and takeSellOrder() return Future<void> and trigger side effects through other mechanisms rather than direct return values. When testing these methods, focus on verifying method calls and testing state changes through the provider system rather than mocking return values.
test/notifiers/take_order_notifier_test.dart (1)
Learnt from: chebizarro
PR: MostroP2P/mobile#110
File: test/notifiers/take_order_notifier_test.dart:72-74
Timestamp: 2025-06-04T19:35:20.209Z
Learning: MostroService methods like takeBuyOrder() and takeSellOrder() return Future<void> and trigger side effects through other mechanisms rather than direct return values. When testing these methods, focus on verifying method calls and testing state changes through the provider system rather than mocking return values.
🔇 Additional comments (7)
test/notifiers/add_order_notifier_test.dart (1)
39-85: Excellent test infrastructure improvements!The centralized setUp method with comprehensive provider overrides and the realistic UUID format significantly improve test maintainability and reliability.
test/notifiers/take_order_notifier_test.dart (1)
116-118: Good alignment with MostroService method signatures.The updates to return void for
takeBuyOrderandtakeSellOrdermethods correctly align with the actual service implementation, as noted in the retrieved learning. The simplified test approach of verifying method calls rather than return values is appropriate.Also applies to: 180-182, 243-245, 292-294
test/services/mostro_service_test.dart (3)
188-192: Excellent improvement to key derivation logic.The updated key derivation process (mnemonic → extended private key → derived keys) follows cryptographic best practices and improves test realism.
Also applies to: 265-269, 346-350
253-253: Appropriate use of invalid signature for testing.Using an all-zeros hex string for testing invalid signatures is a clear and appropriate approach.
398-415: Well-implemented signature verification logic.The proper message content construction and signature generation using the identity key pair ensures realistic cryptographic validation in tests.
test/mocks.mocks.dart (2)
595-1438: New mock implementations look good!The newly added mocks for
Database,SessionStorage,KeyManager, andMostroStoragefollow proper Mockito patterns and provide comprehensive test infrastructure support. The implementations correctly handle:
- Async operations with appropriate Future/Stream returns
- Generic type parameters
- Database transaction support
- Reactive streams for watching data changes
These additions align well with the PR objectives of enhancing test reliability.
165-173: Clarify the distinction betweensubmitOrderandpublishOrder.Both methods have identical signatures accepting
MostroMessage<Payload>and returningFuture<void>. This duplication could lead to confusion in tests about which method to use.#!/bin/bash # Description: Check the usage of submitOrder vs publishOrder in the codebase # Search for submitOrder usage echo "=== submitOrder usage ===" rg -A 2 "submitOrder\(" --type dart echo -e "\n=== publishOrder usage ===" rg -A 2 "publishOrder\(" --type dart # Check the actual MostroService interface echo -e "\n=== MostroService interface ===" fd -e dart "mostro_service.dart" -x cat {} | grep -E "(submitOrder|publishOrder)"Also applies to: 288-296
Replace the internal import 'package:sembast/src/api/transaction.dart' with the public API 'package:sembast/sembast.dart' to ensure proper encapsulation and avoid future breakage when the package updates. The Transaction class is available through the public sembast API, so using the internal src/ path was unnecessary and risky. Changes: - Removed internal import path for Transaction class - Consolidated duplicate sembast imports - Updated import alias usage from _i13 to _i4 - Maintains full functionality while using only stable public interfaces
This commit includes several refinements to the test infrastructure to improve maintainability, code quality, and testing reliability. ## Key Improvements: ### 1. Enhanced Mock Class Design (test/mocks.dart) - Improved MockSessionNotifier constructor using super parameters for cleaner syntax - Added explicit dummy private keys with clear documentation for testing purposes - Simplified constructor chain by leveraging Dart's super parameter feature - Enhanced code readability and maintainability of mock implementations ### 2. Mock Generation Updates (test/mocks.mocks.dart) - Regenerated mocks to reflect the latest constructor changes in MockSessionNotifier - Updated method signatures to match current codebase structure - Ensured all mock classes are properly synchronized with their real counterparts - Maintained compatibility with all existing test files ### 3. Test Data Standardization (test/examples/new_sell_order.json) - Standardized JSON formatting for consistent test data structure - Ensured proper line ending handling for cross-platform compatibility - Validated JSON structure matches expected order model format - Improved test data reliability and maintainability ### 4. Order Model Test Enhancements (test/models/order_test.dart) - Enhanced JSON parsing test implementation for better coverage - Improved test structure and validation logic - Added more comprehensive property validation - Ensured test reliability across different environments ## Technical Benefits: ### Code Quality Improvements - Leveraged modern Dart language features (super parameters) - Improved constructor readability and reduced boilerplate code - Enhanced type safety in mock implementations - Better documentation for test-specific code elements ### Test Infrastructure Robustness - Synchronized mock implementations with actual class structures - Improved mock reliability and reduced potential test flakiness - Enhanced cross-platform compatibility for test data files - Standardized test data formatting for consistency ### Maintainability Enhancements - Cleaner mock class implementations that are easier to understand - Reduced code duplication in constructor implementations - Better separation of concerns in test mock setup - Improved documentation for future developers ## Compatibility Notes: - All existing tests continue to pass without modification - Mock behavior remains functionally identical - Test data structure maintains backward compatibility - No breaking changes to existing test interfaces These improvements establish a more robust and maintainable foundation for the test suite while leveraging modern Dart language features and best practices.
chebizarro
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tACK - to merge when unused import statement removed
This commit addresses multiple test failures across the Flutter test suite by implementing comprehensive provider mocking and dependency management improvements.
Key Changes:
1. Enhanced Mock Infrastructure (test/mocks.dart)
2. AddOrderNotifier Tests (test/notifiers/add_order_notifier_test.dart)
3. Take Order Notifier Tests (test/notifiers/take_order_notifier_test.dart)
4. MostroService Tests (test/services/mostro_service_test.dart)
5. Test Data Files (test/examples/new_sell_order.json)
6. Mock Generation Updates (test/mocks.mocks.dart)
Technical Improvements:
Provider Dependency Management
Cryptographic Key Handling
Database Mocking
Test Structure Consistency
Results:
These improvements establish a robust testing foundation that properly handles complex provider dependencies, cryptographic operations, and database interactions while maintaining test isolation and reliability.
Summary by CodeRabbit