@terreno/test 0.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bunfig.toml +3 -0
- package/dist/cache/mongoTestCache.d.ts +16 -0
- package/dist/cache/mongoTestCache.js +541 -0
- package/dist/env/setTerrenoTestEnv.d.ts +13 -0
- package/dist/env/setTerrenoTestEnv.js +89 -0
- package/dist/http/authAsUser.d.ts +17 -0
- package/dist/http/authAsUser.js +165 -0
- package/dist/http/authAsUser.test.d.ts +1 -0
- package/dist/http/authAsUser.test.js +93 -0
- package/dist/http/getBaseServer.d.ts +9 -0
- package/dist/http/getBaseServer.js +33 -0
- package/dist/http/getBaseServer.test.d.ts +1 -0
- package/dist/http/getBaseServer.test.js +76 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +46 -0
- package/dist/logging/setupEnvironment.d.ts +2 -0
- package/dist/logging/setupEnvironment.js +19 -0
- package/dist/logging/silenceLogs.d.ts +20 -0
- package/dist/logging/silenceLogs.js +168 -0
- package/dist/logging/testLogger.d.ts +7 -0
- package/dist/logging/testLogger.js +22 -0
- package/dist/mocks/sentryBun.d.ts +2 -0
- package/dist/mocks/sentryBun.js +136 -0
- package/dist/mongo/connection.d.ts +16 -0
- package/dist/mongo/connection.js +134 -0
- package/dist/mongo/connection.test.d.ts +1 -0
- package/dist/mongo/connection.test.js +28 -0
- package/dist/mongo/ensureMongoBinary.d.ts +6 -0
- package/dist/mongo/ensureMongoBinary.js +104 -0
- package/dist/mongo/mongoServer.d.ts +26 -0
- package/dist/mongo/mongoServer.js +424 -0
- package/dist/preload/defaultBackendPreload.d.ts +1 -0
- package/dist/preload/defaultBackendPreload.js +8 -0
- package/dist/preload/memoryMongo.d.ts +0 -0
- package/dist/preload/memoryMongo.js +2 -0
- package/dist/preload/registerBackendPreload.d.ts +33 -0
- package/dist/preload/registerBackendPreload.js +302 -0
- package/dist/transaction/testTransaction.d.ts +91 -0
- package/dist/transaction/testTransaction.js +719 -0
- package/dist/utils/ensureAllIndexes.d.ts +2 -0
- package/dist/utils/ensureAllIndexes.js +84 -0
- package/dist/utils/timeout.d.ts +1 -0
- package/dist/utils/timeout.js +45 -0
- package/dist/utils/waitForDocuments.d.ts +13 -0
- package/dist/utils/waitForDocuments.js +127 -0
- package/package.json +65 -0
- package/src/cache/mongoTestCache.ts +311 -0
- package/src/env/setTerrenoTestEnv.ts +50 -0
- package/src/http/authAsUser.test.ts +40 -0
- package/src/http/authAsUser.ts +59 -0
- package/src/http/getBaseServer.test.ts +30 -0
- package/src/http/getBaseServer.ts +34 -0
- package/src/index.ts +53 -0
- package/src/logging/setupEnvironment.ts +15 -0
- package/src/logging/silenceLogs.ts +134 -0
- package/src/logging/testLogger.ts +19 -0
- package/src/mocks/sentryBun.ts +140 -0
- package/src/mongo/connection.test.ts +30 -0
- package/src/mongo/connection.ts +65 -0
- package/src/mongo/ensureMongoBinary.ts +25 -0
- package/src/mongo/mongoServer.ts +214 -0
- package/src/preload/defaultBackendPreload.ts +7 -0
- package/src/preload/memoryMongo.ts +1 -0
- package/src/preload/registerBackendPreload.ts +174 -0
- package/src/transaction/testTransaction.ts +524 -0
- package/src/utils/ensureAllIndexes.ts +11 -0
- package/src/utils/timeout.ts +3 -0
- package/src/utils/waitForDocuments.ts +50 -0
- package/tsconfig.json +31 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
12
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
13
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
14
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
15
|
+
function step(op) {
|
|
16
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
17
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
18
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
19
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
20
|
+
switch (op[0]) {
|
|
21
|
+
case 0: case 1: t = op; break;
|
|
22
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
23
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
24
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
25
|
+
default:
|
|
26
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
27
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
28
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
29
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
30
|
+
if (t[2]) _.ops.pop();
|
|
31
|
+
_.trys.pop(); continue;
|
|
32
|
+
}
|
|
33
|
+
op = body.call(thisArg, _);
|
|
34
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
35
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var __values = (this && this.__values) || function(o) {
|
|
39
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
40
|
+
if (m) return m.call(o);
|
|
41
|
+
if (o && typeof o.length === "number") return {
|
|
42
|
+
next: function () {
|
|
43
|
+
if (o && i >= o.length) o = void 0;
|
|
44
|
+
return { value: o && o[i++], done: !o };
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
48
|
+
};
|
|
49
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
50
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
51
|
+
};
|
|
52
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
53
|
+
exports.ensureAllIndexes = void 0;
|
|
54
|
+
var mongoose_1 = __importDefault(require("mongoose"));
|
|
55
|
+
/** Ensures all registered Mongoose model indexes exist on the database. */
|
|
56
|
+
var ensureAllIndexes = function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
57
|
+
var models, indexPromises, models_1, models_1_1, modelName;
|
|
58
|
+
var e_1, _a;
|
|
59
|
+
return __generator(this, function (_b) {
|
|
60
|
+
switch (_b.label) {
|
|
61
|
+
case 0:
|
|
62
|
+
models = Object.keys(mongoose_1.default.models);
|
|
63
|
+
indexPromises = [];
|
|
64
|
+
try {
|
|
65
|
+
for (models_1 = __values(models), models_1_1 = models_1.next(); !models_1_1.done; models_1_1 = models_1.next()) {
|
|
66
|
+
modelName = models_1_1.value;
|
|
67
|
+
indexPromises.push(mongoose_1.default.models[modelName].createIndexes());
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
71
|
+
finally {
|
|
72
|
+
try {
|
|
73
|
+
if (models_1_1 && !models_1_1.done && (_a = models_1.return)) _a.call(models_1);
|
|
74
|
+
}
|
|
75
|
+
finally { if (e_1) throw e_1.error; }
|
|
76
|
+
}
|
|
77
|
+
return [4 /*yield*/, Promise.all(indexPromises)];
|
|
78
|
+
case 1:
|
|
79
|
+
_b.sent();
|
|
80
|
+
return [2 /*return*/];
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}); };
|
|
84
|
+
exports.ensureAllIndexes = ensureAllIndexes;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const timeout: (ms: number) => Promise<NodeJS.Timeout>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
12
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
13
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
14
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
15
|
+
function step(op) {
|
|
16
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
17
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
18
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
19
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
20
|
+
switch (op[0]) {
|
|
21
|
+
case 0: case 1: t = op; break;
|
|
22
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
23
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
24
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
25
|
+
default:
|
|
26
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
27
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
28
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
29
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
30
|
+
if (t[2]) _.ops.pop();
|
|
31
|
+
_.trys.pop(); continue;
|
|
32
|
+
}
|
|
33
|
+
op = body.call(thisArg, _);
|
|
34
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
35
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.timeout = void 0;
|
|
40
|
+
var timeout = function (ms) { return __awaiter(void 0, void 0, void 0, function () {
|
|
41
|
+
return __generator(this, function (_a) {
|
|
42
|
+
return [2 /*return*/, new Promise(function (resolve) { return setTimeout(resolve, ms); })];
|
|
43
|
+
});
|
|
44
|
+
}); };
|
|
45
|
+
exports.timeout = timeout;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { FilterQuery, Model } from "mongoose";
|
|
2
|
+
export interface WaitForDocumentsOptions {
|
|
3
|
+
timeoutMs?: number;
|
|
4
|
+
intervalMs?: number;
|
|
5
|
+
sort?: Record<string, 1 | -1>;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Polls until at least `count` documents match the query.
|
|
9
|
+
* Useful when writes are asynchronous (audit logs, webhooks, etc.).
|
|
10
|
+
*/
|
|
11
|
+
export declare const waitForDocuments: <T>(model: Model<T>, query: FilterQuery<T>, count?: number, { timeoutMs, intervalMs, sort, }?: WaitForDocumentsOptions) => Promise<T[]>;
|
|
12
|
+
/** Polls until a single document matches the query. */
|
|
13
|
+
export declare const waitForDocument: <T>(model: Model<T>, query: FilterQuery<T>, options?: WaitForDocumentsOptions) => Promise<T>;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
12
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
13
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
14
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
15
|
+
function step(op) {
|
|
16
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
17
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
18
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
19
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
20
|
+
switch (op[0]) {
|
|
21
|
+
case 0: case 1: t = op; break;
|
|
22
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
23
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
24
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
25
|
+
default:
|
|
26
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
27
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
28
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
29
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
30
|
+
if (t[2]) _.ops.pop();
|
|
31
|
+
_.trys.pop(); continue;
|
|
32
|
+
}
|
|
33
|
+
op = body.call(thisArg, _);
|
|
34
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
35
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var __read = (this && this.__read) || function (o, n) {
|
|
39
|
+
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
40
|
+
if (!m) return o;
|
|
41
|
+
var i = m.call(o), r, ar = [], e;
|
|
42
|
+
try {
|
|
43
|
+
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
44
|
+
}
|
|
45
|
+
catch (error) { e = { error: error }; }
|
|
46
|
+
finally {
|
|
47
|
+
try {
|
|
48
|
+
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
49
|
+
}
|
|
50
|
+
finally { if (e) throw e.error; }
|
|
51
|
+
}
|
|
52
|
+
return ar;
|
|
53
|
+
};
|
|
54
|
+
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
55
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
56
|
+
if (ar || !(i in from)) {
|
|
57
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
58
|
+
ar[i] = from[i];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
62
|
+
};
|
|
63
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
64
|
+
exports.waitForDocument = exports.waitForDocuments = void 0;
|
|
65
|
+
/**
|
|
66
|
+
* Polls until at least `count` documents match the query.
|
|
67
|
+
* Useful when writes are asynchronous (audit logs, webhooks, etc.).
|
|
68
|
+
*/
|
|
69
|
+
var waitForDocuments = function (model_1, query_1) {
|
|
70
|
+
var args_1 = [];
|
|
71
|
+
for (var _i = 2; _i < arguments.length; _i++) {
|
|
72
|
+
args_1[_i - 2] = arguments[_i];
|
|
73
|
+
}
|
|
74
|
+
return __awaiter(void 0, __spreadArray([model_1, query_1], __read(args_1), false), void 0, function (model, query, count, _a) {
|
|
75
|
+
var start, q, documents, found;
|
|
76
|
+
if (count === void 0) { count = 1; }
|
|
77
|
+
var _b = _a === void 0 ? {} : _a, _c = _b.timeoutMs, timeoutMs = _c === void 0 ? 5000 : _c, _d = _b.intervalMs, intervalMs = _d === void 0 ? 100 : _d, sort = _b.sort;
|
|
78
|
+
return __generator(this, function (_e) {
|
|
79
|
+
switch (_e.label) {
|
|
80
|
+
case 0:
|
|
81
|
+
start = Date.now();
|
|
82
|
+
_e.label = 1;
|
|
83
|
+
case 1:
|
|
84
|
+
if (!(Date.now() - start < timeoutMs)) return [3 /*break*/, 4];
|
|
85
|
+
q = model.find(query);
|
|
86
|
+
if (sort) {
|
|
87
|
+
q = q.sort(sort);
|
|
88
|
+
}
|
|
89
|
+
return [4 /*yield*/, q.exec()];
|
|
90
|
+
case 2:
|
|
91
|
+
documents = _e.sent();
|
|
92
|
+
if (documents.length >= count) {
|
|
93
|
+
return [2 /*return*/, documents];
|
|
94
|
+
}
|
|
95
|
+
return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, intervalMs); })];
|
|
96
|
+
case 3:
|
|
97
|
+
_e.sent();
|
|
98
|
+
return [3 /*break*/, 1];
|
|
99
|
+
case 4: return [4 /*yield*/, model.countDocuments(query)];
|
|
100
|
+
case 5:
|
|
101
|
+
found = _e.sent();
|
|
102
|
+
throw new Error("Timed out after ".concat(timeoutMs, "ms waiting for ").concat(count, " document(s) on ").concat(model.modelName, " matching ").concat(JSON.stringify(query), " (found ").concat(found, ")"));
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
exports.waitForDocuments = waitForDocuments;
|
|
108
|
+
/** Polls until a single document matches the query. */
|
|
109
|
+
var waitForDocument = function (model_1, query_1) {
|
|
110
|
+
var args_1 = [];
|
|
111
|
+
for (var _i = 2; _i < arguments.length; _i++) {
|
|
112
|
+
args_1[_i - 2] = arguments[_i];
|
|
113
|
+
}
|
|
114
|
+
return __awaiter(void 0, __spreadArray([model_1, query_1], __read(args_1), false), void 0, function (model, query, options) {
|
|
115
|
+
var results;
|
|
116
|
+
if (options === void 0) { options = {}; }
|
|
117
|
+
return __generator(this, function (_a) {
|
|
118
|
+
switch (_a.label) {
|
|
119
|
+
case 0: return [4 /*yield*/, (0, exports.waitForDocuments)(model, query, 1, options)];
|
|
120
|
+
case 1:
|
|
121
|
+
results = _a.sent();
|
|
122
|
+
return [2 /*return*/, results[0]];
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
exports.waitForDocument = waitForDocument;
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"author": "Josh Gachnang",
|
|
3
|
+
"bugs": {
|
|
4
|
+
"url": "https://github.com/FlourishHealth/terreno/issues"
|
|
5
|
+
},
|
|
6
|
+
"dependencies": {
|
|
7
|
+
"express": "^5.2.1",
|
|
8
|
+
"lodash": "^4.17.23",
|
|
9
|
+
"qs": "^6.14.1",
|
|
10
|
+
"winston": "^3.18.3"
|
|
11
|
+
},
|
|
12
|
+
"description": "Shared Bun test helpers, MongoDB preload utilities, and HTTP fixtures for Terreno packages",
|
|
13
|
+
"devDependencies": {
|
|
14
|
+
"@biomejs/biome": "^2.3.6",
|
|
15
|
+
"@types/bun": "^1.2.4",
|
|
16
|
+
"@types/express": "^5.0.6",
|
|
17
|
+
"@types/supertest": "^6.0.2",
|
|
18
|
+
"mongodb-memory-server": "^11.0.1",
|
|
19
|
+
"mongodb-memory-server-core": "^11.0.1",
|
|
20
|
+
"mongodb-memory-server-global": "^11.0.1",
|
|
21
|
+
"mongoose": "8.23.0",
|
|
22
|
+
"supertest": "^7.0.0",
|
|
23
|
+
"typescript": "~5.9.2"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/FlourishHealth/terreno#readme",
|
|
26
|
+
"keywords": [
|
|
27
|
+
"bun",
|
|
28
|
+
"mongodb",
|
|
29
|
+
"supertest",
|
|
30
|
+
"terreno",
|
|
31
|
+
"testing"
|
|
32
|
+
],
|
|
33
|
+
"license": "Apache-2.0",
|
|
34
|
+
"main": "dist/index.js",
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"default": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./preload/memoryMongo": "./src/preload/memoryMongo.ts"
|
|
41
|
+
},
|
|
42
|
+
"name": "@terreno/test",
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"mongoose": ">=8.0.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+ssh://git@github.com/FlourishHealth/terreno.git"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"compile": "bun tsc",
|
|
55
|
+
"compile:watch": "bun tsc -w",
|
|
56
|
+
"dev": "bun tsc -w",
|
|
57
|
+
"ensure-mongo-binary": "bun ./src/mongo/ensureMongoBinary.ts",
|
|
58
|
+
"lint": "biome check ./src",
|
|
59
|
+
"lint:fix": "biome check --write ./src",
|
|
60
|
+
"test": "bun test",
|
|
61
|
+
"test:ci": "bun test"
|
|
62
|
+
},
|
|
63
|
+
"types": "dist/index.d.ts",
|
|
64
|
+
"version": "0.22.1"
|
|
65
|
+
}
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import * as crypto from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import mongoose from "mongoose";
|
|
5
|
+
|
|
6
|
+
import {testLogger} from "../logging/testLogger";
|
|
7
|
+
|
|
8
|
+
import {buildDatabaseUri} from "../mongo/connection";
|
|
9
|
+
import {restartMongoServer, startMongoServer, waitForDatabaseReady} from "../mongo/mongoServer";
|
|
10
|
+
import {ensureAllIndexes} from "../utils/ensureAllIndexes";
|
|
11
|
+
import {resetTestSessionAfterReconnect} from "../transaction/testTransaction";
|
|
12
|
+
|
|
13
|
+
const HASH_FILE = "source-hash.txt";
|
|
14
|
+
const CACHED_DATA_FILE = "cached-data.json";
|
|
15
|
+
const CACHED_COLLECTIONS_FILE = "cached-collections.json";
|
|
16
|
+
const MAX_CACHE_AGE_MS = 60 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
export interface MongoTestCacheOptions {
|
|
19
|
+
cacheDir: string;
|
|
20
|
+
sourceDirs: string[];
|
|
21
|
+
createTestData: () => Promise<unknown>;
|
|
22
|
+
publishedUriEnvVar?: string;
|
|
23
|
+
baseDatabaseName?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface MongoTestCacheController {
|
|
27
|
+
loadTestDataFromCache: () => Promise<void>;
|
|
28
|
+
setupTestCache: (options?: {force?: boolean}) => Promise<void>;
|
|
29
|
+
cleanCache: () => void;
|
|
30
|
+
cacheFilesExist: () => boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const getAllTsFiles = (dir: string): string[] => {
|
|
34
|
+
const files: string[] = [];
|
|
35
|
+
if (!fs.existsSync(dir)) {
|
|
36
|
+
return files;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const entries = fs.readdirSync(dir, {withFileTypes: true});
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
const fullPath = path.join(dir, entry.name);
|
|
42
|
+
if (entry.isDirectory()) {
|
|
43
|
+
files.push(...getAllTsFiles(fullPath));
|
|
44
|
+
} else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
|
|
45
|
+
files.push(fullPath);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return files;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const calculateSourceFilesHash = (sourceDirs: string[]): string => {
|
|
52
|
+
const tsFiles = sourceDirs.flatMap((dir) => getAllTsFiles(dir)).sort();
|
|
53
|
+
const hash = crypto.createHash("sha256");
|
|
54
|
+
for (const file of tsFiles) {
|
|
55
|
+
hash.update(file);
|
|
56
|
+
hash.update(fs.readFileSync(file, "utf-8"));
|
|
57
|
+
}
|
|
58
|
+
return hash.digest("hex");
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const getSavedHash = (cacheDir: string): string | null => {
|
|
62
|
+
const hashFilePath = path.join(cacheDir, HASH_FILE);
|
|
63
|
+
if (!fs.existsSync(hashFilePath)) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
return fs.readFileSync(hashFilePath, "utf-8").trim();
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const saveHash = (cacheDir: string, hash: string): void => {
|
|
74
|
+
fs.mkdirSync(cacheDir, {recursive: true});
|
|
75
|
+
fs.writeFileSync(path.join(cacheDir, HASH_FILE), hash);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const cacheFilesExist = (cacheDir: string): boolean => {
|
|
79
|
+
const dataFilePath = path.join(cacheDir, CACHED_DATA_FILE);
|
|
80
|
+
const collectionsFilePath = path.join(cacheDir, CACHED_COLLECTIONS_FILE);
|
|
81
|
+
const hashFilePath = path.join(cacheDir, HASH_FILE);
|
|
82
|
+
|
|
83
|
+
if (
|
|
84
|
+
!fs.existsSync(dataFilePath) ||
|
|
85
|
+
!fs.existsSync(collectionsFilePath) ||
|
|
86
|
+
!fs.existsSync(hashFilePath)
|
|
87
|
+
) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (!process.env.CI) {
|
|
92
|
+
const cacheAge = Date.now() - fs.statSync(dataFilePath).mtimeMs;
|
|
93
|
+
if (cacheAge > MAX_CACHE_AGE_MS) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return true;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const convertValue = (value: unknown): unknown => {
|
|
102
|
+
if (value === null || value === undefined) {
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
if (typeof value === "string") {
|
|
106
|
+
if (value.match(/^\d{4}-\d{2}-\d{2}T/)) {
|
|
107
|
+
return new Date(value);
|
|
108
|
+
}
|
|
109
|
+
if (value.match(/^[0-9a-fA-F]{24}$/)) {
|
|
110
|
+
return new mongoose.Types.ObjectId(value);
|
|
111
|
+
}
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
if (Array.isArray(value)) {
|
|
115
|
+
return value.map((item) => convertValue(item));
|
|
116
|
+
}
|
|
117
|
+
if (typeof value === "object") {
|
|
118
|
+
const converted: Record<string, unknown> = {};
|
|
119
|
+
for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
|
|
120
|
+
converted[key] = convertValue(nested);
|
|
121
|
+
}
|
|
122
|
+
return converted;
|
|
123
|
+
}
|
|
124
|
+
return value;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const getReconnectUri = (publishedUriEnvVar: string, baseDatabaseName: string): string => {
|
|
128
|
+
const uri = process.env[publishedUriEnvVar];
|
|
129
|
+
if (!uri) {
|
|
130
|
+
throw new Error(`[mongoTestCache] ${publishedUriEnvVar} is not set`);
|
|
131
|
+
}
|
|
132
|
+
return buildDatabaseUri({databaseName: mongoose.connection.name || baseDatabaseName, uri});
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const ensureConnectionReady = async (
|
|
136
|
+
publishedUriEnvVar: string,
|
|
137
|
+
baseDatabaseName: string
|
|
138
|
+
): Promise<void> => {
|
|
139
|
+
const maxQuickAttempts = 3;
|
|
140
|
+
const delayMs = 200;
|
|
141
|
+
|
|
142
|
+
for (let attempt = 1; attempt <= maxQuickAttempts; attempt++) {
|
|
143
|
+
const state = mongoose.connection.readyState;
|
|
144
|
+
if (state === 1) {
|
|
145
|
+
try {
|
|
146
|
+
await mongoose.connection.db!.admin().command({ping: 1});
|
|
147
|
+
return;
|
|
148
|
+
} catch {
|
|
149
|
+
// stale connection
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (state === 0 || state === 3) {
|
|
154
|
+
try {
|
|
155
|
+
if (state === 3) {
|
|
156
|
+
await mongoose.disconnect().catch(() => {});
|
|
157
|
+
}
|
|
158
|
+
await mongoose.connect(getReconnectUri(publishedUriEnvVar, baseDatabaseName), {
|
|
159
|
+
connectTimeoutMS: 2000,
|
|
160
|
+
serverSelectionTimeoutMS: 2000,
|
|
161
|
+
socketTimeoutMS: 2000,
|
|
162
|
+
});
|
|
163
|
+
await mongoose.connection.db!.admin().command({ping: 1});
|
|
164
|
+
await resetTestSessionAfterReconnect();
|
|
165
|
+
return;
|
|
166
|
+
} catch {
|
|
167
|
+
// retry
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (attempt < maxQuickAttempts) {
|
|
172
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
await restartMongoServer({baseDatabaseName, publishedUriEnvVar});
|
|
177
|
+
await resetTestSessionAfterReconnect();
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const loadTestDataIntoDb = async (cachedCollections: Record<string, unknown[]>): Promise<void> => {
|
|
181
|
+
const clearPromises: Array<Promise<unknown>> = [];
|
|
182
|
+
for (const collectionName of Object.keys(cachedCollections)) {
|
|
183
|
+
clearPromises.push(mongoose.connection.db!.collection(collectionName).deleteMany({}));
|
|
184
|
+
}
|
|
185
|
+
await Promise.all(clearPromises);
|
|
186
|
+
|
|
187
|
+
const restorePromises: Array<Promise<unknown>> = [];
|
|
188
|
+
for (const collectionName of Object.keys(cachedCollections)) {
|
|
189
|
+
const docs = cachedCollections[collectionName];
|
|
190
|
+
if (!docs || docs.length === 0) {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const convertedDocs = docs.map((doc) => convertValue(doc));
|
|
194
|
+
restorePromises.push(
|
|
195
|
+
mongoose.connection.db!
|
|
196
|
+
.collection(collectionName)
|
|
197
|
+
.insertMany(convertedDocs as Record<string, unknown>[], {ordered: false})
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const restoreResults = await Promise.allSettled(restorePromises);
|
|
202
|
+
for (const result of restoreResults) {
|
|
203
|
+
if (result.status === "rejected") {
|
|
204
|
+
const error = result.reason as {code?: number; writeErrors?: Array<{code?: number}>};
|
|
205
|
+
const isDuplicateKey =
|
|
206
|
+
error?.code === 11000 ||
|
|
207
|
+
error?.writeErrors?.every((writeError) => writeError.code === 11000);
|
|
208
|
+
if (!isDuplicateKey) {
|
|
209
|
+
throw result.reason;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
await ensureAllIndexes();
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
export const createMongoTestCache = (options: MongoTestCacheOptions): MongoTestCacheController => {
|
|
217
|
+
const publishedUriEnvVar = options.publishedUriEnvVar ?? "TERRENO_TEST_MONGO_URI";
|
|
218
|
+
const baseDatabaseName = options.baseDatabaseName ?? "terrenoTest_base";
|
|
219
|
+
|
|
220
|
+
let cachedSourceHash: string | null = null;
|
|
221
|
+
let cachedCollectionsInMemory: Record<string, unknown[]> | null = null;
|
|
222
|
+
let inflightSetupTestCache: Promise<void> | null = null;
|
|
223
|
+
|
|
224
|
+
const getSourceHash = (): string => {
|
|
225
|
+
if (!cachedSourceHash) {
|
|
226
|
+
cachedSourceHash = calculateSourceFilesHash(options.sourceDirs);
|
|
227
|
+
}
|
|
228
|
+
return cachedSourceHash;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const cleanCache = (): void => {
|
|
232
|
+
for (const file of [CACHED_DATA_FILE, CACHED_COLLECTIONS_FILE, HASH_FILE]) {
|
|
233
|
+
const filePath = path.join(options.cacheDir, file);
|
|
234
|
+
if (fs.existsSync(filePath)) {
|
|
235
|
+
fs.unlinkSync(filePath);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
cachedCollectionsInMemory = null;
|
|
239
|
+
cachedSourceHash = null;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const setupTestCache = async ({force = false}: {force?: boolean} = {}): Promise<void> => {
|
|
243
|
+
const currentHash = calculateSourceFilesHash(options.sourceDirs);
|
|
244
|
+
const savedHash = getSavedHash(options.cacheDir);
|
|
245
|
+
|
|
246
|
+
if (!force && savedHash === currentHash && cacheFilesExist(options.cacheDir)) {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const isAlreadyConnected = mongoose.connection.readyState === 1;
|
|
251
|
+
if (!isAlreadyConnected) {
|
|
252
|
+
await startMongoServer({baseDatabaseName, publishedUriEnvVar, useReplSet: true});
|
|
253
|
+
await waitForDatabaseReady();
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const cachedData = await options.createTestData();
|
|
257
|
+
const cachedCollections: Record<string, unknown[]> = {};
|
|
258
|
+
|
|
259
|
+
for (const collectionName of Object.keys(mongoose.connection.collections)) {
|
|
260
|
+
const collection = mongoose.connection.collections[collectionName];
|
|
261
|
+
const docs = await collection.find({}).toArray();
|
|
262
|
+
cachedCollections[collectionName] = docs.map((doc) => JSON.parse(JSON.stringify(doc)));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
fs.mkdirSync(options.cacheDir, {recursive: true});
|
|
266
|
+
fs.writeFileSync(path.join(options.cacheDir, CACHED_DATA_FILE), JSON.stringify(cachedData));
|
|
267
|
+
fs.writeFileSync(
|
|
268
|
+
path.join(options.cacheDir, CACHED_COLLECTIONS_FILE),
|
|
269
|
+
JSON.stringify(cachedCollections)
|
|
270
|
+
);
|
|
271
|
+
saveHash(options.cacheDir, currentHash);
|
|
272
|
+
cachedCollectionsInMemory = cachedCollections;
|
|
273
|
+
testLogger.info(`[mongoTestCache] Test data cached to ${options.cacheDir}`);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const loadTestDataFromCache = async (): Promise<void> => {
|
|
277
|
+
fs.mkdirSync(options.cacheDir, {recursive: true});
|
|
278
|
+
|
|
279
|
+
const cachedFilePath = path.join(options.cacheDir, CACHED_COLLECTIONS_FILE);
|
|
280
|
+
const currentHash = getSourceHash();
|
|
281
|
+
const savedHash = getSavedHash(options.cacheDir);
|
|
282
|
+
const cacheValid = cacheFilesExist(options.cacheDir) && savedHash === currentHash;
|
|
283
|
+
|
|
284
|
+
if (!cacheValid) {
|
|
285
|
+
if (!inflightSetupTestCache) {
|
|
286
|
+
inflightSetupTestCache = setupTestCache().finally(() => {
|
|
287
|
+
inflightSetupTestCache = null;
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
await inflightSetupTestCache;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (!cachedCollectionsInMemory) {
|
|
294
|
+
cachedCollectionsInMemory = JSON.parse(fs.readFileSync(cachedFilePath, "utf-8"));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (!cachedCollectionsInMemory) {
|
|
298
|
+
throw new Error("[mongoTestCache] Cached collections were not loaded");
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
await ensureConnectionReady(publishedUriEnvVar, baseDatabaseName);
|
|
302
|
+
await loadTestDataIntoDb(cachedCollectionsInMemory);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
cacheFilesExist: () => cacheFilesExist(options.cacheDir),
|
|
307
|
+
cleanCache,
|
|
308
|
+
loadTestDataFromCache,
|
|
309
|
+
setupTestCache,
|
|
310
|
+
};
|
|
311
|
+
};
|