Repository navigation
Expand file tree
/
Copy pathllms.txt
More file actions
572 lines (494 loc) · 30.8 KB
/
Copy pathllms.txt
File metadata and controls
572 lines (494 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# rasuvaeff/understudy
Test double library for PHP 8.3 - 8.5 with a call-closure API.
## Install
```bash
composer require --dev rasuvaeff/understudy
```
Namespace: `Rasuvaeff\Understudy`. Requires PHP 8.3 - 8.5 and `ext-tokenizer`.
No runtime deps; `ext-mbstring` is not needed.
## Rules
- A call is specified by making it inside a closure, never by a method-name
string: `when(fn () => $repo->find(123))`.
- A parameter the specification does not spell means "whatever was passed"
where the contract declares it optional, and is refused unless `Arg::rest()`
covers it where the contract declares it required. A real call still logs the
contract's default for an argument the caller omitted, so `tag('a')` and
`tag('a', 1)` are one call.
- The closure must contain **exactly one** direct call on a double, and it
runs exactly once. Two calls — nested in the arguments of another
(`fn () => $repo->find($repo->count())`) or side by side — raise
`InvalidCallSpecification` naming both. The recording answers the call with
the type's default and lets the closure finish; code after the call that
does not survive the default does not fail the specification.
- `returns()` is checked against the declared return type at registration:
a value on `: void` (`returns(null)` is allowed), anything on `: never`, and
a value the type cannot hold (`null` on a non-nullable type, an array or an
object on a scalar, an object of the wrong class) raise
`InvalidCallSpecification`/`InvalidSpecificationArgument` with the double's
label. No stricter than the engine: generated methods are not under
`strict_types`, so `returns('5')` on `: int` answers `5`. `answers()` is
judged only at the call; a wrong type there is PHP's own `TypeError`.
- A double exposes nothing beyond its contract. All operations are static
methods on `Understudy`, or the free functions `when()` / `expect()` /
`expectSequence()` / `verify()`.
- Interfaces and classes. A class may be the first target only (PHP has single
inheritance); interfaces follow it. The target's constructor and destructor
never run, private and static methods are left alone, protected ones are
dispatched but unconfigurable, a writable public property keeps a declared
default and otherwise starts empty -- including one PROMOTED through the
constructor, which is skipped, so it differs from the real object -- and a
`clone` is a double of its own.
- Refused before generation, each with the reason: a `final` class, a class with
a non-private `final` instance method, an enum, a trait, an internal class, an
anonymous class, a class that is not the first target; and — checked on the
contract and every interface it extends — `Throwable`, `DateTimeInterface`,
`UnitEnum`/`BackedEnum`, `Traversable` without `Iterator`/`IteratorAggregate`,
plus an interface declaring `__construct`. All `UnsupportedTarget`, never a
fatal out of `eval()`. A double cannot be thrown: construct a real exception
for `throws()`.
- A class double is never partial: a concrete method of an abstract target is
dispatched, its body does not run. Real code needs a real instance and
`forwarding()`; `Invocation::callOriginal()` needs the same. A `readonly`
promoted property of a class target stays uninitialized (reading it raises
PHP's own error); a plain typed one starts at the empty value of its type.
- An abstract hooked property (PHP 8.4+: an interface property, or an
`abstract` one on a class) is rendered: the generated class declares it with
the dispatcher inside the hook. Exactly the declared hooks; a get-only
property refuses a write with PHP's own error. A read answers the forwarding
target's value, else what the code under test wrote (`{ get; set; }` behaves
like a plain property), else the same default table as method returns
(`defaults()` registrations, depth-1 nested double). A property read is NOT
a call: not recorded, not specifiable, not judged by strict mode — the
"exactly one direct call" rule is about calls, and reads are invisible to
it. Still refused: a readonly class target carrying an abstract hook, and a
`&get` hook. A concrete hook on a class target stays inherited.
- Parameter defaults are reproduced, not approximated. An object default is
rendered from its own source expression — `new Foo(1)` and `[new Foo(1)]`
alike — which is never evaluated during generation. Refusal is narrow: a
default whose source names `self`, `static` or `parent` (they would resolve
against the generated class), or an object value with no source form to
render. A default is never silently replaced with `null`.
- `Understudy::forwarding($double, $real)` delegates every unmatched call to
`$real` and records it. `$real` must satisfy every contract of the double.
`Understudy::forwarding($double)` only turns the mode on for a double built by
`Understudy::for($real)`. Configured calls still win; an expectation that only
counts still forwards.
- `Understudy::delegate(Contract::class, $real)` is `for()` + `forwarding()` in
one expression and returns the double. The target is validated the same way.
- `Invocation::callOriginal()` delegates one call from inside `answers()`,
whatever the mode. On an inline double it runs the parent body on the double;
otherwise on the real instance. Without a target it raises
`OriginalCallUnavailable` — nothing copied the state, so the parent
implementation would read properties the skipped constructor never filled.
- A CLASS double forwards inline: the doubled class's bodies run on the double,
over state copied from the instance when `forwarding()` was called, so a
self-call re-enters the double and meets stubs, protocols and the call log.
It needs the instance to be exactly the doubled class — a subclass instance
keeps the proxy form — and an inline double cannot be re-pointed at a second
instance (`ForwardingTargetMismatch`). `static::class` inside a real body is
the generated class; `final` and `private` methods are not intercepted.
- An INTERFACE double proxies: it records the boundary call only, and a real
method calling itself is not visible. A fluent method that returned the real
instance comes back as the double; a `: static` method returning another
instance of the real class raises `OriginalReturnTypeViolation`. Inline, a
`clone $this` is adopted while the body runs and comes back forwarding (no
stubs copied); a `new static` raises `OriginalReturnTypeViolation`, because
no context knows that object.
- `Understudy::bypassFinals(FinalX::class)` lifts `final` off one class before
it loads; `Understudy::bypassFinals()` does it for every class the process
loads from then on. Opt-in, and order-dependent: it works only for classes not
yet read from disk. `final` on methods is never lifted, so a class carrying one
is still refused. Not available for a PHAR or a preloaded class: that source
never passes through `file://`. A warm opcode cache does not reseal a
bypassed class; whether the file lands in the cache at all differs by
platform and is not something to rely on. When a class is still final
at `for()`, the refusal distinguishes bypass never enabled, enabled for other
classes but not this one, and enabled but out of reach.
- `Understudy::defaults(Contract::class, fn () => $value)` says what a loose
default should be. Nearest registration wins by distance in the type graph;
an equal-distance tie raises `AmbiguousDefaultFactory`, a wrong-typed result
raises `InvalidDefaultValue`. Per context, dropped by `reset()`. It outranks
`null` on a nullable return: `?Book` answers with the registered Book, and
is `null` only when nothing was registered for it.
- Without a registration, a doublable return type becomes a double of its own,
one level deep, adopted into the context that owns the outer double — a
fresh one per call (`$o->inner() !== $o->inner()`); stub the method when the
collaborator must be stable.
- `Understudy::wire(Sut::class, $overrides)` returns
`array{sut: object, doubles: array<string, object>}`. It reads the constructor
only. Object parameters become doubles; a nullable object still does; an
intersection becomes one double of both; a union of several object types, a
scalar without a default, and a by-reference parameter are refused. A variadic
tail is left empty unless an override fills it, which takes a list and checks
every element against the declared type. Overrides replace by parameter name
and are not repeated in `doubles`. Every refusal happens before the constructor
runs. Filling a variadic tail passes the parameters before it positionally, so
an omitted optional one has its declared default materialized.
- A method declared `&method()` returns a reference into a stable per-double,
per-method slot, so a mutation through it survives to the next read. The slot
is seeded by the mode's own answer and then kept; a configured answer replaces
it, a loose default does not.
- `Invocation::args` is what the call received; `Invocation::argsAfter()` is what
the arguments became once it was answered, and is null unless the method has a
by-reference parameter.
- A `clone` belongs to the context that cloned it, like anything `for()` builds:
`__clone()` gets no reference to the original, so its owner cannot be
recovered. Clone in the scope that will configure or verify the copy.
- Static contract methods are implemented only so the generated class is
concrete. Calling one raises `InvalidCallSpecification`; inject an instance
dependency instead.
- The call log retains returned values until `reset()`, which runner adapters
call *after* `#[AfterTest]`/`tearDown()` — a returned stream is still open
while your teardown runs. `Understudy::lean($double)` keeps invocations
(method, args, sequence — matching, `verify()`, `transcript()`,
`nothingElse()` unchanged) but not returned values; `returned()` then raises
`OutcomeUnavailable`. One-way. Alternatively build and use the double inside
`Understudy::scope()`, which drops the context before lifecycle teardown.
- `Understudy::reset()` after each test. Nothing is process-global on purpose:
state lives per execution context and each Fiber gets its own — that is
isolation, and it covers the recording phase, the call log and the sequence
counter.
- Accounting is wider than isolation: `verifyAll()`, `reset()`, `idle()` and
`checkpoint()` span EVERY context still holding doubles, not just the
caller's. A test body run in a Fiber owns a context the adapter never stands
in, and skipping it let an unmet `expect()` pass unnoticed.
- Without `label()`, the second and later doubles of one contract in a context
are numbered in reports: `Repo`, `Repo#2`. An explicit label outranks it.
- A failure message renders an object argument as `App\Book#1 {title: 'Dune'}`.
The `#N` is an alias numbered within that one message in order of first
appearance — never an object id, which is reused after a collection — so the
same instance keeps one number and a rebuilt copy gets another. The braces
list public properties only, up to five: no getter is called to render a
message, and an object with nothing public renders as its alias alone.
- A strict double's refusal names the call and everything configured for that
method that did not accept it, with each rejecting argument marked from the
expectation's side — including a position the call never carried. Up to five,
then a count. With nothing configured for the method there is nothing to
compare against, and the message stays one line.
## API
### Creating
```php
use Rasuvaeff\Understudy\Understudy;
$repo = Understudy::for(BookRepository::class); // returns BookRepository
$both = Understudy::for(BookRepository::class, Countable::class); // several interfaces
$cls = Understudy::for(DoctrineBookRepository::class); // a class target
$spy = Understudy::for($realInstance); // wraps it, does not delegate yet
```
`for(class-string<T> $target, class-string ...$interfaces): T`
For several interfaces, parameters are widened contravariantly, returns use the
narrowest compatible declaration or a synthesised interface intersection, and
parameter names come from the first (primary) interface so named arguments are
deterministic.
### Stubbing — `when()`
`when()` returns a `WhenBuilder<TReturn>`; each of its methods returns the same
builder, so actions can be replaced while configuring.
```php
use function Rasuvaeff\Understudy\when;
use Rasuvaeff\Understudy\Arg;
use Rasuvaeff\Understudy\Invocation;
when(fn () => $repo->find(1))->returns($book);
when(fn () => $repo->find(1))->returns($first, $second); // one per call, last repeats
when(fn () => $repo->find(1))->throws(new NotFound());
when(fn () => $repo->save(Arg::any()))->throwsWith( // built per call, from the call
fn (Invocation $call) => new Rejected($call->arg('book')),
);
when(fn () => $repo->find(Arg::any()))->answers(
fn (Invocation $call) => new Book((string) $call->args[0]),
);
```
Matching: two tiers, whichever order they were declared in — a specification
that pins at least one argument (a literal, any matcher except `Arg::any()`,
or a tail pinned empty by `Arg::none()`) is tried before one that says
nothing about any argument (`Arg::any()` everywhere, an unspelled optional,
`Arg::rest()`/`remaining()`); within a tier most recently registered wins and
earlier stubs remain as fallbacks on argument mismatch — a catch-all
registered after a specific stub steals nothing. A matching call-count
expectation keeps answering after its count is exhausted. Two specifics are
never compared for narrowness; registration order decides. Arguments match
by `===`, or by matcher.
### Joint constraints — `where()`
```php
when(fn () => $ledger->transfer(Arg::any(), Arg::any()))
->where(fn ($from, $to) => $from <= $to)
->returns(true);
verify(fn () => $ledger->transfer(Arg::any(), Arg::any()),
times: 1, where: fn ($from, $to) => $from <= $to);
```
`->where($guard, $description = 'where(…)')` narrows a specification by a
predicate over the WHOLE argument list, positionally — the Mockery
`withArgs(closure)` row. Asked only after every position matched; a refused
call falls through to broader expectations. `expect()` takes one too. One
guard per expectation (a second is refused); the guard runs inside the code
under test and its exceptions are the test's own. When positions matched but
the guard refused, the failure marks the guard: `transfer(any(), any())
*where(…)*`.
### Matchers — `Arg`
| Matcher | Matches |
|---|---|
| `any()` | anything, including null |
| `int(min:, max:)` | an `int` in range; a numeric string does not match |
| `float(min:, max:)` | a `float` in range; an `int` does not match |
| `string(matches:)` | a string, optionally against a PCRE pattern |
| `bool()` | a boolean |
| `same($v)` | strict identity; for objects the same instance |
| `not($v)` | negates a literal or another matcher |
| `allOf(...)` | everything every operand accepts; an operand is a matcher or a literal |
| `anyOf(...)` | anything at least one operand accepts |
| `instanceOf($class)` | an instance of the class or interface; a name that is not loadable is refused, not silently never-matching |
| `satisfies($fn, $description)` | whatever the predicate accepts |
| `containing($entries)` | an array holding these entries and possibly more |
| `count(minimum:, maximum:)` | an array or `Countable` of that size |
| `which($method, $value)` | an object whose getter answers this value |
| `none()` | an empty variadic tail; last argument only |
| `remaining()` | the whole variadic tail, any length; last argument only |
| `rest()` | declared parameters left unspelled; last argument only — the one matcher that lets a specification stop before a REQUIRED parameter: `when(fn () => $s->recordOutcome('svc', Arg::rest()))`. Stopping before one without it is refused |
An optional parameter needs no matcher: the contract lets a caller omit it, so
a specification that omits it says nothing about it and matches whatever was
passed there. Failure messages render such a position as `…`, never as
`any()`. A matcher inside a plain array argument is refused (an array is
compared by identity) — `Arg::containing()` describes part of an array and
reads matchers in its entries, nested.
Every `Arg::*` returns `mixed`, so passing one where the contract says `int`
is not a type error in an IDE. `which()` calls only a public, non-static
method needing no arguments; anything else, including a getter that throws, is
a mismatch rather than an error — but a predicate handed to `satisfies()` is
the test's own code, so an exception in it travels. A matcher that could never
match is refused at construction with `InvalidSpecificationArgument`: an
inverted range (`int`/`float`/`count`), a pattern PCRE cannot compile, and
`instanceOf()` naming a type that is not loadable. A matcher that reaches a
real call on a *double* raises `MatcherLeaked`; one handed to a real object is
out of the engine's sight and is simply a wrong argument (the PHPStan plugin's
`understudy.matcherLeak` is the textual guard).
`Arg::captor(?class-string $class = null): Captor` builds a typed argument
captor — the replacement for reading `args[N]` out of the call log:
```php
$options = Arg::captor(DeliveryOptions::class); // Captor<DeliveryOptions>
when(fn () => $store->temporaryUrl(Arg::any(), Arg::any(), $options->capture()))
->returns('https://…');
$subject->run();
$options->last(); // DeliveryOptions, typed; NothingCaptured when empty
$options->all(); // list<DeliveryOptions>, in call order
```
`capture()` matches like `instanceOf($class)` (untyped: like `any()`); the
value is recorded only once the whole specification matched. A captor inside
`allOf()`/`anyOf()`/`not()`/`containing()` is refused where it is written: it
would match and record nothing. Works in
`when()`, `expect()` and `verify()` (a `verify()` captures from the calls it
claimed, on success only); in an `expectSequence()` step it matches but does
not record. Captured values are dropped with the context —
`reset()`, a closing `scope()` — and the captor is then empty again.
### Expecting — `expect()`
`expect()` returns an `ExpectBuilder<TReturn>`, which extends
`WhenBuilder<TReturn>` and adds `ordered()`.
```php
use function Rasuvaeff\Understudy\expect;
expect(fn () => $repo->save($book)); // exactly once
expect(fn () => $repo->count())->times(2); // exactly twice
expect(fn () => $repo->count())->times(1, 3); // a range
expect(fn () => $repo->count())->times(1, null); // no upper bound
expect(fn () => $repo->find(1))->returns($book); // behaviour too
Understudy::verifyAll(); // checks them all
Understudy::verifyAll(strictStubs: true); // and unused stubs
```
`expect()` is a claim about how often a call happens, checked by
`verifyAll()`. A plain `when()` stub is permission rather than a claim, and
becomes checkable only through `times()`. `verifyAll()` returns
`int<0, max>` — how many checks it verified: one per claim, one per plain
stub under `strictStubs`, one per ordering constraint, one per armed
protocol. It throws on any failed check, so the number counts passed checks
only; `verify()` checks made earlier are not recounted.
A stub and an expectation for the exact same call do not stack: both orders
are refused at registration with `ConflictingExpectation`. Combine behaviour
and count in one registration — `expect(...)->returns(...)` or
`when(...)->times(n)` — and declare a repeated count once with `times()`.
A broad stub under a narrower expectation (overlap, not equality) still
composes as documented.
An expectation without an action still answers: counting and answering are
separate concerns, so `expect(fn () => $repo->count())` is complete on its own
and the mode's type-safe default supplies the value. A matched expectation
also satisfies a strict double — the call was expected.
Pest declares its own global `expect()`. Import this one as
`use function Rasuvaeff\Understudy\expect as expectCall;`, or call
`Understudy::expect()`.
### Chaining behaviour — `then()`
```php
when(fn () => $breaker->call($operation))
->returns('ok')
->then()->throws(new ConnectionLost())
->then()->answers(fn (Invocation $i) => 'recovered');
```
One link per call; the last link keeps answering after the chain runs out.
A verb without `then()` refines the same link rather than adding one.
### Verifying — `verify()`
```php
use function Rasuvaeff\Understudy\verify;
verify(fn () => $repo->save($book)); // at least once
verify(fn () => $repo->save($book), times: 2); // exactly
verify(fn () => $repo->save($book), minimum: 2); // lower bound only
verify(fn () => $repo->save($book), maximum: 5);
verify(fn () => $repo->ping(), never: true);
Understudy::unused($repo); // no calls at all
```
### The ledger — has everything been described?
```php
Understudy::nothingElse($repo); // every call was accounted for
Understudy::nothingElse($repo, $clock, $mailer); // across several doubles
Understudy::allVerified($repo); // expectations met AND nothing else
Understudy::verifySequence( // the exact protocol, across doubles
fn () => $repo->begin(),
fn () => $repo->save($book),
fn () => $repo->commit(),
);
```
A call is *accounted for* when an `expect()` matched it or a **successful**
`verify()` claimed it. A `when()` stub accounts for nothing — it is
permission, not a description. A failed `verify()` accounts for nothing
either.
`expect(...)->ordered()` requires the ordered expectations to be satisfied in
declaration order relative to each other; unrelated calls may happen in
between. `allVerified()` checks ordering as well. `verifySequence()` is the
tool when the whole protocol matters; it compares double identity in addition
to method and arguments.
```php
Understudy::expectSequence( // armed BEFORE the subject runs
fn () => $repo->begin(),
fn () => $repo->save($book),
fn () => $repo->commit(),
);
$service->handle($command); // fails HERE, on the call out of turn
```
`expectSequence()` is the fail-fast form: both tools above raise in teardown,
where the stack trace points at `verifyAll()`. Rules, all of them load-bearing:
- Totality is scoped to the doubles the protocol names. A double it never names
is invisible to it.
- On a named double a call must be the step due, or match something the test
configured. Anything else is refused at the call — so a query the subject
makes between two steps has to be stubbed with `when()`.
- Each step is due exactly once, in order. Re-calling a step the protocol has
moved past is out of turn. Use `ordered()` for a relative order that tolerates
repeats.
- Arming is also a claim: `verifyAll()` reports the steps the subject never
reached, which is what still fails the test when the subject swallows the
refusal in a broad `catch`.
- One protocol at a time; a finished one may be replaced. `checkpoint()`
verifies it and then drops it.
- The failure is a `VerificationFailed` carrying `FailureKind::OutOfSequence`,
the same kind `verifySequence()` reports.
### Phases and scopes
```php
Understudy::checkpoint(); // verify, then forget what is settled
$result = Understudy::scope(fn () => ...); // nested context, verified on success
Understudy::transcript($repo); // every call and outcome, for reading
Understudy::idle(); // true when the test holds no doubles, in any context
```
`scope()` returns whatever the callback returns and drops its context either
way; a failure inside the callback is never replaced by a teardown error. On
success it verifies the context it opened and only that one — the enclosing
context is still running, and its open claims are answered for by
`verifyAll()`, `checkpoint()` and the runner adapter's teardown. A double
created there becomes forgotten when the scope closes. Configuration
and verification require the owning context; normal calls from another Fiber
are allowed and are routed to the owner's log.
`checkpoint()` keeps the understudies, their modes and their labels, and
clears the expectations and the SETTLED calls of the current phase — settled
meaning claimed by a matching `expect()` or a successful `verify()`. A call
covered by a `when()` stub alone is never claimed and survives, because
`nothingElse()` still reads it.
`transcript()` retains every invocation until `reset()` (see `checkpoint()`
above: it clears only the settled ones); avoid unbounded hot loops through
doubles when arguments or results hold large object graphs.
Failure raises `VerificationFailed`, whose message names the double, the
expectation, the actual count, and marks differing arguments with `*`.
### Call log — `calls()` and `lastCall()`
```php
$calls = Understudy::calls(fn () => $repo->find(Arg::any())); // list<Invocation>
$last = Understudy::lastCall(fn () => $repo->find(Arg::any())); // ?Invocation
```
`Invocation`: `->method`, `->args`, `->arg(int|string)`, `->sequence`, `->sensitiveArguments`,
`->argsAfter()`, `->didReturn()`, `->didThrow()`, `->returned()`, `->thrown()`,
`->callOriginal()`. The outcome is asked about, never inferred from a value:
`null` is a valid return.
`returned()` on a call that threw raises `OutcomeUnavailable` — `null` is a
valid return value and cannot signal "nothing".
`lastCall()` answers the newest matching call or null — the null-safe
replacement for `count($calls) - 1`, which static analysis reads as
`int<-1, max>`.
### Retiring a double — `forget()`
```php
Understudy::forget($replaced);
```
For a double the test built and then replaced: verification (including
`strictStubs`), accounting and reset stop seeing it. Any call on it — or any
question about its calls — raises `ForgottenDouble` naming `forget()`. The
same guard after a `scope()` closed names the scope; after `reset()`, the reset.
One-way; a replacement is a different object.
### Modes and naming
```php
Understudy::strict($repo); // unmatched call fails; answers with $repo
Understudy::label($repo, 'primary cache'); // name it in failures; answers with $repo
Understudy::reset(); // drop the current context
```
Loose (default) answers with a type-safe default: `null` for `void`/`mixed`/
nullable, `false`, `0`, `0.0`, `''`, `[]`, `new stdClass()`, an empty
`Generator`, an `EmptyIterator`, a no-op callable. A type with no safe default
raises `NoDefaultValue`; a `never` method raises `NeverMethodCalled`. A method
declared `: static` answers with the double itself; `: self` names the contract
and answers with a nested double.
### Exceptions
All implement `Rasuvaeff\Understudy\Exception\UnderstudyError`.
| Exception | Raised when |
|---|---|
| `InvalidCallSpecification` | the SHAPE of a specification is wrong: the closure made no call on a double, called a static method or threw first; a tail matcher is not the last argument; the specification stopped before a required parameter without `Arg::rest()`; a matcher nested inside an array argument; a captor inside a combinator; an empty `allOf()`/`anyOf()`; `verify()` arguments that contradict each other; a facade handed an object that is not a double; a protocol armed over a running one |
| `InvalidSpecificationArgument` | a VALUE no run could act on: `times(5, 2)`, a negative count, `returns()` with nothing to return, an inverted `Arg::int/float/count()` range, an `Arg::string()` pattern PCRE cannot compile, `Arg::instanceOf()` naming a type that is not loadable, `Invocation::arg()` naming a parameter the method does not declare. Extends `\InvalidArgumentException` |
| `UnsupportedTarget` | target missing, undoublable, or targets conflict |
| `StrictModeViolation` | a strict double got an unconfigured call |
| `NoDefaultValue` | loose mode has no safe value for the return type |
| `NeverMethodCalled` | a `: never` method was called without a configured throw |
| `OutcomeUnavailable` | `returned()` asked of a call that threw |
| `MatcherLeaked` | a matcher was passed to a real call, not a specification |
| `NothingCaptured` | `Captor::last()` read before any matched call captured a value |
| `ConflictingExpectation` | a when() and an expect() name the exact same call — they would not compose |
| `ForgottenDouble` | a double outlived the context that created it |
| `ContextOwnershipViolation` | configuration or verification used a double from another context |
| `AmbiguousDefaultFactory` | two registered factories are equally close to the requested type |
| `InvalidDefaultValue` | a registered factory produced something the contract cannot hold |
| `CannotWire` | the subject cannot be built, or a constructor parameter cannot be decided |
| `BypassUnavailable` | `bypassFinals()` on a loaded class, a non-class, or over another source transformer |
| `ForwardingTargetMismatch` | the instance offered to `forwarding()` misses a contract of the double |
| `OriginalCallUnavailable` | forwarding or `callOriginal()` with no real instance to delegate to |
| `OriginalReturnTypeViolation` | a forwarded `static` method returned another instance of the real class |
| `VerificationFailed` | a verification about the tested code failed |
### Structured failures — `failures()`
```php
try {
Understudy::verifyAll();
} catch (VerificationFailed $e) {
foreach ($e->failures() as $failure) {
$failure->kind; // FailureKind::UnmetExpectation | StrictStubUnused
// | OutOfOrder | OutOfSequence | UnaccountedCalls
// | UnusedDouble
$failure->double; // label of the double
$failure->expectation; // call spec, e.g. 'find(1)'
$failure->expectedMinimum; // claimed lower bound, or null
$failure->expectedMaximum; // claimed upper bound (null = unbounded), or null
$failure->actualCount;
$failure->observedCalls; // list<Invocation> the report shows
$failure->expectedCalls; // OutOfSequence only: the specified protocol
$failure->summary; // this failure's rendered text
}
}
```
The readonly fields of `VerificationFailure` and the existing `FailureKind`
cases are stable: renaming, removing or retyping one is a major-version change.
A NEW kind, or a field newly populated for an existing kind, may arrive in a
minor — match on `FailureKind` with a `default` arm, never exhaustively.
## Compatibility
The `1.x` public contract is every `@api` type, member name, signature, and
readonly field. `@internal` types may change in any release. Constructors only
gain optional parameters at the end. Failure messages are prose; consume
`VerificationFailed::failures()` instead. Release order is core first, then
Testo, Psalm, PHPUnit, and PHPStan satellites. Each satellite `1.x` line
requires `rasuvaeff/understudy:^1.0`.
## Not supported
Static method mocking, patching at the point of use, deep stubs, duck doubles,
sharing state across processes.