BIT-15744: add remaining unit tests for admin-ui, api routes, collector-worker db, ingest-api services
Complete test coverage implementation for errors.bitreport.pt: admin-ui (98 tests): - test/components/: AppShell, DataAlert, IncidentNotes, KpiCard, SeverityBadge, StateBadge - test/lib/: format, demo-incidents, incidents-data, incidents-data-api, stats-data, stats-data-api - vitest.config.ts with jsdom + v8 coverage + @vitejs/plugin-react api route tests (54 tests): - src/routes/admin/auth.test.ts (15 tests) - src/routes/admin/incidents.test.ts (11 tests) - src/routes/admin/stats.test.ts (18 tests) - src/routes/public/errorMonitoringStats.test.ts (10 tests) collector-worker db/scheduler tests (22 tests): - src/db/collectorRunWriter.test.ts (10 tests) - src/db/loadActiveSources.test.ts (6 tests) - src/scheduler/runHttpSourceOnce.test.ts (6 tests) ingest-api service tests (13 tests): - src/buildApp.test.ts, plugins/prometheus.test.ts - services/ingestAuth.test.ts, services/processIngestBatch.utils.test.ts Total: 187 additional tests (255 total across all modules). All pass. Paperclip-Issue: BIT-15744 Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1 parent
989a92ba07
commit
3d4444eb21
33 files changed
+6374
-24
No files matched your search
Generated
+315
@@ -24,11 +24,83 @@
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "^20.14.0",
|
||||
"@vitest/coverage-v8": "^1.6.1",
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.4.5",
|
||||
"vitest": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@ampproject/remapping": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
|
||||
"integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@jridgewell/gen-mapping": "^0.3.5",
|
||||
"@jridgewell/trace-mapping": "^0.3.24"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/helper-string-parser": {
|
||||
"version": "7.27.1",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
|
||||
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/helper-validator-identifier": {
|
||||
"version": "7.28.5",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
|
||||
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/parser": {
|
||||
"version": "7.29.2",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
|
||||
"integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.0"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/types": {
|
||||
"version": "7.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
|
||||
"integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/helper-string-parser": "^7.27.1",
|
||||
"@babel/helper-validator-identifier": "^7.28.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@bcoe/v8-coverage": {
|
||||
"version": "0.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz",
|
||||
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.27.4",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
|
||||
@@ -629,6 +701,16 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@istanbuljs/schema": {
|
||||
"version": "0.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
|
||||
"integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/schemas": {
|
||||
"version": "29.6.3",
|
||||
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
|
||||
@@ -642,6 +724,27 @@
|
||||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.5.0",
|
||||
"@jridgewell/trace-mapping": "^0.3.24"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/resolve-uri": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
|
||||
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
"version": "1.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
|
||||
@@ -649,6 +752,17 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@jridgewell/trace-mapping": {
|
||||
"version": "0.3.31",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
|
||||
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/resolve-uri": "^3.1.0",
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@lukeed/ms": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
|
||||
@@ -1086,6 +1200,34 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/coverage-v8": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-1.6.1.tgz",
|
||||
"integrity": "sha512-6YeRZwuO4oTGKxD3bijok756oktHSIm3eczVVzNe3scqzuhLwltIF3S9ZL/vwOVIpURmU6SnZhziXXAfw8/Qlw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@ampproject/remapping": "^2.2.1",
|
||||
"@bcoe/v8-coverage": "^0.2.3",
|
||||
"debug": "^4.3.4",
|
||||
"istanbul-lib-coverage": "^3.2.2",
|
||||
"istanbul-lib-report": "^3.0.1",
|
||||
"istanbul-lib-source-maps": "^5.0.4",
|
||||
"istanbul-reports": "^3.1.6",
|
||||
"magic-string": "^0.30.5",
|
||||
"magicast": "^0.3.3",
|
||||
"picocolors": "^1.0.0",
|
||||
"std-env": "^3.5.0",
|
||||
"strip-literal": "^2.0.0",
|
||||
"test-exclude": "^6.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vitest": "1.6.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz",
|
||||
@@ -2091,6 +2233,16 @@
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/has-unicode": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
|
||||
@@ -2106,6 +2258,13 @@
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/html-escaper": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
|
||||
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
|
||||
@@ -2221,6 +2380,76 @@
|
||||
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/istanbul-lib-coverage": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
|
||||
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/istanbul-lib-report": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
|
||||
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"istanbul-lib-coverage": "^3.0.0",
|
||||
"make-dir": "^4.0.0",
|
||||
"supports-color": "^7.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/istanbul-lib-report/node_modules/make-dir": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
|
||||
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"semver": "^7.5.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/istanbul-lib-source-maps": {
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz",
|
||||
"integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@jridgewell/trace-mapping": "^0.3.23",
|
||||
"debug": "^4.1.1",
|
||||
"istanbul-lib-coverage": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/istanbul-reports": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
|
||||
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"html-escaper": "^2.0.0",
|
||||
"istanbul-lib-report": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/jackspeak": {
|
||||
"version": "3.4.3",
|
||||
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
|
||||
@@ -2350,6 +2579,18 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/magicast": {
|
||||
"version": "0.3.5",
|
||||
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz",
|
||||
"integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.25.4",
|
||||
"@babel/types": "^7.25.4",
|
||||
"source-map-js": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
||||
@@ -3450,6 +3691,19 @@
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/supports-color": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
||||
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-flag": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
|
||||
@@ -3486,6 +3740,67 @@
|
||||
"bintrees": "1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/test-exclude": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz",
|
||||
"integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@istanbuljs/schema": "^0.1.2",
|
||||
"glob": "^7.1.4",
|
||||
"minimatch": "^3.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/test-exclude/node_modules/brace-expansion": {
|
||||
"version": "1.1.14",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz",
|
||||
"integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0",
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/test-exclude/node_modules/glob": {
|
||||
"version": "7.2.3",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.1.1",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/test-exclude/node_modules/minimatch": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
|
||||
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/thread-stream": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
|
||||
|
||||
+1
-1
@@ -30,9 +30,9 @@
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "^20.14.0",
|
||||
"@vitest/coverage-v8": "^1.6.1",
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.4.5",
|
||||
"@vitest/coverage-v8": "^1.6.0",
|
||||
"vitest": "^1.6.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* Tests for admin auth routes.
|
||||
* Exercises login, refresh, logout, and /me without a live database.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import cookie from '@fastify/cookie';
|
||||
import jwt from '@fastify/jwt';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import adminAuthRoutes from './auth.js';
|
||||
|
||||
vi.mock('bcrypt', () => ({
|
||||
default: {
|
||||
compare: vi.fn().mockResolvedValue(false),
|
||||
hash: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../plugins/audit.js', () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import bcrypt from 'bcrypt';
|
||||
const mockBcrypt = vi.mocked(bcrypt);
|
||||
|
||||
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
|
||||
return {
|
||||
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
|
||||
getConnection: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(cookie, { secret: 'test-cookie-secret' });
|
||||
await app.register(jwt, {
|
||||
secret: 'test-jwt-secret',
|
||||
cookie: { cookieName: '__Host-access', signed: false },
|
||||
});
|
||||
|
||||
const p = pool ?? makePool();
|
||||
app.decorate('db', p as unknown as FastifyInstance['db']);
|
||||
app.decorate('rateLimits', {
|
||||
login: { max: 10, timeWindow: 300_000 },
|
||||
ingest: { max: 1000, timeWindow: 60_000 },
|
||||
global: { max: 500, timeWindow: 60_000 },
|
||||
mutation: { max: 100, timeWindow: 60_000 },
|
||||
});
|
||||
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
|
||||
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
|
||||
});
|
||||
|
||||
await app.register(adminAuthRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('POST /admin/auth/login', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(mockBcrypt.compare).mockResolvedValue(false as never);
|
||||
});
|
||||
|
||||
it('returns 400 for missing email field', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/login',
|
||||
payload: { password: 'secret' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('returns 400 for invalid email format', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/login',
|
||||
payload: { email: 'not-an-email', password: 'secret' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('returns 401 when user not found', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/login',
|
||||
payload: { email: '[email protected]', password: 'pass' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json()).toMatchObject({ error: 'Invalid credentials' });
|
||||
});
|
||||
|
||||
it('returns 401 when password is wrong', async () => {
|
||||
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 1 }];
|
||||
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
|
||||
vi.mocked(mockBcrypt.compare).mockResolvedValue(false as never);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/login',
|
||||
payload: { email: '[email protected]', password: 'wrongpass' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 401 when user is inactive', async () => {
|
||||
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 0 }];
|
||||
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
|
||||
vi.mocked(mockBcrypt.compare).mockResolvedValue(true as never);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/login',
|
||||
payload: { email: '[email protected]', password: 'pass' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 200 with user info on successful login', async () => {
|
||||
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 1 }];
|
||||
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
|
||||
vi.mocked(mockBcrypt.compare).mockResolvedValue(true as never);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/login',
|
||||
payload: { email: '[email protected]', password: 'correct' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ user: { id: 'u1', email: '[email protected]', role: 'admin' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /admin/auth/refresh', () => {
|
||||
it('returns 401 when no refresh token cookie present', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'POST', url: '/admin/auth/refresh' });
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json()).toMatchObject({ error: 'No refresh token' });
|
||||
});
|
||||
|
||||
it('returns 401 when token hash not found in db', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/refresh',
|
||||
headers: { cookie: '__Host-refresh=sometoken' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json()).toMatchObject({ error: 'Refresh token invalid or expired' });
|
||||
});
|
||||
|
||||
it('returns 401 when token is revoked', async () => {
|
||||
const tokenRow = [{
|
||||
id: 't1',
|
||||
user_id: 'u1',
|
||||
expires_at: new Date(Date.now() + 1_000_000),
|
||||
revoked_at: new Date(),
|
||||
}];
|
||||
const pool = makePool(vi.fn().mockResolvedValue([tokenRow as unknown as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/refresh',
|
||||
headers: { cookie: '__Host-refresh=sometoken' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 401 when token is expired', async () => {
|
||||
const tokenRow = [{
|
||||
id: 't1',
|
||||
user_id: 'u1',
|
||||
expires_at: new Date(Date.now() - 1_000),
|
||||
revoked_at: null,
|
||||
}];
|
||||
const pool = makePool(vi.fn().mockResolvedValue([tokenRow as unknown as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/refresh',
|
||||
headers: { cookie: '__Host-refresh=sometoken' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 401 when user no longer active after valid token', async () => {
|
||||
const tokenRow = [{ id: 't1', user_id: 'u1', expires_at: new Date(Date.now() + 1_000_000), revoked_at: null }];
|
||||
const user: RowDataPacket[] = [];
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([tokenRow])
|
||||
.mockResolvedValueOnce([[]])
|
||||
.mockResolvedValue([user]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/refresh',
|
||||
headers: { cookie: '__Host-refresh=sometoken' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json()).toMatchObject({ error: 'User no longer active' });
|
||||
});
|
||||
|
||||
it('returns 200 with ok:true on valid refresh', async () => {
|
||||
const tokenRow = [{ id: 't1', user_id: 'u1', expires_at: new Date(Date.now() + 1_000_000), revoked_at: null }];
|
||||
const userRow = [{ id: 'u1', email: '[email protected]', role: 'admin', is_active: 1 }];
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([tokenRow])
|
||||
.mockResolvedValueOnce([[]])
|
||||
.mockResolvedValueOnce([userRow])
|
||||
.mockResolvedValue([[]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/refresh',
|
||||
headers: { cookie: '__Host-refresh=sometoken' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /admin/auth/logout', () => {
|
||||
it('returns 200 and clears cookies', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/auth/logout',
|
||||
headers: { cookie: '__Host-refresh=sometoken' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('returns 200 even without refresh cookie', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'POST', url: '/admin/auth/logout' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /admin/auth/me', () => {
|
||||
it('returns current user info from auth context', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/admin/auth/me' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({
|
||||
user: { id: 'u1', email: '[email protected]', role: 'admin' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Tests for admin incident routes.
|
||||
* Uses mock DB and bypassed auth decorators — no live database required.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import adminIncidentsRoutes from './incidents.js';
|
||||
|
||||
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
|
||||
return {
|
||||
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
|
||||
getConnection: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: false });
|
||||
const p = pool ?? makePool();
|
||||
app.decorate('db', p as unknown as FastifyInstance['db']);
|
||||
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
|
||||
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
|
||||
});
|
||||
app.decorate('requirePermission', (_perm: string) => async (_req: unknown, _reply: unknown) => {
|
||||
// passthrough — permission already granted by mock authenticate
|
||||
});
|
||||
await app.register(adminIncidentsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
const baseIncident = {
|
||||
id: '42',
|
||||
projectSlug: 'wdmi-store',
|
||||
fingerprint: 'abc123',
|
||||
title: 'Test error',
|
||||
severity: 'high',
|
||||
currentState: 'open',
|
||||
firstSeenAt: '2026-01-01T00:00:00.000Z',
|
||||
lastSeenAt: '2026-01-02T00:00:00.000Z',
|
||||
occurrencesCount: 5,
|
||||
};
|
||||
|
||||
describe('GET /v1/incidents', () => {
|
||||
it('returns empty list when no incidents', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ incidents: [] });
|
||||
});
|
||||
|
||||
it('returns mapped incident list', async () => {
|
||||
const row = {
|
||||
id: '42',
|
||||
projectSlug: 'wdmi-store',
|
||||
fingerprint: 'abc123',
|
||||
title: 'Test error',
|
||||
severity: 'high',
|
||||
currentState: 'open',
|
||||
firstSeenAt: '2026-01-01T00:00:00.000Z',
|
||||
lastSeenAt: '2026-01-02T00:00:00.000Z',
|
||||
occurrencesCount: 5,
|
||||
};
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[row as unknown as RowDataPacket]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { incidents: typeof baseIncident[] };
|
||||
expect(body.incidents).toHaveLength(1);
|
||||
expect(body.incidents[0]).toMatchObject({ id: '42', severity: 'high', currentState: 'open' });
|
||||
});
|
||||
|
||||
it('accepts valid state filter', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents?state=resolved' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts valid severity filter', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents?severity=critical' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts project slug filter', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents?project=myproject' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts search query filter', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents?q=TypeError' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts combined filters', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents?state=open&severity=high&project=proj&q=crash' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ incidents: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /v1/incidents/:id', () => {
|
||||
it('returns 404 for non-numeric id', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents/abc-not-numeric' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('returns 404 when incident not found in db', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents/9999' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('returns incident with occurrences on found', async () => {
|
||||
const incidentRow = {
|
||||
id: '42',
|
||||
projectSlug: 'wdmi-store',
|
||||
fingerprint: 'abc123',
|
||||
title: 'Test error',
|
||||
severity: 'high',
|
||||
currentState: 'open',
|
||||
firstSeenAt: '2026-01-01T00:00:00.000Z',
|
||||
lastSeenAt: '2026-01-02T00:00:00.000Z',
|
||||
occurrencesCount: 1,
|
||||
metadataJson: null,
|
||||
ingestKeyLabel: 'prod-key',
|
||||
};
|
||||
const occurrenceRow = {
|
||||
id: '1',
|
||||
occurredAt: '2026-01-01T00:00:00.000Z',
|
||||
levelRaw: 'error',
|
||||
severity: 'high',
|
||||
message: 'Something failed',
|
||||
stacktrace: null,
|
||||
contextJson: '{"env":"production"}',
|
||||
};
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([[incidentRow as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[occurrenceRow as unknown as RowDataPacket]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents/42' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { incident: { id: string; occurrences: unknown[] } };
|
||||
expect(body.incident.id).toBe('42');
|
||||
expect(body.incident.occurrences).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('handles occurrence with null stacktrace and contextJson', async () => {
|
||||
const incidentRow = {
|
||||
id: '1',
|
||||
projectSlug: 'proj',
|
||||
fingerprint: 'fp',
|
||||
title: 'err',
|
||||
severity: 'low',
|
||||
currentState: 'open',
|
||||
firstSeenAt: '2026-01-01T00:00:00.000Z',
|
||||
lastSeenAt: '2026-01-01T00:00:00.000Z',
|
||||
occurrencesCount: 1,
|
||||
metadataJson: '{"key":"val"}',
|
||||
ingestKeyLabel: null,
|
||||
};
|
||||
const occurrenceRow = {
|
||||
id: '2',
|
||||
occurredAt: '2026-01-01T00:00:00.000Z',
|
||||
levelRaw: 'warn',
|
||||
severity: 'low',
|
||||
message: 'warn',
|
||||
stacktrace: null,
|
||||
contextJson: null,
|
||||
};
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([[incidentRow as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[occurrenceRow as unknown as RowDataPacket]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/incidents/1' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { incident: { metadataJson: unknown; ingestKeyLabel: unknown } };
|
||||
expect(body.incident.metadataJson).toMatchObject({ key: 'val' });
|
||||
expect(body.incident.ingestKeyLabel).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Tests for admin stats routes.
|
||||
* Uses mock DB and bypassed auth decorators — no live database required.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import adminStatsRoutes from './stats.js';
|
||||
|
||||
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
|
||||
return {
|
||||
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
|
||||
getConnection: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: false });
|
||||
const p = pool ?? makePool();
|
||||
app.decorate('db', p as unknown as FastifyInstance['db']);
|
||||
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
|
||||
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
|
||||
});
|
||||
app.decorate('requirePermission', (_perm: string) => async (_req: unknown, _reply: unknown) => {
|
||||
// passthrough
|
||||
});
|
||||
await app.register(adminStatsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('GET /v1/stats/trend', () => {
|
||||
it('returns day granularity by default with empty series', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { granularity: string; dates: string[]; series: Record<string, number[]> };
|
||||
expect(body.granularity).toBe('day');
|
||||
expect(Array.isArray(body.dates)).toBe(true);
|
||||
expect(body.dates.length).toBeGreaterThan(0);
|
||||
expect(body.series).toHaveProperty('critical');
|
||||
expect(body.series).toHaveProperty('high');
|
||||
expect(body.series).toHaveProperty('low');
|
||||
expect(body.series).toHaveProperty('info');
|
||||
});
|
||||
|
||||
it('returns hour granularity when requested', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&hours=5' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { granularity: string; hours: string[] };
|
||||
expect(body.granularity).toBe('hour');
|
||||
expect(body.hours).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('returns 404 when project slug not found for day granularity', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?project=nonexistent' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('returns 404 when project slug not found for hour granularity', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&project=nonexistent' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('maps DB aggregate rows into series data for day granularity', async () => {
|
||||
const today = new Date();
|
||||
const dateStr = today.toISOString().slice(0, 10);
|
||||
const aggRow = { d: dateStr, severity: 'critical', c: 7 };
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=3' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { series: Record<string, number[]> };
|
||||
const criticalSeries = body.series['critical'] ?? [];
|
||||
expect(criticalSeries.some((v) => v === 7)).toBe(true);
|
||||
});
|
||||
|
||||
it('maps DB aggregate rows into series data for hour granularity', async () => {
|
||||
const now = new Date();
|
||||
now.setUTCMinutes(0, 0, 0);
|
||||
now.setUTCMilliseconds(0);
|
||||
const y = now.getUTCFullYear();
|
||||
const mo = String(now.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getUTCDate()).padStart(2, '0');
|
||||
const h = String(now.getUTCHours()).padStart(2, '0');
|
||||
const bucketLabel = `${y}-${mo}-${day} ${h}:00:00`;
|
||||
const aggRow = { b: bucketLabel, severity: 'high', c: 3 };
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&hours=3' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { series: Record<string, number[]> };
|
||||
expect(body.series['high']?.some((v) => v === 3)).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores unknown severity in aggregate rows', async () => {
|
||||
const aggRow = { d: new Date().toISOString().slice(0, 10), severity: 'unknown-severity', c: 10 };
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=1' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { series: Record<string, number[]> };
|
||||
expect(body.series['critical']?.every((v) => v === 0)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts days parameter for day granularity', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=7' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { dates: string[] };
|
||||
expect(body.dates).toHaveLength(7);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /v1/stats/summary', () => {
|
||||
const defaultExecute = vi.fn()
|
||||
.mockResolvedValueOnce([[{ slug: 'proj', total_incidents: 5, open_cnt: 2, investigating_cnt: 0, resolved_cnt: 3, ignored_cnt: 0, critical_cnt: 1 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValueOnce([[{ severity: 'critical', c: 1 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValueOnce([[{ c: 2 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[{ c: 10 } as unknown as RowDataPacket]]);
|
||||
|
||||
it('returns byProject, bySeverity, resolvedLast24h, totalLast24h', async () => {
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([[{ slug: 'proj', total_incidents: 5, open_cnt: 2, investigating_cnt: 0, resolved_cnt: 3, ignored_cnt: 0, critical_cnt: 1 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValueOnce([[{ severity: 'high', c: 4 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValueOnce([[{ c: 2 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[{ c: 10 } as unknown as RowDataPacket]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { byProject: unknown[]; bySeverity: Record<string, number>; resolvedLast24h: number; totalLast24h: number };
|
||||
expect(body.byProject).toHaveLength(1);
|
||||
expect(body.bySeverity.high).toBe(4);
|
||||
expect(body.resolvedLast24h).toBe(2);
|
||||
expect(body.totalLast24h).toBe(10);
|
||||
});
|
||||
|
||||
it('returns 404 when project slug not found', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary?project=nonexistent' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('handles empty results gracefully', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[] as RowDataPacket[]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { byProject: unknown[]; bySeverity: Record<string, number>; resolvedLast24h: number; totalLast24h: number };
|
||||
expect(body.byProject).toHaveLength(0);
|
||||
expect(body.resolvedLast24h).toBe(0);
|
||||
expect(body.totalLast24h).toBe(0);
|
||||
});
|
||||
|
||||
it('skips unknown severity values from summary rows', async () => {
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([[]])
|
||||
.mockResolvedValueOnce([[{ severity: 'badvalue', c: 99 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValueOnce([[{ c: 0 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[{ c: 0 } as unknown as RowDataPacket]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { bySeverity: Record<string, number> };
|
||||
expect(body.bySeverity.critical).toBe(0);
|
||||
});
|
||||
|
||||
it('accepts valid project filter when project exists', async () => {
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([[{ ok: 1 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValueOnce([[]])
|
||||
.mockResolvedValueOnce([[]])
|
||||
.mockResolvedValueOnce([[{ c: 0 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[{ c: 0 } as unknown as RowDataPacket]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary?project=myproject' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /v1/stats/recurrence', () => {
|
||||
it('returns empty top list when no occurrences', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { top: unknown[]; windowDays: number };
|
||||
expect(body.top).toHaveLength(0);
|
||||
expect(body.windowDays).toBe(7);
|
||||
});
|
||||
|
||||
it('maps top incidents correctly', async () => {
|
||||
const row = {
|
||||
id: '1',
|
||||
project_slug: 'proj',
|
||||
fingerprint: 'fp1',
|
||||
title: 'Crash in module',
|
||||
severity: 'critical',
|
||||
current_state: 'open',
|
||||
hits_in_window: 42,
|
||||
lifetime_occurrences: 100,
|
||||
};
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[row as unknown as RowDataPacket]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?days=14&limit=5' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { top: Array<{ hitsInWindow: number; lifetimeOccurrences: number }> };
|
||||
expect(body.top[0]?.hitsInWindow).toBe(42);
|
||||
expect(body.top[0]?.lifetimeOccurrences).toBe(100);
|
||||
});
|
||||
|
||||
it('returns 404 when project slug not found', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?project=nonexistent' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('accepts valid project when it exists', async () => {
|
||||
const execute = vi.fn()
|
||||
.mockResolvedValueOnce([[{ ok: 1 } as unknown as RowDataPacket]])
|
||||
.mockResolvedValue([[] as RowDataPacket[]]);
|
||||
const pool = makePool(execute);
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?project=validproject' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('uses default days=7 and limit=15 when not specified', async () => {
|
||||
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { windowDays: number };
|
||||
expect(body.windowDays).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* Tests for GET /api/error-monitoring/stats
|
||||
* Uses the same in-process Fastify injection pattern as other route tests.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import errorMonitoringStatsRoutes from './errorMonitoringStats.js';
|
||||
|
||||
vi.mock('../../plugins/prometheus.js', () => ({
|
||||
metricsGauges: {
|
||||
occurrences24hGauge: { set: vi.fn() },
|
||||
resolved24hGauge: { set: vi.fn() },
|
||||
incidentsBySeverityGauge: { labels: vi.fn().mockReturnValue({ set: vi.fn() }) },
|
||||
incidentsTotalGauge: { labels: vi.fn().mockReturnValue({ set: vi.fn() }) },
|
||||
projectIncidentsGauge: {
|
||||
reset: vi.fn(),
|
||||
labels: vi.fn().mockReturnValue({ set: vi.fn() }),
|
||||
},
|
||||
projectResolutionRateGauge: {
|
||||
reset: vi.fn(),
|
||||
labels: vi.fn().mockReturnValue({ set: vi.fn() }),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
function makeExecute(responses: unknown[][]) {
|
||||
let call = 0;
|
||||
return vi.fn().mockImplementation(() => Promise.resolve([responses[call++] ?? []]));
|
||||
}
|
||||
|
||||
async function buildApp(execute: ReturnType<typeof vi.fn>): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: false });
|
||||
app.decorate('db', { execute } as unknown as FastifyInstance['db']);
|
||||
await app.register(errorMonitoringStatsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
const PREV_KEY = process.env.ERROR_RESOLVE_API_KEY;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.ERROR_RESOLVE_API_KEY = 'test-stats-key';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (PREV_KEY === undefined) {
|
||||
delete process.env.ERROR_RESOLVE_API_KEY;
|
||||
} else {
|
||||
process.env.ERROR_RESOLVE_API_KEY = PREV_KEY;
|
||||
}
|
||||
});
|
||||
|
||||
describe('GET /api/error-monitoring/stats', () => {
|
||||
function makeDefaultExecute() {
|
||||
return makeExecute([
|
||||
// sevRows
|
||||
[
|
||||
{ severity: 'critical', c: 5 } as RowDataPacket,
|
||||
{ severity: 'high', c: 10 } as RowDataPacket,
|
||||
{ severity: 'unknown_sev', c: 1 } as RowDataPacket,
|
||||
],
|
||||
// stateRows
|
||||
[
|
||||
{ state: 'open', c: 8 } as RowDataPacket,
|
||||
{ state: 'resolved', c: 7 } as RowDataPacket,
|
||||
],
|
||||
// vol24h
|
||||
[{ c: 42 } as RowDataPacket],
|
||||
// res24h
|
||||
[{ c: 3 } as RowDataPacket],
|
||||
// hourlyRows
|
||||
[
|
||||
{ hour_bucket: '2026-01-01 00:00:00', severity: 'high', cnt: 2 } as RowDataPacket,
|
||||
{ hour_bucket: '2026-01-01 00:00:00', severity: 'bad_sev', cnt: 1 } as RowDataPacket,
|
||||
],
|
||||
// projRows
|
||||
[
|
||||
{
|
||||
slug: 'wdmi',
|
||||
total: 10,
|
||||
open_cnt: 3,
|
||||
investigating_cnt: 2,
|
||||
resolved_cnt: 4,
|
||||
ignored_cnt: 1,
|
||||
critical_cnt: 2,
|
||||
} as RowDataPacket,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
it('returns 401 without a valid api_key', async () => {
|
||||
const execute = makeExecute([]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({ method: 'GET', url: '/api/error-monitoring/stats' });
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 200 with api_key query param', async () => {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('returns correct bySeverity counts', async () => {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
const body = res.json<{ bySeverity: Record<string, number> }>();
|
||||
expect(body.bySeverity.critical).toBe(5);
|
||||
expect(body.bySeverity.high).toBe(10);
|
||||
expect(body.bySeverity.medium).toBe(0);
|
||||
expect(body.bySeverity.low).toBe(0);
|
||||
expect(body.bySeverity.info).toBe(0);
|
||||
});
|
||||
|
||||
it('returns correct byState counts', async () => {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
const body = res.json<{ byState: Record<string, number> }>();
|
||||
expect(body.byState.open).toBe(8);
|
||||
expect(body.byState.resolved).toBe(7);
|
||||
});
|
||||
|
||||
it('returns correct 24h ingestion volume', async () => {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
const body = res.json<{ ingestion: { last24h: number; resolvedLast24h: number } }>();
|
||||
expect(body.ingestion.last24h).toBe(42);
|
||||
expect(body.ingestion.resolvedLast24h).toBe(3);
|
||||
});
|
||||
|
||||
it('returns 24-entry hourlyTrend array (zero-filled)', async () => {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
const body = res.json<{ ingestion: { hourlyTrend: unknown[] } }>();
|
||||
expect(body.ingestion.hourlyTrend).toHaveLength(24);
|
||||
});
|
||||
|
||||
it('returns correct per-project metrics with resolutionRate', async () => {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
const body = res.json<{
|
||||
projects: Array<{ slug: string; total: number; resolved: number; resolutionRate: number }>;
|
||||
}>();
|
||||
expect(body.projects).toHaveLength(1);
|
||||
const proj = body.projects[0];
|
||||
expect(proj.slug).toBe('wdmi');
|
||||
expect(proj.total).toBe(10);
|
||||
expect(proj.resolved).toBe(4);
|
||||
expect(proj.resolutionRate).toBe(0.4);
|
||||
});
|
||||
|
||||
it('returns resolutionRate of 0 when total is 0', async () => {
|
||||
const execute = makeExecute([
|
||||
[],
|
||||
[],
|
||||
[{ c: 0 } as RowDataPacket],
|
||||
[{ c: 0 } as RowDataPacket],
|
||||
[],
|
||||
[
|
||||
{
|
||||
slug: 'empty-proj',
|
||||
total: 0,
|
||||
open_cnt: 0,
|
||||
investigating_cnt: 0,
|
||||
resolved_cnt: 0,
|
||||
ignored_cnt: 0,
|
||||
critical_cnt: 0,
|
||||
} as RowDataPacket,
|
||||
],
|
||||
]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=test-stats-key',
|
||||
});
|
||||
const body = res.json<{ projects: Array<{ resolutionRate: number }> }>();
|
||||
expect(body.projects[0].resolutionRate).toBe(0);
|
||||
});
|
||||
|
||||
it('returns 401 with wrong api_key', async () => {
|
||||
const execute = makeExecute([]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?api_key=wrong-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('accepts view_errors query param when DEBUG_VIEW_ERRORS_KEY is set', async () => {
|
||||
const prevViewKey = process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
process.env.DEBUG_VIEW_ERRORS_KEY = 'view-only-key';
|
||||
try {
|
||||
const execute = makeDefaultExecute();
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/stats?view_errors=view-only-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
} finally {
|
||||
if (prevViewKey === undefined) delete process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
else process.env.DEBUG_VIEW_ERRORS_KEY = prevViewKey;
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user