node-red-contrib-octopus-intelligent 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,220 @@
1
+ # Test Suite Documentation
2
+
3
+ This directory contains unit tests for the Octopus Intelligent Node-RED node.
4
+
5
+ ## Test Structure
6
+
7
+ ```
8
+ __tests__/
9
+ ├── bugs.test.js # Bug regression tests
10
+ ├── charging-timers.test.js # Timer management tests
11
+ ├── data-processing.test.js # Data processing and payload construction tests
12
+ ├── charging-now-validation.test.js # Charging state validation mode tests
13
+ └── README.md # This file
14
+ ```
15
+
16
+ ## Running Tests
17
+
18
+ ### Run All Tests
19
+ ```bash
20
+ npm test
21
+ ```
22
+
23
+ ### Run Tests in Watch Mode
24
+ ```bash
25
+ npm run test:watch
26
+ ```
27
+
28
+ ### Run Tests with Coverage
29
+ ```bash
30
+ npm run test:coverage
31
+ ```
32
+
33
+ ### Run Specific Test File
34
+ ```bash
35
+ npm test bugs.test.js
36
+ npm test charging-timers.test.js
37
+ npm test data-processing.test.js
38
+ ```
39
+
40
+ ### Run Specific Test Suite
41
+ ```bash
42
+ npm test -- -t "Bug #1"
43
+ npm test -- -t "setupChargingTimers"
44
+ ```
45
+
46
+ ## Test Coverage
47
+
48
+ ### Bug Regression Tests (`bugs.test.js`)
49
+
50
+ Tests that prevent previously fixed bugs from reoccurring:
51
+
52
+ **Bug #1: Charging Now Initialization State**
53
+ - ✅ Active slot at initialization
54
+ - ✅ No active slot at initialization
55
+ - ✅ Slot ending during initialization
56
+ - ✅ No premature state publish from announceControls()
57
+
58
+ **Bug #2: Charging Now State Synchronization**
59
+ - ✅ Slot cancelled between polls
60
+ - ✅ New active slot added between polls
61
+ - ✅ Regular polling during active slot
62
+ - ✅ State published on every fetchData call
63
+
64
+ ### Charging Timer Tests (`charging-timers.test.js`)
65
+
66
+ Tests for timer management and charging state detection:
67
+
68
+ **publishChargingState()**
69
+ - ✅ Set chargingNow to true and publish ON
70
+ - ✅ Set chargingNow to false and publish OFF
71
+ - ✅ Handle MQTT disabled
72
+ - ✅ Handle missing broker gracefully
73
+
74
+ **clearChargingTimers()**
75
+ - ✅ Clear all active timers
76
+ - ✅ Handle clearing when no timers set
77
+ - ✅ Clear only active timers
78
+
79
+ **setupChargingTimers()**
80
+ - ✅ Currently charging (active slot)
81
+ - ✅ Future slot (not charging)
82
+ - ✅ No slots (car not plugged in)
83
+ - ✅ Multiple slots with first active
84
+ - ✅ Slot just ended
85
+ - ✅ Timer cleanup on re-run
86
+
87
+ **Slot Filtering Logic**
88
+ - ✅ Filter out past slots
89
+ - ✅ Calculate total energy correctly
90
+ - ✅ Calculate charging window correctly
91
+
92
+ ### Data Processing Tests (`data-processing.test.js`)
93
+
94
+ Tests for API response processing and payload construction:
95
+
96
+ **buildDefaultPayload()**
97
+ - ✅ Create default payload with current state
98
+ - ✅ Preserve confirmed and pending state
99
+
100
+ **Payload Construction from API**
101
+ - ✅ Two future slots
102
+ - ✅ Active slot (charging now)
103
+ - ✅ No slots
104
+ - ✅ Three slots
105
+ - ✅ Past slots filtered out
106
+ - ✅ Mixed past and future slots
107
+ - ✅ Preferences extraction
108
+ - ✅ Bump charge source detection
109
+
110
+ ### Charging Now Validation Tests (`charging-now-validation.test.js`)
111
+
112
+ Tests for charging state detection during validation mode (Issue #5):
113
+
114
+ **setupChargingTimers() Direct Tests**
115
+ - ✅ Active slot detection (chargingNow=true)
116
+ - ✅ Future slot detection (chargingNow=false)
117
+ - ✅ Slot boundary - start time (inclusive)
118
+ - ✅ Slot boundary - end time (exclusive)
119
+
120
+ **BEFORE FIX: Validation Mode Bug**
121
+ - ✅ Demonstrates bug: validation mode skips setupChargingTimers()
122
+ - ✅ Comparison: normal mode works correctly
123
+
124
+ **AFTER FIX: Validation Mode Fixed**
125
+ - ✅ Verifies fix: validation mode now updates charging state
126
+ - ✅ Reconciliation loop NOT started in validation mode
127
+ - ✅ Reconciliation loop IS started in normal mode (once)
128
+
129
+ **User-Provided Real Data**
130
+ - ⏭️ Placeholder for user's actual charging slot data
131
+
132
+ ## Test Data
133
+
134
+ Test mocks are defined in `/test-mocks.js`:
135
+
136
+ - **mockAuthSuccess** - Successful authentication response
137
+ - **mockDataWithSlots** - API response with 2 future slots
138
+ - **mockDataWithActiveSlot** - API response with 1 active slot
139
+ - **mockDataNoSlots** - API response with no slots
140
+ - **mockDataWithThreeSlots** - API response with 3 slots
141
+ - **expectedPayloadTwoSlots** - Expected Node-RED payload format
142
+ - **expectedPayloadActiveSlot** - Expected payload with active slot
143
+ - **expectedPayloadNoSlots** - Expected payload with no slots
144
+
145
+ ## Test Utilities
146
+
147
+ Helper functions for creating mocks:
148
+
149
+ - `createMockAxios(responses)` - Mock axios HTTP client
150
+ - `createMockBroker()` - Mock MQTT broker
151
+ - `createMockNode()` - Mock Node-RED node
152
+ - `generateMockDataWithActiveSlot()` - Generate data with currently active slot (NOW - 30min to NOW + 3.5hrs)
153
+ - `generateMockDataWithFutureSlot()` - Generate data with future slot only (NOW + 2hrs to NOW + 6hrs)
154
+
155
+ ## Coverage Goals
156
+
157
+ - **Branches:** 80%+
158
+ - **Functions:** 80%+
159
+ - **Lines:** 80%+
160
+ - **Statements:** 80%+
161
+
162
+ ## Current Coverage Status
163
+
164
+ Run `npm run test:coverage` to see current coverage metrics.
165
+
166
+ ## Pending Tests
167
+
168
+ The following tests are documented but not yet implemented (waiting for additional API response examples):
169
+
170
+ - Authentication flow tests
171
+ - Preference mutation tests
172
+ - Error handling tests (invalid API key, rate limiting, etc.)
173
+ - setPreferences() validation tests
174
+ - Exponential backoff retry tests
175
+
176
+ See `unit_test.md` for full test specifications.
177
+
178
+ ## Test Principles
179
+
180
+ 1. **Isolation** - Each test is independent and doesn't rely on others
181
+ 2. **Determinism** - Tests use fake timers and mocked dates for consistency
182
+ 3. **Clarity** - Test names clearly describe what is being tested
183
+ 4. **Documentation** - JSDoc comments explain scenario, given, and expected
184
+ 5. **Regression Prevention** - All fixed bugs have corresponding tests
185
+
186
+ ## Debugging Tests
187
+
188
+ ### View Test Output
189
+ ```bash
190
+ npm test -- --verbose
191
+ ```
192
+
193
+ ### Run Single Test
194
+ ```bash
195
+ npm test -- -t "should initialize with chargingNow=true when slot is active"
196
+ ```
197
+
198
+ ### Debug with Node Inspector
199
+ ```bash
200
+ node --inspect-brk node_modules/.bin/jest --runInBand
201
+ ```
202
+
203
+ Then open `chrome://inspect` in Chrome.
204
+
205
+ ## Contributing
206
+
207
+ When adding new features or fixing bugs:
208
+
209
+ 1. Write a failing test first (TDD)
210
+ 2. Implement the fix/feature
211
+ 3. Verify the test passes
212
+ 4. Update documentation if needed
213
+ 5. Run full test suite before committing
214
+
215
+ ## References
216
+
217
+ - Jest Documentation: https://jestjs.io/
218
+ - Test Mocks: `/test-mocks.js`
219
+ - Bug Tracking: `/bugs.md`
220
+ - Unit Test Plan: `/unit_test.md`
@@ -0,0 +1,194 @@
1
+ # Test Implementation Summary
2
+
3
+ ## Tests Implemented: MQTT Refresh Cooldown (v1.0.4.9)
4
+
5
+ **File:** `__tests__/mqtt-refresh-cooldown.test.js`
6
+
7
+ **Test Results:** ✅ **5/5 PASSED**
8
+
9
+ ---
10
+
11
+ ## Test Coverage
12
+
13
+ ### Test 1.2: MQTT Button - Rapid Clicking During Cooldown
14
+ **Status:** ✅ PASSED
15
+
16
+ **What it tests:**
17
+ - Simulates user clicking "Octopus Refresh API" button 5 times in 2 seconds
18
+ - Verifies only the first click executes
19
+ - Confirms subsequent 4 clicks are blocked
20
+ - Validates warning messages are logged for each blocked attempt
21
+ - Checks Node-RED status updates show cooldown countdown
22
+
23
+ **Implementation approach:**
24
+ - Uses local payload input/output (no actual Node-RED runtime)
25
+ - Mocks `Date.now()` to control time progression
26
+ - Tracks published MQTT messages in `publishedMessages` array
27
+ - Tracks warnings in `warnings` array
28
+ - Simulates button presses by calling `pressMqttRefreshButton()` function
29
+
30
+ **Key assertions:**
31
+ ```javascript
32
+ expect(result1.blocked).toBe(false); // First click works
33
+ expect(result2.blocked).toBe(true); // Second click blocked
34
+ expect(publishedMessages).toHaveLength(1); // Only 1 MQTT message
35
+ expect(warnings).toHaveLength(4); // 4 blocked attempts logged
36
+ ```
37
+
38
+ ---
39
+
40
+ ### Test 4.2: Countdown Doesn't Go Negative
41
+ **Status:** ✅ PASSED (validated within Test 1.2 context)
42
+
43
+ **What it tests:**
44
+ - Button pressed, 30-second cooldown starts
45
+ - After 30 seconds, timer expires
46
+ - `refresh_available_at` changes from ISO timestamp to `null`
47
+ - Value remains `null` after expiry (doesn't show "5 seconds ago")
48
+ - Can refresh again after cooldown expires
49
+
50
+ **Implementation approach:**
51
+ - Uses time advancement via `advanceTime()` helper
52
+ - Checks payload values at T+0s, T+29s, T+30s, T+35s
53
+ - Validates timer cleanup and null state persistence
54
+
55
+ **Key assertions:**
56
+ ```javascript
57
+ // At T+0s: Timestamp published
58
+ expect(initialPayload.refresh_available_at).not.toBeNull();
59
+ expect(initialPayload.refresh_available_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);
60
+
61
+ // At T+30s: Null published (NOT negative time)
62
+ expect(expiryPayload.refresh_available_at).toBeNull();
63
+
64
+ // At T+35s: Still null (no additional publishes)
65
+ expect(publishedMessages).toHaveLength(2);
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Additional Tests Implemented
71
+
72
+ ### Test 3: Correct Timestamp Values Throughout Lifecycle
73
+ **Status:** ✅ PASSED
74
+
75
+ Validates exact payload values at:
76
+ - T+0s: Future timestamp (30s ahead)
77
+ - T+15s: No publish (midpoint)
78
+ - T+30s: Null published (expiry)
79
+ - T+31s: No publish (after expiry)
80
+
81
+ **Result:** Confirms exactly 2 MQTT messages per refresh (start + expiry)
82
+
83
+ ---
84
+
85
+ ### Test 4: Timer Cleanup
86
+ **Status:** ✅ PASSED
87
+
88
+ Verifies:
89
+ - Timer is created when button pressed
90
+ - Timer executes at 30 seconds
91
+ - Timer is removed from active timers after execution
92
+ - New timer can be created for subsequent refresh
93
+
94
+ ---
95
+
96
+ ### Test 5: MQTT Message Structure
97
+ **Status:** ✅ PASSED
98
+
99
+ Validates published messages contain:
100
+ - Correct topic: `nodered_octopus/{account}/status`
101
+ - Correct payload structure with all required fields
102
+ - ISO 8601 timestamp format
103
+ - `retain: true` option
104
+
105
+ ---
106
+
107
+ ## Test Architecture
108
+
109
+ ### Mock Strategy
110
+ ```javascript
111
+ // Time control
112
+ jest.spyOn(Date, 'now').mockImplementation(() => currentTime);
113
+
114
+ // Timer tracking
115
+ jest.spyOn(global, 'setTimeout').mockImplementation((callback, delay) => {
116
+ timers.push({ callback, delay, executeAt: currentTime + delay });
117
+ });
118
+
119
+ // MQTT publish tracking
120
+ node.broker.client.publish = jest.fn((topic, payload, options) => {
121
+ publishedMessages.push({ topic, payload: JSON.parse(payload), options });
122
+ });
123
+ ```
124
+
125
+ ### State Management
126
+ - **Persistent across calls:** `lastManualRefresh`, `cooldownExpiryTimer`, `lastKnownState`
127
+ - **Reset per test:** `publishedMessages`, `warnings`, `timers`
128
+ - **Controlled advancement:** `advanceTime(milliseconds)` helper
129
+
130
+ ### Helper Functions
131
+ ```javascript
132
+ pressMqttRefreshButton() // Simulates MQTT button press
133
+ advanceTime(ms) // Advances time and executes timers
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Coverage Summary
139
+
140
+ | Feature | Test | Status |
141
+ |---------|------|--------|
142
+ | MQTT rate limiting (30s) | Test 1.2 | ✅ PASS |
143
+ | Rapid click blocking | Test 1.2 | ✅ PASS |
144
+ | Countdown expiry | Test 4.2 | ✅ PASS |
145
+ | No negative countdown | Test 4.2 | ✅ PASS |
146
+ | Timestamp values | Test 3 | ✅ PASS |
147
+ | Timer cleanup | Test 4 | ✅ PASS |
148
+ | MQTT message structure | Test 5 | ✅ PASS |
149
+
150
+ **Total:** 7 features tested across 5 test cases
151
+
152
+ ---
153
+
154
+ ## Running the Tests
155
+
156
+ ```bash
157
+ # Run only these tests
158
+ npm test -- mqtt-refresh-cooldown.test.js
159
+
160
+ # Run all tests
161
+ npm test
162
+
163
+ # Run with coverage
164
+ npm run test:coverage
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Test Output Example
170
+
171
+ ```
172
+ PASS __tests__/mqtt-refresh-cooldown.test.js
173
+ MQTT Refresh Button Cooldown
174
+ ✓ Test 1.2: Should block rapid MQTT button clicks during cooldown (7 ms)
175
+ ✓ Test 4.2: Should clear countdown at expiry and not go negative (4 ms)
176
+ ✓ Should publish correct timestamp values throughout cooldown lifecycle (1 ms)
177
+ ✓ Should properly clean up cooldown timer after expiry (1 ms)
178
+ ✓ Should publish MQTT messages with correct structure (1 ms)
179
+
180
+ Test Suites: 1 passed, 1 total
181
+ Tests: 5 passed, 5 total
182
+ ```
183
+
184
+ ---
185
+
186
+ ## Next Steps
187
+
188
+ Remaining tests from test plan to implement:
189
+ - Test 1.4: Node-RED Input - No Rate Limiting
190
+ - Test 1.5: Mixed MQTT and Node-RED Refreshes
191
+ - Test 2.1-2.4: API Complexity Tracking
192
+ - Test 3.1-3.2: Refresh Button Existence
193
+ - Edge cases (E1-E3)
194
+ - Performance tests (P1-P2)