Skip to content

Commit 5905521

Browse files
author
teycir
committed
fix(test): enhance rate limit test accuracy and mock integrity
- Updated mock database logic to prevent object mutations during UPDATE operations - Ensured SELECT queries return copies of data to simulate snapshot behavior - Refined test expectations for exact remaining counts instead of loose bounds - Added clarifying comments to rate limit test steps for better readability These changes improve the test's fidelity to actual database behavior, reducing potential flakiness and ensuring precise validation of rate limiting logic.
1 parent 89b8ec4 commit 5905521

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

tests/unit/securityDB.test.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,16 @@ describe('DB-backed Security', () => {
1212
prepare: (sql: string) => ({
1313
bind: (...args: any[]) => ({
1414
run: async () => {
15-
if (sql.includes('INSERT INTO rate_limits')) {
15+
if (sql.includes('INSERT OR REPLACE INTO rate_limits')) {
1616
store.set(args[0], { count: 1, reset_at: args[1] });
1717
return { success: true };
1818
}
1919
if (sql.includes('UPDATE rate_limits')) {
2020
const existing = store.get(args[0]);
21-
if (existing) existing.count++;
21+
if (existing) {
22+
// Create new object to avoid mutation affecting the returned snapshot
23+
store.set(args[0], { ...existing, count: existing.count + 1 });
24+
}
2225
return { success: true };
2326
}
2427
if (sql.includes('INSERT INTO nonces')) {
@@ -29,8 +32,10 @@ describe('DB-backed Security', () => {
2932
return { success: true };
3033
},
3134
first: async () => {
32-
if (sql.includes('rate_limits')) {
33-
return store.get(args[0]) || null;
35+
if (sql.includes('SELECT count, reset_at FROM rate_limits')) {
36+
const data = store.get(args[0]);
37+
// Return a copy to simulate database snapshot behavior
38+
return data ? { ...data } : null;
3439
}
3540
return null;
3641
},
@@ -44,16 +49,20 @@ describe('DB-backed Security', () => {
4449
it('should enforce rate limits', async () => {
4550
const key = 'test-fingerprint';
4651

52+
// First request: INSERT count=1, remaining = limit - 1 = 2 - 1 = 1
4753
const r1 = await db.checkRateLimit(key, 2, 60000);
4854
expect(r1.allowed).toBe(true);
4955
expect(r1.remaining).toBe(1);
5056

57+
// Second request: existing.count=1, UPDATE to 2, remaining = limit - existing.count - 1 = 2 - 1 - 1 = 0
5158
const r2 = await db.checkRateLimit(key, 2, 60000);
5259
expect(r2.allowed).toBe(true);
53-
expect(r2.remaining).toBeGreaterThanOrEqual(0);
60+
expect(r2.remaining).toBe(0);
5461

62+
// Third request: existing.count=2, count >= limit (2 >= 2), blocked
5563
const r3 = await db.checkRateLimit(key, 2, 60000);
5664
expect(r3.allowed).toBe(false);
65+
expect(r3.remaining).toBe(0);
5766
});
5867

5968
it('should reset rate limits after window', async () => {

0 commit comments

Comments
 (0)