Spaces:
Sleeping
Sleeping
Commit ·
62e3094
1
Parent(s): 25059bd
test: add server unit tests and restructure test suite
Browse files- Add unit tests for the HTTP request handler and route parsing
- Organize test files by module directory
- README.md +13 -11
- tests/README.md +12 -18
- tests/db/sql-logger.test.js +55 -0
- tests/helpers/index.js +1 -0
- tests/{server.test.js → server/integration.test.js} +2 -2
- tests/server/server.test.js +223 -0
- vitest.config.js +0 -1
README.md
CHANGED
|
@@ -175,18 +175,20 @@ json-api-server/
|
|
| 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 |
-
│ │
|
|
|
|
| 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 |
-
│ │
|
| 189 |
-
│ ├──
|
|
|
|
| 190 |
│ ├── README.md # Testing documentation
|
| 191 |
│ └── helpers/
|
| 192 |
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
|
@@ -217,7 +219,7 @@ bin/start.js → src/load-env.js (loads .env per NODE_ENV, skipped in production
|
|
| 217 |
├── src/config.js (centralized config, auto-loads dotenv)
|
| 218 |
├── src/database.js (SQLite CRUD)
|
| 219 |
├── src/redis.js (pure RESP + AUTH + URL)
|
| 220 |
-
└── src/rate-limiter.js (Redis || in-memory)
|
| 221 |
|
| 222 |
# Standalone scripts: npm run db:migrate / npm run db:seed / npm run db:setup (config.js loads dotenv automatically)
|
| 223 |
```
|
|
@@ -265,12 +267,12 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
|
|
| 265 |
|
| 266 |
## Testing
|
| 267 |
|
| 268 |
-
Uses **vitest** with **V8 native coverage**.
|
| 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, ~
|
| 274 |
```
|
| 275 |
|
| 276 |
See [tests/README.md](tests/README.md) for full documentation.
|
|
|
|
| 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 (6)
|
| 179 |
│ ├── db/
|
| 180 |
+
│ │ ├── database.test.js # Database CRUD, pagination, search, sort (5)
|
| 181 |
+
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 182 |
+
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 183 |
+
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
| 184 |
│ ├── middleware/
|
| 185 |
+
│ │ └── rate-limiter.test.js # In-memory and Redis rate limiter paths (6)
|
| 186 |
│ ├── redis/
|
| 187 |
+
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options (25)
|
| 188 |
│ ├── server/
|
| 189 |
+
│ │ ├── coverage-printlog.test.js # V8 coverage: printLog, startServer, 500 catch (2)
|
| 190 |
+
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (50)
|
| 191 |
+
│ │ └── server.test.js # Server request handler and startup paths (5)
|
| 192 |
│ ├── README.md # Testing documentation
|
| 193 |
│ └── helpers/
|
| 194 |
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
|
|
|
| 219 |
├── src/config.js (centralized config, auto-loads dotenv)
|
| 220 |
├── src/database.js (SQLite CRUD)
|
| 221 |
├── src/redis.js (pure RESP + AUTH + URL)
|
| 222 |
+
└── src/rate-limiter.js (Redis || in-memory, config loaded lazily per call)
|
| 223 |
|
| 224 |
# Standalone scripts: npm run db:migrate / npm run db:seed / npm run db:setup (config.js loads dotenv automatically)
|
| 225 |
```
|
|
|
|
| 267 |
|
| 268 |
## Testing
|
| 269 |
|
| 270 |
+
Uses **vitest** with **V8 native coverage**. 111 tests across 10 test files cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
|
| 271 |
|
| 272 |
```bash
|
| 273 |
npm test # Run all tests once
|
| 274 |
npm run test:watch # Watch mode
|
| 275 |
+
npm run test:coverage # With coverage report (~92% statements, ~89% branches)
|
| 276 |
```
|
| 277 |
|
| 278 |
See [tests/README.md](tests/README.md) for full documentation.
|
tests/README.md
CHANGED
|
@@ -23,24 +23,26 @@ tests/
|
|
| 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 |
-
|
|
|
|
| 33 |
helpers/
|
| 34 |
-
coverage.js #
|
| 35 |
index.js # startServer / stopServer / request utilities
|
| 36 |
seed.js # Standalone script to create & seed temp DB
|
| 37 |
```
|
| 38 |
|
| 39 |
-
**Total:
|
| 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 |
|
|
@@ -55,8 +57,10 @@ Unit tests cover every source module individually. Each module has its own test
|
|
| 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 |
|
|
@@ -82,18 +86,8 @@ npm run test:coverage
|
|
| 82 |
| Metric | Coverage |
|
| 83 |
|-------------|----------|
|
| 84 |
| Statements | ~92% |
|
| 85 |
-
| Branches | ~
|
| 86 |
-
| Functions | ~
|
| 87 |
-
| Lines | ~
|
| 88 |
|
| 89 |
-
|
| 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.
|
|
|
|
| 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 |
+
sql-logger.test.js # SQL query logger wrapping tests (5 tests)
|
| 27 |
middleware/
|
| 28 |
rate-limiter.test.js # In-memory and Redis rate limiter paths (6 tests)
|
| 29 |
redis/
|
| 30 |
redis.test.js # RESP protocol encoding/parsing, constructor options (25 tests)
|
| 31 |
server/
|
| 32 |
coverage-printlog.test.js # Server ESM coverage via CJS cache injection (2 tests)
|
| 33 |
+
integration.test.js # API integration tests — real HTTP + SQLite (50 tests)
|
| 34 |
+
server.test.js # Server request handler and startup paths (5 tests)
|
| 35 |
helpers/
|
| 36 |
+
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
| 37 |
index.js # startServer / stopServer / request utilities
|
| 38 |
seed.js # Standalone script to create & seed temp DB
|
| 39 |
```
|
| 40 |
|
| 41 |
+
**Total: 111 tests across 10 test files.**
|
| 42 |
|
| 43 |
## Test design
|
| 44 |
|
| 45 |
+
### Integration tests (`tests/server/integration.test.js`)
|
| 46 |
|
| 47 |
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.
|
| 48 |
|
|
|
|
| 57 |
| `rate-limiter.js` | `tests/middleware/rate-limiter.test.js` | Module imported once; `createRateLimiter()` with different configs per test |
|
| 58 |
| `redis.js` | `tests/redis/redis.test.js` | RESP encoding/parsing directly; constructor options |
|
| 59 |
| `server.js` | `tests/server/coverage-printlog.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock |
|
| 60 |
+
| `server.js` | `tests/server/server.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock |
|
| 61 |
| `migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
|
| 62 |
| `seed.js` | `tests/db/seed.test.js` | Dependency injection — `database` and `fetch` injected |
|
| 63 |
+
| `sql-logger.js` | `tests/db/sql-logger.test.js`| Proxy wrapper behavior on exec/prepare/run/get/all |
|
| 64 |
|
| 65 |
### Key testing patterns
|
| 66 |
|
|
|
|
| 86 |
| Metric | Coverage |
|
| 87 |
|-------------|----------|
|
| 88 |
| Statements | ~92% |
|
| 89 |
+
| Branches | ~89% |
|
| 90 |
+
| Functions | ~93% |
|
| 91 |
+
| Lines | ~94% |
|
| 92 |
|
| 93 |
+
All source files reach moderate coverage. Low-coverage areas: `rate-limiter.js` and `redis.js` (Redis unavailable in test mode, falls back to in-memory); `migrate.js` and `seed.js` CLI paths run as child processes.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/db/sql-logger.test.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
| 2 |
+
|
| 3 |
+
describe('sql-logger.js', () => {
|
| 4 |
+
beforeEach(() => {
|
| 5 |
+
vi.resetModules()
|
| 6 |
+
})
|
| 7 |
+
|
| 8 |
+
it('returns non-special properties on wrapped stmt', async () => {
|
| 9 |
+
const { wrapStmt } = await import('../../src/sql-logger.js')
|
| 10 |
+
const stmt = { run: () => {}, customProp: 42 }
|
| 11 |
+
const wrapped = wrapStmt(stmt, 'SELECT 1')
|
| 12 |
+
expect(wrapped.customProp).toBe(42)
|
| 13 |
+
})
|
| 14 |
+
|
| 15 |
+
it('returns non-special properties on wrapped db', async () => {
|
| 16 |
+
const { wrapDb } = await import('../../src/sql-logger.js')
|
| 17 |
+
const db = { exec: () => {}, prepare: () => ({}), name: 'testdb' }
|
| 18 |
+
const wrapped = wrapDb(db)
|
| 19 |
+
expect(wrapped.name).toBe('testdb')
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
it('wraps exec and logs SQL', async () => {
|
| 23 |
+
const { wrapDb } = await import('../../src/sql-logger.js')
|
| 24 |
+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
| 25 |
+
const rawExec = vi.fn()
|
| 26 |
+
const db = { exec: rawExec, prepare: () => ({}) }
|
| 27 |
+
const wrapped = wrapDb(db)
|
| 28 |
+
wrapped.exec('SELECT 1')
|
| 29 |
+
expect(spy).toHaveBeenCalledWith('[SQL]', 'SELECT 1')
|
| 30 |
+
expect(rawExec).toHaveBeenCalledWith('SELECT 1')
|
| 31 |
+
spy.mockRestore()
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
it('wraps prepare and returns wrapped stmt', async () => {
|
| 35 |
+
const { wrapDb } = await import('../../src/sql-logger.js')
|
| 36 |
+
const rawRun = vi.fn()
|
| 37 |
+
const db = { exec: () => {}, prepare: () => ({ run: rawRun }) }
|
| 38 |
+
const wrapped = wrapDb(db)
|
| 39 |
+
const stmt = wrapped.prepare('INSERT INTO t VALUES (?)')
|
| 40 |
+
expect(typeof stmt.run).toBe('function')
|
| 41 |
+
})
|
| 42 |
+
|
| 43 |
+
it('wrapped stmt logs SQL on run/get/all', async () => {
|
| 44 |
+
const { wrapStmt } = await import('../../src/sql-logger.js')
|
| 45 |
+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
| 46 |
+
const rawRun = vi.fn()
|
| 47 |
+
const stmt = { run: rawRun }
|
| 48 |
+
const wrapped = wrapStmt(stmt, 'INSERT 1')
|
| 49 |
+
wrapped.run('a', 'b')
|
| 50 |
+
expect(spy).toHaveBeenCalledWith('[SQL]', 'INSERT 1', '["a","b"]')
|
| 51 |
+
wrapped.run()
|
| 52 |
+
expect(spy).toHaveBeenCalledWith('[SQL]', 'INSERT 1', '')
|
| 53 |
+
spy.mockRestore()
|
| 54 |
+
})
|
| 55 |
+
})
|
tests/helpers/index.js
CHANGED
|
@@ -26,6 +26,7 @@ export async function startServer() {
|
|
| 26 |
process.env.DB_PATH = dbPath;
|
| 27 |
process.env.START_SERVER = 'false';
|
| 28 |
process.env.REDIS_URL = '';
|
|
|
|
| 29 |
|
| 30 |
const serverModule = await import('../../src/server.js');
|
| 31 |
serverInstance = serverModule.server;
|
|
|
|
| 26 |
process.env.DB_PATH = dbPath;
|
| 27 |
process.env.START_SERVER = 'false';
|
| 28 |
process.env.REDIS_URL = '';
|
| 29 |
+
process.env.RATE_LIMIT_ENABLED = 'false';
|
| 30 |
|
| 31 |
const serverModule = await import('../../src/server.js');
|
| 32 |
serverInstance = serverModule.server;
|
tests/{server.test.js → server/integration.test.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
import { beforeAll, afterAll, describe, it, expect
|
| 2 |
-
import { startServer, stopServer, request } from './helpers';
|
| 3 |
|
| 4 |
beforeAll(async () => {
|
| 5 |
await startServer();
|
|
|
|
| 1 |
+
import { beforeAll, afterAll, describe, it, expect } from 'vitest';
|
| 2 |
+
import { startServer, stopServer, request } from '../helpers';
|
| 3 |
|
| 4 |
beforeAll(async () => {
|
| 5 |
await startServer();
|
tests/server/server.test.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-srv-'))
|
| 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('server.js', () => {
|
| 26 |
+
it('handles 500 when db throws', async () => {
|
| 27 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH')
|
| 28 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv1.db') })
|
| 29 |
+
const mockDb = {
|
| 30 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 31 |
+
getWrappedDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 32 |
+
listAll: () => { throw new Error('boom') },
|
| 33 |
+
getOne: () => null,
|
| 34 |
+
insertOne: () => { throw new Error('duplicate') },
|
| 35 |
+
updateOne: () => null,
|
| 36 |
+
deleteOne: () => null,
|
| 37 |
+
nextId: () => 1,
|
| 38 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos'],
|
| 39 |
+
}
|
| 40 |
+
clearCjs('../../src/server.js', '../../src/database.js', '../../src/rate-limiter.js')
|
| 41 |
+
const resolvedDb = _require.resolve('../../src/database.js')
|
| 42 |
+
_require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 43 |
+
try {
|
| 44 |
+
vi.resetModules()
|
| 45 |
+
const { requestHandler } = await import('../../src/server.js')
|
| 46 |
+
|
| 47 |
+
const mkReq = (url, method, body) => ({
|
| 48 |
+
url, method, headers: {}, socket: { remoteAddress: '::1' },
|
| 49 |
+
on: (evt, cb) => {
|
| 50 |
+
if (evt === 'data' && body) cb(body)
|
| 51 |
+
if (evt === 'end') queueMicrotask(() => cb())
|
| 52 |
+
},
|
| 53 |
+
})
|
| 54 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 55 |
+
|
| 56 |
+
const res1 = mkRes()
|
| 57 |
+
await requestHandler(mkReq('/api/users', 'GET'), res1)
|
| 58 |
+
expect(res1.writeHead).toHaveBeenCalledWith(500, expect.anything())
|
| 59 |
+
|
| 60 |
+
const res2 = mkRes()
|
| 61 |
+
await requestHandler(mkReq('/api/users', 'POST', '{"name":"X"}'), res2)
|
| 62 |
+
expect(res2.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 63 |
+
|
| 64 |
+
const res3 = mkRes()
|
| 65 |
+
await requestHandler(mkReq('/api/users/1', 'PUT', 'bad-json'), res3)
|
| 66 |
+
expect(res3.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 67 |
+
|
| 68 |
+
const res4 = mkRes()
|
| 69 |
+
await requestHandler(mkReq('/api/users/1', 'PATCH', 'bad-json'), res4)
|
| 70 |
+
expect(res4.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 71 |
+
|
| 72 |
+
const res5 = mkRes()
|
| 73 |
+
await requestHandler(mkReq('/api/users', 'POST', ''), res5)
|
| 74 |
+
expect(res5.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 75 |
+
} finally {
|
| 76 |
+
delete _require.cache[resolvedDb]
|
| 77 |
+
}
|
| 78 |
+
restore(s)
|
| 79 |
+
})
|
| 80 |
+
|
| 81 |
+
it('covers listen block', async () => {
|
| 82 |
+
const s = save('PORT', 'REDIS_URL')
|
| 83 |
+
setEnv({ PORT: '0', REDIS_URL: '' })
|
| 84 |
+
delete process.env.START_SERVER
|
| 85 |
+
vi.resetModules()
|
| 86 |
+
const mod = await import('../../src/server.js')
|
| 87 |
+
const onError = (err) => { throw err }
|
| 88 |
+
mod.server.on('error', onError)
|
| 89 |
+
await new Promise((resolve) => {
|
| 90 |
+
if (mod.server.listening) return resolve()
|
| 91 |
+
mod.server.on('listening', resolve)
|
| 92 |
+
})
|
| 93 |
+
expect(mod.server.listening).toBe(true)
|
| 94 |
+
await new Promise((r) => mod.server.close(r))
|
| 95 |
+
restore(s)
|
| 96 |
+
})
|
| 97 |
+
|
| 98 |
+
it('covers Redis in banner', async () => {
|
| 99 |
+
const s = save('START_SERVER', 'REDIS_URL', 'DB_PATH')
|
| 100 |
+
setEnv({ START_SERVER: 'false', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-redis-banner.db') })
|
| 101 |
+
|
| 102 |
+
const mockDb = {
|
| 103 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 104 |
+
getWrappedDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 105 |
+
listAll: () => [],
|
| 106 |
+
getOne: () => null,
|
| 107 |
+
insertOne: () => null,
|
| 108 |
+
updateOne: () => null,
|
| 109 |
+
deleteOne: () => null,
|
| 110 |
+
nextId: () => 1,
|
| 111 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos'],
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
const resolvedRedis = _require.resolve('../../src/redis.js')
|
| 115 |
+
const resolvedDb = _require.resolve('../../src/database.js')
|
| 116 |
+
|
| 117 |
+
const mockClient = {
|
| 118 |
+
connect: vi.fn().mockResolvedValue(),
|
| 119 |
+
ping: vi.fn().mockResolvedValue(),
|
| 120 |
+
connected: true,
|
| 121 |
+
quit: vi.fn().mockResolvedValue(),
|
| 122 |
+
send: vi.fn().mockResolvedValue(),
|
| 123 |
+
}
|
| 124 |
+
const mockRedisClass = function() { return mockClient }
|
| 125 |
+
|
| 126 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 127 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 128 |
+
_require.cache[resolvedRedis] = {
|
| 129 |
+
exports: mockRedisClass,
|
| 130 |
+
id: resolvedRedis, filename: resolvedRedis, loaded: true,
|
| 131 |
+
}
|
| 132 |
+
_require.cache[resolvedDb] = {
|
| 133 |
+
exports: mockDb,
|
| 134 |
+
id: resolvedDb, filename: resolvedDb, loaded: true,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
| 138 |
+
|
| 139 |
+
try {
|
| 140 |
+
clearCjs('../../src/server.js', '../../src/rate-limiter.js')
|
| 141 |
+
vi.resetModules()
|
| 142 |
+
const { printLog } = await import('../../src/server.js')
|
| 143 |
+
printLog()
|
| 144 |
+
expect(logSpy.mock.calls.some(c => String(c[0]).includes('Redis'))).toBe(true)
|
| 145 |
+
} finally {
|
| 146 |
+
logSpy.mockRestore()
|
| 147 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 148 |
+
else delete _require.cache[resolvedRedis]
|
| 149 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 150 |
+
else delete _require.cache[resolvedDb]
|
| 151 |
+
clearCjs('../../src/server.js', '../../src/rate-limiter.js')
|
| 152 |
+
}
|
| 153 |
+
restore(s)
|
| 154 |
+
})
|
| 155 |
+
|
| 156 |
+
it('covers Memory in banner', async () => {
|
| 157 |
+
const s = save('START_SERVER', 'REDIS_URL', 'REDIS_PORT')
|
| 158 |
+
setEnv({ START_SERVER: 'false', REDIS_URL: '', REDIS_PORT: '1' })
|
| 159 |
+
vi.resetModules()
|
| 160 |
+
const { printLog } = await import('../../src/server.js')
|
| 161 |
+
printLog()
|
| 162 |
+
restore(s)
|
| 163 |
+
})
|
| 164 |
+
|
| 165 |
+
it('covers Redis connected path in IIFE', async () => {
|
| 166 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH')
|
| 167 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-redis.db') })
|
| 168 |
+
|
| 169 |
+
const mockDb = {
|
| 170 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 171 |
+
getWrappedDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 172 |
+
listAll: () => [],
|
| 173 |
+
getOne: () => null,
|
| 174 |
+
insertOne: () => null,
|
| 175 |
+
updateOne: () => null,
|
| 176 |
+
deleteOne: () => null,
|
| 177 |
+
nextId: () => 1,
|
| 178 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos'],
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
const resolvedRedis = _require.resolve('../../src/redis.js')
|
| 182 |
+
const resolvedDb = _require.resolve('../../src/database.js')
|
| 183 |
+
|
| 184 |
+
const mockClient = {
|
| 185 |
+
connect: vi.fn().mockResolvedValue(),
|
| 186 |
+
ping: vi.fn().mockResolvedValue(),
|
| 187 |
+
connected: true,
|
| 188 |
+
quit: vi.fn().mockResolvedValue(),
|
| 189 |
+
send: vi.fn().mockResolvedValue(),
|
| 190 |
+
}
|
| 191 |
+
const mockRedisClass = function() { return mockClient }
|
| 192 |
+
|
| 193 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 194 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 195 |
+
_require.cache[resolvedRedis] = {
|
| 196 |
+
exports: mockRedisClass,
|
| 197 |
+
id: resolvedRedis, filename: resolvedRedis, loaded: true,
|
| 198 |
+
}
|
| 199 |
+
_require.cache[resolvedDb] = {
|
| 200 |
+
exports: mockDb,
|
| 201 |
+
id: resolvedDb, filename: resolvedDb, loaded: true,
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
| 205 |
+
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
| 206 |
+
|
| 207 |
+
try {
|
| 208 |
+
clearCjs('../../src/server.js', '../../src/rate-limiter.js')
|
| 209 |
+
vi.resetModules()
|
| 210 |
+
await import('../../src/server.js')
|
| 211 |
+
expect(logSpy).toHaveBeenCalledWith('[Redis] Connected ✓')
|
| 212 |
+
} finally {
|
| 213 |
+
logSpy.mockRestore()
|
| 214 |
+
warnSpy.mockRestore()
|
| 215 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 216 |
+
else delete _require.cache[resolvedRedis]
|
| 217 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 218 |
+
else delete _require.cache[resolvedDb]
|
| 219 |
+
clearCjs('../../src/server.js', '../../src/rate-limiter.js')
|
| 220 |
+
}
|
| 221 |
+
restore(s)
|
| 222 |
+
})
|
| 223 |
+
})
|
vitest.config.js
CHANGED
|
@@ -2,7 +2,6 @@ import { defineConfig } from 'vitest/config'
|
|
| 2 |
|
| 3 |
process.env.NODE_ENV = 'test';
|
| 4 |
process.env.PORT = '3199';
|
| 5 |
-
process.env.RATE_LIMIT_ENABLED = 'false';
|
| 6 |
|
| 7 |
export default defineConfig({
|
| 8 |
test: {
|
|
|
|
| 2 |
|
| 3 |
process.env.NODE_ENV = 'test';
|
| 4 |
process.env.PORT = '3199';
|
|
|
|
| 5 |
|
| 6 |
export default defineConfig({
|
| 7 |
test: {
|