@switchbot/homebridge-switchbot 5.0.0-beta.40 → 5.0.0-beta.42

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,417 @@
1
+ import type { API, Logging } from 'homebridge'
2
+
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+
7
+ import { describe, expect, it, vi } from 'vitest'
8
+
9
+ import { ApiRequestTracker } from '../utils.js'
10
+
11
+ // Helper to create isolated test environment for each test
12
+ function createTestEnvironment(pluginName = 'SwitchBotTest') {
13
+ const testId = Math.random().toString(36).substring(7)
14
+ const testDir = join(tmpdir(), `switchbot-test-${testId}`)
15
+
16
+ // Create test directory
17
+ if (!existsSync(testDir)) {
18
+ mkdirSync(testDir, { recursive: true })
19
+ }
20
+
21
+ const testStatsFile = join(testDir, `${pluginName.toLowerCase()}-api-stats.json`)
22
+
23
+ // Mock API with a unique storage path per test
24
+ const mockApi = {
25
+ user: {
26
+ storagePath: () => testDir,
27
+ },
28
+ } as unknown as API
29
+
30
+ // Mock logger
31
+ const mockLog = {
32
+ info: vi.fn(),
33
+ warn: vi.fn(),
34
+ error: vi.fn(),
35
+ debug: vi.fn(),
36
+ } as unknown as Logging
37
+
38
+ return { mockApi, mockLog, testStatsFile, testDir }
39
+ }
40
+
41
+ // Cleanup helper
42
+ function cleanup(testDir: string) {
43
+ try {
44
+ if (existsSync(testDir)) {
45
+ const files = readdirSync(testDir)
46
+ for (const file of files) {
47
+ try {
48
+ unlinkSync(join(testDir, file))
49
+ } catch {
50
+ // ignore
51
+ }
52
+ }
53
+ rmdirSync(testDir)
54
+ }
55
+ } catch {
56
+ // ignore
57
+ }
58
+ }
59
+
60
+ describe('apiRequestTracker', () => {
61
+ describe('initialization', () => {
62
+ it('should create a new tracker with default limits', () => {
63
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
64
+ try {
65
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
66
+ expect(tracker).toBeDefined()
67
+ expect(tracker.getCount()).toBe(0)
68
+ expect(tracker.getDate()).toBe(new Date().toISOString().split('T')[0])
69
+ } finally {
70
+ cleanup(testDir)
71
+ }
72
+ })
73
+
74
+ it('should respect custom daily limit', () => {
75
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
76
+ try {
77
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
78
+ dailyLimit: 5000,
79
+ reserveForCommands: 500,
80
+ })
81
+ expect(tracker).toBeDefined()
82
+ } finally {
83
+ cleanup(testDir)
84
+ }
85
+ })
86
+
87
+ it('should load existing stats from file', () => {
88
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
89
+ try {
90
+ // Create a tracker, increment, and verify persistence
91
+ const tracker1 = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
92
+ tracker1.track()
93
+ tracker1.track()
94
+ expect(tracker1.getCount()).toBe(2)
95
+
96
+ // Create a new tracker instance and verify it loads the count
97
+ const tracker2 = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
98
+ expect(tracker2.getCount()).toBe(2)
99
+ } finally {
100
+ cleanup(testDir)
101
+ }
102
+ })
103
+ })
104
+
105
+ describe('track() - legacy method', () => {
106
+ it('should increment the counter', () => {
107
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
108
+ try {
109
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
110
+ expect(tracker.getCount()).toBe(0)
111
+ tracker.track()
112
+ expect(tracker.getCount()).toBe(1)
113
+ tracker.track()
114
+ expect(tracker.getCount()).toBe(2)
115
+ } finally {
116
+ cleanup(testDir)
117
+ }
118
+ })
119
+
120
+ it('should persist count to file', () => {
121
+ const { mockApi, mockLog, testStatsFile, testDir } = createTestEnvironment()
122
+ try {
123
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
124
+ tracker.track()
125
+ tracker.track()
126
+ tracker.track()
127
+
128
+ // Read the stats file directly
129
+ const statsContent = readFileSync(testStatsFile, 'utf8')
130
+ const stats = JSON.parse(statsContent)
131
+ expect(stats.count).toBe(3)
132
+ expect(stats.date).toBe(new Date().toISOString().split('T')[0])
133
+ } finally {
134
+ cleanup(testDir)
135
+ }
136
+ })
137
+ })
138
+
139
+ describe('trySpend() - budget enforcement', () => {
140
+ it('should allow commands when under soft cap', () => {
141
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
142
+ try {
143
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
144
+ dailyLimit: 100,
145
+ reserveForCommands: 20,
146
+ })
147
+ // Use 50 requests (well under soft cap of 80)
148
+ for (let i = 0; i < 50; i++) {
149
+ expect(tracker.trySpend('command')).toBe(true)
150
+ }
151
+ expect(tracker.getCount()).toBe(50)
152
+ } finally {
153
+ cleanup(testDir)
154
+ }
155
+ })
156
+
157
+ it('should allow polling when under soft cap', () => {
158
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
159
+ try {
160
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
161
+ dailyLimit: 100,
162
+ reserveForCommands: 20,
163
+ })
164
+ // Use 50 requests
165
+ for (let i = 0; i < 50; i++) {
166
+ expect(tracker.trySpend('poll')).toBe(true)
167
+ }
168
+ expect(tracker.getCount()).toBe(50)
169
+ } finally {
170
+ cleanup(testDir)
171
+ }
172
+ })
173
+
174
+ it('should block polling at soft cap when pausePollingAtReserve is true', () => {
175
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
176
+ try {
177
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
178
+ dailyLimit: 100,
179
+ reserveForCommands: 20,
180
+ pausePollingAtReserve: true, // Enable soft cap blocking
181
+ })
182
+ // Use up to soft cap (80 requests)
183
+ for (let i = 0; i < 80; i++) {
184
+ tracker.track()
185
+ }
186
+ expect(tracker.getCount()).toBe(80)
187
+
188
+ // Polling should be blocked at soft cap
189
+ expect(tracker.trySpend('poll')).toBe(false)
190
+ expect(tracker.trySpend('discovery')).toBe(false)
191
+
192
+ // Commands should still work
193
+ expect(tracker.trySpend('command')).toBe(true)
194
+ expect(tracker.getCount()).toBe(81)
195
+ } finally {
196
+ cleanup(testDir)
197
+ }
198
+ })
199
+
200
+ it('should block all requests at hard cap', () => {
201
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
202
+ try {
203
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
204
+ dailyLimit: 100,
205
+ reserveForCommands: 20,
206
+ })
207
+ // Use up to hard cap
208
+ for (let i = 0; i < 100; i++) {
209
+ tracker.track()
210
+ }
211
+ expect(tracker.getCount()).toBe(100)
212
+
213
+ // All request types should be blocked
214
+ expect(tracker.trySpend('poll')).toBe(false)
215
+ expect(tracker.trySpend('discovery')).toBe(false)
216
+ expect(tracker.trySpend('command')).toBe(false)
217
+ expect(tracker.getCount()).toBe(100)
218
+ } finally {
219
+ cleanup(testDir)
220
+ }
221
+ })
222
+
223
+ it('should support batch spending', () => {
224
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
225
+ try {
226
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
227
+ dailyLimit: 100,
228
+ reserveForCommands: 20,
229
+ })
230
+ expect(tracker.trySpend('poll', 10)).toBe(true)
231
+ expect(tracker.getCount()).toBe(10)
232
+
233
+ expect(tracker.trySpend('command', 5)).toBe(true)
234
+ expect(tracker.getCount()).toBe(15)
235
+ } finally {
236
+ cleanup(testDir)
237
+ }
238
+ })
239
+ })
240
+
241
+ describe('webhookOnlyOnReserve mode', () => {
242
+ it('should continue polling beyond soft cap when pausePollingAtReserve is false', () => {
243
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
244
+ try {
245
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
246
+ dailyLimit: 100,
247
+ reserveForCommands: 20,
248
+ pausePollingAtReserve: false,
249
+ })
250
+ // Use 85 requests (past soft cap)
251
+ for (let i = 0; i < 85; i++) {
252
+ tracker.track()
253
+ }
254
+ expect(tracker.getCount()).toBe(85)
255
+
256
+ // Polling should still work (not paused at reserve)
257
+ expect(tracker.trySpend('poll')).toBe(true)
258
+ expect(tracker.getCount()).toBe(86)
259
+ } finally {
260
+ cleanup(testDir)
261
+ }
262
+ })
263
+
264
+ it('should stop polling at soft cap when pausePollingAtReserve is true', () => {
265
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
266
+ try {
267
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
268
+ dailyLimit: 100,
269
+ reserveForCommands: 20,
270
+ pausePollingAtReserve: true,
271
+ })
272
+ // Use up to soft cap
273
+ for (let i = 0; i < 80; i++) {
274
+ tracker.track()
275
+ }
276
+ expect(tracker.getCount()).toBe(80)
277
+
278
+ // Polling should be blocked
279
+ expect(tracker.trySpend('poll')).toBe(false)
280
+ expect(tracker.getCount()).toBe(80)
281
+
282
+ // Commands should still work
283
+ expect(tracker.trySpend('command')).toBe(true)
284
+ expect(tracker.getCount()).toBe(81)
285
+ } finally {
286
+ cleanup(testDir)
287
+ }
288
+ })
289
+ })
290
+
291
+ describe('warning logs', () => {
292
+ it('should log warning when reaching soft cap with pausePollingAtReserve enabled', () => {
293
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
294
+ try {
295
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
296
+ dailyLimit: 100,
297
+ reserveForCommands: 20,
298
+ pausePollingAtReserve: true, // Enable soft cap warning
299
+ })
300
+ // Use up to soft cap
301
+ for (let i = 0; i < 80; i++) {
302
+ tracker.track()
303
+ }
304
+
305
+ // Trigger soft cap warning by attempting poll (will be blocked)
306
+ tracker.trySpend('poll')
307
+ expect(mockLog.warn).toHaveBeenCalledWith(
308
+ expect.stringContaining('Near daily limit'),
309
+ )
310
+ } finally {
311
+ cleanup(testDir)
312
+ }
313
+ })
314
+
315
+ it('should log error when reaching hard cap', () => {
316
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
317
+ try {
318
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
319
+ dailyLimit: 100,
320
+ reserveForCommands: 20,
321
+ })
322
+ // Use up to hard cap
323
+ for (let i = 0; i < 100; i++) {
324
+ tracker.track()
325
+ }
326
+
327
+ // Trigger hard cap error
328
+ tracker.trySpend('command')
329
+ expect(mockLog.error).toHaveBeenCalledWith(
330
+ expect.stringContaining('Daily limit'),
331
+ )
332
+ } finally {
333
+ cleanup(testDir)
334
+ }
335
+ })
336
+ })
337
+
338
+ describe('hourly logging', () => {
339
+ it('should log immediately on startup', () => {
340
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
341
+ try {
342
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
343
+ tracker.startHourlyLogging()
344
+ tracker.stopHourlyLogging()
345
+ expect(mockLog.info).toHaveBeenCalledWith(
346
+ expect.stringContaining('[API Stats] Today'),
347
+ )
348
+ } finally {
349
+ cleanup(testDir)
350
+ }
351
+ })
352
+
353
+ it('should stop logging when stopHourlyLogging is called', () => {
354
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
355
+ try {
356
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest')
357
+ tracker.startHourlyLogging()
358
+ tracker.stopHourlyLogging()
359
+ // Should not throw
360
+ expect(true).toBe(true)
361
+ } finally {
362
+ cleanup(testDir)
363
+ }
364
+ })
365
+ })
366
+
367
+ describe('edge cases', () => {
368
+ it('should handle zero daily limit', () => {
369
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
370
+ try {
371
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
372
+ dailyLimit: 0,
373
+ reserveForCommands: 0,
374
+ })
375
+ // All requests should be blocked immediately
376
+ expect(tracker.trySpend('poll')).toBe(false)
377
+ expect(tracker.trySpend('command')).toBe(false)
378
+ expect(tracker.getCount()).toBe(0)
379
+ } finally {
380
+ cleanup(testDir)
381
+ }
382
+ })
383
+
384
+ it('should handle reserve larger than limit', () => {
385
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
386
+ try {
387
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
388
+ dailyLimit: 100,
389
+ reserveForCommands: 150,
390
+ pausePollingAtReserve: true, // Enable soft cap blocking
391
+ })
392
+ // Soft cap would be negative (100 - 150 = -50), clamped to 0
393
+ // With pausePollingAtReserve=true, polling should be blocked immediately
394
+ expect(tracker.trySpend('poll')).toBe(false)
395
+ // Commands up to hard cap should work
396
+ expect(tracker.trySpend('command')).toBe(true)
397
+ } finally {
398
+ cleanup(testDir)
399
+ }
400
+ })
401
+
402
+ it('should handle negative values in config', () => {
403
+ const { mockApi, mockLog, testDir } = createTestEnvironment()
404
+ try {
405
+ const tracker = new ApiRequestTracker(mockApi, mockLog, 'SwitchBotTest', {
406
+ dailyLimit: -100,
407
+ reserveForCommands: -50,
408
+ })
409
+ // Should be treated as 0
410
+ expect(tracker.trySpend('poll')).toBe(false)
411
+ expect(tracker.trySpend('command')).toBe(false)
412
+ } finally {
413
+ cleanup(testDir)
414
+ }
415
+ })
416
+ })
417
+ })