@orieljs/testing 0.1.0-alpha.12 → 0.1.0-alpha.14

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/dist/index.d.ts CHANGED
@@ -76,6 +76,7 @@ declare class PendingCommand implements PromiseLike<number> {
76
76
  private readonly app;
77
77
  readonly command: string;
78
78
  readonly parameters: Record<string, unknown>;
79
+ private readonly answers;
79
80
  private readonly checks;
80
81
  private result;
81
82
  constructor(app: Application, command: string, parameters?: Record<string, unknown>);
@@ -90,6 +91,8 @@ declare class PendingCommand implements PromiseLike<number> {
90
91
  assertSuccessful(): this;
91
92
  assertOk(): this;
92
93
  assertFailed(): this;
94
+ /** Answers the command's questions (ask(), secret(), confirm(), choice()), in order. A question beyond them fails. */
95
+ withAnswers(...answers: string[]): this;
93
96
  /** Runs the command once and checks the expectations; resolves to the exit code. */
94
97
  run(): Promise<number>;
95
98
  then<R1 = number, R2 = never>(onfulfilled?: ((value: number) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
@@ -455,6 +458,10 @@ declare class HttpClient {
455
458
  protected scopeSession(scope: Container): Session | undefined;
456
459
  buildRequest(method: string, uri: string, options: RequestOptions): Request;
457
460
  protected baseUrl(): string;
461
+ /** The cookies as EncryptCookies would leave them, since no middleware runs for a Live test. */
462
+ protected plainCookies(): Record<string, string>;
463
+ /** A cookie kept from a response is as it was sent: encrypted, unless the app excepts it. */
464
+ protected decrypted(name: string, value: string): string | undefined;
458
465
  protected cookieHeader(): string;
459
466
  /** Like a browser: cookies the app sets are sent back on later requests in the same test; deleted ones are dropped. */
460
467
  protected rememberCookies(response: Response): void;
@@ -637,6 +644,16 @@ declare abstract class TestCase extends InteractsWithTime {
637
644
  * already set (the shell, CI, vitest.config) win, like phpunit's non-forced <env>.
638
645
  */
639
646
  declare const TESTING_ENVIRONMENT: Readonly<Record<string, string>>;
647
+ /**
648
+ * What a test run's vitest.config.ts spreads into `test`: the testing environment, and whether files run at the same time.
649
+ * The tests run on SQLite in memory, or on TEST_DATABASE_URL's database, one file at a time, as they share it. DB_URL and
650
+ * DB_CONNECTION never count: RefreshDatabase wipes the database it runs on, and Bun loads .env before the tests start, so
651
+ * honouring them could wipe a production database. It prints which database the run is on.
652
+ */
653
+ declare function testingConfig(env?: NodeJS.ProcessEnv, log?: (line: string) => void, cwd?: string): {
654
+ env: Record<string, string>;
655
+ fileParallelism: boolean;
656
+ };
640
657
  declare function applyEnvironment(values: Record<string, string>, env?: NodeJS.ProcessEnv): void;
641
658
 
642
659
  /** The request scope's ViewFactory: records every view made, so TestResponse can assert on it (assertViewIs/Has). */
@@ -671,7 +688,7 @@ declare const RefreshDatabaseState: {
671
688
  };
672
689
  /** Runs a console command through the ConsoleKernel contract; a non-zero exit fails the test with its output. */
673
690
  declare function runCommand(app: Application, command: string, parameters?: Record<string, unknown>): Promise<void>;
674
- /** Laravel's usingInMemoryDatabase(): the default connection's database is ':memory:'. */
691
+ /** Laravel's usingInMemoryDatabase(), by the driver too: only SQLite has a database in memory, whatever DB_DATABASE says. */
675
692
  declare function usingInMemoryDatabase(app: Application): boolean;
676
693
  /**
677
694
  * Laravel's RefreshDatabase.
@@ -1087,4 +1104,4 @@ declare const FakeFile: {
1087
1104
  image(name: string, width?: number, height?: number): File;
1088
1105
  };
1089
1106
 
1090
- export { AnonymousNotifiable, AssertableInertia, AssertableJson, type BatchRecord, type BootOptions, BusFake, type CountOrFilter, DatabaseMigrations, type DatabaseTestOptions, DatabaseTransactions, type DispatchedEvent, EventFake, type ExpectedErrors, type ExpectedListener, FakeDisk, FakeFile, HttpClient, InteractsWithApplication, InteractsWithConsole, InteractsWithDatabase, InteractsWithTime, type JsonStructure, MailFake, MailRecord, MakesHttpRequests, NotificationFake, PendingCommand, type PushedJob, QueueFake, RefreshDatabase, RefreshDatabaseState, type RequestData, type RequestOptions, type ResponseContext, type ResponseCookie, SHOULD_QUEUE, type SentNotification, StorageFake, TESTING_ENVIRONMENT, type TableOrModel, type Target, TestCase, type TestHooks, TestResponse, type TestTrait, type TravelDate, Wormhole, actingAsAuthFactory, addresses, applyEnvironment, cookieHeader, cookiePrefix, decryptCookie, encryptCookie, flatten, freezeSecond, freezeTime, guessMimeType, inertiaPageOf, install, isExpired, isQueueable, matches, nameOf, parseSetCookie, recordingExceptionHandler, recordingViewFactory, responseCookies, runCommand, travel, travelBack, travelTo, usingInMemoryDatabase };
1107
+ export { AnonymousNotifiable, AssertableInertia, AssertableJson, type BatchRecord, type BootOptions, BusFake, type CountOrFilter, DatabaseMigrations, type DatabaseTestOptions, DatabaseTransactions, type DispatchedEvent, EventFake, type ExpectedErrors, type ExpectedListener, FakeDisk, FakeFile, HttpClient, InteractsWithApplication, InteractsWithConsole, InteractsWithDatabase, InteractsWithTime, type JsonStructure, MailFake, MailRecord, MakesHttpRequests, NotificationFake, PendingCommand, type PushedJob, QueueFake, RefreshDatabase, RefreshDatabaseState, type RequestData, type RequestOptions, type ResponseContext, type ResponseCookie, SHOULD_QUEUE, type SentNotification, StorageFake, TESTING_ENVIRONMENT, type TableOrModel, type Target, TestCase, type TestHooks, TestResponse, type TestTrait, type TravelDate, Wormhole, actingAsAuthFactory, addresses, applyEnvironment, cookieHeader, cookiePrefix, decryptCookie, encryptCookie, flatten, freezeSecond, freezeTime, guessMimeType, inertiaPageOf, install, isExpired, isQueueable, matches, nameOf, parseSetCookie, recordingExceptionHandler, recordingViewFactory, responseCookies, runCommand, testingConfig, travel, travelBack, travelTo, usingInMemoryDatabase };
package/dist/index.js CHANGED
@@ -209,6 +209,7 @@ var PendingCommand = class {
209
209
  app;
210
210
  command;
211
211
  parameters;
212
+ answers = [];
212
213
  checks = [];
213
214
  result;
214
215
  /** A line of output equals `line` exactly; with no argument, the command printed something. */
@@ -261,6 +262,11 @@ ${output}`, { actual: output, expected: text }));
261
262
  assertFailed() {
262
263
  return this.assertNotExitCode(0);
263
264
  }
265
+ /** Answers the command's questions (ask(), secret(), confirm(), choice()), in order. A question beyond them fails. */
266
+ withAnswers(...answers) {
267
+ this.answers.push(...answers);
268
+ return this;
269
+ }
264
270
  /** Runs the command once and checks the expectations; resolves to the exit code. */
265
271
  run() {
266
272
  return this.result ??= this.execute();
@@ -271,7 +277,7 @@ ${output}`, { actual: output, expected: text }));
271
277
  async execute() {
272
278
  if (!this.app.bound(ConsoleKernel)) throw new Error(`Cannot run [${this.command}]: the Console component (ConsoleKernel) is not registered.`);
273
279
  const kernel = this.app.make(ConsoleKernel);
274
- const exitCode = await kernel.call(this.command, this.parameters);
280
+ const exitCode = await kernel.call(this.command, this.parameters, { answers: this.answers });
275
281
  const output = kernel.output();
276
282
  const lines = output.split("\n").map((line) => line.replace(/\r$/, ""));
277
283
  for (const check of this.checks) check(output, lines, exitCode);
@@ -338,6 +344,103 @@ async function assertNotSoftDeleted(db, table, data = {}, connection, deletedAtC
338
344
 
339
345
  // Database/traits.ts
340
346
  import { ConfigRepository, ConsoleKernel as ConsoleKernel2, DatabaseManager } from "@orieljs/contracts";
347
+
348
+ // environment.ts
349
+ import { existsSync, readFileSync } from "fs";
350
+ import { join } from "path";
351
+ import { parse } from "dotenv";
352
+ var TESTING_ENVIRONMENT = Object.freeze({
353
+ APP_ENV: "testing",
354
+ BCRYPT_ROUNDS: "4",
355
+ CACHE_STORE: "array",
356
+ DB_CONNECTION: "sqlite",
357
+ DB_DATABASE: ":memory:",
358
+ DB_URL: "",
359
+ MAIL_MAILER: "array",
360
+ QUEUE_CONNECTION: "sync",
361
+ SESSION_DRIVER: "array"
362
+ });
363
+ var DRIVERS = {
364
+ "postgres:": { driver: "pgsql", port: "5432" },
365
+ "postgresql:": { driver: "pgsql", port: "5432" },
366
+ "mysql:": { driver: "mysql", port: "3306" },
367
+ "mariadb:": { driver: "mysql", port: "3306" }
368
+ };
369
+ var DEFAULT_PORTS = { pgsql: "5432", mysql: "3306", mariadb: "3306" };
370
+ var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
371
+ var placeOf = (host, port, database) => `${LOOPBACK.has(host.toLowerCase()) ? "localhost" : host.toLowerCase()}:${port}/${database}`;
372
+ function parseAddress(address) {
373
+ let url;
374
+ try {
375
+ url = new URL(address);
376
+ } catch {
377
+ return void 0;
378
+ }
379
+ const known = DRIVERS[url.protocol];
380
+ if (known === void 0) return void 0;
381
+ const database = decodeURIComponent(url.pathname.slice(1));
382
+ const port = url.port || known.port;
383
+ return { driver: known.driver, database, place: placeOf(url.hostname, port, database), shown: `${url.hostname}:${port}/${database}` };
384
+ }
385
+ function dotEnv(cwd) {
386
+ const file = join(cwd, ".env");
387
+ return existsSync(file) ? parse(readFileSync(file, "utf8")) : {};
388
+ }
389
+ function serverDatabase(connection) {
390
+ if (typeof connection.url === "string" && connection.url !== "") return parseAddress(connection.url);
391
+ const driver = String(connection.driver ?? "");
392
+ const port = DEFAULT_PORTS[driver];
393
+ if (port === void 0) return void 0;
394
+ const host = String(connection.host ?? "127.0.0.1");
395
+ const at = String(connection.port ?? port);
396
+ const database = String(connection.database ?? "oriel");
397
+ return { driver, place: placeOf(host, at, database), shown: `${host}:${at}/${database}` };
398
+ }
399
+ function ownDatabases(env, cwd) {
400
+ const file = dotEnv(cwd);
401
+ const setting = (key) => env[key] !== void 0 && env[key] !== "" ? env[key] : file[key] !== "" ? file[key] : void 0;
402
+ const places = [];
403
+ for (const url of [env.DB_URL, file.DB_URL]) {
404
+ const place = url === void 0 || url === "" ? void 0 : parseAddress(url)?.place;
405
+ if (place !== void 0) places.push(place);
406
+ }
407
+ const port = DEFAULT_PORTS[setting("DB_CONNECTION") ?? ""];
408
+ if (port !== void 0) places.push(placeOf(setting("DB_HOST") ?? "127.0.0.1", setting("DB_PORT") ?? port, setting("DB_DATABASE") ?? "oriel"));
409
+ return places;
410
+ }
411
+ function testingConfig(env = process.env, log = (line) => console.log(line), cwd = process.cwd()) {
412
+ const address = env.TEST_DATABASE_URL;
413
+ if (address === void 0 || address === "") {
414
+ const ignored = env.DB_CONNECTION !== void 0 && env.DB_CONNECTION !== "" && env.DB_CONNECTION !== "sqlite" || env.DB_URL !== void 0 && env.DB_URL !== "";
415
+ log(`Tests run on SQLite, in memory.${ignored ? " DB_CONNECTION and DB_URL are ignored in tests: set TEST_DATABASE_URL to use another database." : ""}`);
416
+ return { env: { ...TESTING_ENVIRONMENT }, fileParallelism: true };
417
+ }
418
+ const database = parseAddress(address);
419
+ if (database === void 0) throw new Error("TEST_DATABASE_URL must be a postgres:// or mysql:// address.");
420
+ if (database.database === "") throw new Error("TEST_DATABASE_URL must name a database.");
421
+ if (ownDatabases(env, cwd).includes(database.place)) {
422
+ throw new Error("TEST_DATABASE_URL is the app's own database (DB_URL): the tests would wipe it.");
423
+ }
424
+ log(`Tests run on ${database.driver} at ${database.shown} (TEST_DATABASE_URL), one file at a time.`);
425
+ return {
426
+ env: { ...TESTING_ENVIRONMENT, DB_CONNECTION: database.driver, DB_URL: address, DB_DATABASE: database.database },
427
+ fileParallelism: false
428
+ };
429
+ }
430
+ function applyEnvironment(values, env = process.env) {
431
+ for (const [key, value] of Object.entries(values)) env[key] ??= value;
432
+ }
433
+ function clonePlain(value) {
434
+ if (Array.isArray(value)) return value.map((item) => clonePlain(item));
435
+ if (typeof value === "object" && value !== null) {
436
+ const proto = Object.getPrototypeOf(value);
437
+ if (proto !== Object.prototype && proto !== null) return value;
438
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePlain(item)]));
439
+ }
440
+ return value;
441
+ }
442
+
443
+ // Database/traits.ts
341
444
  var RefreshDatabaseState = { migrated: false };
342
445
  async function runCommand(app, command, parameters = {}) {
343
446
  if (!app.bound(ConsoleKernel2)) throw new Error(`Running [${command}] needs the Console component (ConsoleKernel is not bound).`);
@@ -353,7 +456,8 @@ function seedOptions(test) {
353
456
  function usingInMemoryDatabase(app) {
354
457
  const config = app.make(ConfigRepository);
355
458
  const name = config.get("database.default");
356
- return name !== void 0 && config.get(`database.connections.${name}.database`) === ":memory:";
459
+ if (name === void 0) return false;
460
+ return config.get(`database.connections.${name}.driver`) === "sqlite" && config.get(`database.connections.${name}.database`) === ":memory:";
357
461
  }
358
462
  function connectionsOf(test) {
359
463
  const db = test.app.make(DatabaseManager);
@@ -375,9 +479,19 @@ async function rollBackTo(connection, level) {
375
479
  current = next;
376
480
  }
377
481
  }
482
+ function refuseOwnDatabase(app, trait) {
483
+ const config = app.make(ConfigRepository);
484
+ const connection = config.get(`database.connections.${config.get("database.default")}`);
485
+ const target2 = serverDatabase(connection ?? {});
486
+ if (target2 === void 0 || !ownDatabases({}, app.basePath()).includes(target2.place)) return;
487
+ throw new Error(
488
+ `${trait} would empty the app's own database (${target2.driver} at ${target2.shown}, from .env). Give the tests a database of their own: set TEST_DATABASE_URL, and spread testingConfig() into vitest.config.ts.`
489
+ );
490
+ }
378
491
  var RefreshDatabase = {
379
492
  async setUp(test) {
380
493
  if (usingInMemoryDatabase(test.app)) return runCommand(test.app, "migrate", seedOptions(test));
494
+ refuseOwnDatabase(test.app, "RefreshDatabase");
381
495
  if (!RefreshDatabaseState.migrated) {
382
496
  if (test.migrateFreshUsing !== void 0) await test.migrateFreshUsing();
383
497
  else await runCommand(test.app, "migrate:fresh", seedOptions(test));
@@ -388,6 +502,7 @@ var RefreshDatabase = {
388
502
  };
389
503
  var DatabaseMigrations = {
390
504
  async setUp(test) {
505
+ refuseOwnDatabase(test.app, "DatabaseMigrations");
391
506
  await runCommand(test.app, "migrate:fresh", seedOptions(test));
392
507
  test.beforeApplicationDestroyed(() => runCommand(test.app, "migrate:rollback"));
393
508
  }
@@ -401,33 +516,10 @@ var DatabaseTransactions = {
401
516
  // Concerns/MakesHttpRequests.ts
402
517
  import { AuthFactory as AuthFactory2, token } from "@orieljs/contracts";
403
518
 
404
- // environment.ts
405
- var TESTING_ENVIRONMENT = Object.freeze({
406
- APP_ENV: "testing",
407
- BCRYPT_ROUNDS: "4",
408
- CACHE_STORE: "array",
409
- DB_CONNECTION: "sqlite",
410
- DB_DATABASE: ":memory:",
411
- MAIL_MAILER: "array",
412
- QUEUE_CONNECTION: "sync",
413
- SESSION_DRIVER: "array"
414
- });
415
- function applyEnvironment(values, env = process.env) {
416
- for (const [key, value] of Object.entries(values)) env[key] ??= value;
417
- }
418
- function clonePlain(value) {
419
- if (Array.isArray(value)) return value.map((item) => clonePlain(item));
420
- if (typeof value === "object" && value !== null) {
421
- const proto = Object.getPrototypeOf(value);
422
- if (proto !== Object.prototype && proto !== null) return value;
423
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePlain(item)]));
424
- }
425
- return value;
426
- }
427
-
428
519
  // Http/HttpClient.ts
429
520
  import {
430
521
  AuthFactory,
522
+ CookieJar,
431
523
  ConfigRepository as ConfigRepository3,
432
524
  Encrypter as Encrypter2,
433
525
  ExceptionHandler,
@@ -443,8 +535,8 @@ import { Encrypter, UrlGenerator } from "@orieljs/contracts";
443
535
  import { Arr as Arr3 } from "@orieljs/support";
444
536
 
445
537
  // Fluent/AssertableInertia.ts
446
- import { existsSync } from "fs";
447
- import { join } from "path";
538
+ import { existsSync as existsSync2 } from "fs";
539
+ import { join as join2 } from "path";
448
540
  import { ConfigRepository as ConfigRepository2 } from "@orieljs/contracts";
449
541
  import { Arr as Arr2 } from "@orieljs/support";
450
542
 
@@ -745,7 +837,7 @@ var AssertableInertia = class _AssertableInertia extends AssertableJson {
745
837
  if (shouldExist === true || shouldExist === void 0 && config?.get("inertia.testing.ensure_pages_exist", true) !== false) {
746
838
  const paths = config?.get("inertia.pages.paths", []) ?? [];
747
839
  const extensions = config?.get("inertia.pages.extensions", []) ?? [];
748
- const exists = paths.some((path) => extensions.some((extension) => existsSync(join(path, `${value}.${extension}`))));
840
+ const exists = paths.some((path) => extensions.some((extension) => existsSync2(join2(path, `${value}.${extension}`))));
749
841
  if (!exists) fail(`Inertia page component file [${value}] does not exist.`);
750
842
  }
751
843
  return this;
@@ -1590,16 +1682,39 @@ var HttpClient = class {
1590
1682
  const result = await scope.run(async () => {
1591
1683
  this.beforeRequest(scope, context);
1592
1684
  if (context.session !== void 0) this.applyPending(context.session);
1593
- scope.instance(HttpRequest, new IncomingRequest(request));
1685
+ const incoming = new IncomingRequest(request);
1686
+ incoming.setCookies(this.plainCookies());
1687
+ scope.instance(HttpRequest, incoming);
1594
1688
  if (scope.bound(AuthFactory)) {
1595
1689
  try {
1596
1690
  await scope.make(AuthFactory).guard().check();
1597
1691
  } catch {
1598
1692
  }
1599
1693
  }
1600
- return run();
1694
+ const result2 = await run();
1695
+ if (scope.bound(CookieJar)) {
1696
+ for (const cookie of scope.make(CookieJar).queued()) {
1697
+ if (cookie.minutes < 0) this.cookies.delete(cookie.name);
1698
+ else this.cookies.set(cookie.name, { value: cookie.value, encrypt: true });
1699
+ }
1700
+ }
1701
+ if (scope.bound(AuthFactory)) {
1702
+ try {
1703
+ ;
1704
+ scope.make(AuthFactory).guard().keepPasswordHash?.();
1705
+ } catch {
1706
+ }
1707
+ }
1708
+ return result2;
1601
1709
  });
1602
1710
  await scope.run(() => this.afterRequest(scope, context));
1711
+ if (context.session !== void 0) {
1712
+ const carried = clonePlain(context.session.all());
1713
+ this.sessionChanges.splice(0, Infinity, (session) => {
1714
+ session.flush();
1715
+ session.put(clonePlain(carried));
1716
+ });
1717
+ }
1603
1718
  return result;
1604
1719
  }
1605
1720
  /** Runs the request through the app's real HttpKernel, in a request scope this client owns. */
@@ -1718,8 +1833,25 @@ var HttpClient = class {
1718
1833
  const configured = this.app.bound(ConfigRepository3) ? this.app.make(ConfigRepository3).get("app.url") : void 0;
1719
1834
  return typeof configured === "string" && configured !== "" ? configured : "http://localhost";
1720
1835
  }
1836
+ /** The cookies as EncryptCookies would leave them, since no middleware runs for a Live test. */
1837
+ plainCookies() {
1838
+ const plain = {};
1839
+ for (const [name, { value, encrypt }] of this.cookies) {
1840
+ plain[name] = encrypt ? value : this.decrypted(name, value) ?? value;
1841
+ }
1842
+ return plain;
1843
+ }
1844
+ /** A cookie kept from a response is as it was sent: encrypted, unless the app excepts it. */
1845
+ decrypted(name, value) {
1846
+ try {
1847
+ return this.app.bound(Encrypter2) ? decryptCookie(this.app.make(Encrypter2), name, value) : void 0;
1848
+ } catch {
1849
+ return void 0;
1850
+ }
1851
+ }
1721
1852
  cookieHeader() {
1722
- const encrypter = this.app.bound(Encrypter2) ? this.app.make(Encrypter2) : void 0;
1853
+ const needsKey = [...this.cookies.values()].some(({ encrypt }) => encrypt);
1854
+ const encrypter = needsKey && this.app.bound(Encrypter2) ? this.app.make(Encrypter2) : void 0;
1723
1855
  const values = /* @__PURE__ */ new Map();
1724
1856
  for (const [name, { value, encrypt }] of this.cookies) {
1725
1857
  values.set(name, encrypt && encrypter !== void 0 ? encryptCookie(encrypter, name, value) : value);
@@ -3675,6 +3807,7 @@ export {
3675
3807
  recordingViewFactory,
3676
3808
  responseCookies,
3677
3809
  runCommand,
3810
+ testingConfig,
3678
3811
  travel,
3679
3812
  travelBack,
3680
3813
  travelTo,