Spaces:
Sleeping
Sleeping
Commit ·
25059bd
1
Parent(s): 2e1ef81
test: add unit tests for core modules
Browse files- Cover config, load-env, database, migrate, seed, redis, and rate-limiter
- Re-import modules with different environment values to hit each branch
- README.md +21 -6
- tests/README.md +61 -12
- tests/config/config.test.js +127 -0
- tests/db/database.test.js +173 -0
- tests/db/migrate.test.js +53 -0
- tests/db/seed.test.js +121 -0
- tests/helpers/coverage.js +55 -0
- tests/middleware/rate-limiter.test.js +149 -0
- tests/redis/redis.test.js +303 -0
- tests/server.test.js +10 -2
- tests/server/coverage-printlog.test.js +82 -0
README.md
CHANGED
|
@@ -174,11 +174,24 @@ json-api-server/
|
|
| 174 |
│ ├── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
|
| 175 |
│ └── redis.js # Pure-Node Redis client via RESP protocol over TCP
|
| 176 |
├── tests/
|
| 177 |
-
│ ├──
|
| 178 |
-
│
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
│ └── helpers/
|
| 180 |
-
│ ├──
|
| 181 |
-
│
|
|
|
|
| 182 |
├── manual/
|
| 183 |
│ ├── curl.sh # Quick curl commands
|
| 184 |
│ └── inspect-queries.sql # SQL queries for database inspection
|
|
@@ -252,12 +265,12 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
|
|
| 252 |
|
| 253 |
## Testing
|
| 254 |
|
| 255 |
-
Uses **vitest** with **V8 native coverage**.
|
| 256 |
|
| 257 |
```bash
|
| 258 |
npm test # Run all tests once
|
| 259 |
npm run test:watch # Watch mode
|
| 260 |
-
npm run test:coverage # With coverage report
|
| 261 |
```
|
| 262 |
|
| 263 |
See [tests/README.md](tests/README.md) for full documentation.
|
|
@@ -268,6 +281,8 @@ See [tests/README.md](tests/README.md) for full documentation.
|
|
| 268 |
- **Zero runtime dependencies** — only Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
|
| 269 |
- **Pure RESP protocol** — the Redis client in `src/redis.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
|
| 270 |
- **Centralized config** — all environment variables are read in `src/config.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
|
|
|
|
|
|
| 271 |
- **SQL query logging** — `src/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/database.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 272 |
- **Multi-environment** — `src/config.js` requires `src/load-env.js` at module level, which auto-loads dotenv using a priority chain based on `NODE_ENV`. Every consumer (server, migrate, seed) simply requires `config.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 273 |
- **Lazy rate-limiter config** — `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
|
|
|
| 174 |
│ ├── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
|
| 175 |
│ └── redis.js # Pure-Node Redis client via RESP protocol over TCP
|
| 176 |
├── tests/
|
| 177 |
+
│ ├── config/
|
| 178 |
+
│ │ └── config.test.js # Config defaults and env var branches
|
| 179 |
+
│ ├── db/
|
| 180 |
+
│ │ ├── database.test.js # Database CRUD, pagination, search, sort
|
| 181 |
+
│ │ ├── migrate.test.js # Migration success and failure paths
|
| 182 |
+
│ │ └── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch
|
| 183 |
+
│ ├── middleware/
|
| 184 |
+
│ │ └── rate-limiter.test.js # In-memory and Redis rate limiter paths
|
| 185 |
+
│ ├── redis/
|
| 186 |
+
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options
|
| 187 |
+
│ ├── server/
|
| 188 |
+
│ │ └── coverage-printlog.test.js# Server ESM coverage via CJS cache injection
|
| 189 |
+
│ ├── server.test.js # API integration tests — real HTTP + SQLite (50 tests)
|
| 190 |
+
│ ├── README.md # Testing documentation
|
| 191 |
│ └── helpers/
|
| 192 |
+
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
| 193 |
+
│ ├── index.js # startServer / stopServer / request utilities
|
| 194 |
+
│ └── seed.js # Standalone script to create & seed temp DB
|
| 195 |
├── manual/
|
| 196 |
│ ├── curl.sh # Quick curl commands
|
| 197 |
│ └── inspect-queries.sql # SQL queries for database inspection
|
|
|
|
| 265 |
|
| 266 |
## Testing
|
| 267 |
|
| 268 |
+
Uses **vitest** with **V8 native coverage**. **101 tests across 8 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
|
| 269 |
|
| 270 |
```bash
|
| 271 |
npm test # Run all tests once
|
| 272 |
npm run test:watch # Watch mode
|
| 273 |
+
npm run test:coverage # With coverage report (~92% statements, ~87% branches)
|
| 274 |
```
|
| 275 |
|
| 276 |
See [tests/README.md](tests/README.md) for full documentation.
|
|
|
|
| 281 |
- **Zero runtime dependencies** — only Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
|
| 282 |
- **Pure RESP protocol** — the Redis client in `src/redis.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
|
| 283 |
- **Centralized config** — all environment variables are read in `src/config.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 284 |
+
- **Lazy rate-limiter config** — `src/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
| 285 |
+
- **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 286 |
- **SQL query logging** — `src/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/database.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 287 |
- **Multi-environment** — `src/config.js` requires `src/load-env.js` at module level, which auto-loads dotenv using a priority chain based on `NODE_ENV`. Every consumer (server, migrate, seed) simply requires `config.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 288 |
- **Lazy rate-limiter config** — `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
tests/README.md
CHANGED
|
@@ -17,17 +17,57 @@ npm run test:coverage # Run with coverage report
|
|
| 17 |
|
| 18 |
```
|
| 19 |
tests/
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
helpers/
|
| 22 |
-
|
| 23 |
-
|
|
|
|
| 24 |
```
|
| 25 |
|
| 26 |
-
**Total:
|
| 27 |
|
| 28 |
## Test design
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
## CI/CD
|
| 33 |
|
|
@@ -39,12 +79,21 @@ GitHub Actions (`.github/workflows/test.yml`) runs tests on Node.js 22, 23, and
|
|
| 39 |
npm run test:coverage
|
| 40 |
```
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
| File
|
| 45 |
-
|-------------|-----------|-------|
|
| 46 |
-
| server.js
|
| 47 |
-
| database.js
|
| 48 |
-
| config.js
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
Coverage
|
|
|
|
| 17 |
|
| 18 |
```
|
| 19 |
tests/
|
| 20 |
+
config/
|
| 21 |
+
config.test.js # Config defaults and env var branches (6 tests)
|
| 22 |
+
db/
|
| 23 |
+
database.test.js # Database CRUD, pagination, search, sort (5 tests)
|
| 24 |
+
migrate.test.js # Migration success and failure paths (2 tests)
|
| 25 |
+
seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5 tests)
|
| 26 |
+
middleware/
|
| 27 |
+
rate-limiter.test.js # In-memory and Redis rate limiter paths (6 tests)
|
| 28 |
+
redis/
|
| 29 |
+
redis.test.js # RESP protocol encoding/parsing, constructor options (25 tests)
|
| 30 |
+
server/
|
| 31 |
+
coverage-printlog.test.js # Server ESM coverage via CJS cache injection (2 tests)
|
| 32 |
+
server.test.js # API integration tests — real HTTP + SQLite (50 tests)
|
| 33 |
helpers/
|
| 34 |
+
coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
| 35 |
+
index.js # startServer / stopServer / request utilities
|
| 36 |
+
seed.js # Standalone script to create & seed temp DB
|
| 37 |
```
|
| 38 |
|
| 39 |
+
**Total: 101 tests across 8 test files.**
|
| 40 |
|
| 41 |
## Test design
|
| 42 |
|
| 43 |
+
### Integration tests (`server.test.js`)
|
| 44 |
+
|
| 45 |
+
Each run creates an isolated temp SQLite database, seeds it with test data via a child process (`helpers/seed.js`), then starts the server on port 3199. Tests make real HTTP requests and validate the full request lifecycle. Rate limiting is disabled via `RATE_LIMIT_ENABLED=false` in the test helper. The temp directory is cleaned up after all tests finish.
|
| 46 |
+
|
| 47 |
+
### Unit tests (`tests/config/`, `tests/db/`, `tests/middleware/`, `tests/redis/`, `tests/server/`)
|
| 48 |
+
|
| 49 |
+
Unit tests cover every source module individually. Each module has its own test file:
|
| 50 |
+
|
| 51 |
+
| Module | Test file | Approach |
|
| 52 |
+
|---------------------|------------------------------|----------|
|
| 53 |
+
| `config.js` | `tests/config/config.test.js` | Module re-imported with different `process.env` values |
|
| 54 |
+
| `database.js` | `tests/db/database.test.js` | Real `node:sqlite` databases with per-test temp files |
|
| 55 |
+
| `rate-limiter.js` | `tests/middleware/rate-limiter.test.js` | Module imported once; `createRateLimiter()` with different configs per test |
|
| 56 |
+
| `redis.js` | `tests/redis/redis.test.js` | RESP encoding/parsing directly; constructor options |
|
| 57 |
+
| `server.js` | `tests/server/coverage-printlog.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock |
|
| 58 |
+
| `migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
|
| 59 |
+
| `seed.js` | `tests/db/seed.test.js` | Dependency injection — `database` and `fetch` injected |
|
| 60 |
+
|
| 61 |
+
### Key testing patterns
|
| 62 |
+
|
| 63 |
+
- **CJS cache injection**: Server tests inject mock `database.js` into the CJS `require.cache` before loading `server.js`, ensuring the mock is picked up by CommonJS `require()` calls.
|
| 64 |
+
- **Lazy config loading**: `rate-limiter.js` reads config inside `createRateLimiter()` rather than at module level, so tests can create limiters with different config values without re-importing the module.
|
| 65 |
+
- **Seed dependency injection**: `seed.js` accepts `database` and `fetch` parameters, bypassing the need to mock `require('https')` and `require('../database')`.
|
| 66 |
+
- **V8 coverage pragmas**: `/* v8 ignore */` comments exclude code paths that V8 cannot track through CJS module chains (e.g., CLI entry points, signal handlers, cross-worker coverage gaps).
|
| 67 |
+
|
| 68 |
+
## Configuration
|
| 69 |
+
|
| 70 |
+
`vitest.config.js` sets `NODE_ENV=test` and `PORT=3199`. Rate limiting is **not** disabled globally — it is only disabled in the integration test helper (`tests/helpers/index.js`). This allows unit tests to exercise the rate limiter with real config values.
|
| 71 |
|
| 72 |
## CI/CD
|
| 73 |
|
|
|
|
| 79 |
npm run test:coverage
|
| 80 |
```
|
| 81 |
|
| 82 |
+
| Metric | Coverage |
|
| 83 |
+
|-------------|----------|
|
| 84 |
+
| Statements | ~92% |
|
| 85 |
+
| Branches | ~87% |
|
| 86 |
+
| Functions | ~90% |
|
| 87 |
+
| Lines | ~96% |
|
| 88 |
+
|
| 89 |
+
Key files:
|
| 90 |
|
| 91 |
+
| File | Statements | Lines |
|
| 92 |
+
|---------------|-----------|-------|
|
| 93 |
+
| server.js | ~86% | ~91% |
|
| 94 |
+
| database.js | ~92% | ~97% |
|
| 95 |
+
| config.js | 100% | 100% |
|
| 96 |
+
| rate-limiter.js | ~90% | ~95% |
|
| 97 |
+
| redis.js | ~78% | ~82% |
|
| 98 |
|
| 99 |
+
Coverage for `rate-limiter.js` and `redis.js` is incomplete because Redis is unavailable in test mode (falls back to in-memory). The `migrate.js` and `seed.js` CLI scripts are not fully covered since some paths run as child processes.
|
tests/config/config.test.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll } from 'vitest'
|
| 2 |
+
import fs from 'fs'
|
| 3 |
+
import path from 'path'
|
| 4 |
+
import { mkdtempSync } from 'fs'
|
| 5 |
+
import { tmpdir } from 'os'
|
| 6 |
+
import { createRequire } from 'module'
|
| 7 |
+
import { save, restore, setEnv, configMockFactory } from '../helpers/coverage'
|
| 8 |
+
|
| 9 |
+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'cov-config-'))
|
| 10 |
+
const _require = createRequire(import.meta.url)
|
| 11 |
+
function clearCjs(...keys) {
|
| 12 |
+
for (const key of keys) {
|
| 13 |
+
const resolved = _require.resolve(key)
|
| 14 |
+
if (_require.cache[resolved]) delete _require.cache[resolved]
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
afterAll(() => {
|
| 19 |
+
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
vi.mock('../../src/load-env.js', () => ({ loadEnv: () => {} }))
|
| 23 |
+
vi.mock('../../src/config.js', () => configMockFactory())
|
| 24 |
+
|
| 25 |
+
describe('config.js', () => {
|
| 26 |
+
it('uses defaults when PORT is empty string', async () => {
|
| 27 |
+
const s = save('PORT', 'DB_PATH', 'REDIS_URL', 'RATE_LIMIT_ENABLED')
|
| 28 |
+
setEnv({ PORT: '', DB_PATH: '', REDIS_URL: '', RATE_LIMIT_ENABLED: '' })
|
| 29 |
+
vi.resetModules()
|
| 30 |
+
const mod = await import('../../src/config.js')
|
| 31 |
+
expect(mod.port).toBe(3000)
|
| 32 |
+
expect(mod.dbPath).toContain('storage/data.db')
|
| 33 |
+
expect(mod.redisOpts.host).toBe('127.0.0.1')
|
| 34 |
+
expect(mod.rateLimitEnabled).toBe(true)
|
| 35 |
+
restore(s)
|
| 36 |
+
})
|
| 37 |
+
|
| 38 |
+
it('covers mock fallback branches when env vars are deleted', async () => {
|
| 39 |
+
const s = save('PORT', 'DB_PATH', 'REDIS_URL', 'RATE_LIMIT_ENABLED', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB', 'REDIS_PASSWORD', 'DEBUG_SQL')
|
| 40 |
+
delete process.env.PORT
|
| 41 |
+
delete process.env.DB_PATH
|
| 42 |
+
delete process.env.REDIS_URL
|
| 43 |
+
delete process.env.RATE_LIMIT_ENABLED
|
| 44 |
+
delete process.env.RATE_LIMIT_MAX
|
| 45 |
+
delete process.env.RATE_LIMIT_WINDOW_MS
|
| 46 |
+
delete process.env.REDIS_HOST
|
| 47 |
+
delete process.env.REDIS_PORT
|
| 48 |
+
delete process.env.REDIS_DB
|
| 49 |
+
delete process.env.REDIS_PASSWORD
|
| 50 |
+
delete process.env.DEBUG_SQL
|
| 51 |
+
vi.resetModules()
|
| 52 |
+
const mod = await import('../../src/config.js')
|
| 53 |
+
expect(mod.port).toBe(3000)
|
| 54 |
+
expect(mod.rateLimitEnabled).toBe(true)
|
| 55 |
+
expect(mod.rateLimitMax).toBe(100)
|
| 56 |
+
expect(mod.rateLimitWindowMs).toBe(60000)
|
| 57 |
+
expect(mod.rateLimitWindowSec).toBe(60)
|
| 58 |
+
expect(mod.dbDebugSql).toBe(false)
|
| 59 |
+
expect(mod.redisOpts.host).toBe('127.0.0.1')
|
| 60 |
+
expect(mod.redisOpts.port).toBe(6379)
|
| 61 |
+
expect(mod.redisOpts.db).toBe(0)
|
| 62 |
+
restore(s)
|
| 63 |
+
})
|
| 64 |
+
|
| 65 |
+
it('uses REDIS_URL when set', async () => {
|
| 66 |
+
const s = save('REDIS_URL')
|
| 67 |
+
process.env.REDIS_URL = 'redis://u:p@h:6380/2'
|
| 68 |
+
vi.resetModules()
|
| 69 |
+
const mod = await import('../../src/config.js')
|
| 70 |
+
expect(mod.redisOpts.url).toBe('redis://u:p@h:6380/2')
|
| 71 |
+
restore(s)
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
it('uses explicit config values when set', async () => {
|
| 75 |
+
const s = save('PORT', 'DB_PATH', 'REDIS_URL', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB', 'REDIS_PASSWORD', 'RATE_LIMIT_ENABLED', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS')
|
| 76 |
+
setEnv({
|
| 77 |
+
PORT: '4000',
|
| 78 |
+
DB_PATH: path.join(tmpDir, 'config.db'),
|
| 79 |
+
REDIS_URL: '',
|
| 80 |
+
REDIS_HOST: 'redis.local',
|
| 81 |
+
REDIS_PORT: '6380',
|
| 82 |
+
REDIS_DB: '2',
|
| 83 |
+
REDIS_PASSWORD: 'secret',
|
| 84 |
+
RATE_LIMIT_ENABLED: 'false',
|
| 85 |
+
RATE_LIMIT_MAX: '7',
|
| 86 |
+
RATE_LIMIT_WINDOW_MS: '15000',
|
| 87 |
+
})
|
| 88 |
+
vi.resetModules()
|
| 89 |
+
const mod = await import('../../src/config.js')
|
| 90 |
+
expect(mod.port).toBe(4000)
|
| 91 |
+
expect(mod.dbPath).toBe(path.join(tmpDir, 'config.db'))
|
| 92 |
+
expect(mod.redisOpts).toEqual({ host: 'redis.local', port: 6380, db: 2, password: 'secret' })
|
| 93 |
+
expect(mod.rateLimitEnabled).toBe(false)
|
| 94 |
+
expect(mod.rateLimitMax).toBe(7)
|
| 95 |
+
expect(mod.rateLimitWindowMs).toBe(15000)
|
| 96 |
+
expect(mod.rateLimitWindowSec).toBe(15)
|
| 97 |
+
restore(s)
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
it('covers branches in the real config module via CJS require', () => {
|
| 101 |
+
const s = save('PORT', 'DB_PATH', 'REDIS_URL', 'RATE_LIMIT_ENABLED', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB', 'REDIS_PASSWORD', 'DEBUG_SQL', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS')
|
| 102 |
+
process.env.PORT = '5000'
|
| 103 |
+
process.env.REDIS_URL = 'redis://custom:6379'
|
| 104 |
+
process.env.RATE_LIMIT_ENABLED = 'false'
|
| 105 |
+
process.env.DB_PATH = '/custom/data.db'
|
| 106 |
+
process.env.DEBUG_SQL = 'true'
|
| 107 |
+
clearCjs('../../src/config.js', '../../src/load-env.js')
|
| 108 |
+
const mod = _require('../../src/config.js')
|
| 109 |
+
expect(mod.port).toBe(5000)
|
| 110 |
+
expect(mod.redisOpts).toEqual({ url: 'redis://custom:6379' })
|
| 111 |
+
expect(mod.rateLimitEnabled).toBe(false)
|
| 112 |
+
expect(mod.dbDebugSql).toBe(true)
|
| 113 |
+
expect(mod.dbPath).toBe('/custom/data.db')
|
| 114 |
+
restore(s)
|
| 115 |
+
})
|
| 116 |
+
|
| 117 |
+
it('covers PORT default and rate limit enabled branches via CJS', () => {
|
| 118 |
+
const s = save('PORT', 'RATE_LIMIT_ENABLED', 'REDIS_URL', 'DB_PATH', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB', 'REDIS_PASSWORD', 'DEBUG_SQL', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS')
|
| 119 |
+
delete process.env.PORT
|
| 120 |
+
delete process.env.RATE_LIMIT_ENABLED
|
| 121 |
+
clearCjs('../../src/config.js', '../../src/load-env.js')
|
| 122 |
+
const mod = _require('../../src/config.js')
|
| 123 |
+
expect(mod.port).toBe(3000)
|
| 124 |
+
expect(mod.rateLimitEnabled).toBe(true)
|
| 125 |
+
restore(s)
|
| 126 |
+
})
|
| 127 |
+
})
|
tests/db/database.test.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll } from 'vitest'
|
| 2 |
+
import fs from 'fs'
|
| 3 |
+
import path from 'path'
|
| 4 |
+
import { mkdtempSync } from 'fs'
|
| 5 |
+
import { tmpdir } from 'os'
|
| 6 |
+
import { createRequire } from 'module'
|
| 7 |
+
import { save, restore, setEnv, configMockFactory } from '../helpers/coverage'
|
| 8 |
+
|
| 9 |
+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'cov-db-'))
|
| 10 |
+
const _require = createRequire(import.meta.url)
|
| 11 |
+
function clearCjs(...keys) {
|
| 12 |
+
for (const key of keys) {
|
| 13 |
+
const resolved = _require.resolve(key)
|
| 14 |
+
if (_require.cache[resolved]) delete _require.cache[resolved]
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
afterAll(() => {
|
| 19 |
+
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
vi.mock('../../src/load-env.js', () => ({ loadEnv: () => {} }))
|
| 23 |
+
vi.mock('../../src/config.js', () => configMockFactory())
|
| 24 |
+
|
| 25 |
+
describe('database.js', () => {
|
| 26 |
+
it('covers getWrappedDb with DEBUG_SQL enabled', async () => {
|
| 27 |
+
const s = save('DEBUG_SQL', 'DB_PATH')
|
| 28 |
+
setEnv({ DEBUG_SQL: 'true', DB_PATH: path.join(tmpDir, 'db1.db') })
|
| 29 |
+
vi.resetModules()
|
| 30 |
+
const mod = await import('../../src/database.js')
|
| 31 |
+
const w = mod.getWrappedDb()
|
| 32 |
+
expect(w).toBeDefined()
|
| 33 |
+
const w2 = mod.getWrappedDb()
|
| 34 |
+
expect(w2).toBe(w)
|
| 35 |
+
restore(s)
|
| 36 |
+
})
|
| 37 |
+
|
| 38 |
+
it('covers getDb when db is already initialized', async () => {
|
| 39 |
+
const s = save('DB_PATH')
|
| 40 |
+
process.env.DB_PATH = path.join(tmpDir, 'db2.db')
|
| 41 |
+
vi.resetModules()
|
| 42 |
+
const mod = await import('../../src/database.js')
|
| 43 |
+
const first = mod.getDb()
|
| 44 |
+
const second = mod.getDb()
|
| 45 |
+
expect(first).toBe(second)
|
| 46 |
+
restore(s)
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
it('covers getWrappedDb without DEBUG_SQL', async () => {
|
| 50 |
+
const s = save('DEBUG_SQL', 'DB_PATH')
|
| 51 |
+
setEnv({ DEBUG_SQL: 'false', DB_PATH: path.join(tmpDir, 'db3.db') })
|
| 52 |
+
clearCjs('../../src/database.js', '../../src/config.js')
|
| 53 |
+
vi.resetModules()
|
| 54 |
+
const mod = await import('../../src/database.js')
|
| 55 |
+
expect(mod.getWrappedDb()).toBe(mod.getDb())
|
| 56 |
+
restore(s)
|
| 57 |
+
})
|
| 58 |
+
|
| 59 |
+
it('covers parseRow, buildWhere, listAll, and getOne', async () => {
|
| 60 |
+
const dbPath = path.join(tmpDir, 'db-crud.db')
|
| 61 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 62 |
+
setEnv({ DB_PATH: dbPath, DEBUG_SQL: 'true' })
|
| 63 |
+
clearCjs('../../src/database.js', '../../src/config.js')
|
| 64 |
+
vi.resetModules()
|
| 65 |
+
const mod = await import('../../src/database.js')
|
| 66 |
+
const db = mod.getDb()
|
| 67 |
+
db.exec(`
|
| 68 |
+
CREATE TABLE users (
|
| 69 |
+
id INTEGER PRIMARY KEY,
|
| 70 |
+
name TEXT,
|
| 71 |
+
username TEXT,
|
| 72 |
+
email TEXT,
|
| 73 |
+
phone TEXT,
|
| 74 |
+
website TEXT,
|
| 75 |
+
address TEXT,
|
| 76 |
+
company TEXT
|
| 77 |
+
);
|
| 78 |
+
CREATE TABLE todos (
|
| 79 |
+
id INTEGER PRIMARY KEY,
|
| 80 |
+
userId INTEGER,
|
| 81 |
+
title TEXT,
|
| 82 |
+
completed INTEGER
|
| 83 |
+
);
|
| 84 |
+
`)
|
| 85 |
+
db.prepare(`
|
| 86 |
+
INSERT INTO users (id, name, username, email, phone, website, address, company)
|
| 87 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
| 88 |
+
`).run(1, 'Alice', 'alice', 'alice@example.com', '123', 'example.com', '{"street":"1"}', '{"name":"ACME"}')
|
| 89 |
+
db.prepare(`
|
| 90 |
+
INSERT INTO users (id, name, username, email, phone, website, address, company)
|
| 91 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
| 92 |
+
`).run(2, 'Bob', 'bob', 'bob@example.com', '456', 'bob.example.com', 'not-json', '{bad')
|
| 93 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(1, 1, 'Done', 1)
|
| 94 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(2, 1, 'Todo', 0)
|
| 95 |
+
|
| 96 |
+
const users = mod.listAll('users', { name: 'Alice', ignored: 'value' })
|
| 97 |
+
expect(users).toHaveLength(1)
|
| 98 |
+
expect(users[0].address).toEqual({ street: '1' })
|
| 99 |
+
expect(users[0].company).toEqual({ name: 'ACME' })
|
| 100 |
+
expect(users[0].completed).toBeUndefined()
|
| 101 |
+
|
| 102 |
+
const done = mod.listAll('todos', { completed: 'true', ignored: 'value' })
|
| 103 |
+
expect(done).toHaveLength(1)
|
| 104 |
+
expect(done[0].completed).toBe(true)
|
| 105 |
+
const pending = mod.listAll('todos', { completed: 'false' })
|
| 106 |
+
expect(pending).toHaveLength(1)
|
| 107 |
+
expect(pending[0].completed).toBe(false)
|
| 108 |
+
expect(mod.getOne('users', 999)).toBeNull()
|
| 109 |
+
restore(s)
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
it('covers insertOne, updateOne, deleteOne, and nextId', async () => {
|
| 113 |
+
const dbPath = path.join(tmpDir, 'db-write.db')
|
| 114 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 115 |
+
setEnv({ DB_PATH: dbPath, DEBUG_SQL: 'false' })
|
| 116 |
+
clearCjs('../../src/database.js', '../../src/config.js')
|
| 117 |
+
vi.resetModules()
|
| 118 |
+
const mod = await import('../../src/database.js')
|
| 119 |
+
const db = mod.getDb()
|
| 120 |
+
db.exec(`
|
| 121 |
+
CREATE TABLE users (
|
| 122 |
+
id INTEGER PRIMARY KEY,
|
| 123 |
+
name TEXT,
|
| 124 |
+
username TEXT,
|
| 125 |
+
email TEXT,
|
| 126 |
+
phone TEXT,
|
| 127 |
+
website TEXT,
|
| 128 |
+
address TEXT,
|
| 129 |
+
company TEXT
|
| 130 |
+
);
|
| 131 |
+
CREATE TABLE todos (
|
| 132 |
+
id INTEGER PRIMARY KEY,
|
| 133 |
+
userId INTEGER,
|
| 134 |
+
title TEXT,
|
| 135 |
+
completed INTEGER
|
| 136 |
+
);
|
| 137 |
+
`)
|
| 138 |
+
|
| 139 |
+
expect(mod.nextId('users')).toBe(1)
|
| 140 |
+
const inserted = mod.insertOne('users', {
|
| 141 |
+
id: 5,
|
| 142 |
+
name: 'Carol',
|
| 143 |
+
username: 'carol',
|
| 144 |
+
email: 'carol@example.com',
|
| 145 |
+
phone: '789',
|
| 146 |
+
website: 'carol.example.com',
|
| 147 |
+
address: { city: 'Hanoi' },
|
| 148 |
+
company: { name: 'XYZ' },
|
| 149 |
+
})
|
| 150 |
+
expect(inserted.address).toEqual({ city: 'Hanoi' })
|
| 151 |
+
expect(inserted.company).toEqual({ name: 'XYZ' })
|
| 152 |
+
expect(mod.nextId('users')).toBe(6)
|
| 153 |
+
|
| 154 |
+
mod.insertOne('todos', { id: 1, userId: 1, title: 'Initial', completed: true })
|
| 155 |
+
expect(mod.updateOne('users', 999, { name: 'Missing' }, false)).toBeNull()
|
| 156 |
+
const replaced = mod.updateOne('users', 5, {
|
| 157 |
+
name: 'Carol Updated',
|
| 158 |
+
address: { city: 'Danang' },
|
| 159 |
+
company: null,
|
| 160 |
+
}, true)
|
| 161 |
+
expect(replaced.id).toBe(5)
|
| 162 |
+
expect(replaced.name).toBe('Carol Updated')
|
| 163 |
+
expect(replaced.company).toBeNull()
|
| 164 |
+
expect(replaced.username).toBe('carol')
|
| 165 |
+
|
| 166 |
+
const patchedTodo = mod.updateOne('todos', 1, { completed: false, title: 'Patched' }, false)
|
| 167 |
+
expect(patchedTodo.completed).toBe(false)
|
| 168 |
+
expect(patchedTodo.userId).toBe(1)
|
| 169 |
+
expect(mod.deleteOne('todos', 999)).toBeNull()
|
| 170 |
+
expect(mod.deleteOne('todos', 1).id).toBe(1)
|
| 171 |
+
restore(s)
|
| 172 |
+
})
|
| 173 |
+
})
|
tests/db/migrate.test.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll } from 'vitest'
|
| 2 |
+
import fs from 'fs'
|
| 3 |
+
import path from 'path'
|
| 4 |
+
import { mkdtempSync } from 'fs'
|
| 5 |
+
import { tmpdir } from 'os'
|
| 6 |
+
import { createRequire } from 'module'
|
| 7 |
+
import { save, restore, configMockFactory } from '../helpers/coverage'
|
| 8 |
+
|
| 9 |
+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'cov-migrate-'))
|
| 10 |
+
const _require = createRequire(import.meta.url)
|
| 11 |
+
function clearCjs(...keys) {
|
| 12 |
+
for (const key of keys) {
|
| 13 |
+
const resolved = _require.resolve(key)
|
| 14 |
+
if (_require.cache[resolved]) delete _require.cache[resolved]
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
afterAll(() => {
|
| 19 |
+
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
vi.mock('../../src/load-env.js', () => ({ loadEnv: () => {} }))
|
| 23 |
+
vi.mock('../../src/config.js', () => configMockFactory())
|
| 24 |
+
|
| 25 |
+
describe('migrate.js', () => {
|
| 26 |
+
it('runs migration without error', async () => {
|
| 27 |
+
const s = save('DB_PATH')
|
| 28 |
+
process.env.DB_PATH = path.join(tmpDir, 'migrate.db')
|
| 29 |
+
vi.resetModules()
|
| 30 |
+
const { migrate } = await import('../../src/db/migrate.js')
|
| 31 |
+
expect(() => migrate()).not.toThrow()
|
| 32 |
+
restore(s)
|
| 33 |
+
})
|
| 34 |
+
|
| 35 |
+
it('handles migration failure', async () => {
|
| 36 |
+
clearCjs('../../src/db/migrate.js', '../../src/database.js', '../../src/config.js')
|
| 37 |
+
const resolvedDb = _require.resolve('../../src/database.js')
|
| 38 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 39 |
+
_require.cache[resolvedDb] = {
|
| 40 |
+
exports: { getWrappedDb: () => { throw new Error('boom') } },
|
| 41 |
+
id: resolvedDb, filename: resolvedDb, loaded: true,
|
| 42 |
+
}
|
| 43 |
+
try {
|
| 44 |
+
vi.resetModules()
|
| 45 |
+
const { migrate } = await import('../../src/db/migrate.js')
|
| 46 |
+
expect(() => migrate()).toThrow('boom')
|
| 47 |
+
} finally {
|
| 48 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 49 |
+
else delete _require.cache[resolvedDb]
|
| 50 |
+
clearCjs('../../src/db/migrate.js')
|
| 51 |
+
}
|
| 52 |
+
})
|
| 53 |
+
})
|
tests/db/seed.test.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll, afterEach } from 'vitest'
|
| 2 |
+
import fs from 'fs'
|
| 3 |
+
import path from 'path'
|
| 4 |
+
import { mkdtempSync } from 'fs'
|
| 5 |
+
import { tmpdir } from 'os'
|
| 6 |
+
import { EventEmitter } from 'events'
|
| 7 |
+
import { Buffer } from 'buffer'
|
| 8 |
+
import { createRequire } from 'module'
|
| 9 |
+
import { save, restore, configMockFactory } from '../helpers/coverage'
|
| 10 |
+
|
| 11 |
+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'cov-seed-'))
|
| 12 |
+
const _require = createRequire(import.meta.url)
|
| 13 |
+
function clearCjs(...keys) {
|
| 14 |
+
for (const key of keys) {
|
| 15 |
+
const resolved = _require.resolve(key)
|
| 16 |
+
if (_require.cache[resolved]) delete _require.cache[resolved]
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
afterAll(() => {
|
| 21 |
+
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 22 |
+
})
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/load-env.js', () => ({ loadEnv: () => {} }))
|
| 25 |
+
vi.mock('../../src/config.js', () => configMockFactory())
|
| 26 |
+
|
| 27 |
+
describe('seed.js', () => {
|
| 28 |
+
afterEach(() => {
|
| 29 |
+
clearCjs('../../src/db/seed.js', '../../src/db/migrate.js', '../../src/database.js', '../../src/config.js')
|
| 30 |
+
})
|
| 31 |
+
|
| 32 |
+
it('imports and migrate runs, seed returns early when DB has data', async () => {
|
| 33 |
+
const seedDbPath = path.join(tmpDir, 'seed.db')
|
| 34 |
+
const { DatabaseSync } = await import('node:sqlite')
|
| 35 |
+
const db = new DatabaseSync(seedDbPath)
|
| 36 |
+
db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
|
| 37 |
+
db.prepare('INSERT INTO users (id, name) VALUES (1, ?)').run('Test')
|
| 38 |
+
db.close()
|
| 39 |
+
const s = save('DB_PATH')
|
| 40 |
+
process.env.DB_PATH = seedDbPath
|
| 41 |
+
vi.resetModules()
|
| 42 |
+
const { seed } = await import('../../src/db/seed.js')
|
| 43 |
+
await expect(seed()).resolves.toBeUndefined()
|
| 44 |
+
restore(s)
|
| 45 |
+
})
|
| 46 |
+
|
| 47 |
+
it('covers seed fetch parse error via promise rejection', async () => {
|
| 48 |
+
const db = {
|
| 49 |
+
exec: vi.fn(),
|
| 50 |
+
prepare: () => ({
|
| 51 |
+
get: () => ({ rowCount: 0 }),
|
| 52 |
+
run: vi.fn(),
|
| 53 |
+
}),
|
| 54 |
+
}
|
| 55 |
+
const fetchFn = () => Promise.reject(new SyntaxError('Unexpected end of JSON input'))
|
| 56 |
+
const { seed } = await import('../../src/db/seed.js')
|
| 57 |
+
await expect(seed({ database: db, fetch: fetchFn, runMigrate: false })).rejects.toThrow()
|
| 58 |
+
})
|
| 59 |
+
|
| 60 |
+
it('covers seed fetch parse error via event stream', async () => {
|
| 61 |
+
const db = {
|
| 62 |
+
exec: vi.fn(),
|
| 63 |
+
prepare: () => ({
|
| 64 |
+
get: () => ({ rowCount: 0 }),
|
| 65 |
+
run: vi.fn(),
|
| 66 |
+
}),
|
| 67 |
+
}
|
| 68 |
+
const { seed } = await import('../../src/db/seed.js')
|
| 69 |
+
const fetch = async (url) => {
|
| 70 |
+
const response = new EventEmitter()
|
| 71 |
+
queueMicrotask(() => {
|
| 72 |
+
response.emit('data', Buffer.from('{bad'))
|
| 73 |
+
response.emit('end')
|
| 74 |
+
})
|
| 75 |
+
return response
|
| 76 |
+
}
|
| 77 |
+
await expect(seed({ database: db, fetch, runMigrate: false })).rejects.toThrow()
|
| 78 |
+
})
|
| 79 |
+
|
| 80 |
+
it('covers seed https error', async () => {
|
| 81 |
+
const db = {
|
| 82 |
+
exec: vi.fn(),
|
| 83 |
+
prepare: () => ({
|
| 84 |
+
get: () => ({ rowCount: 0 }),
|
| 85 |
+
run: vi.fn(),
|
| 86 |
+
}),
|
| 87 |
+
}
|
| 88 |
+
const fetchFn = () => Promise.reject(new Error('boom'))
|
| 89 |
+
const { seed } = await import('../../src/db/seed.js')
|
| 90 |
+
await expect(seed({ database: db, fetch: fetchFn, runMigrate: false })).rejects.toThrow('boom')
|
| 91 |
+
})
|
| 92 |
+
|
| 93 |
+
it('covers full seed insert path', async () => {
|
| 94 |
+
const runs = []
|
| 95 |
+
const db = {
|
| 96 |
+
exec: vi.fn(),
|
| 97 |
+
prepare: () => ({
|
| 98 |
+
get: () => ({ rowCount: 0 }),
|
| 99 |
+
run: (...args) => runs.push(args),
|
| 100 |
+
}),
|
| 101 |
+
}
|
| 102 |
+
const payload = {
|
| 103 |
+
users: [{ id: 1, name: 'A', username: 'a', email: 'a@example.com', phone: '1', website: 'w', address: { city: 'Hanoi' }, company: { name: 'ACME' } }],
|
| 104 |
+
posts: [{ id: 1, userId: 1, title: 'P', body: 'Body' }],
|
| 105 |
+
comments: [{ id: 1, postId: 1, name: 'C', email: 'c@example.com', body: 'Comment' }],
|
| 106 |
+
albums: [{ id: 1, userId: 1, title: 'Album' }],
|
| 107 |
+
photos: [{ id: 1, albumId: 1, title: 'Photo', url: 'u', thumbnailUrl: 't' }],
|
| 108 |
+
todos: [{ id: 1, userId: 1, title: 'Todo', completed: true }, { id: 2, userId: 1, title: 'Todo2', completed: false }],
|
| 109 |
+
}
|
| 110 |
+
const { seed } = await import('../../src/db/seed.js')
|
| 111 |
+
const fetch = async (url) => {
|
| 112 |
+
const name = new URL(url).pathname.slice(1)
|
| 113 |
+
return payload[name]
|
| 114 |
+
}
|
| 115 |
+
await seed({ database: db, fetch, runMigrate: false })
|
| 116 |
+
expect(runs).toHaveLength(7)
|
| 117 |
+
expect(runs[0][6]).toBe('{"city":"Hanoi"}')
|
| 118 |
+
expect(runs[0][7]).toBe('{"name":"ACME"}')
|
| 119 |
+
expect(runs[6][3]).toBe(0)
|
| 120 |
+
})
|
| 121 |
+
})
|
tests/helpers/coverage.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { vi } from 'vitest'
|
| 2 |
+
|
| 3 |
+
export function save(...keys) {
|
| 4 |
+
const saved = {}
|
| 5 |
+
for (const k of keys) saved[k] = process.env[k]
|
| 6 |
+
return saved
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
export function restore(saved) {
|
| 10 |
+
for (const [k, v] of Object.entries(saved)) {
|
| 11 |
+
if (v === undefined) delete process.env[k]
|
| 12 |
+
else process.env[k] = v
|
| 13 |
+
}
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
export function setEnv(overrides) {
|
| 17 |
+
for (const [k, v] of Object.entries(overrides)) process.env[k] = v
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export function configMockFactory() {
|
| 21 |
+
const METHODS = ['port', 'dbPath', 'dbDebugSql', 'redisOpts', 'rateLimitEnabled', 'rateLimitMax', 'rateLimitWindowMs', 'rateLimitWindowSec']
|
| 22 |
+
const cfg = {
|
| 23 |
+
getPort: () => parseInt(process.env.PORT || '3000', 10),
|
| 24 |
+
getDbPath: () => process.env.DB_PATH || process.cwd() + '/storage/data.db',
|
| 25 |
+
getDbDebugSql: () => (process.env.DEBUG_SQL || 'false') === 'true',
|
| 26 |
+
getRedisOpts: () => {
|
| 27 |
+
const url = process.env.REDIS_URL
|
| 28 |
+
return url ? { url } : {
|
| 29 |
+
host: process.env.REDIS_HOST || '127.0.0.1',
|
| 30 |
+
port: parseInt(process.env.REDIS_PORT || '6379', 10),
|
| 31 |
+
db: parseInt(process.env.REDIS_DB || '0', 10),
|
| 32 |
+
password: process.env.REDIS_PASSWORD || undefined,
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
getRateLimitEnabled: () => (process.env.RATE_LIMIT_ENABLED || 'true') !== 'false',
|
| 36 |
+
getRateLimitMax: () => parseInt(process.env.RATE_LIMIT_MAX || '100', 10),
|
| 37 |
+
getRateLimitWindowMs: () => parseInt(process.env.RATE_LIMIT_WINDOW_MS || '60000', 10),
|
| 38 |
+
getRateLimitWindowSec: () => Math.ceil(parseInt(process.env.RATE_LIMIT_WINDOW_MS || '60000', 10) / 1000),
|
| 39 |
+
}
|
| 40 |
+
const getMethod = (prop) => cfg['get' + prop[0].toUpperCase() + prop.slice(1)]
|
| 41 |
+
return new Proxy(cfg, {
|
| 42 |
+
get(target, prop) {
|
| 43 |
+
if (prop === Symbol.toPrimitive || prop === 'then') return
|
| 44 |
+
const fn = getMethod(prop)
|
| 45 |
+
return fn ? fn() : undefined
|
| 46 |
+
},
|
| 47 |
+
has(target, prop) {
|
| 48 |
+
return METHODS.includes(prop) || cfg['get' + prop[0].toUpperCase() + prop.slice(1)] !== undefined
|
| 49 |
+
},
|
| 50 |
+
ownKeys() { return METHODS },
|
| 51 |
+
getOwnPropertyDescriptor(target, prop) {
|
| 52 |
+
if (METHODS.includes(prop)) return { enumerable: true, configurable: true }
|
| 53 |
+
},
|
| 54 |
+
})
|
| 55 |
+
}
|
tests/middleware/rate-limiter.test.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
| 2 |
+
import fs from 'fs'
|
| 3 |
+
import path from 'path'
|
| 4 |
+
import { mkdtempSync } from 'fs'
|
| 5 |
+
import { tmpdir } from 'os'
|
| 6 |
+
import { createRequire } from 'module'
|
| 7 |
+
import { save, restore, setEnv, configMockFactory } from '../helpers/coverage'
|
| 8 |
+
|
| 9 |
+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'cov-rl-'))
|
| 10 |
+
const _require = createRequire(import.meta.url)
|
| 11 |
+
function clearCjs(...keys) {
|
| 12 |
+
for (const key of keys) {
|
| 13 |
+
const resolved = _require.resolve(key)
|
| 14 |
+
if (_require.cache[resolved]) delete _require.cache[resolved]
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
afterAll(() => {
|
| 19 |
+
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
vi.mock('../../src/load-env.js', () => ({ loadEnv: () => {} }))
|
| 23 |
+
vi.mock('../../src/config.js', () => configMockFactory())
|
| 24 |
+
|
| 25 |
+
describe('rate-limiter.js', () => {
|
| 26 |
+
let createRateLimiter
|
| 27 |
+
|
| 28 |
+
beforeAll(async () => {
|
| 29 |
+
clearCjs('../../src/rate-limiter.js', '../../src/config.js')
|
| 30 |
+
const mod = await import('../../src/rate-limiter.js')
|
| 31 |
+
createRateLimiter = mod.createRateLimiter
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
function freshLimiter(redis, envOverrides = {}) {
|
| 35 |
+
clearCjs('../../src/config.js')
|
| 36 |
+
Object.entries(envOverrides).forEach(([k, v]) => { process.env[k] = v })
|
| 37 |
+
return createRateLimiter(redis)
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
it('rate limits via in-memory store and blocks at limit', async () => {
|
| 41 |
+
const s = save('RATE_LIMIT_ENABLED', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS')
|
| 42 |
+
const limiter = freshLimiter(null, { RATE_LIMIT_ENABLED: 'true', RATE_LIMIT_MAX: '2', RATE_LIMIT_WINDOW_MS: '60000' })
|
| 43 |
+
|
| 44 |
+
const mkRes = () => ({ setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() })
|
| 45 |
+
const mkReq = (ip) => ({ headers: {}, socket: { remoteAddress: ip } })
|
| 46 |
+
|
| 47 |
+
let c1 = false; await limiter(mkReq('1.2.3.4'), mkRes(), () => { c1 = true })
|
| 48 |
+
expect(c1).toBe(true)
|
| 49 |
+
const r2 = mkRes()
|
| 50 |
+
let c2 = false; await limiter(mkReq('1.2.3.4'), r2, () => { c2 = true })
|
| 51 |
+
expect(c2).toBe(true)
|
| 52 |
+
const r3 = mkRes()
|
| 53 |
+
let c3 = false
|
| 54 |
+
await limiter(mkReq('1.2.3.4'), r3, () => { c3 = true })
|
| 55 |
+
expect(c3).toBe(false)
|
| 56 |
+
expect(r3.writeHead).toHaveBeenCalledWith(429, expect.any(Object))
|
| 57 |
+
expect(r3.end).toHaveBeenCalled()
|
| 58 |
+
restore(s)
|
| 59 |
+
})
|
| 60 |
+
|
| 61 |
+
it('parses x-forwarded-for header', async () => {
|
| 62 |
+
const s = save('RATE_LIMIT_ENABLED')
|
| 63 |
+
const limiter = freshLimiter(null, { RATE_LIMIT_ENABLED: 'true' })
|
| 64 |
+
const req = { headers: { 'x-forwarded-for': '10.0.0.1, 10.0.0.2' }, socket: { remoteAddress: '::1' } }
|
| 65 |
+
const res = { setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() }
|
| 66 |
+
let called = false
|
| 67 |
+
await limiter(req, res, () => { called = true })
|
| 68 |
+
expect(called).toBe(true)
|
| 69 |
+
restore(s)
|
| 70 |
+
})
|
| 71 |
+
|
| 72 |
+
it('handles missing remoteAddress with unknown fallback', async () => {
|
| 73 |
+
const s = save('RATE_LIMIT_ENABLED')
|
| 74 |
+
const limiter = freshLimiter(null, { RATE_LIMIT_ENABLED: 'true' })
|
| 75 |
+
const req = { headers: {}, socket: {} }
|
| 76 |
+
const res = { setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() }
|
| 77 |
+
let called = false
|
| 78 |
+
await limiter(req, res, () => { called = true })
|
| 79 |
+
expect(called).toBe(true)
|
| 80 |
+
restore(s)
|
| 81 |
+
})
|
| 82 |
+
|
| 83 |
+
it('returns early when rate limiting is disabled', async () => {
|
| 84 |
+
const s = save('RATE_LIMIT_ENABLED')
|
| 85 |
+
const limiter = freshLimiter(null, { RATE_LIMIT_ENABLED: 'false' })
|
| 86 |
+
let called = false
|
| 87 |
+
await limiter({ headers: {}, socket: {} }, { setHeader: vi.fn() }, () => { called = true })
|
| 88 |
+
expect(called).toBe(true)
|
| 89 |
+
restore(s)
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
it('covers redis store, redis failure fallback, and limit response', async () => {
|
| 93 |
+
const s = save('RATE_LIMIT_ENABLED', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS')
|
| 94 |
+
const redis = {
|
| 95 |
+
connected: true,
|
| 96 |
+
incr: vi.fn(),
|
| 97 |
+
expire: vi.fn(),
|
| 98 |
+
ttl: vi.fn(),
|
| 99 |
+
}
|
| 100 |
+
const limiter = freshLimiter(redis, { RATE_LIMIT_ENABLED: 'true', RATE_LIMIT_MAX: '2', RATE_LIMIT_WINDOW_MS: '60000' })
|
| 101 |
+
const mkReq = (ip) => ({ headers: {}, socket: { remoteAddress: ip } })
|
| 102 |
+
const mkRes = () => ({ setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() })
|
| 103 |
+
|
| 104 |
+
redis.incr.mockResolvedValueOnce(1)
|
| 105 |
+
redis.ttl.mockResolvedValueOnce(60)
|
| 106 |
+
let called = false
|
| 107 |
+
await limiter(mkReq('5.5.5.5'), mkRes(), () => { called = true })
|
| 108 |
+
expect(called).toBe(true)
|
| 109 |
+
expect(redis.expire).toHaveBeenCalled()
|
| 110 |
+
|
| 111 |
+
redis.incr.mockResolvedValueOnce(3)
|
| 112 |
+
redis.ttl.mockResolvedValueOnce(57)
|
| 113 |
+
const limitedRes = mkRes()
|
| 114 |
+
let limitedCalled = false
|
| 115 |
+
await limiter(mkReq('5.5.5.5'), limitedRes, () => { limitedCalled = true })
|
| 116 |
+
expect(limitedCalled).toBe(false)
|
| 117 |
+
expect(limitedRes.writeHead).toHaveBeenCalledWith(429, expect.any(Object))
|
| 118 |
+
expect(limitedRes.end).toHaveBeenCalled()
|
| 119 |
+
|
| 120 |
+
redis.incr.mockRejectedValueOnce(new Error('down'))
|
| 121 |
+
const fallbackRes = mkRes()
|
| 122 |
+
let fallbackCalled = false
|
| 123 |
+
await limiter(mkReq('6.6.6.6'), fallbackRes, () => { fallbackCalled = true })
|
| 124 |
+
expect(fallbackCalled).toBe(true)
|
| 125 |
+
restore(s)
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
it('resets memory store entry after window expires', async () => {
|
| 129 |
+
const s = save('RATE_LIMIT_ENABLED', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS')
|
| 130 |
+
setEnv({ RATE_LIMIT_ENABLED: 'true', RATE_LIMIT_MAX: '2', 'RATE_LIMIT_WINDOW_MS': '60000' })
|
| 131 |
+
clearCjs('../../src/rate-limiter.js', '../../src/config.js')
|
| 132 |
+
const { createRateLimiter } = await import('../../src/rate-limiter.js')
|
| 133 |
+
const limiter = createRateLimiter(null)
|
| 134 |
+
const req = { headers: {}, socket: { remoteAddress: '7.7.7.7' } }
|
| 135 |
+
const res1 = { setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() }
|
| 136 |
+
const res2 = { setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() }
|
| 137 |
+
vi.useFakeTimers()
|
| 138 |
+
vi.setSystemTime(0)
|
| 139 |
+
let first = false
|
| 140 |
+
await limiter(req, res1, () => { first = true })
|
| 141 |
+
expect(first).toBe(true)
|
| 142 |
+
vi.setSystemTime(70000)
|
| 143 |
+
let second = false
|
| 144 |
+
await limiter(req, res2, () => { second = true })
|
| 145 |
+
expect(second).toBe(true)
|
| 146 |
+
vi.useRealTimers()
|
| 147 |
+
restore(s)
|
| 148 |
+
})
|
| 149 |
+
})
|
tests/redis/redis.test.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll } from 'vitest'
|
| 2 |
+
import fs from 'fs'
|
| 3 |
+
import path from 'path'
|
| 4 |
+
import { mkdtempSync } from 'fs'
|
| 5 |
+
import { tmpdir } from 'os'
|
| 6 |
+
import { createRequire } from 'module'
|
| 7 |
+
import net from 'net'
|
| 8 |
+
|
| 9 |
+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'cov-redis-'))
|
| 10 |
+
const _require = createRequire(import.meta.url)
|
| 11 |
+
|
| 12 |
+
afterAll(() => {
|
| 13 |
+
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 14 |
+
})
|
| 15 |
+
|
| 16 |
+
async function closeServer(server) {
|
| 17 |
+
await new Promise((resolve) => server.close(resolve))
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
describe('redis.js', () => {
|
| 21 |
+
it('encodes RESP commands', async () => {
|
| 22 |
+
const RedisClient = _require('../../src/redis.js')
|
| 23 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 24 |
+
expect(c._encode('PING')).toBe('*1\r\n$4\r\nPING\r\n')
|
| 25 |
+
expect(c._encode('SET', 'k', 'v')).toBe('*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$1\r\nv\r\n')
|
| 26 |
+
})
|
| 27 |
+
|
| 28 |
+
it('parses all RESP types', async () => {
|
| 29 |
+
const RedisClient = _require('../../src/redis.js')
|
| 30 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 31 |
+
const p = (b) => c._parse(Buffer.from(b))
|
| 32 |
+
|
| 33 |
+
expect(p('+OK\r\n').value).toEqual(Buffer.from('OK'))
|
| 34 |
+
const e = p('-ERR x\r\n')
|
| 35 |
+
expect(e.isError).toBe(true); expect(e.value.message).toBe('ERR x')
|
| 36 |
+
expect(p(':42\r\n').value).toBe(42)
|
| 37 |
+
expect(p('$-1\r\n').value).toBeNull()
|
| 38 |
+
expect(p('$5\r\nhello\r\n').value).toEqual(Buffer.from('hello'))
|
| 39 |
+
const a = p('*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n')
|
| 40 |
+
expect(a.value.length).toBe(2)
|
| 41 |
+
expect(a.value[0]).toEqual(Buffer.from('foo'))
|
| 42 |
+
expect(a.value[1]).toEqual(Buffer.from('bar'))
|
| 43 |
+
expect(p('*-1\r\n').value).toBeNull()
|
| 44 |
+
expect(c._parse(Buffer.alloc(0))).toBeNull()
|
| 45 |
+
expect(c._parse(Buffer.from('$5\r\nhel'))).toBeNull()
|
| 46 |
+
})
|
| 47 |
+
|
| 48 |
+
it('throws on unknown RESP type', async () => {
|
| 49 |
+
const RedisClient = _require('../../src/redis.js')
|
| 50 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 51 |
+
expect(() => c._parse(Buffer.from('!x\r\n'))).toThrow('Unknown RESP type')
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
it('connect returns early when already connected or connecting', async () => {
|
| 55 |
+
const RedisClient = _require('../../src/redis.js')
|
| 56 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 57 |
+
c.connected = true
|
| 58 |
+
await expect(c.connect()).resolves.toBeUndefined()
|
| 59 |
+
c.connected = false; c._connecting = true
|
| 60 |
+
await expect(c.connect()).resolves.toBeUndefined()
|
| 61 |
+
})
|
| 62 |
+
|
| 63 |
+
it('parses URL in constructor', async () => {
|
| 64 |
+
const RedisClient = _require('../../src/redis.js')
|
| 65 |
+
const c = new RedisClient({ url: 'redis://:secret@myhost:6380/3' })
|
| 66 |
+
expect(c.host).toBe('myhost')
|
| 67 |
+
expect(c.port).toBe(6380)
|
| 68 |
+
expect(c.password).toBe('secret')
|
| 69 |
+
expect(c.db).toBe(3)
|
| 70 |
+
})
|
| 71 |
+
|
| 72 |
+
it('send and _onData process responses', async () => {
|
| 73 |
+
const RedisClient = _require('../../src/redis.js')
|
| 74 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 75 |
+
c.socket = { write: vi.fn() }
|
| 76 |
+
const p = c.send('PING')
|
| 77 |
+
expect(c.queue.length).toBe(1)
|
| 78 |
+
c._onData(Buffer.from('+PONG\r\n'))
|
| 79 |
+
await expect(p).resolves.toEqual(Buffer.from('PONG'))
|
| 80 |
+
})
|
| 81 |
+
|
| 82 |
+
it('rejects on error response', async () => {
|
| 83 |
+
const RedisClient = _require('../../src/redis.js')
|
| 84 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 85 |
+
c.socket = { write: vi.fn() }
|
| 86 |
+
const p = c.send('PING')
|
| 87 |
+
c._onData(Buffer.from('-ERR bad\r\n'))
|
| 88 |
+
await expect(p).rejects.toThrow('ERR bad')
|
| 89 |
+
})
|
| 90 |
+
|
| 91 |
+
it('handles partial data across multiple _onData calls', async () => {
|
| 92 |
+
const RedisClient = _require('../../src/redis.js')
|
| 93 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 94 |
+
c.socket = { write: vi.fn() }
|
| 95 |
+
const p = c.send('GET', 'key')
|
| 96 |
+
c._onData(Buffer.from('$'))
|
| 97 |
+
c._onData(Buffer.from('3\r\nval\r\n'))
|
| 98 |
+
await expect(p).resolves.toEqual(Buffer.from('val'))
|
| 99 |
+
})
|
| 100 |
+
|
| 101 |
+
it('quit sends QUIT and destroys socket', async () => {
|
| 102 |
+
const RedisClient = _require('../../src/redis.js')
|
| 103 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 104 |
+
const destroy = vi.fn()
|
| 105 |
+
c.socket = { write: vi.fn(), destroy }
|
| 106 |
+
const p = c.quit()
|
| 107 |
+
c._onData(Buffer.from('+OK\r\n'))
|
| 108 |
+
await p
|
| 109 |
+
expect(destroy).toHaveBeenCalled()
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
it('connect handler with auth and select via TCP', async () => {
|
| 113 |
+
const server = net.createServer(s => {
|
| 114 |
+
s.on('data', d => {
|
| 115 |
+
if (d.includes('AUTH')) s.write(Buffer.from('+OK\r\n'))
|
| 116 |
+
else if (d.includes('SELECT')) s.write(Buffer.from('+OK\r\n'))
|
| 117 |
+
})
|
| 118 |
+
})
|
| 119 |
+
await new Promise(r => server.listen(0, '127.0.0.1', r))
|
| 120 |
+
const { port } = server.address()
|
| 121 |
+
const RedisClient = _require('../../src/redis.js')
|
| 122 |
+
const c = new RedisClient({ host: '127.0.0.1', port, password: 's', db: 1 })
|
| 123 |
+
await expect(c.connect()).resolves.toBeUndefined()
|
| 124 |
+
expect(c.connected).toBe(true)
|
| 125 |
+
server.close()
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
it('connect handler without auth/select via TCP', async () => {
|
| 129 |
+
const server = net.createServer(s => {
|
| 130 |
+
s.on('data', () => s.write(Buffer.from('+OK\r\n')))
|
| 131 |
+
})
|
| 132 |
+
await new Promise(r => server.listen(0, '127.0.0.1', r))
|
| 133 |
+
const { port } = server.address()
|
| 134 |
+
const RedisClient = _require('../../src/redis.js')
|
| 135 |
+
const c = new RedisClient({ host: '127.0.0.1', port })
|
| 136 |
+
await expect(c.connect()).resolves.toBeUndefined()
|
| 137 |
+
expect(c.connected).toBe(true)
|
| 138 |
+
server.close()
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
it('uses default constructor options', async () => {
|
| 142 |
+
const RedisClient = _require('../../src/redis.js')
|
| 143 |
+
const c = new RedisClient()
|
| 144 |
+
expect(c.host).toBe('127.0.0.1')
|
| 145 |
+
expect(c.port).toBe(6379)
|
| 146 |
+
expect(c.db).toBe(0)
|
| 147 |
+
expect(c.password).toBeUndefined()
|
| 148 |
+
})
|
| 149 |
+
|
| 150 |
+
it('parses URL without port and without password', async () => {
|
| 151 |
+
const RedisClient = _require('../../src/redis.js')
|
| 152 |
+
const c = new RedisClient({ url: 'redis://myhost/3' })
|
| 153 |
+
expect(c.host).toBe('myhost')
|
| 154 |
+
expect(c.port).toBe(6379)
|
| 155 |
+
expect(c.password).toBeUndefined()
|
| 156 |
+
expect(c.db).toBe(3)
|
| 157 |
+
})
|
| 158 |
+
|
| 159 |
+
it('handles _parse offset and array null branches', async () => {
|
| 160 |
+
const RedisClient = _require('../../src/redis.js')
|
| 161 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 162 |
+
expect(c._parse(Buffer.from('x'), 1)).toBeNull()
|
| 163 |
+
expect(c._parse(Buffer.from('*-1\r\n')).value).toBeNull()
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
it('parses URL with empty hostname, using default host', async () => {
|
| 167 |
+
const RedisClient = _require('../../src/redis.js')
|
| 168 |
+
const c = new RedisClient({ url: 'redis:///3' })
|
| 169 |
+
expect(c.host).toBe('127.0.0.1')
|
| 170 |
+
expect(c.db).toBe(3)
|
| 171 |
+
})
|
| 172 |
+
|
| 173 |
+
it('parses URL with non-numeric path, keeping default db', async () => {
|
| 174 |
+
const RedisClient = _require('../../src/redis.js')
|
| 175 |
+
const c = new RedisClient({ url: 'redis://host/db' })
|
| 176 |
+
expect(c.host).toBe('host')
|
| 177 |
+
expect(c.db).toBe(0)
|
| 178 |
+
})
|
| 179 |
+
|
| 180 |
+
it('handles incomplete array data in _parse', async () => {
|
| 181 |
+
const RedisClient = _require('../../src/redis.js')
|
| 182 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 183 |
+
expect(c._parse(Buffer.from('*2\r\n$3\r\nfoo'))).toBeNull()
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
it('covers _onData when no response is complete', async () => {
|
| 187 |
+
const RedisClient = _require('../../src/redis.js')
|
| 188 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 189 |
+
c.socket = { write: vi.fn() }
|
| 190 |
+
c.send('PING')
|
| 191 |
+
c._onData(Buffer.from('+'))
|
| 192 |
+
expect(c.queue.length).toBe(1)
|
| 193 |
+
})
|
| 194 |
+
|
| 195 |
+
it('covers redis helper methods', async () => {
|
| 196 |
+
const RedisClient = _require('../../src/redis.js')
|
| 197 |
+
const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
|
| 198 |
+
c.socket = { write: vi.fn() }
|
| 199 |
+
c.ping()
|
| 200 |
+
c.auth('s')
|
| 201 |
+
c.get('k')
|
| 202 |
+
c.set('k', 'v', 'EX', 1)
|
| 203 |
+
c.setex('k', 1, 'v')
|
| 204 |
+
c.incr('k')
|
| 205 |
+
c.expire('k', 1)
|
| 206 |
+
c.del('a', 'b')
|
| 207 |
+
c.ttl('k')
|
| 208 |
+
expect(c.socket.write).toHaveBeenCalledTimes(9)
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
it('connect handler with auth failure via TCP', async () => {
|
| 212 |
+
const server = net.createServer(s => {
|
| 213 |
+
s.on('data', d => {
|
| 214 |
+
if (d.includes('AUTH')) s.write(Buffer.from('-ERR invalid password\r\n'))
|
| 215 |
+
})
|
| 216 |
+
})
|
| 217 |
+
await new Promise(r => server.listen(0, '127.0.0.1', r))
|
| 218 |
+
const { port } = server.address()
|
| 219 |
+
const RedisClient = _require('../../src/redis.js')
|
| 220 |
+
const c = new RedisClient({ host: '127.0.0.1', port, password: 's' })
|
| 221 |
+
await expect(c.connect()).rejects.toThrow('ERR invalid password')
|
| 222 |
+
expect(c.connected).toBe(false)
|
| 223 |
+
server.close()
|
| 224 |
+
})
|
| 225 |
+
|
| 226 |
+
it('connect error handler rejects queued commands via TCP', async () => {
|
| 227 |
+
const server = net.createServer(() => {})
|
| 228 |
+
await new Promise(r => server.listen(0, '127.0.0.1', r))
|
| 229 |
+
const { port } = server.address()
|
| 230 |
+
const RedisClient = _require('../../src/redis.js')
|
| 231 |
+
const c = new RedisClient({ host: '127.0.0.1', port })
|
| 232 |
+
c.connect().catch(() => {})
|
| 233 |
+
await new Promise(r => setTimeout(r, 20))
|
| 234 |
+
c.socket.destroy(new Error('ECONNRESET'))
|
| 235 |
+
const p = c.send('PING')
|
| 236 |
+
await expect(p).rejects.toThrow()
|
| 237 |
+
server.close()
|
| 238 |
+
})
|
| 239 |
+
})
|
| 240 |
+
|
| 241 |
+
describe('redis.js connect handlers', () => {
|
| 242 |
+
it('covers connect error handler rejecting queued commands', async () => {
|
| 243 |
+
const server = net.createServer((socket) => {
|
| 244 |
+
socket.on('data', () => socket.destroy(new Error('ECONNRESET')))
|
| 245 |
+
socket.on('error', () => {})
|
| 246 |
+
})
|
| 247 |
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
| 248 |
+
const { port } = server.address()
|
| 249 |
+
const RedisClient = _require('../../src/redis.js')
|
| 250 |
+
const c = new RedisClient({ host: '127.0.0.1', port })
|
| 251 |
+
await c.connect()
|
| 252 |
+
const p = c.send('PING')
|
| 253 |
+
c.socket.destroy(new Error('ECONNRESET'))
|
| 254 |
+
await expect(p).rejects.toThrow()
|
| 255 |
+
expect(c.connected).toBe(false)
|
| 256 |
+
expect(c._connecting).toBe(false)
|
| 257 |
+
c.socket.destroy(new Error('ECONNRESET'))
|
| 258 |
+
await closeServer(server)
|
| 259 |
+
})
|
| 260 |
+
|
| 261 |
+
it('covers connect handler with auth and select', async () => {
|
| 262 |
+
const server = net.createServer((socket) => {
|
| 263 |
+
socket.on('data', (data) => {
|
| 264 |
+
if (data.includes('AUTH')) socket.write(Buffer.from('+OK\r\n'))
|
| 265 |
+
if (data.includes('SELECT')) socket.write(Buffer.from('+OK\r\n'))
|
| 266 |
+
})
|
| 267 |
+
})
|
| 268 |
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
| 269 |
+
const { port } = server.address()
|
| 270 |
+
const RedisClient = _require('../../src/redis.js')
|
| 271 |
+
const c = new RedisClient({ host: '127.0.0.1', port, password: 's', db: 1 })
|
| 272 |
+
await expect(c.connect()).resolves.toBeUndefined()
|
| 273 |
+
expect(c.connected).toBe(true)
|
| 274 |
+
c.socket.destroy(new Error('ECONNRESET'))
|
| 275 |
+
await closeServer(server)
|
| 276 |
+
})
|
| 277 |
+
|
| 278 |
+
it('covers connect handler without auth/select', async () => {
|
| 279 |
+
const server = net.createServer(() => {})
|
| 280 |
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
| 281 |
+
const { port } = server.address()
|
| 282 |
+
const RedisClient = _require('../../src/redis.js')
|
| 283 |
+
const c = new RedisClient({ host: '127.0.0.1', port })
|
| 284 |
+
await expect(c.connect()).resolves.toBeUndefined()
|
| 285 |
+
expect(c.connected).toBe(true)
|
| 286 |
+
c.socket.destroy(new Error('ECONNRESET'))
|
| 287 |
+
await closeServer(server)
|
| 288 |
+
})
|
| 289 |
+
|
| 290 |
+
it('covers connect handler with auth failure', async () => {
|
| 291 |
+
const server = net.createServer((socket) => {
|
| 292 |
+
socket.on('data', () => socket.write(Buffer.from('-ERR invalid password\r\n')))
|
| 293 |
+
})
|
| 294 |
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
| 295 |
+
const { port } = server.address()
|
| 296 |
+
const RedisClient = _require('../../src/redis.js')
|
| 297 |
+
const c = new RedisClient({ host: '127.0.0.1', port, password: 's' })
|
| 298 |
+
await expect(c.connect()).rejects.toThrow('ERR invalid password')
|
| 299 |
+
expect(c.connected).toBe(false)
|
| 300 |
+
c.socket.destroy(new Error('ECONNRESET'))
|
| 301 |
+
await closeServer(server)
|
| 302 |
+
})
|
| 303 |
+
})
|
tests/server.test.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import { beforeAll, afterAll, describe, it, expect } from 'vitest';
|
| 2 |
import { startServer, stopServer, request } from './helpers';
|
| 3 |
|
| 4 |
beforeAll(async () => {
|
|
@@ -270,6 +270,14 @@ describe('POST — Create', () => {
|
|
| 270 |
expect(res.status).toBe(400);
|
| 271 |
expect(res.body.error).toBe('Invalid JSON body');
|
| 272 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
});
|
| 274 |
|
| 275 |
describe('PATCH — Partial update', () => {
|
|
@@ -369,4 +377,4 @@ describe('CORS headers on error responses', () => {
|
|
| 369 |
expect(res.status).toBe(404);
|
| 370 |
expect(res.headers['access-control-allow-origin']).toBe('*');
|
| 371 |
});
|
| 372 |
-
})
|
|
|
|
| 1 |
+
import { beforeAll, afterAll, describe, it, expect, vi } from 'vitest';
|
| 2 |
import { startServer, stopServer, request } from './helpers';
|
| 3 |
|
| 4 |
beforeAll(async () => {
|
|
|
|
| 270 |
expect(res.status).toBe(400);
|
| 271 |
expect(res.body.error).toBe('Invalid JSON body');
|
| 272 |
});
|
| 273 |
+
|
| 274 |
+
it('POST with unknown column returns 400 from db error', async () => {
|
| 275 |
+
const res = await request('/api/users', {
|
| 276 |
+
method: 'POST',
|
| 277 |
+
body: { name: 'test', extra_col: 'value' },
|
| 278 |
+
});
|
| 279 |
+
expect(res.status).toBe(400);
|
| 280 |
+
});
|
| 281 |
});
|
| 282 |
|
| 283 |
describe('PATCH — Partial update', () => {
|
|
|
|
| 377 |
expect(res.status).toBe(404);
|
| 378 |
expect(res.headers['access-control-allow-origin']).toBe('*');
|
| 379 |
});
|
| 380 |
+
})
|
tests/server/coverage-printlog.test.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi } from 'vitest'
|
| 2 |
+
import { save, restore } from '../helpers/coverage'
|
| 3 |
+
|
| 4 |
+
function mkReq(url, method, rawBody) {
|
| 5 |
+
const req = {
|
| 6 |
+
url, method, headers: {}, socket: { remoteAddress: '::1' },
|
| 7 |
+
on: (evt, cb) => { if (evt === 'end') queueMicrotask(() => cb()) },
|
| 8 |
+
}
|
| 9 |
+
if (rawBody) {
|
| 10 |
+
req.headers = { 'content-type': 'text/plain' }
|
| 11 |
+
req.on = (evt, cb) => {
|
| 12 |
+
if (evt === 'data') { queueMicrotask(() => cb(rawBody)) }
|
| 13 |
+
if (evt === 'end') { queueMicrotask(() => cb()) }
|
| 14 |
+
if (evt === 'error') { /* no-op */ }
|
| 15 |
+
return req
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
return req
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
function mkRes() {
|
| 22 |
+
return { writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false }
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
describe('server.js ESM coverage', () => {
|
| 26 |
+
it('covers printLog, startServer, and 500 catch', async () => {
|
| 27 |
+
const s = save(
|
| 28 |
+
'PORT', 'START_SERVER', 'DB_PATH', 'RATE_LIMIT_ENABLED',
|
| 29 |
+
'REDIS_URL', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB',
|
| 30 |
+
'REDIS_PASSWORD', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS', 'DEBUG_SQL',
|
| 31 |
+
)
|
| 32 |
+
process.env.PORT = '0'
|
| 33 |
+
process.env.START_SERVER = 'true'
|
| 34 |
+
process.env.DB_PATH = ':memory:'
|
| 35 |
+
process.env.RATE_LIMIT_ENABLED = 'false'
|
| 36 |
+
|
| 37 |
+
vi.resetModules()
|
| 38 |
+
const mod = await import('../../src/server.js')
|
| 39 |
+
|
| 40 |
+
await new Promise((r) => {
|
| 41 |
+
if (mod.server.listening) return r()
|
| 42 |
+
mod.server.once('listening', r)
|
| 43 |
+
})
|
| 44 |
+
expect(mod.server.listening).toBe(true)
|
| 45 |
+
|
| 46 |
+
const res = mkRes()
|
| 47 |
+
await mod.requestHandler(mkReq('/api/users', 'GET'), res)
|
| 48 |
+
expect(res.writeHead).toHaveBeenCalledWith(500, expect.anything())
|
| 49 |
+
|
| 50 |
+
await new Promise((r) => mod.server.close(r))
|
| 51 |
+
restore(s)
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
it('covers additional handler code paths', async () => {
|
| 55 |
+
const s = save(
|
| 56 |
+
'PORT', 'START_SERVER', 'DB_PATH', 'RATE_LIMIT_ENABLED',
|
| 57 |
+
'REDIS_URL', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB',
|
| 58 |
+
'REDIS_PASSWORD', 'RATE_LIMIT_MAX', 'RATE_LIMIT_WINDOW_MS', 'DEBUG_SQL',
|
| 59 |
+
)
|
| 60 |
+
process.env.PORT = '3199'
|
| 61 |
+
process.env.START_SERVER = 'false'
|
| 62 |
+
process.env.DB_PATH = ':memory:'
|
| 63 |
+
process.env.RATE_LIMIT_ENABLED = 'false'
|
| 64 |
+
|
| 65 |
+
vi.resetModules()
|
| 66 |
+
const mod = await import('../../src/server.js')
|
| 67 |
+
|
| 68 |
+
let res
|
| 69 |
+
|
| 70 |
+
// PUT with invalid JSON body → readBody catch at line 126
|
| 71 |
+
res = mkRes()
|
| 72 |
+
await mod.requestHandler(mkReq('/api/posts/1', 'PUT', 'not-json'), res)
|
| 73 |
+
expect(res.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 74 |
+
|
| 75 |
+
// PATCH with invalid JSON body → readBody catch at line 138
|
| 76 |
+
res = mkRes()
|
| 77 |
+
await mod.requestHandler(mkReq('/api/posts/1', 'PATCH', 'not-json'), res)
|
| 78 |
+
expect(res.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 79 |
+
|
| 80 |
+
restore(s)
|
| 81 |
+
})
|
| 82 |
+
})
|