@orieljs/testing 0.1.0-alpha.5 → 0.1.0-alpha.7

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.js CHANGED
@@ -1,3 +1,128 @@
1
+ // time.ts
2
+ var original;
3
+ var testNow;
4
+ var realDate = () => original ?? globalThis.Date;
5
+ function install() {
6
+ if (original !== void 0) return;
7
+ const Real = original = globalThis.Date;
8
+ const current = () => testNow ?? Real.now();
9
+ const Travelling = new Proxy(Real, {
10
+ construct: (target2, args, newTarget) => Reflect.construct(target2, args.length === 0 ? [current()] : args, newTarget === Travelling ? target2 : newTarget),
11
+ apply: (target2) => new target2(current()).toString(),
12
+ get: (target2, property) => property === "now" ? current : Reflect.get(target2, property, target2)
13
+ });
14
+ globalThis.Date = Travelling;
15
+ }
16
+ function setTestNow(date) {
17
+ const time = new (realDate())(date).getTime();
18
+ if (Number.isNaN(time)) throw new TypeError(`Invalid date: ${String(date)}`);
19
+ install();
20
+ testNow = time;
21
+ return new (realDate())(time);
22
+ }
23
+ function thenTravelBack(callback) {
24
+ let result;
25
+ try {
26
+ result = callback();
27
+ } catch (error) {
28
+ travelBack();
29
+ throw error;
30
+ }
31
+ if (result instanceof Promise) return result.finally(travelBack);
32
+ travelBack();
33
+ return result;
34
+ }
35
+ function travelTo(date, callback) {
36
+ const at = setTestNow(date);
37
+ if (callback) return thenTravelBack(() => callback(at));
38
+ }
39
+ function travelBack() {
40
+ if (original !== void 0) globalThis.Date = original;
41
+ original = void 0;
42
+ testNow = void 0;
43
+ return /* @__PURE__ */ new Date();
44
+ }
45
+ function freezeTime(callback) {
46
+ const at = new (realDate())(testNow ?? Date.now());
47
+ if (callback) return travelTo(at, callback);
48
+ travelTo(at);
49
+ return at;
50
+ }
51
+ function freezeSecond(callback) {
52
+ const at = new (realDate())(testNow ?? Date.now());
53
+ at.setMilliseconds(0);
54
+ if (callback) return travelTo(at, callback);
55
+ travelTo(at);
56
+ return at;
57
+ }
58
+ function travel(value) {
59
+ return new Wormhole(value);
60
+ }
61
+ var Wormhole = class {
62
+ constructor(value) {
63
+ this.value = value;
64
+ }
65
+ value;
66
+ millisecond(callback) {
67
+ return this.milliseconds(callback);
68
+ }
69
+ milliseconds(callback) {
70
+ return this.#move((date) => date.setTime(date.getTime() + this.value), callback);
71
+ }
72
+ second(callback) {
73
+ return this.seconds(callback);
74
+ }
75
+ seconds(callback) {
76
+ return this.#move((date) => date.setTime(date.getTime() + this.value * 1e3), callback);
77
+ }
78
+ minute(callback) {
79
+ return this.minutes(callback);
80
+ }
81
+ minutes(callback) {
82
+ return this.#move((date) => date.setTime(date.getTime() + this.value * 6e4), callback);
83
+ }
84
+ hour(callback) {
85
+ return this.hours(callback);
86
+ }
87
+ hours(callback) {
88
+ return this.#move((date) => date.setTime(date.getTime() + this.value * 36e5), callback);
89
+ }
90
+ day(callback) {
91
+ return this.days(callback);
92
+ }
93
+ days(callback) {
94
+ return this.#move((date) => date.setUTCDate(date.getUTCDate() + this.value), callback);
95
+ }
96
+ week(callback) {
97
+ return this.weeks(callback);
98
+ }
99
+ weeks(callback) {
100
+ return this.#move((date) => date.setUTCDate(date.getUTCDate() + this.value * 7), callback);
101
+ }
102
+ month(callback) {
103
+ return this.months(callback);
104
+ }
105
+ months(callback) {
106
+ return this.#move((date) => date.setUTCMonth(date.getUTCMonth() + this.value), callback);
107
+ }
108
+ year(callback) {
109
+ return this.years(callback);
110
+ }
111
+ years(callback) {
112
+ return this.#move((date) => date.setUTCFullYear(date.getUTCFullYear() + this.value), callback);
113
+ }
114
+ /** Laravel's Wormhole::back(). */
115
+ static back() {
116
+ return travelBack();
117
+ }
118
+ #move(step, callback) {
119
+ const date = new (realDate())(testNow ?? Date.now());
120
+ step(date);
121
+ setTestNow(date);
122
+ if (callback) return thenTravelBack(callback);
123
+ }
124
+ };
125
+
1
126
  // Console/PendingCommand.ts
2
127
  import { ConsoleKernel } from "@orieljs/contracts";
3
128
 
@@ -276,19 +401,6 @@ var DatabaseTransactions = {
276
401
  // Concerns/MakesHttpRequests.ts
277
402
  import { AuthFactory as AuthFactory2, token } from "@orieljs/contracts";
278
403
 
279
- // Http/HttpClient.ts
280
- import {
281
- AuthFactory,
282
- ConfigRepository as ConfigRepository3,
283
- Encrypter as Encrypter2,
284
- ExceptionHandler,
285
- HttpKernel,
286
- HttpRequest,
287
- Session,
288
- ViewFactory
289
- } from "@orieljs/contracts";
290
- import { IncomingRequest } from "@orieljs/http";
291
-
292
404
  // environment.ts
293
405
  var TESTING_ENVIRONMENT = Object.freeze({
294
406
  APP_ENV: "testing",
@@ -313,6 +425,19 @@ function clonePlain(value) {
313
425
  return value;
314
426
  }
315
427
 
428
+ // Http/HttpClient.ts
429
+ import {
430
+ AuthFactory,
431
+ ConfigRepository as ConfigRepository3,
432
+ Encrypter as Encrypter2,
433
+ ExceptionHandler,
434
+ HttpKernel,
435
+ HttpRequest,
436
+ Session,
437
+ ViewFactory
438
+ } from "@orieljs/contracts";
439
+ import { IncomingRequest } from "@orieljs/http";
440
+
316
441
  // TestResponse.ts
317
442
  import { Encrypter, UrlGenerator } from "@orieljs/contracts";
318
443
  import { Arr as Arr3 } from "@orieljs/support";
@@ -1424,6 +1549,11 @@ var HttpClient = class {
1424
1549
  defaultGuard;
1425
1550
  /** Session attributes carried from one request to the next (Laravel keeps one session store per test). */
1426
1551
  session;
1552
+ /**
1553
+ * withSession() and flushSession() since the last started session: applied to the stored session (the one the
1554
+ * session cookie points to) once the next request starts it, so they win over what it holds, as in Laravel.
1555
+ */
1556
+ sessionChanges = [];
1427
1557
  /** from(url): the session's previous URL for the next request only (Laravel sets it once). */
1428
1558
  previousUrl;
1429
1559
  /** Requests whose actingAs users reached the guards (the AuthFactory they went through). */
@@ -1459,6 +1589,7 @@ var HttpClient = class {
1459
1589
  const context = { request, app: this.app, client: this };
1460
1590
  const result = await scope.run(async () => {
1461
1591
  this.beforeRequest(scope, context);
1592
+ if (context.session !== void 0) this.applyPending(context.session);
1462
1593
  scope.instance(HttpRequest, new IncomingRequest(request));
1463
1594
  if (scope.bound(AuthFactory)) {
1464
1595
  try {
@@ -1499,6 +1630,7 @@ var HttpClient = class {
1499
1630
  const session = this.scopeSession(scope);
1500
1631
  if (session !== void 0) {
1501
1632
  if (this.session !== void 0) session.put(clonePlain(this.session));
1633
+ if (this.sessionChanges.length > 0) this.applyOnStart(session);
1502
1634
  if (this.previousUrl !== void 0) session.setPreviousUrl(this.previousUrl);
1503
1635
  context.session = session;
1504
1636
  }
@@ -1531,6 +1663,20 @@ var HttpClient = class {
1531
1663
  else this.users.set(guard, user);
1532
1664
  }
1533
1665
  }
1666
+ /** Applies the pending withSession()/flushSession() changes once the session has loaded what it stored. */
1667
+ applyOnStart(session) {
1668
+ const start = session.start.bind(session);
1669
+ session.start = async () => {
1670
+ await start();
1671
+ this.applyPending(session);
1672
+ };
1673
+ }
1674
+ /** Applies the pending withSession()/flushSession() changes to the session, once. */
1675
+ applyPending(session) {
1676
+ if (this.sessionChanges.length === 0) return;
1677
+ for (const change of this.sessionChanges.splice(0)) change(session);
1678
+ if (!session.has("_token")) session.regenerateToken();
1679
+ }
1534
1680
  /** The request's (scoped) Session, created now so the carried attributes are in place before StartSession. */
1535
1681
  scopeSession(scope) {
1536
1682
  if (!scope.bound(Session)) return void 0;
@@ -1805,14 +1951,17 @@ var MakesHttpRequests = class extends InteractsWithApplication {
1805
1951
  this.http.previousUrl = url;
1806
1952
  return this.withHeader("Referer", url);
1807
1953
  }
1808
- /** Puts data in the session for the following requests (Laravel's withSession()). */
1954
+ /** Puts data in the session for the following requests, over what the stored session holds (Laravel's withSession()). */
1809
1955
  withSession(data) {
1810
- this.http.session = { ...this.http.session, ...data };
1956
+ const values = clonePlain(data);
1957
+ this.http.session = { ...this.http.session, ...values };
1958
+ this.http.sessionChanges.push((session) => session.put(clonePlain(values)));
1811
1959
  return this;
1812
1960
  }
1813
- /** Empties the session carried between requests. */
1961
+ /** Empties the session, the stored one included, so the next request starts with none (Laravel's flushSession()). */
1814
1962
  flushSession() {
1815
1963
  this.http.session = {};
1964
+ this.http.sessionChanges.splice(0, Infinity, (session) => session.flush());
1816
1965
  return this;
1817
1966
  }
1818
1967
  /** Every following request is authenticated as `user` on `guard` (which also becomes the default guard). */
@@ -1956,14 +2105,40 @@ var InteractsWithConsole = class extends InteractsWithDatabase {
1956
2105
  }
1957
2106
  };
1958
2107
 
2108
+ // Concerns/InteractsWithTime.ts
2109
+ var InteractsWithTime = class extends InteractsWithConsole {
2110
+ travelTo(date, callback) {
2111
+ return callback ? travelTo(date, callback) : travelTo(date);
2112
+ }
2113
+ travel(value) {
2114
+ return travel(value);
2115
+ }
2116
+ travelBack() {
2117
+ return travelBack();
2118
+ }
2119
+ freezeTime(callback) {
2120
+ return callback ? freezeTime(callback) : freezeTime();
2121
+ }
2122
+ freezeSecond(callback) {
2123
+ return callback ? freezeSecond(callback) : freezeSecond();
2124
+ }
2125
+ async tearDown() {
2126
+ try {
2127
+ await super.tearDown();
2128
+ } finally {
2129
+ travelBack();
2130
+ }
2131
+ }
2132
+ };
2133
+
1959
2134
  // TestCase.ts
1960
- var TestCase = class extends InteractsWithConsole {
2135
+ var TestCase = class extends InteractsWithTime {
1961
2136
  };
1962
2137
 
1963
2138
  // Fakes/support.ts
1964
2139
  import { currentContainer } from "@orieljs/container";
1965
2140
  import { facade } from "@orieljs/support";
1966
- function install(token2, fake) {
2141
+ function install2(token2, fake) {
1967
2142
  facade(token2).swap(fake);
1968
2143
  return fake;
1969
2144
  }
@@ -1999,6 +2174,24 @@ function isQueueable(job) {
1999
2174
 
2000
2175
  // Fakes/EventFake.ts
2001
2176
  import { EventDispatcher } from "@orieljs/contracts";
2177
+ import { Str } from "@orieljs/support";
2178
+ var isClass = (value) => typeof value === "function" && typeof value.prototype?.handle === "function";
2179
+ var asPair = (listener) => {
2180
+ if (Array.isArray(listener) && listener.length === 2 && typeof listener[1] === "string") return [listener[0], listener[1]];
2181
+ return isClass(listener) ? [listener, "handle"] : void 0;
2182
+ };
2183
+ function listenerMatches(registered, expected) {
2184
+ if (expected === Function) return typeof registered === "function" && !isClass(registered);
2185
+ const [left, right] = [asPair(registered), asPair(expected)];
2186
+ if (left && right) return left[0] === right[0] && left[1] === right[1];
2187
+ return registered === expected;
2188
+ }
2189
+ function listenerName(listener) {
2190
+ const pair = asPair(listener);
2191
+ if (pair === void 0) return "Closure";
2192
+ const [owner, method] = pair;
2193
+ return Array.isArray(listener) ? `${owner.name}@${method}` : owner.name;
2194
+ }
2002
2195
  var EventFake = class _EventFake {
2003
2196
  constructor(dispatcher, eventsToFake = [], eventsToDispatch = []) {
2004
2197
  this.dispatcher = dispatcher;
@@ -2011,11 +2204,11 @@ var EventFake = class _EventFake {
2011
2204
  events = [];
2012
2205
  /** Installs the fake (on the current container) and returns it: `const events = EventFake.fake([OrderShipped])`. */
2013
2206
  static fake(eventsToFake = []) {
2014
- return install(EventDispatcher, new _EventFake(_EventFake.original(), [eventsToFake].flat()));
2207
+ return install2(EventDispatcher, new _EventFake(_EventFake.original(), [eventsToFake].flat()));
2015
2208
  }
2016
2209
  /** Fakes every event except these. */
2017
2210
  static fakeExcept(eventsToDispatch) {
2018
- return install(EventDispatcher, new _EventFake(_EventFake.original(), [], [eventsToDispatch].flat()));
2211
+ return install2(EventDispatcher, new _EventFake(_EventFake.original(), [], [eventsToDispatch].flat()));
2019
2212
  }
2020
2213
  static original() {
2021
2214
  const current = bound(EventDispatcher);
@@ -2072,9 +2265,20 @@ var EventFake = class _EventFake {
2072
2265
 
2073
2266
  - ${names.join("\n- ")}`);
2074
2267
  }
2075
- /** The original dispatcher has a listener for the event. */
2076
- assertListening(event) {
2077
- assert(this.hasListeners(event), `Event [${nameOf(event)}] does not have any listeners.`);
2268
+ /**
2269
+ * Laravel's assertListening(event, listener): the original dispatcher has that listener for the event (a class, a
2270
+ * [class, method] pair, the same closure, or Function for any closure; wildcard listeners count for a string event).
2271
+ * With only the event, any listener will do.
2272
+ */
2273
+ assertListening(event, listener) {
2274
+ if (listener === void 0) {
2275
+ assert(this.hasListeners(event), `Event [${nameOf(event)}] does not have any listeners.`);
2276
+ return;
2277
+ }
2278
+ assert(
2279
+ this.listenersFor(event).some((registered) => listenerMatches(registered, listener)),
2280
+ `Event [${nameOf(event)}] does not have the [${listenerName(listener)}] listener attached to it`
2281
+ );
2078
2282
  }
2079
2283
  /** The recorded events (objects, or names for string events) that match. */
2080
2284
  dispatched(event, callback) {
@@ -2083,6 +2287,17 @@ var EventFake = class _EventFake {
2083
2287
  hasDispatched(event) {
2084
2288
  return this.dispatched(event).length > 0;
2085
2289
  }
2290
+ /** The original dispatcher's listeners for the event, as registered, wildcard ones included for a string event. */
2291
+ listenersFor(event) {
2292
+ const raw = this.dispatcher?.getRawListeners?.();
2293
+ if (raw === void 0) return [];
2294
+ const listeners = [...raw.get(event) ?? []];
2295
+ if (typeof event !== "string") return listeners;
2296
+ for (const [key, list] of raw) {
2297
+ if (typeof key === "string" && key !== event && key.includes("*") && Str.is(key, event)) listeners.push(...list);
2298
+ }
2299
+ return listeners;
2300
+ }
2086
2301
  shouldFake(event) {
2087
2302
  if (matchesAny(event, this.eventsToDispatch)) return false;
2088
2303
  return this.eventsToFake.length === 0 || matchesAny(event, this.eventsToFake);
@@ -2140,10 +2355,10 @@ var BusFake = class _BusFake {
2140
2355
  /** The rest of the chain, by the first job (Bus.chain([a, b, c]) records a with [b, c]). */
2141
2356
  chains = /* @__PURE__ */ new Map();
2142
2357
  static fake(jobsToFake = []) {
2143
- return install(BusDispatcher, new _BusFake(_BusFake.original(), [jobsToFake].flat()));
2358
+ return install2(BusDispatcher, new _BusFake(_BusFake.original(), [jobsToFake].flat()));
2144
2359
  }
2145
2360
  static fakeExcept(jobsToDispatch) {
2146
- return install(BusDispatcher, new _BusFake(_BusFake.original(), [], [jobsToDispatch].flat()));
2361
+ return install2(BusDispatcher, new _BusFake(_BusFake.original(), [], [jobsToDispatch].flat()));
2147
2362
  }
2148
2363
  static original() {
2149
2364
  const current = bound(BusDispatcher);
@@ -2352,10 +2567,10 @@ var QueueFake = class _QueueFake {
2352
2567
  jobsToPush;
2353
2568
  jobs = [];
2354
2569
  static fake(jobsToFake = []) {
2355
- return install(QueueManager, new _QueueFake(_QueueFake.original(), [jobsToFake].flat()));
2570
+ return install2(QueueManager, new _QueueFake(_QueueFake.original(), [jobsToFake].flat()));
2356
2571
  }
2357
2572
  static fakeExcept(jobsToPush) {
2358
- return install(QueueManager, new _QueueFake(_QueueFake.original(), [], [jobsToPush].flat()));
2573
+ return install2(QueueManager, new _QueueFake(_QueueFake.original(), [], [jobsToPush].flat()));
2359
2574
  }
2360
2575
  static original() {
2361
2576
  const current = bound(QueueManager);
@@ -2537,13 +2752,14 @@ var MailFake = class _MailFake {
2537
2752
  records = [];
2538
2753
  static fake() {
2539
2754
  const current = bound(MailManager);
2540
- return install(MailManager, new _MailFake(current instanceof _MailFake ? current.manager : current));
2755
+ return install2(MailManager, new _MailFake(current instanceof _MailFake ? current.manager : current));
2541
2756
  }
2542
2757
  // MailManager ----------------------------------------------------------------------------------------------
2543
2758
  mailer(name) {
2544
2759
  return {
2545
2760
  to: (recipients) => this.pending(name, recipients),
2546
2761
  send: (mailable) => this.sendVia(name, mailable, empty()),
2762
+ sendNow: (mailable) => this.sendNowVia(name, mailable, empty()),
2547
2763
  queue: (mailable) => this.queueVia(name, mailable, empty(), void 0)
2548
2764
  };
2549
2765
  }
@@ -2553,6 +2769,10 @@ var MailFake = class _MailFake {
2553
2769
  send(mailable) {
2554
2770
  return this.sendVia(void 0, mailable, empty());
2555
2771
  }
2772
+ /** Recorded as sent, never queued, like the real sendNow(). */
2773
+ sendNow(mailable) {
2774
+ return this.sendNowVia(void 0, mailable, empty());
2775
+ }
2556
2776
  queue(mailable) {
2557
2777
  return this.queueVia(void 0, mailable, empty(), void 0);
2558
2778
  }
@@ -2636,6 +2856,7 @@ var MailFake = class _MailFake {
2636
2856
  return pending;
2637
2857
  },
2638
2858
  send: (mailable) => this.sendVia(mailer, mailable, overrides),
2859
+ sendNow: (mailable) => this.sendNowVia(mailer, mailable, overrides),
2639
2860
  queue: (mailable) => this.queueVia(mailer, mailable, overrides, void 0),
2640
2861
  later: (delay, mailable) => this.queueVia(mailer, mailable, overrides, delay)
2641
2862
  };
@@ -2645,6 +2866,10 @@ var MailFake = class _MailFake {
2645
2866
  await this.record(mailer, mailable, overrides, isQueueable(mailable), void 0);
2646
2867
  return void 0;
2647
2868
  }
2869
+ async sendNowVia(mailer, mailable, overrides) {
2870
+ await this.record(mailer, mailable, overrides, false, void 0);
2871
+ return void 0;
2872
+ }
2648
2873
  async queueVia(mailer, mailable, overrides, delay) {
2649
2874
  await this.record(mailer, mailable, overrides, true, delay);
2650
2875
  }
@@ -2719,7 +2944,7 @@ var NotificationFake = class _NotificationFake {
2719
2944
  notifications = [];
2720
2945
  static fake() {
2721
2946
  const current = bound(NotificationDispatcher);
2722
- return install(NotificationDispatcher, new _NotificationFake(current instanceof _NotificationFake ? current.dispatcher : current));
2947
+ return install2(NotificationDispatcher, new _NotificationFake(current instanceof _NotificationFake ? current.dispatcher : current));
2723
2948
  }
2724
2949
  // NotificationDispatcher -------------------------------------------------------------------------------------
2725
2950
  async send(notifiables, notification) {
@@ -3087,7 +3312,7 @@ var StorageFake = class _StorageFake {
3087
3312
  static fake(disk) {
3088
3313
  const current = bound(FilesystemManager);
3089
3314
  const config = bound(ConfigRepository4);
3090
- const fake = current instanceof _StorageFake ? current : install(FilesystemManager, new _StorageFake(current, config?.get("filesystems.default", "local") ?? "local"));
3315
+ const fake = current instanceof _StorageFake ? current : install2(FilesystemManager, new _StorageFake(current, config?.get("filesystems.default", "local") ?? "local"));
3091
3316
  const name = disk ?? fake.defaultDisk;
3092
3317
  const faked = new FakeDisk(name);
3093
3318
  fake.disks.set(name, faked);
@@ -3413,6 +3638,7 @@ export {
3413
3638
  InteractsWithApplication,
3414
3639
  InteractsWithConsole,
3415
3640
  InteractsWithDatabase,
3641
+ InteractsWithTime,
3416
3642
  MailFake,
3417
3643
  MailRecord,
3418
3644
  MakesHttpRequests,
@@ -3426,6 +3652,7 @@ export {
3426
3652
  TESTING_ENVIRONMENT,
3427
3653
  TestCase,
3428
3654
  TestResponse,
3655
+ Wormhole,
3429
3656
  actingAsAuthFactory,
3430
3657
  addresses,
3431
3658
  applyEnvironment,
@@ -3434,9 +3661,11 @@ export {
3434
3661
  decryptCookie,
3435
3662
  encryptCookie,
3436
3663
  flatten,
3664
+ freezeSecond,
3665
+ freezeTime,
3437
3666
  guessMimeType,
3438
3667
  inertiaPageOf,
3439
- install,
3668
+ install2 as install,
3440
3669
  isExpired,
3441
3670
  isQueueable,
3442
3671
  matches,
@@ -3446,6 +3675,9 @@ export {
3446
3675
  recordingViewFactory,
3447
3676
  responseCookies,
3448
3677
  runCommand,
3678
+ travel,
3679
+ travelBack,
3680
+ travelTo,
3449
3681
  usingInMemoryDatabase
3450
3682
  };
3451
3683
  //# sourceMappingURL=index.js.map