@backstage/backend-test-utils 1.0.1-next.1 → 1.0.1-next.2

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/backend-app-api/src/lib/DependencyGraph.cjs.js +182 -0
  3. package/dist/backend-app-api/src/lib/DependencyGraph.cjs.js.map +1 -0
  4. package/dist/backend-app-api/src/wiring/ServiceRegistry.cjs.js +240 -0
  5. package/dist/backend-app-api/src/wiring/ServiceRegistry.cjs.js.map +1 -0
  6. package/dist/cache/TestCaches.cjs.js +159 -0
  7. package/dist/cache/TestCaches.cjs.js.map +1 -0
  8. package/dist/cache/memcache.cjs.js +62 -0
  9. package/dist/cache/memcache.cjs.js.map +1 -0
  10. package/dist/cache/redis.cjs.js +62 -0
  11. package/dist/cache/redis.cjs.js.map +1 -0
  12. package/dist/cache/types.cjs.js +25 -0
  13. package/dist/cache/types.cjs.js.map +1 -0
  14. package/dist/database/TestDatabases.cjs.js +128 -0
  15. package/dist/database/TestDatabases.cjs.js.map +1 -0
  16. package/dist/database/mysql.cjs.js +188 -0
  17. package/dist/database/mysql.cjs.js.map +1 -0
  18. package/dist/database/postgres.cjs.js +143 -0
  19. package/dist/database/postgres.cjs.js.map +1 -0
  20. package/dist/database/sqlite.cjs.js +40 -0
  21. package/dist/database/sqlite.cjs.js.map +1 -0
  22. package/dist/database/types.cjs.js +68 -0
  23. package/dist/database/types.cjs.js.map +1 -0
  24. package/dist/filesystem/MockDirectory.cjs.js +152 -0
  25. package/dist/filesystem/MockDirectory.cjs.js.map +1 -0
  26. package/dist/index.cjs.js +25 -2327
  27. package/dist/index.cjs.js.map +1 -1
  28. package/dist/msw/registerMswTestHooks.cjs.js +10 -0
  29. package/dist/msw/registerMswTestHooks.cjs.js.map +1 -0
  30. package/dist/next/services/MockAuthService.cjs.js +111 -0
  31. package/dist/next/services/MockAuthService.cjs.js.map +1 -0
  32. package/dist/next/services/MockHttpAuthService.cjs.js +87 -0
  33. package/dist/next/services/MockHttpAuthService.cjs.js.map +1 -0
  34. package/dist/next/services/MockRootLoggerService.cjs.js +49 -0
  35. package/dist/next/services/MockRootLoggerService.cjs.js.map +1 -0
  36. package/dist/next/services/MockUserInfoService.cjs.js +26 -0
  37. package/dist/next/services/MockUserInfoService.cjs.js.map +1 -0
  38. package/dist/next/services/mockCredentials.cjs.js +148 -0
  39. package/dist/next/services/mockCredentials.cjs.js.map +1 -0
  40. package/dist/next/services/mockServices.cjs.js +294 -0
  41. package/dist/next/services/mockServices.cjs.js.map +1 -0
  42. package/dist/next/wiring/ServiceFactoryTester.cjs.js +61 -0
  43. package/dist/next/wiring/ServiceFactoryTester.cjs.js.map +1 -0
  44. package/dist/next/wiring/TestBackend.cjs.js +258 -0
  45. package/dist/next/wiring/TestBackend.cjs.js.map +1 -0
  46. package/dist/util/errorHandler.cjs.js +18 -0
  47. package/dist/util/errorHandler.cjs.js.map +1 -0
  48. package/dist/util/getDockerImageForName.cjs.js +8 -0
  49. package/dist/util/getDockerImageForName.cjs.js.map +1 -0
  50. package/dist/util/isDockerDisabledForTests.cjs.js +8 -0
  51. package/dist/util/isDockerDisabledForTests.cjs.js.map +1 -0
  52. package/package.json +8 -8
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+
3
+ var errors = require('@backstage/errors');
4
+ var crypto = require('crypto');
5
+ var knexFactory = require('knex');
6
+ var pgConnectionString = require('pg-connection-string');
7
+ var uuid = require('uuid');
8
+ var types = require('./types.cjs.js');
9
+
10
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
11
+
12
+ var knexFactory__default = /*#__PURE__*/_interopDefaultCompat(knexFactory);
13
+
14
+ async function waitForPostgresReady(connection) {
15
+ const startTime = Date.now();
16
+ let lastError;
17
+ let attempts = 0;
18
+ for (; ; ) {
19
+ attempts += 1;
20
+ let knex;
21
+ try {
22
+ knex = knexFactory__default.default({
23
+ client: "pg",
24
+ connection: {
25
+ // make a copy because the driver mutates this
26
+ ...connection
27
+ }
28
+ });
29
+ const result = await knex.select(knex.raw("version()"));
30
+ if (Array.isArray(result) && result[0]?.version) {
31
+ return;
32
+ }
33
+ } catch (e) {
34
+ lastError = e;
35
+ } finally {
36
+ await knex?.destroy();
37
+ }
38
+ if (Date.now() - startTime > 3e4) {
39
+ throw new Error(
40
+ `Timed out waiting for the database to be ready for connections, ${attempts} attempts, ${lastError ? `last error was ${errors.stringifyError(lastError)}` : "(no errors thrown)"}`
41
+ );
42
+ }
43
+ await new Promise((resolve) => setTimeout(resolve, 100));
44
+ }
45
+ }
46
+ async function startPostgresContainer(image) {
47
+ const user = "postgres";
48
+ const password = uuid.v4();
49
+ const { GenericContainer } = await import('testcontainers');
50
+ const container = await new GenericContainer(image).withExposedPorts(5432).withEnvironment({ POSTGRES_PASSWORD: password }).withTmpFs({ "/var/lib/postgresql/data": "rw" }).start();
51
+ const host = container.getHost();
52
+ const port = container.getMappedPort(5432);
53
+ const connection = { host, port, user, password };
54
+ const stopContainer = async () => {
55
+ await container.stop({ timeout: 1e4 });
56
+ };
57
+ await waitForPostgresReady(connection);
58
+ return { connection, stopContainer };
59
+ }
60
+ class PostgresEngine {
61
+ static async create(properties) {
62
+ const { connectionStringEnvironmentVariableName, dockerImageName } = properties;
63
+ if (connectionStringEnvironmentVariableName) {
64
+ const connectionString = process.env[connectionStringEnvironmentVariableName];
65
+ if (connectionString) {
66
+ const connection = pgConnectionString.parse(connectionString);
67
+ return new PostgresEngine(
68
+ properties,
69
+ connection
70
+ );
71
+ }
72
+ }
73
+ if (dockerImageName) {
74
+ const { connection, stopContainer } = await startPostgresContainer(
75
+ dockerImageName
76
+ );
77
+ return new PostgresEngine(properties, connection, stopContainer);
78
+ }
79
+ throw new Error(`Test databasee for ${properties.name} not configured`);
80
+ }
81
+ #properties;
82
+ #connection;
83
+ #knexInstances;
84
+ #databaseNames;
85
+ #stopContainer;
86
+ constructor(properties, connection, stopContainer) {
87
+ this.#properties = properties;
88
+ this.#connection = connection;
89
+ this.#knexInstances = [];
90
+ this.#databaseNames = [];
91
+ this.#stopContainer = stopContainer;
92
+ }
93
+ async createDatabaseInstance() {
94
+ const adminConnection = this.#connectAdmin();
95
+ try {
96
+ const databaseName = `db${crypto.randomBytes(16).toString("hex")}`;
97
+ await adminConnection.raw("CREATE DATABASE ??", [databaseName]);
98
+ this.#databaseNames.push(databaseName);
99
+ const knexInstance = knexFactory__default.default({
100
+ client: this.#properties.driver,
101
+ connection: {
102
+ ...this.#connection,
103
+ database: databaseName
104
+ },
105
+ ...types.LARGER_POOL_CONFIG
106
+ });
107
+ this.#knexInstances.push(knexInstance);
108
+ return knexInstance;
109
+ } finally {
110
+ await adminConnection.destroy();
111
+ }
112
+ }
113
+ async shutdown() {
114
+ for (const instance of this.#knexInstances) {
115
+ await instance.destroy();
116
+ }
117
+ const adminConnection = this.#connectAdmin();
118
+ try {
119
+ for (const databaseName of this.#databaseNames) {
120
+ await adminConnection.raw("DROP DATABASE ??", [databaseName]);
121
+ }
122
+ } finally {
123
+ await adminConnection.destroy();
124
+ }
125
+ await this.#stopContainer?.();
126
+ }
127
+ #connectAdmin() {
128
+ return knexFactory__default.default({
129
+ client: this.#properties.driver,
130
+ connection: {
131
+ ...this.#connection,
132
+ database: "postgres"
133
+ },
134
+ pool: {
135
+ acquireTimeoutMillis: 1e4
136
+ }
137
+ });
138
+ }
139
+ }
140
+
141
+ exports.PostgresEngine = PostgresEngine;
142
+ exports.startPostgresContainer = startPostgresContainer;
143
+ //# sourceMappingURL=postgres.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.cjs.js","sources":["../../src/database/postgres.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringifyError } from '@backstage/errors';\nimport { randomBytes } from 'crypto';\nimport knexFactory, { Knex } from 'knex';\nimport { parse as parsePgConnectionString } from 'pg-connection-string';\nimport { v4 as uuid } from 'uuid';\nimport { Engine, LARGER_POOL_CONFIG, TestDatabaseProperties } from './types';\n\nasync function waitForPostgresReady(\n connection: Knex.PgConnectionConfig,\n): Promise<void> {\n const startTime = Date.now();\n\n let lastError: Error | undefined;\n let attempts = 0;\n for (;;) {\n attempts += 1;\n\n let knex: Knex | undefined;\n try {\n knex = knexFactory({\n client: 'pg',\n connection: {\n // make a copy because the driver mutates this\n ...connection,\n },\n });\n const result = await knex.select(knex.raw('version()'));\n if (Array.isArray(result) && result[0]?.version) {\n return;\n }\n } catch (e) {\n lastError = e;\n } finally {\n await knex?.destroy();\n }\n\n if (Date.now() - startTime > 30_000) {\n throw new Error(\n `Timed out waiting for the database to be ready for connections, ${attempts} attempts, ${\n lastError\n ? `last error was ${stringifyError(lastError)}`\n : '(no errors thrown)'\n }`,\n );\n }\n\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n}\n\nexport async function startPostgresContainer(image: string): Promise<{\n connection: Knex.PgConnectionConfig;\n stopContainer: () => Promise<void>;\n}> {\n const user = 'postgres';\n const password = uuid();\n\n // Lazy-load to avoid side-effect of importing testcontainers\n const { GenericContainer } = await import('testcontainers');\n\n const container = await new GenericContainer(image)\n .withExposedPorts(5432)\n .withEnvironment({ POSTGRES_PASSWORD: password })\n .withTmpFs({ '/var/lib/postgresql/data': 'rw' })\n .start();\n\n const host = container.getHost();\n const port = container.getMappedPort(5432);\n const connection = { host, port, user, password };\n const stopContainer = async () => {\n await container.stop({ timeout: 10_000 });\n };\n\n await waitForPostgresReady(connection);\n\n return { connection, stopContainer };\n}\n\nexport class PostgresEngine implements Engine {\n static async create(\n properties: TestDatabaseProperties,\n ): Promise<PostgresEngine> {\n const { connectionStringEnvironmentVariableName, dockerImageName } =\n properties;\n\n if (connectionStringEnvironmentVariableName) {\n const connectionString =\n process.env[connectionStringEnvironmentVariableName];\n if (connectionString) {\n const connection = parsePgConnectionString(connectionString);\n return new PostgresEngine(\n properties,\n connection as Knex.PgConnectionConfig,\n );\n }\n }\n\n if (dockerImageName) {\n const { connection, stopContainer } = await startPostgresContainer(\n dockerImageName,\n );\n return new PostgresEngine(properties, connection, stopContainer);\n }\n\n throw new Error(`Test databasee for ${properties.name} not configured`);\n }\n\n readonly #properties: TestDatabaseProperties;\n readonly #connection: Knex.PgConnectionConfig;\n readonly #knexInstances: Knex[];\n readonly #databaseNames: string[];\n readonly #stopContainer?: () => Promise<void>;\n\n constructor(\n properties: TestDatabaseProperties,\n connection: Knex.PgConnectionConfig,\n stopContainer?: () => Promise<void>,\n ) {\n this.#properties = properties;\n this.#connection = connection;\n this.#knexInstances = [];\n this.#databaseNames = [];\n this.#stopContainer = stopContainer;\n }\n\n async createDatabaseInstance(): Promise<Knex> {\n const adminConnection = this.#connectAdmin();\n try {\n const databaseName = `db${randomBytes(16).toString('hex')}`;\n\n await adminConnection.raw('CREATE DATABASE ??', [databaseName]);\n this.#databaseNames.push(databaseName);\n\n const knexInstance = knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: databaseName,\n },\n ...LARGER_POOL_CONFIG,\n });\n this.#knexInstances.push(knexInstance);\n\n return knexInstance;\n } finally {\n await adminConnection.destroy();\n }\n }\n\n async shutdown(): Promise<void> {\n for (const instance of this.#knexInstances) {\n await instance.destroy();\n }\n\n const adminConnection = this.#connectAdmin();\n try {\n for (const databaseName of this.#databaseNames) {\n await adminConnection.raw('DROP DATABASE ??', [databaseName]);\n }\n } finally {\n await adminConnection.destroy();\n }\n\n await this.#stopContainer?.();\n }\n\n #connectAdmin(): Knex {\n return knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: 'postgres',\n },\n pool: {\n acquireTimeoutMillis: 10000,\n },\n });\n }\n}\n"],"names":["knexFactory","stringifyError","uuid","parsePgConnectionString","randomBytes","LARGER_POOL_CONFIG"],"mappings":";;;;;;;;;;;;;AAuBA,eAAe,qBACb,UACe,EAAA;AACf,EAAM,MAAA,SAAA,GAAY,KAAK,GAAI,EAAA,CAAA;AAE3B,EAAI,IAAA,SAAA,CAAA;AACJ,EAAA,IAAI,QAAW,GAAA,CAAA,CAAA;AACf,EAAS,WAAA;AACP,IAAY,QAAA,IAAA,CAAA,CAAA;AAEZ,IAAI,IAAA,IAAA,CAAA;AACJ,IAAI,IAAA;AACF,MAAA,IAAA,GAAOA,4BAAY,CAAA;AAAA,QACjB,MAAQ,EAAA,IAAA;AAAA,QACR,UAAY,EAAA;AAAA;AAAA,UAEV,GAAG,UAAA;AAAA,SACL;AAAA,OACD,CAAA,CAAA;AACD,MAAA,MAAM,SAAS,MAAM,IAAA,CAAK,OAAO,IAAK,CAAA,GAAA,CAAI,WAAW,CAAC,CAAA,CAAA;AACtD,MAAA,IAAI,MAAM,OAAQ,CAAA,MAAM,KAAK,MAAO,CAAA,CAAC,GAAG,OAAS,EAAA;AAC/C,QAAA,OAAA;AAAA,OACF;AAAA,aACO,CAAG,EAAA;AACV,MAAY,SAAA,GAAA,CAAA,CAAA;AAAA,KACZ,SAAA;AACA,MAAA,MAAM,MAAM,OAAQ,EAAA,CAAA;AAAA,KACtB;AAEA,IAAA,IAAI,IAAK,CAAA,GAAA,EAAQ,GAAA,SAAA,GAAY,GAAQ,EAAA;AACnC,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,gEAAA,EAAmE,QAAQ,CACzE,WAAA,EAAA,SAAA,GACI,kBAAkBC,qBAAe,CAAA,SAAS,CAAC,CAAA,CAAA,GAC3C,oBACN,CAAA,CAAA;AAAA,OACF,CAAA;AAAA,KACF;AAEA,IAAA,MAAM,IAAI,OAAQ,CAAA,CAAA,OAAA,KAAW,UAA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A,GAAA;AAAA,OACxB;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF;;;;;"}
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ var knexFactory = require('knex');
4
+
5
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
6
+
7
+ var knexFactory__default = /*#__PURE__*/_interopDefaultCompat(knexFactory);
8
+
9
+ class SqliteEngine {
10
+ static async create(properties) {
11
+ return new SqliteEngine(properties);
12
+ }
13
+ #properties;
14
+ #instances;
15
+ constructor(properties) {
16
+ this.#properties = properties;
17
+ this.#instances = [];
18
+ }
19
+ async createDatabaseInstance() {
20
+ const instance = knexFactory__default.default({
21
+ client: this.#properties.driver,
22
+ connection: ":memory:",
23
+ useNullAsDefault: true
24
+ });
25
+ instance.client.pool.on("createSuccess", (_eventId, resource) => {
26
+ resource.run("PRAGMA foreign_keys = ON", () => {
27
+ });
28
+ });
29
+ this.#instances.push(instance);
30
+ return instance;
31
+ }
32
+ async shutdown() {
33
+ for (const instance of this.#instances) {
34
+ await instance.destroy();
35
+ }
36
+ }
37
+ }
38
+
39
+ exports.SqliteEngine = SqliteEngine;
40
+ //# sourceMappingURL=sqlite.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.cjs.js","sources":["../../src/database/sqlite.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport knexFactory, { Knex } from 'knex';\nimport { Engine, TestDatabaseProperties } from './types';\n\nexport class SqliteEngine implements Engine {\n static async create(\n properties: TestDatabaseProperties,\n ): Promise<SqliteEngine> {\n return new SqliteEngine(properties);\n }\n\n readonly #properties: TestDatabaseProperties;\n readonly #instances: Knex[];\n\n constructor(properties: TestDatabaseProperties) {\n this.#properties = properties;\n this.#instances = [];\n }\n\n async createDatabaseInstance(): Promise<Knex> {\n const instance = knexFactory({\n client: this.#properties.driver,\n connection: ':memory:',\n useNullAsDefault: true,\n });\n\n instance.client.pool.on('createSuccess', (_eventId: any, resource: any) => {\n resource.run('PRAGMA foreign_keys = ON', () => {});\n });\n\n this.#instances.push(instance);\n return instance;\n }\n\n async shutdown(): Promise<void> {\n for (const instance of this.#instances) {\n await instance.destroy();\n }\n }\n}\n"],"names":["knexFactory"],"mappings":";;;;;;;;AAmBO,MAAM,YAA+B,CAAA;AAAA,EAC1C,aAAa,OACX,UACuB,EAAA;AACvB,IAAO,OAAA,IAAI,aAAa,UAAU,CAAA,CAAA;AAAA,GACpC;AAAA,EAES,WAAA,CAAA;AAAA,EACA,UAAA,CAAA;AAAA,EAET,YAAY,UAAoC,EAAA;AAC9C,IAAA,IAAA,CAAK,WAAc,GAAA,UAAA,CAAA;AACnB,IAAA,IAAA,CAAK,aAAa,EAAC,CAAA;AAAA,GACrB;AAAA,EAEA,MAAM,sBAAwC,GAAA;AAC5C,IAAA,MAAM,WAAWA,4BAAY,CAAA;AAAA,MAC3B,MAAA,EAAQ,KAAK,WAAY,CAAA,MAAA;AAAA,MACzB,UAAY,EAAA,UAAA;AAAA,MACZ,gBAAkB,EAAA,IAAA;AAAA,KACnB,CAAA,CAAA;AAED,IAAA,QAAA,CAAS,OAAO,IAAK,CAAA,EAAA,CAAG,eAAiB,EAAA,CAAC,UAAe,QAAkB,KAAA;AACzE,MAAS,QAAA,CAAA,GAAA,CAAI,4BAA4B,MAAM;AAAA,OAAE,CAAA,CAAA;AAAA,KAClD,CAAA,CAAA;AAED,IAAK,IAAA,CAAA,UAAA,CAAW,KAAK,QAAQ,CAAA,CAAA;AAC7B,IAAO,OAAA,QAAA,CAAA;AAAA,GACT;AAAA,EAEA,MAAM,QAA0B,GAAA;AAC9B,IAAW,KAAA,MAAA,QAAA,IAAY,KAAK,UAAY,EAAA;AACtC,MAAA,MAAM,SAAS,OAAQ,EAAA,CAAA;AAAA,KACzB;AAAA,GACF;AACF;;;;"}
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+
3
+ var getDockerImageForName = require('../util/getDockerImageForName.cjs.js');
4
+
5
+ const allDatabases = Object.freeze({
6
+ POSTGRES_16: {
7
+ name: "Postgres 16.x",
8
+ driver: "pg",
9
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:16"),
10
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES16_CONNECTION_STRING"
11
+ },
12
+ POSTGRES_15: {
13
+ name: "Postgres 15.x",
14
+ driver: "pg",
15
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:15"),
16
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES15_CONNECTION_STRING"
17
+ },
18
+ POSTGRES_14: {
19
+ name: "Postgres 14.x",
20
+ driver: "pg",
21
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:14"),
22
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES14_CONNECTION_STRING"
23
+ },
24
+ POSTGRES_13: {
25
+ name: "Postgres 13.x",
26
+ driver: "pg",
27
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:13"),
28
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES13_CONNECTION_STRING"
29
+ },
30
+ POSTGRES_12: {
31
+ name: "Postgres 12.x",
32
+ driver: "pg",
33
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:12"),
34
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES12_CONNECTION_STRING"
35
+ },
36
+ POSTGRES_11: {
37
+ name: "Postgres 11.x",
38
+ driver: "pg",
39
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:11"),
40
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES11_CONNECTION_STRING"
41
+ },
42
+ POSTGRES_9: {
43
+ name: "Postgres 9.x",
44
+ driver: "pg",
45
+ dockerImageName: getDockerImageForName.getDockerImageForName("postgres:9"),
46
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_POSTGRES9_CONNECTION_STRING"
47
+ },
48
+ MYSQL_8: {
49
+ name: "MySQL 8.x",
50
+ driver: "mysql2",
51
+ dockerImageName: getDockerImageForName.getDockerImageForName("mysql:8"),
52
+ connectionStringEnvironmentVariableName: "BACKSTAGE_TEST_DATABASE_MYSQL8_CONNECTION_STRING"
53
+ },
54
+ SQLITE_3: {
55
+ name: "SQLite 3.x",
56
+ driver: "better-sqlite3"
57
+ }
58
+ });
59
+ const LARGER_POOL_CONFIG = {
60
+ pool: {
61
+ min: 0,
62
+ max: 50
63
+ }
64
+ };
65
+
66
+ exports.LARGER_POOL_CONFIG = LARGER_POOL_CONFIG;
67
+ exports.allDatabases = allDatabases;
68
+ //# sourceMappingURL=types.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.cjs.js","sources":["../../src/database/types.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Knex } from 'knex';\nimport { getDockerImageForName } from '../util/getDockerImageForName';\n\nexport interface Engine {\n createDatabaseInstance(): Promise<Knex>;\n shutdown(): Promise<void>;\n}\n\n/**\n * The possible databases to test against.\n *\n * @public\n */\nexport type TestDatabaseId =\n | 'POSTGRES_16'\n | 'POSTGRES_15'\n | 'POSTGRES_14'\n | 'POSTGRES_13'\n | 'POSTGRES_12'\n | 'POSTGRES_11'\n | 'POSTGRES_9'\n | 'MYSQL_8'\n | 'SQLITE_3';\n\nexport type TestDatabaseProperties = {\n name: string;\n driver: string;\n dockerImageName?: string;\n connectionStringEnvironmentVariableName?: string;\n};\n\nexport const allDatabases: Record<TestDatabaseId, TestDatabaseProperties> =\n Object.freeze({\n POSTGRES_16: {\n name: 'Postgres 16.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:16'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES16_CONNECTION_STRING',\n },\n POSTGRES_15: {\n name: 'Postgres 15.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:15'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES15_CONNECTION_STRING',\n },\n POSTGRES_14: {\n name: 'Postgres 14.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:14'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES14_CONNECTION_STRING',\n },\n POSTGRES_13: {\n name: 'Postgres 13.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:13'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES13_CONNECTION_STRING',\n },\n POSTGRES_12: {\n name: 'Postgres 12.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:12'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES12_CONNECTION_STRING',\n },\n POSTGRES_11: {\n name: 'Postgres 11.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:11'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES11_CONNECTION_STRING',\n },\n POSTGRES_9: {\n name: 'Postgres 9.x',\n driver: 'pg',\n dockerImageName: getDockerImageForName('postgres:9'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_POSTGRES9_CONNECTION_STRING',\n },\n MYSQL_8: {\n name: 'MySQL 8.x',\n driver: 'mysql2',\n dockerImageName: getDockerImageForName('mysql:8'),\n connectionStringEnvironmentVariableName:\n 'BACKSTAGE_TEST_DATABASE_MYSQL8_CONNECTION_STRING',\n },\n SQLITE_3: {\n name: 'SQLite 3.x',\n driver: 'better-sqlite3',\n },\n });\n\nexport const LARGER_POOL_CONFIG = {\n pool: {\n min: 0,\n max: 50,\n },\n};\n"],"names":["getDockerImageForName"],"mappings":";;;;AA+Ca,MAAA,YAAA,GACX,OAAO,MAAO,CAAA;AAAA,EACZ,WAAa,EAAA;AAAA,IACX,IAAM,EAAA,eAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,aAAa,CAAA;AAAA,IACpD,uCACE,EAAA,sDAAA;AAAA,GACJ;AAAA,EACA,WAAa,EAAA;AAAA,IACX,IAAM,EAAA,eAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,aAAa,CAAA;AAAA,IACpD,uCACE,EAAA,sDAAA;AAAA,GACJ;AAAA,EACA,WAAa,EAAA;AAAA,IACX,IAAM,EAAA,eAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,aAAa,CAAA;AAAA,IACpD,uCACE,EAAA,sDAAA;AAAA,GACJ;AAAA,EACA,WAAa,EAAA;AAAA,IACX,IAAM,EAAA,eAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,aAAa,CAAA;AAAA,IACpD,uCACE,EAAA,sDAAA;AAAA,GACJ;AAAA,EACA,WAAa,EAAA;AAAA,IACX,IAAM,EAAA,eAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,aAAa,CAAA;AAAA,IACpD,uCACE,EAAA,sDAAA;AAAA,GACJ;AAAA,EACA,WAAa,EAAA;AAAA,IACX,IAAM,EAAA,eAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,aAAa,CAAA;AAAA,IACpD,uCACE,EAAA,sDAAA;AAAA,GACJ;AAAA,EACA,UAAY,EAAA;AAAA,IACV,IAAM,EAAA,cAAA;AAAA,IACN,MAAQ,EAAA,IAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,YAAY,CAAA;AAAA,IACnD,uCACE,EAAA,qDAAA;AAAA,GACJ;AAAA,EACA,OAAS,EAAA;AAAA,IACP,IAAM,EAAA,WAAA;AAAA,IACN,MAAQ,EAAA,QAAA;AAAA,IACR,eAAA,EAAiBA,4CAAsB,SAAS,CAAA;AAAA,IAChD,uCACE,EAAA,kDAAA;AAAA,GACJ;AAAA,EACA,QAAU,EAAA;AAAA,IACR,IAAM,EAAA,YAAA;AAAA,IACN,MAAQ,EAAA,gBAAA;AAAA,GACV;AACF,CAAC,EAAA;AAEI,MAAM,kBAAqB,GAAA;AAAA,EAChC,IAAM,EAAA;AAAA,IACJ,GAAK,EAAA,CAAA;AAAA,IACL,GAAK,EAAA,EAAA;AAAA,GACP;AACF;;;;;"}
@@ -0,0 +1,152 @@
1
+ 'use strict';
2
+
3
+ var os = require('os');
4
+ var backendPluginApi = require('@backstage/backend-plugin-api');
5
+ var fs = require('fs-extra');
6
+ var textextensions = require('textextensions');
7
+ var path = require('path');
8
+
9
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
10
+
11
+ var os__default = /*#__PURE__*/_interopDefaultCompat(os);
12
+ var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
13
+ var textextensions__default = /*#__PURE__*/_interopDefaultCompat(textextensions);
14
+
15
+ const tmpdirMarker = Symbol("os-tmpdir-mock");
16
+ class MockDirectoryImpl {
17
+ #root;
18
+ constructor(root) {
19
+ this.#root = root;
20
+ }
21
+ get path() {
22
+ return this.#root;
23
+ }
24
+ resolve(...paths) {
25
+ return path.resolve(this.#root, ...paths);
26
+ }
27
+ setContent(root) {
28
+ this.remove();
29
+ return this.addContent(root);
30
+ }
31
+ addContent(root) {
32
+ const entries = this.#transformInput(root);
33
+ for (const entry of entries) {
34
+ const fullPath = path.resolve(this.#root, entry.path);
35
+ if (!backendPluginApi.isChildPath(this.#root, fullPath)) {
36
+ throw new Error(
37
+ `Provided path must resolve to a child path of the mock directory, got '${fullPath}'`
38
+ );
39
+ }
40
+ if (entry.type === "dir") {
41
+ fs__default.default.ensureDirSync(fullPath);
42
+ } else if (entry.type === "file") {
43
+ fs__default.default.ensureDirSync(path.dirname(fullPath));
44
+ fs__default.default.writeFileSync(fullPath, entry.content);
45
+ } else if (entry.type === "callback") {
46
+ fs__default.default.ensureDirSync(path.dirname(fullPath));
47
+ entry.callback({
48
+ path: fullPath,
49
+ symlink(target) {
50
+ fs__default.default.symlinkSync(target, fullPath);
51
+ }
52
+ });
53
+ }
54
+ }
55
+ }
56
+ content(options) {
57
+ const shouldReadAsText = (typeof options?.shouldReadAsText === "boolean" ? () => options?.shouldReadAsText : options?.shouldReadAsText) ?? ((path$1) => textextensions__default.default.includes(path.extname(path$1).slice(1)));
58
+ const root = path.resolve(this.#root, options?.path ?? "");
59
+ if (!backendPluginApi.isChildPath(this.#root, root)) {
60
+ throw new Error(
61
+ `Provided path must resolve to a child path of the mock directory, got '${root}'`
62
+ );
63
+ }
64
+ function read(path$1) {
65
+ if (!fs__default.default.pathExistsSync(path$1)) {
66
+ return void 0;
67
+ }
68
+ const entries = fs__default.default.readdirSync(path$1, { withFileTypes: true });
69
+ return Object.fromEntries(
70
+ entries.map((entry) => {
71
+ const fullPath = path.resolve(path$1, entry.name);
72
+ if (entry.isDirectory()) {
73
+ return [entry.name, read(fullPath)];
74
+ }
75
+ const content = fs__default.default.readFileSync(fullPath);
76
+ const relativePosixPath = path.relative(root, fullPath).split(path.win32.sep).join(path.posix.sep);
77
+ if (shouldReadAsText(relativePosixPath, content)) {
78
+ return [entry.name, content.toString("utf8")];
79
+ }
80
+ return [entry.name, content];
81
+ })
82
+ );
83
+ }
84
+ return read(root);
85
+ }
86
+ clear = () => {
87
+ this.setContent({});
88
+ };
89
+ remove = () => {
90
+ fs__default.default.rmSync(this.#root, { recursive: true, force: true, maxRetries: 10 });
91
+ };
92
+ #transformInput(input) {
93
+ const entries = [];
94
+ function traverse(node, path) {
95
+ if (typeof node === "string") {
96
+ entries.push({
97
+ type: "file",
98
+ path,
99
+ content: Buffer.from(node, "utf8")
100
+ });
101
+ } else if (node instanceof Buffer) {
102
+ entries.push({ type: "file", path, content: node });
103
+ } else if (typeof node === "function") {
104
+ entries.push({ type: "callback", path, callback: node });
105
+ } else {
106
+ entries.push({ type: "dir", path });
107
+ for (const [name, child] of Object.entries(node)) {
108
+ traverse(child, path ? `${path}/${name}` : name);
109
+ }
110
+ }
111
+ }
112
+ traverse(input, "");
113
+ return entries;
114
+ }
115
+ }
116
+ function createMockDirectory(options) {
117
+ const tmpDir = process.env.RUNNER_TEMP || os__default.default.tmpdir();
118
+ const root = fs__default.default.mkdtempSync(path.join(tmpDir, "backstage-tmp-test-dir-"));
119
+ const mocker = new MockDirectoryImpl(root);
120
+ const origTmpdir = options?.mockOsTmpDir ? os__default.default.tmpdir : void 0;
121
+ if (origTmpdir) {
122
+ if (Object.hasOwn(origTmpdir, tmpdirMarker)) {
123
+ throw new Error(
124
+ "Cannot mock os.tmpdir() when it has already been mocked"
125
+ );
126
+ }
127
+ const mock = Object.assign(() => mocker.path, { [tmpdirMarker]: true });
128
+ os__default.default.tmpdir = mock;
129
+ }
130
+ const needsCleanup = !process.env.CI;
131
+ if (needsCleanup) {
132
+ process.on("beforeExit", mocker.remove);
133
+ }
134
+ try {
135
+ afterAll(() => {
136
+ if (origTmpdir) {
137
+ os__default.default.tmpdir = origTmpdir;
138
+ }
139
+ if (needsCleanup) {
140
+ mocker.remove();
141
+ }
142
+ });
143
+ } catch {
144
+ }
145
+ if (options?.content) {
146
+ mocker.setContent(options.content);
147
+ }
148
+ return mocker;
149
+ }
150
+
151
+ exports.createMockDirectory = createMockDirectory;
152
+ //# sourceMappingURL=MockDirectory.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MockDirectory.cjs.js","sources":["../../src/filesystem/MockDirectory.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport os from 'os';\nimport { isChildPath } from '@backstage/backend-plugin-api';\nimport fs from 'fs-extra';\nimport textextensions from 'textextensions';\nimport {\n dirname,\n extname,\n join as joinPath,\n resolve as resolvePath,\n relative as relativePath,\n win32,\n posix,\n} from 'path';\n\nconst tmpdirMarker = Symbol('os-tmpdir-mock');\n\n/**\n * A context that allows for more advanced file system operations when writing mock directory content.\n *\n * @public\n */\nexport interface MockDirectoryContentCallbackContext {\n /** Absolute path to the location of this piece of content on the filesystem */\n path: string;\n\n /** Creates a symbolic link at the current location */\n symlink(target: string): void;\n}\n\n/**\n * A callback that allows for more advanced file system operations when writing mock directory content.\n *\n * @public\n */\nexport type MockDirectoryContentCallback = (\n ctx: MockDirectoryContentCallbackContext,\n) => void;\n\n/**\n * The content of a mock directory represented by a nested object structure.\n *\n * @remarks\n *\n * When used as input, the keys may contain forward slashes to indicate nested directories.\n * Then returned as output, each directory will always be represented as a separate object.\n *\n * @example\n * ```ts\n * {\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * }\n * ```\n *\n * @public\n */\nexport type MockDirectoryContent = {\n [name in string]:\n | MockDirectoryContent\n | string\n | Buffer\n | MockDirectoryContentCallback;\n};\n\n/**\n * Options for {@link MockDirectory.content}.\n *\n * @public\n */\nexport interface MockDirectoryContentOptions {\n /**\n * The path to read content from. Defaults to the root of the mock directory.\n *\n * An absolute path can also be provided, as long as it is a child path of the mock directory.\n */\n path?: string;\n\n /**\n * Whether or not to return files as text rather than buffers.\n *\n * Defaults to checking the file extension against a list of known text extensions.\n */\n shouldReadAsText?: boolean | ((path: string, buffer: Buffer) => boolean);\n}\n\n/**\n * A utility for creating a mock directory that is automatically cleaned up.\n *\n * @public\n */\nexport interface MockDirectory {\n /**\n * The path to the root of the mock directory\n */\n readonly path: string;\n\n /**\n * Resolves a path relative to the root of the mock directory.\n */\n resolve(...paths: string[]): string;\n\n /**\n * Sets the content of the mock directory. This will remove any existing content.\n *\n * @example\n * ```ts\n * mockDir.setContent({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n setContent(root: MockDirectoryContent): void;\n\n /**\n * Adds content of the mock directory. This will overwrite existing files.\n *\n * @example\n * ```ts\n * mockDir.addContent({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n addContent(root: MockDirectoryContent): void;\n\n /**\n * Reads the content of the mock directory.\n *\n * @remarks\n *\n * Text files will be returned as strings, while binary files will be returned as buffers.\n * By default the file extension is used to determine whether a file should be read as text.\n *\n * @example\n * ```ts\n * expect(mockDir.content()).toEqual({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir': {\n * 'file.txt': 'content',\n * },\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n content(\n options?: MockDirectoryContentOptions,\n ): MockDirectoryContent | undefined;\n\n /**\n * Clears the content of the mock directory, ensuring that the directory itself exists.\n */\n clear(): void;\n\n /**\n * Removes the mock directory and all its contents.\n */\n remove(): void;\n}\n\n/** @internal */\ntype MockEntry =\n | {\n type: 'file';\n path: string;\n content: Buffer;\n }\n | {\n type: 'dir';\n path: string;\n }\n | {\n type: 'callback';\n path: string;\n callback: MockDirectoryContentCallback;\n };\n\n/** @internal */\nclass MockDirectoryImpl {\n readonly #root: string;\n\n constructor(root: string) {\n this.#root = root;\n }\n\n get path(): string {\n return this.#root;\n }\n\n resolve(...paths: string[]): string {\n return resolvePath(this.#root, ...paths);\n }\n\n setContent(root: MockDirectoryContent): void {\n this.remove();\n\n return this.addContent(root);\n }\n\n addContent(root: MockDirectoryContent): void {\n const entries = this.#transformInput(root);\n\n for (const entry of entries) {\n const fullPath = resolvePath(this.#root, entry.path);\n if (!isChildPath(this.#root, fullPath)) {\n throw new Error(\n `Provided path must resolve to a child path of the mock directory, got '${fullPath}'`,\n );\n }\n\n if (entry.type === 'dir') {\n fs.ensureDirSync(fullPath);\n } else if (entry.type === 'file') {\n fs.ensureDirSync(dirname(fullPath));\n fs.writeFileSync(fullPath, entry.content);\n } else if (entry.type === 'callback') {\n fs.ensureDirSync(dirname(fullPath));\n entry.callback({\n path: fullPath,\n symlink(target: string) {\n fs.symlinkSync(target, fullPath);\n },\n });\n }\n }\n }\n\n content(\n options?: MockDirectoryContentOptions,\n ): MockDirectoryContent | undefined {\n const shouldReadAsText =\n (typeof options?.shouldReadAsText === 'boolean'\n ? () => options?.shouldReadAsText\n : options?.shouldReadAsText) ??\n ((path: string) => textextensions.includes(extname(path).slice(1)));\n\n const root = resolvePath(this.#root, options?.path ?? '');\n if (!isChildPath(this.#root, root)) {\n throw new Error(\n `Provided path must resolve to a child path of the mock directory, got '${root}'`,\n );\n }\n\n function read(path: string): MockDirectoryContent | undefined {\n if (!fs.pathExistsSync(path)) {\n return undefined;\n }\n\n const entries = fs.readdirSync(path, { withFileTypes: true });\n return Object.fromEntries(\n entries.map(entry => {\n const fullPath = resolvePath(path, entry.name);\n\n if (entry.isDirectory()) {\n return [entry.name, read(fullPath)];\n }\n const content = fs.readFileSync(fullPath);\n const relativePosixPath = relativePath(root, fullPath)\n .split(win32.sep)\n .join(posix.sep);\n\n if (shouldReadAsText(relativePosixPath, content)) {\n return [entry.name, content.toString('utf8')];\n }\n return [entry.name, content];\n }),\n );\n }\n\n return read(root);\n }\n\n clear = (): void => {\n this.setContent({});\n };\n\n remove = (): void => {\n fs.rmSync(this.#root, { recursive: true, force: true, maxRetries: 10 });\n };\n\n #transformInput(input: MockDirectoryContent[string]): MockEntry[] {\n const entries: MockEntry[] = [];\n\n function traverse(node: MockDirectoryContent[string], path: string) {\n if (typeof node === 'string') {\n entries.push({\n type: 'file',\n path,\n content: Buffer.from(node, 'utf8'),\n });\n } else if (node instanceof Buffer) {\n entries.push({ type: 'file', path, content: node });\n } else if (typeof node === 'function') {\n entries.push({ type: 'callback', path, callback: node });\n } else {\n entries.push({ type: 'dir', path });\n for (const [name, child] of Object.entries(node)) {\n traverse(child, path ? `${path}/${name}` : name);\n }\n }\n }\n\n traverse(input, '');\n\n return entries;\n }\n}\n\n/**\n * Options for {@link createMockDirectory}.\n *\n * @public\n */\nexport interface CreateMockDirectoryOptions {\n /**\n * In addition to creating a temporary directory, also mock `os.tmpdir()` to return the\n * mock directory path until the end of the test suite.\n *\n * @returns\n */\n mockOsTmpDir?: boolean;\n\n /**\n * Initializes the directory with the given content, see {@link MockDirectory.setContent}.\n */\n content?: MockDirectoryContent;\n}\n\n/**\n * Creates a new temporary mock directory that will be removed after the tests have completed.\n *\n * @public\n * @remarks\n *\n * This method is intended to be called outside of any test, either at top-level or\n * within a `describe` block. It will call `afterAll` to make sure that the mock directory\n * is removed after the tests have run.\n *\n * @example\n * ```ts\n * describe('MySubject', () => {\n * const mockDir = createMockDirectory();\n *\n * beforeEach(mockDir.clear);\n *\n * it('should work', () => {\n * // ... use mockDir\n * })\n * })\n * ```\n */\nexport function createMockDirectory(\n options?: CreateMockDirectoryOptions,\n): MockDirectory {\n const tmpDir = process.env.RUNNER_TEMP || os.tmpdir(); // GitHub Actions\n const root = fs.mkdtempSync(joinPath(tmpDir, 'backstage-tmp-test-dir-'));\n\n const mocker = new MockDirectoryImpl(root);\n\n const origTmpdir = options?.mockOsTmpDir ? os.tmpdir : undefined;\n if (origTmpdir) {\n if (Object.hasOwn(origTmpdir, tmpdirMarker)) {\n throw new Error(\n 'Cannot mock os.tmpdir() when it has already been mocked',\n );\n }\n const mock = Object.assign(() => mocker.path, { [tmpdirMarker]: true });\n os.tmpdir = mock;\n }\n\n // In CI we expect there to be no need to clean up temporary directories\n const needsCleanup = !process.env.CI;\n if (needsCleanup) {\n process.on('beforeExit', mocker.remove);\n }\n\n try {\n afterAll(() => {\n if (origTmpdir) {\n os.tmpdir = origTmpdir;\n }\n if (needsCleanup) {\n mocker.remove();\n }\n });\n } catch {\n /* ignore */\n }\n\n if (options?.content) {\n mocker.setContent(options.content);\n }\n\n return mocker;\n}\n"],"names":["resolvePath","isChildPath","fs","dirname","path","textextensions","extname","relativePath","win32","posix","os","joinPath"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,YAAA,GAAe,OAAO,gBAAgB,CAAA,CAAA;AAwL5C,MAAM,iBAAkB,CAAA;AAAA,EACb,KAAA,CAAA;AAAA,EAET,YAAY,IAAc,EAAA;AACxB,IAAA,IAAA,CAAK,KAAQ,GAAA,IAAA,CAAA;AAAA,GACf;AAAA,EAEA,IAAI,IAAe,GAAA;AACjB,IAAA,OAAO,IAAK,CAAA,KAAA,CAAA;AAAA,GACd;AAAA,EAEA,WAAW,KAAyB,EAAA;AAClC,IAAA,OAAOA,YAAY,CA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