@cratis/pi 8.14.0 → 8.16.0
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/package/corpus/skills/cratis-screenplay-model-interaction/SKILL.md +5 -4
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/csharp-host-api.md +12 -1
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/csharp.md +1 -0
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/localized-strings.md +2 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/SKILL.md +1 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +34 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-decision-reads.md +4 -7
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-query-scenario.md +7 -8
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-read-models.md +1 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +25 -3
- package/package/corpus/skills/cratis-specifications-observe-ui/SKILL.md +20 -0
- package/package/corpus/skills/cratis-specifications-observe-ui/references/typescript.md +17 -0
- package/package/corpus/skills/cratis-specifications-test-application-ui/SKILL.md +9 -2
- package/package/corpus/skills/cratis-specifications-test-application-ui/references/typescript.md +45 -1
- package/package/corpus/skills/cratis-specifications-test-typescript-behavior/SKILL.md +21 -0
- package/package/corpus/skills/cratis-specifications-test-typescript-behavior/references/typescript.md +58 -3
- package/package.json +1 -1
|
@@ -170,13 +170,14 @@ See [Shell and design](references/shell-and-data.md) for the shell skeleton, `ar
|
|
|
170
170
|
|
|
171
171
|
### Profiles, design, sample data and strings
|
|
172
172
|
|
|
173
|
-
|
|
173
|
+
Rules: [Localized strings](references/localized-strings.md).
|
|
174
174
|
|
|
175
|
-
- `ui profile <Name>` (top level; several allowed) — `target platform`, `target size compact|regular|expanded`, `theme`, `root template [blueprint <Bp>] <Name> [version "<range>"]` with `option <n> <v>`, `identity` (`name`, `logo initials|icon|image`, `show name`), `appearance` → `color scheme light|dark|system`, `new screens use template …`, `packages` (in priority order, `core` as fallback), `icons` and `sample data` (`active <Pack>`, `shape <S> maps to <ReadModel>`, `bind <ReadModel> to <Pack>`). A screen never names
|
|
176
|
-
- `design system <Name>` (top level, once) — `modes`, `default theme` (required), `tokens` by category (color, space, size, radius, border, shadow, font, type, motion, opacity, z), `components` with `parts`, `variant` and `state`, `words`
|
|
175
|
+
- `ui profile <Name>` (top level; several allowed) — `target platform`, `target size compact|regular|expanded`, `theme`, `root template [blueprint <Bp>] <Name> [version "<range>"]` with `option <n> <v>`, `identity` (`name`, `logo initials|icon|image`, `show name`), `appearance` → `color scheme light|dark|system`, `new screens use template …`, `packages` (in priority order, `core` as fallback), `icons` and `sample data` (`active <Pack>`, `shape <S> maps to <ReadModel>`, `bind <ReadModel> to <Pack>`). A screen never names one.
|
|
176
|
+
- `design system <Name>` (top level, once) — `modes`, `default theme` (required), `tokens` by category (color, space, size, radius, border, shadow, font, type, motion, opacity, z), `components` with `parts`, `variant` and `state`, `words` and `rules contrast <part> on <part> at least <ratio>`.
|
|
177
177
|
- `theme <Name>` (top level) — `implements <DesignSystem>`, `compatible with <Package>`, `palette`, `values`, and per-mode blocks. Every color token needs a value in every mode. A profile's theme must implement the design system.
|
|
178
178
|
- `sample data <Name>` (top level) — `title`, `locale`, and `shape <ReadModel>` with `row` and `<field> = <literal>` (nested rows for collections). Activate it from a profile.
|
|
179
|
-
- `<base>.<locale>.strings` companion files with `key = "value"` — use `$strings.<key>` for
|
|
179
|
+
- `<base>.<locale>.strings` companion files with `key = "value"` — use `$strings.<key>` for titles, labels, toolbar button titles, notify, confirm and validation messages.
|
|
180
|
+
- Values use ICU 1 apostrophe quoting (`''`, `'{'`); a placeholder is one name or number, no plural or select.
|
|
180
181
|
|
|
181
182
|
### Tools and SDK surfaces
|
|
182
183
|
|
package/package/corpus/skills/cratis-screenplay-model-interaction/references/csharp-host-api.md
CHANGED
|
@@ -170,8 +170,19 @@ foreach (var file in files.FindIn("models/helpdesk"))
|
|
|
170
170
|
|
|
171
171
|
var english = new StringsFile([new StringsEntry("tickets.fields.subject", "Subject")]);
|
|
172
172
|
File.WriteAllText("models/helpdesk/tickets.en.strings", english.Write());
|
|
173
|
+
|
|
174
|
+
var entry = new StringsEntry("tickets.assigned", "Assigned to {assignee}, don''t reply");
|
|
175
|
+
foreach (var part in entry.Parts())
|
|
176
|
+
{
|
|
177
|
+
switch (part)
|
|
178
|
+
{
|
|
179
|
+
case StringsText text: Console.Write(text.Text); break;
|
|
180
|
+
case StringsPlaceholder placeholder: Console.Write($"<{placeholder.Name}>"); break;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
173
183
|
```
|
|
174
184
|
|
|
175
185
|
- `FindIn(root)` matches `StringsFiles.Pattern` (`**/*.strings`) and orders results by `RelativePath`; `Path` is absolute. `BaseName` and `Locale` come from `<base>.<locale>.strings`; `Locale` is `null` without a locale segment.
|
|
176
|
-
- `Parse` skips blank lines and `//` comments and throws `InvalidStringsLine` (with the line number) for anything else. A key starts with a letter or underscore and continues in dotted word segments. A value is double-quoted, cannot contain `"` and has no escapes
|
|
186
|
+
- `Parse` skips blank lines and `//` comments and throws `InvalidStringsLine` (with the line number) for anything else. A key starts with a letter or underscore and continues in dotted word segments. A value is double-quoted, cannot contain `"` and has no escapes. Values stay verbatim: `Parse` applies no placeholder or quoting rules.
|
|
187
|
+
- `StringsValue.Parse(value)` and `StringsEntry.Parts()` return the value as ordered `StringsText` (`Text`) and `StringsPlaceholder` (`Name`) parts with ICU MessageFormat 1 apostrophe quoting removed: `''` is an apostrophe, `'{'` and `'}'` are literal braces, an unclosed quote runs to the end. A placeholder is one name or a number 0–32767 without leading zeros. They throw `InvalidStringsValue` (with `Position`, the 0-based index of the offending character) for an unbalanced brace, braces around anything but one name or number, or an apostrophe directly before `<` or `>`.
|
|
177
188
|
- `Write()` emits the canonical form: one entry per line, keys padded to the longest. It drops comments and blank lines, so don't round-trip a hand-commented file through it.
|
|
@@ -118,6 +118,7 @@ return 0;
|
|
|
118
118
|
| `DesignSystemResolver.SelectTheme` / `.SelectMode` / `.Resolve` | Flatten a profile's theme and mode into tokens and component parts. |
|
|
119
119
|
| `UiProfileShellBinder.Bind` | Check profile shells against the blueprints a host has installed. |
|
|
120
120
|
| `StringsFile` / `StringsFiles` | Find, parse and write `.strings` files. |
|
|
121
|
+
| `StringsValue.Parse` / `StringsEntry.Parts` | Split a value into ordered `StringsText` and `StringsPlaceholder` parts; throws `InvalidStringsValue` with a `Position`. `StringsFile.Parse` keeps values verbatim. |
|
|
121
122
|
|
|
122
123
|
## Not supported in this SDK
|
|
123
124
|
|
package/package/corpus/skills/cratis-screenplay-model-interaction/references/localized-strings.md
CHANGED
|
@@ -8,6 +8,8 @@ invoices.fields.number = "Invoice number"
|
|
|
8
8
|
notifications.invoiceRegistered = "Invoice {number} from Acme"
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
A value uses ICU MessageFormat 1 apostrophe quoting: `''` is an apostrophe, `'{'` and `'}'` are literal braces, so `'{number}'` is the text `{number}`, and an apostrophe directly before `<` or `>` is refused (write `''<`). A placeholder is a single name, or a number 0–32767 without leading zeros. Plural, select and typed forms such as `{count, number}` are not supported. Every locale of a key uses the same placeholder names.
|
|
12
|
+
|
|
11
13
|
Use the same dotted keys and preserve `{number}` and any other placeholders in each locale's file, such as `invoicing.nb.strings`. At a screen label or title, use the unquoted reference; for example, a form field can use:
|
|
12
14
|
|
|
13
15
|
```play
|
|
@@ -73,6 +73,7 @@ Names in examples across this skill's references are illustrative.
|
|
|
73
73
|
4. For an accepted event-writing command, assert the event, source and values. For a response-only command or query, assert the promised response fields or rows instead.
|
|
74
74
|
5. Await every assertion that returns a task, future or promise; otherwise the runner can finish before a failing assertion completes.
|
|
75
75
|
6. For delivery against a running kernel, wait on a bounded completion signal for the observer or append under test, not a sleep or polling loop. Without that signal, an append does not prove delivery.
|
|
76
|
+
7. Before combining two scenarios, seeding one fact in two places, or handing a scenario's read surface to the code under test, read what each scenario does not prove and which members it has in your language reference. A member another scenario has is not implied, and a hand-built substitute for the read surface proves no fold.
|
|
76
77
|
|
|
77
78
|
For a decision or validation rule, the spec should fail if the rule is removed and pass when it is restored. For delivery, require the exact promised observation after the completion signal.
|
|
78
79
|
|
|
@@ -19,7 +19,16 @@ Applies to `CommandScenario<TCommand>` with `Cratis.Arc.Testing.Commands` and, f
|
|
|
19
19
|
|
|
20
20
|
Set everything here before the first `Execute` or `Validate`. The caller and pinned generated values cannot change after that call.
|
|
21
21
|
|
|
22
|
-
- **History.** `_scenario.Given.ForEventSource(id).Events(first, second)` supplies the events the command
|
|
22
|
+
- **History.** `_scenario.Given.ForEventSource(id).Events(first, second)` supplies the events the command decides on. Where they land depends on the scenario's mode, which the scenario selects from the command type when it is constructed:
|
|
23
|
+
|
|
24
|
+
| Mode | The scenario is in it when | `Given...Events(...)` | `_scenario.EventScenario` |
|
|
25
|
+
| --- | --- | --- | --- |
|
|
26
|
+
| Decision | The command's read protection is `On` or `Measure`, or it carries `[ProtectedDecision]`, or a `Handle()`/`Provide()` parameter or a discoverable validator's constructor takes `DecisionRead<T>`, `IDecisionReads`, `IStreamReads`, `StreamDecision`, a per-stream read model or a guarded generated value | Enters the one log that injected read models, event-log reads, constraints and the commit all use | Throws `EventScenarioUnavailableInDecisionMode` |
|
|
27
|
+
| Legacy | Read protection is `Off` for the command and none of those dependencies is declared | Feeds only the read models injected into the command; never enters the event log | `EventScenario.Given` fills only the log, which event-log reads and constraints see; injected read models do not see it |
|
|
28
|
+
|
|
29
|
+
When the Chronicle build props are imported, an unset `CratisReadProtection` defaults the command assembly to `On`. Without a command or assembly declaration, it resolves to `Off`. `[Unprotected]` sets rollout to `Off`; otherwise the command declaration overrides the assembly declaration. An `Off` command still uses the decision store if it declares `[ProtectedDecision]` or a decision dependency. The runtime ceiling can lower enforcement without changing the scenario's store. Do not lower protection to make a spec pass.
|
|
30
|
+
|
|
31
|
+
For a per-stream model, add `.OnRoute(route)` before `.Events(...)`, resolving the route from `_scenario.EventRoutes`; in legacy mode that makes `.Events(...)` throw `RoutedEventSeedingRequiresDecisionReads`. In legacy mode a command that needs a fact both in an injected read model and in the log needs it seeded in both places, and events the command appends never reach the `Given` seeds. An observable query shared with that scenario combines both histories, so a fact seeded in both is folded twice there.
|
|
23
32
|
- **A fixed read model.** `_scenario.Given.ForEventSource(id).ReadModel(instance)` pins the instance the command receives. A pin wins over seeded events for that model and key. It cannot back a `DecisionRead<T>` parameter (`PinnedReadModelCannotProvideDecisionToken`) or a per-stream model; seed events for those.
|
|
24
33
|
- **The caller.** `.WithClaims(new Claim(ClaimTypes.Role, "Dispatcher"))` runs the command as an authenticated caller with those claims, `.WithPrincipal(principal)` uses an existing `ClaimsPrincipal`, and `.Unauthenticated()` runs it anonymously. These set the principal authorization reads; they do not exercise login or token validation.
|
|
25
34
|
- **Server-generated values.** `_scenario.PinGeneratedValue("orderId", id)` fixes a generated parameter so the spec can assert it. When the exact value is irrelevant, call `.AllowGeneration()`. With neither, `Execute` returns a result carrying a `GeneratedValueNotPinned` exception instead of running the command.
|
|
@@ -117,6 +126,30 @@ The check does not evaluate tenant-membership verification: when the provider ha
|
|
|
117
126
|
|
|
118
127
|
The result also exposes `Outcome` (`Authorized`, `Denied`, `Unsupported`), `ReasonCode` (set when unsupported) and a `Message` safe to print. Use it for a matrix of roles and policies across commands; keep one pipeline scenario per command to prove authorization actually gates execution.
|
|
119
128
|
|
|
129
|
+
These are the `Unsupported` diagnostics. Inspection can stop before policy evaluation; evaluation itself can also return `Unsupported`. If multiple discovered filters make the check unsupported, the first encountered wins. Most causes lie in the command type or the provider, not in the caller, so one of them can turn every cell of a matrix for that command, or for that whole provider, into Unsupported:
|
|
130
|
+
|
|
131
|
+
| `ReasonCode` | Cause | Scope |
|
|
132
|
+
| --- | --- | --- |
|
|
133
|
+
| `context-invalid` | The supplied context has another command type, no command, another provider, or was already evaluated | This call |
|
|
134
|
+
| `approval-required` | The command carries `[RequiresApproval]`, whether or not an approval flow is registered | Every caller of this command |
|
|
135
|
+
| `host-required` | An HTTP request is active in the provider | Every command |
|
|
136
|
+
| `services-missing` | Arc's authorization services are not registered in the provider | Every command |
|
|
137
|
+
| `runtime-unsupported` | The provider's policy runtime is not Arc's own | Every command |
|
|
138
|
+
| `tenant-membership` | Tenant membership is registered in the provider | Every command |
|
|
139
|
+
| `availability-gate` | An availability gate gates this command | This command |
|
|
140
|
+
| `custom-filter` | The provider discovers any `ICommandFilter` that is not one of Arc's own, whether or not that filter would act on this command | Every command |
|
|
141
|
+
| `principal-unavailable` | The principal override and accessor in the provider do not return the supplied principal | Every command |
|
|
142
|
+
| `host-required` | The declaration names an authentication scheme | This command |
|
|
143
|
+
| `resource-required` | The declaration has a requirement evaluated asynchronously, such as a policy that reads the command, and no command instance or context was passed | This command; pass the instance |
|
|
144
|
+
| `principal-selection` | The runtime selected another authenticated identity than the one supplied | This command |
|
|
145
|
+
| `async-runtime-required` | A requirement needs an asynchronous authorization runtime the provider does not have | This command |
|
|
146
|
+
| `invalid-configuration` | Invalid or ambiguous authorization declarations or policy registrations | This command |
|
|
147
|
+
| `read-model-key-resolution` | Authorization encountered a read-model key-resolution denial; reproduce binding in a command scenario | This command |
|
|
148
|
+
|
|
149
|
+
A matrix therefore has two kinds of expected cell, and both are asserted with the verdict helpers, never by comparing `Outcome` or `Message` strings: `ShouldBeAuthorized()` or `ShouldBeDenied()` where the check can evaluate, and `ShouldBeUnsupported()` plus the `ReasonCode` where it cannot. An Unsupported cell is not a pass or a fail of the rule: add a `CommandScenario` or hosted spec for it. Expecting `Authorized` for a `[RequiresApproval]` command, or a role verdict from a provider that discovers a custom filter, is a wrong expectation.
|
|
150
|
+
|
|
151
|
+
If authorization and validation succeed, both `Execute` and `Validate` refuse a `[RequiresApproval]` command with no registered flow, with `IsAuthorized == false`; the handler does not run. `Validate` runs authorization and the validation filters and then that approval refusal; it never resolves arguments or runs `Provide()` or `Handle()`, so a refusal those raise is proven only with `Execute`.
|
|
152
|
+
|
|
120
153
|
## Check wiring across all commands
|
|
121
154
|
|
|
122
155
|
A scenario proves one invocation. `CommandWiring` checks every command's declarations against the application's configured, scoped service provider, so a `Handle()` dependency or a discoverable validator's constructor dependency that is not registered fails one spec instead of surfacing at run time.
|
|
@@ -4,10 +4,7 @@ Applies when a command claims uniqueness, or decides from history that another w
|
|
|
4
4
|
|
|
5
5
|
## Prove a uniqueness claim
|
|
6
6
|
|
|
7
|
-
Exercise a real claim, then a conflicting one from a different source.
|
|
8
|
-
|
|
9
|
-
- `_scenario.EventScenario.Given.ForEventSource(id).Events(...)` appends to the scenario's event log. Constraints see these events.
|
|
10
|
-
- `_scenario.Given.ForEventSource(id).Events(...)` supplies the state the command's read models are built from.
|
|
7
|
+
Exercise a real claim, then a conflicting one from a different source. This example uses decision mode. Seed the existing claim through `Given` so the constraint sees it in the shared log. For a legacy-mode scenario, seed the constraint's history through `EventScenario.Given` instead.
|
|
11
8
|
|
|
12
9
|
This fragment assumes the application registers a unique-name constraint over `CarrierRegistered.Name` and exposes its registered name as `CarrierConstraintNames.UniqueName`. Seeding an event does not register a constraint.
|
|
13
10
|
|
|
@@ -19,7 +16,7 @@ public class when_registering_a_carrier_with_a_taken_name : Specification
|
|
|
19
16
|
readonly CommandScenario<RegisterCarrier> _scenario = new();
|
|
20
17
|
CommandResult _result = null!;
|
|
21
18
|
|
|
22
|
-
|
|
19
|
+
void Establish() => _scenario.Given.ForEventSource(_existing).Events(new CarrierRegistered("Aster"));
|
|
23
20
|
async Task Because() => _result = await _scenario.Execute(new RegisterCarrier(_carrier, "Aster"));
|
|
24
21
|
void Destroy() => _scenario.Dispose();
|
|
25
22
|
|
|
@@ -32,12 +29,12 @@ public class when_registering_a_carrier_with_a_taken_name : Specification
|
|
|
32
29
|
|
|
33
30
|
## Prove a guarded decision
|
|
34
31
|
|
|
35
|
-
A command
|
|
32
|
+
A command whose read protection is `On` or `Measure` runs in decision mode automatically, and so does one with `[ProtectedDecision]`, a `DecisionRead<T>` parameter or a per-stream read model. Read protection is `On` unless the project or the command turns it off, so this is the usual mode; the exact rule is the mode table in [csharp-command-results.md](csharp-command-results.md). One shared log then supplies seeded history, the guarded read and the commit.
|
|
36
33
|
|
|
37
34
|
- Seed with `_scenario.Given.ForEventSource(id).Events(...)`. `_scenario.EventScenario` throws in this mode.
|
|
38
35
|
- Give the command state and assert the outcome. Do not invent sequence numbers or decision tokens, and do not simulate a concurrent writer: the guard itself is the framework's behavior, already covered there.
|
|
39
36
|
- Let Arc complete a protected command's unit of work: the command returns its events. Calling `Commit()` or `Rollback()` on that unit of work directly fails with `ProtectedUnitOfWorkRequiresOwner`. An aggregate root's own `Commit()` is narrower than it looks. Arc completes it as the owner only when read protection is on and the aggregate belongs to that command's own unit of work, not to a unit inherited from an outer command. Otherwise it is a direct completion, which fails the same way once protected reads have enrolled in the unit. A command executing as an occurrence effect refuses any early commit. Where the aggregate commit applies, read first and return that `Commit()` last; in every other case return the events.
|
|
40
|
-
- `EnableDecisionReads()`
|
|
37
|
+
- For an untyped `CommandScenario<object>`, call `EnableDecisionReads()` before seeding or executing. Typed scenarios select their initial store automatically; the same method can explicitly opt a legacy-mode typed scenario into the shared log.
|
|
41
38
|
- `AppendConcurrently(source, events)` (or `(source, route, events)`) queues competing events to append after the handler reads and before the commit. It is hidden from editor completion and exists to verify the framework's concurrency handling; use it only when the task explicitly asks to prove a guard against an interleaved writer, then assert `ShouldHaveValidationErrorBecauseOf(ValidationResultReason.ConcurrencyViolation)` and that nothing was appended. Queue it before the first `Execute`.
|
|
42
39
|
|
|
43
40
|
Setup errors in decision mode, all fixed in the spec:
|
|
@@ -41,7 +41,7 @@ A successful result without the expected ID does not satisfy the query contract.
|
|
|
41
41
|
|
|
42
42
|
Both `Perform` and `Observe` take optional `paging` (`Paging`) and `sorting` (`Sorting`) arguments after the query arguments and a `CancellationToken` last; `Observe` also takes a `timeout` for the first emission, and `Next(timeout)` one for the next. A scenario extender (`IQueryScenarioExtender`) can publish helpers through `scenario.Context`; the Chronicle package uses it for `Given`.
|
|
43
43
|
|
|
44
|
-
Events seeded through `Given.ForEventSource(id).Events(...)` run the application's own projection or reducer, including children and joins, so the query is proven against the model production would hold. After `Observe`, seed further events and await `observation.Next()` to prove the query pushes the changed model.
|
|
44
|
+
Events seeded through `Given.ForEventSource(id).Events(...)` run the application's own projection or reducer, including children and joins, so the query is proven against the model production would hold. A query method that calls `IReadModels.GetInstances<T>()` is the exception: its result fails with a message containing "not available in test scenarios" for seeded events and pinned instances alike, so prove that query against a running kernel. `GetInstanceById` and `Observe<T>()` are served. After `Observe`, seed further events and await `observation.Next()` to prove the query pushes the changed model.
|
|
45
45
|
|
|
46
46
|
## Observe what a command appends
|
|
47
47
|
|
|
@@ -63,16 +63,15 @@ foreach (var service in commands.Services) queries.Services.Add(service);
|
|
|
63
63
|
foreach (var (key, value) in commands.Context) queries.Context[key] = value;
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
-
Then seed with `queries.Given.ForEventSource(id).Events(...)
|
|
66
|
+
Then seed once with `queries.Given.ForEventSource(id).Events(...)` and run `await commands.Execute(...)`. `QueryScenario` has no mode switch and follows the command scenario's store, which the command type selects (the mode table is in [csharp-command-results.md](csharp-command-results.md)).
|
|
67
67
|
|
|
68
|
-
|
|
68
|
+
Default: after `Execute`, assert the updated content with `await queries.Perform(...)`. To also observe a query backed by `IReadModels.Observe<T>()`, subscribe before executing and await `Next()` only when the append changes the observed result. With effective `On`, a refold that runs inside the command's protected scope can terminate that observation, so verify delivery through the host instead. Do not lower the command's read protection to make the observation pass. Decision mode can also run with rollout `Off`; it still uses the shared log.
|
|
69
69
|
|
|
70
|
-
|
|
71
|
-
| --- | --- | --- |
|
|
72
|
-
| Default | The `Given` seeds plus the command log's successful appends | `Given` seeds feed injected read models and the observation, and never enter the command log |
|
|
73
|
-
| Decision | One log shared by seeds, commands and observation | `Given` seeds enter that log; `commands.EventScenario` throws |
|
|
70
|
+
In legacy mode, `Perform` of an observable query after `Execute` also includes the append, but a query that reads one instance with `GetInstanceById` still returns the seeded state without the command's append.
|
|
74
71
|
|
|
75
|
-
`
|
|
72
|
+
Always assert `IsSuccess` on the result of `Next()` before its data: a failed result has no data, so a cast of `Data` alone hides the reason, which is in `ExceptionMessages`.
|
|
73
|
+
|
|
74
|
+
State each prior event exactly once. After sharing, `queries.Given` and `commands.Given` write to the same seeds: in decision mode both enter the one shared log, and in legacy mode the observation folds those seeds plus every successful append to the command's log, including events placed there with `commands.EventScenario.Given`. An event stated through two of those is folded twice, so counts and sums double. `commands.EventScenario` throws in decision mode.
|
|
76
75
|
|
|
77
76
|
An observed query merges a row pinned with `.ReadModel(instance)` by its identifier: `[Key]`, then `[Subject]`, then a property named `Id`. A pinned instance without a readable identifier, or with a null one, cannot be merged. `scenario.Observe` does not throw for it: the failure arrives as a failed query result carrying the `PinnedReadModelCannotBeObserved` message. Where it arrives depends on when the instance was pinned:
|
|
78
77
|
|
|
@@ -10,7 +10,7 @@ Names are illustrative; the application's own domain language replaces them.
|
|
|
10
10
|
- **Read the result by key.** `scenario.Instance` is the single materialized instance and throws when there are several; use `scenario.InstanceForEventSourceId(id)` or `scenario.Instances` then. `ShouldPartiallyMatchReadModel(id, new { Status = "Held" })` recursively checks only the listed public properties at that key, `ShouldExactlyMatchReadModel(id, expected)` the complete public property set, and `ShouldHaveNoReadModel(id)` absence.
|
|
11
11
|
- **Several sources feed one model.** `CollectEventsFor(id, events)` accumulates events per source and they are processed together on the next read, which a model with children from other streams needs; `await ProcessEventsFor(id, events)` collects bare events for the next read.
|
|
12
12
|
- **Start from existing state when that is the premise.** `await scenario.Given.ForEventSource(id).ReadModel(existing)` seeds an instance; later events fold on top of it. `Given.ForKey(...)` seeds a composite key. Seeding the same key twice throws `ReadModelAlreadySeeded`.
|
|
13
|
-
- **Reuse real envelopes.** `ProcessAppendedEvents(events)` applies `AppendedEvent` values captured elsewhere with their original context.
|
|
13
|
+
- **Reuse real envelopes.** `ProcessAppendedEvents(events)` applies `AppendedEvent` values captured elsewhere with their original context. Only an envelope carries the original `Occurred`, including its UTC offset: a bare event passed to `Given...Events(...)` or `ProcessEventsFor` gets the time of the spec run. A regression about a value taken from the event context therefore needs the envelopes. `DateTimeOffset` equality compares the instant and ignores the offset, so `ShouldEqual` passes when only the offset changed: assert `actual.EqualsExact(expected)` or the `Offset` as well.
|
|
14
14
|
- **Do not replace the definition under test.** `WithProjection(builder => ...)` overrides discovery, including a discovered reducer, so the spec then proves the inline recipe instead of the application's. Use it only for a model with no definition of its own. A missing or ambiguous definition is a failure to fix, not a reason to substitute one.
|
|
15
15
|
- **Catch a silent drop.** `WithStrictEventSubscription()` makes a seeded event the model does not subscribe to throw instead of being ignored.
|
|
16
16
|
|
|
@@ -75,14 +75,36 @@ Every scenario here runs in process. None of them proves observer delivery, stor
|
|
|
75
75
|
|
|
76
76
|
| Scenario | It does not prove | Do not combine |
|
|
77
77
|
| --- | --- | --- |
|
|
78
|
-
| `CommandScenario` | That a query or subscription sees what the command appended. That needs a query scenario sharing its services and context: [csharp-query-scenario.md](csharp-query-scenario.md). |
|
|
79
|
-
| `QueryScenario` | Anything about a command scenario created independently: the two have separate state, so waiting for the next emission times out. | The same event seeded through both `commands.Given` and `queries.Given` once the scenarios are shared: they write to one seed store and the observation folds both copies. Seed each event once. |
|
|
78
|
+
| `CommandScenario` | That a query or subscription sees what the command appended. That needs a query scenario sharing its services and context: [csharp-query-scenario.md](csharp-query-scenario.md). | One fact seeded through both `Given` and `EventScenario.Given`, or `EventScenario` at all in decision mode, where it throws. Decide the mode first: [csharp-command-results.md](csharp-command-results.md). |
|
|
79
|
+
| `QueryScenario` | Anything about a command scenario created independently: the two have separate state, so waiting for the next emission times out. A query whose method calls `IReadModels.GetInstances<T>()`: the result fails with a message containing "not available in test scenarios", whatever was seeded. Prove that query against a running kernel. | The same event seeded through both `commands.Given` and `queries.Given` once the scenarios are shared: they write to one seed store and the observation folds both copies. Seed each event once. |
|
|
80
80
|
| `EventScenario` | That a projection, reducer or reactor was delivered the event by an observer. `ReadModels` folds the scenario's own log on each read. | Appends through `Defaults.Instance.EventStore` or another store: that is a different log, which this scenario's `ReadModels` never reads. |
|
|
81
81
|
| `ReadModelScenario` | Collection reads and subscriptions. It collects its input instead of appending it to a log, so its `ReadModels` serves only `GetInstanceById` for seeded instances. | `ReadModels.GetInstances` or `ReadModels.Observe` expecting the scenario's output: `Observe` throws `ReadModelCannotBeObserved` and `GetInstances` needs a running Chronicle. Assert through `Instance`, `Instances` or `InstanceForEventSourceId`. Hand code that enumerates or observes through `IReadModels` the `ReadModels` of an `EventScenario` instead ([csharp-events.md](csharp-events.md)). |
|
|
82
82
|
| `ReactorScenario` | That anything was sent, appended or executed. The default recorder records what the reactor returned; it does not append events, execute commands or call a registered `IReactorSideEffectHandler`. | An assertion on a gateway or a substitute behind a side-effect handler after a default-recorder run: it was never called. Assert `Produced` or `ShouldHaveProduced<T>`, and prove the effect in a spec of the handler or against a running kernel. |
|
|
83
83
|
|
|
84
84
|
A reactor that returns a custom type still needs an `IReactorSideEffectHandler` claiming that type registered in `scenario.Services`; without one, the scenario throws `InvalidReactorHandlerReturnType`. The registration only makes the return type legal: the recorder keeps the value and the handler does not handle it.
|
|
85
85
|
|
|
86
|
+
### Members each scenario has
|
|
87
|
+
|
|
88
|
+
Use only these. A member a neighbouring scenario has is not implied here: writing it is a compile error, not a setup error.
|
|
89
|
+
|
|
90
|
+
| Scenario | Arrange and act | Read and assert | It has no |
|
|
91
|
+
| --- | --- | --- | --- |
|
|
92
|
+
| `CommandScenario<TCommand>` | `Given`, `WithClaims`, `WithPrincipal`, `Unauthenticated`, `Tenant`, `Clock`, `PinGeneratedValue`, `Services`, `Execute`, `Validate` | The returned `CommandResult`, `LastResult`, `AppendedEvents`, `EventLog`, `ShouldHaveAppendedEvent...`, `ShouldNotHaveAppendedEvents` | `When`, `ReadModels`, `Perform` |
|
|
93
|
+
| `QueryScenario<TReadModel>` | `Given`, `Services`, `Perform`, `Observe` | The returned `QueryResult`; `Initial` and `Next()` on the observation | `When`, `ReadModels`, `EventLog`, `Execute`, `WithClaims`, `WithPrincipal`, `Unauthenticated` |
|
|
94
|
+
| `EventScenario` | `Given`, `When`, `Time` | Append results, `EventLog`, `ReadModels` | `Services`, `Instance`, `Instances` |
|
|
95
|
+
| `ReadModelScenario<TReadModel>` | `Given`, `ProcessEventsFor`, `ProcessAppendedEvents`, `Services`, `Substitutions` | `Instance`, `Instances`, `InstanceForEventSourceId`, `InstanceForKey`, `Should...ReadModel` | `When`, `EventLog`, a working `ReadModels.GetInstances` or `ReadModels.Observe` |
|
|
96
|
+
| `ReactorScenario<TReactor>` | `Given`, `Redeliver`, `Services` | `Produced`, `ProducedEvents`, `PartitionOutcomes`, `ShouldHaveProduced...`, `ShouldHaveDeferred`, `ShouldHaveFailed` | `When`, `EventLog`, `AppendedEvents`, `Instance` |
|
|
97
|
+
|
|
98
|
+
`IReadModels` in process, by where it comes from:
|
|
99
|
+
|
|
100
|
+
| Source of `IReadModels` | `GetInstanceById` | `GetInstances` | `Observe` |
|
|
101
|
+
| --- | --- | --- | --- |
|
|
102
|
+
| `EventScenario.ReadModels` | Folded from the scenario's log | Folded from the scenario's log | Emits the initial collection, then emits changed results after successful append batches |
|
|
103
|
+
| `ReadModelScenario.ReadModels` | Only an instance pinned with `.ReadModel(...)`; `null` for a source that has only events | Throws `GrainNotAvailableInTestScenario` | Throws `ReadModelCannotBeObserved` |
|
|
104
|
+
| Injected into a query run by `QueryScenario` | Folded from the seeds | The query result fails | Emits the folded collection |
|
|
105
|
+
|
|
106
|
+
So the default for code that takes `IReadModels` and enumerates or observes it is an `EventScenario`: append the history with its `Given` and pass its `ReadModels`. Never substitute `IReadModels` by hand to prove such code: a substitute returns what the spec told it and exercises no fold.
|
|
107
|
+
|
|
86
108
|
## Default path: refuse an invalid command
|
|
87
109
|
|
|
88
110
|
Seed another registration so earlier history is distinguishable from this command’s work.
|
|
@@ -161,7 +183,7 @@ Awaited assertions on the scenario: `ShouldHaveAppendedEvent<TCommand, TEvent>(i
|
|
|
161
183
|
|
|
162
184
|
## Seeding before the act
|
|
163
185
|
|
|
164
|
-
`Given.ForEventSource(id)[.OnRoute(route)].Events(...)` and `.ReadModel(instance)`; `EventRoutes` resolves a route; in
|
|
186
|
+
`Given.ForEventSource(id)[.OnRoute(route)].Events(...)` and `.ReadModel(instance)`; `EventRoutes` resolves a route; the scenario runs in decision mode unless the command's read protection is `Off` and it declares no decision dependency: `Given` then seeds one shared log, routed seeds work and `EventScenario` throws. In legacy mode `Given` seeds injected read models only and `EventScenario.Given` seeds the log that constraints see. The mode table is in [csharp-command-results.md](csharp-command-results.md). Guarded reads, uniqueness, competing writers (`AppendConcurrently`) and `DecisionReadAdmissions`: [csharp-decision-reads.md](csharp-decision-reads.md).
|
|
165
187
|
|
|
166
188
|
## Slice
|
|
167
189
|
|
|
@@ -15,6 +15,26 @@ Use the browser frontend's SDK reference regardless of the backend SDK. This ski
|
|
|
15
15
|
- **Native browser check.** Use the existing browser runner for real Tab order, Shift+Tab, or a held key. A play function can test activation after explicitly focusing a trigger, but simulated traversal does not prove native tab order. A browser-mode spec also fits a composition that should not have a story.
|
|
16
16
|
- **Live application check.** Use the running app for a routed page that depends on real identity, commands, or live queries. Do not turn a connected page into a backend-dependent story. When delivery matters, submit a unique value in a disposable namespace and wait for its result on the same page without reloading. See Live submission in your language reference.
|
|
17
17
|
|
|
18
|
+
## What each observation proves
|
|
19
|
+
|
|
20
|
+
| Observation | Proves | Does not prove |
|
|
21
|
+
| --- | --- | --- |
|
|
22
|
+
| Story run in the browser test run, with fixtures | The composition's interaction for the fixture's data: activation, the named dialog, input, dismissal, focus return, feedback for a fixture refusal | Any backend rule, real command acceptance, live query delivery, native Tab order |
|
|
23
|
+
| Native browser check on the isolated preview | Real Tab and Shift+Tab order, focus containment, held-key repeat | Backend behavior; anything outside the browsers it ran in |
|
|
24
|
+
| Live application check | The submitted value became visible without a reload. To prove live delivery, also verify that the update came from the live query, not optimistic state, polling or a refetch. | Which backend rule decided it, the refusal branches, or delivery in another environment |
|
|
25
|
+
| Accessibility scan | That the scanned content has no detectable violation | Keyboard usability or focus order |
|
|
26
|
+
| Static story build or story typecheck | A build checks bundling; a typecheck checks types | That any play function ran or passed |
|
|
27
|
+
|
|
28
|
+
Do not present one as another:
|
|
29
|
+
|
|
30
|
+
- **A fixture refusal as a rule.** A story that shows "name already in use" proves the feedback, not uniqueness. The rule belongs to `cratis-specifications-exercise-backend`.
|
|
31
|
+
- **A story against a running backend.** It is neither deterministic nor a live check. Stop the backend for stories; use the live check for delivery.
|
|
32
|
+
- **Simulated traversal as native order.** A play function's simulated Tab does not prove the browser's tab order.
|
|
33
|
+
- **Two key presses as a held key.** Only a second keydown while the key is still down carries the repeat flag.
|
|
34
|
+
- **A reload in a live check.** A row visible after reload is evidence about the reloaded page, not live delivery.
|
|
35
|
+
- **A reused value in a live check.** A row left by an earlier run satisfies the wait.
|
|
36
|
+
- **An excluded story as a gate.** A story tagged out of the test run has executed nothing.
|
|
37
|
+
|
|
18
38
|
## Default path
|
|
19
39
|
|
|
20
40
|
1. Put the application's relevant providers, router and entry-point styles in the preview. Supply fixed props and data. Before mounting any connected composition, install deterministic identity, query, validation and command fixtures for every path it uses; block unexpected backend traffic. Done when the preview renders correctly with the backend stopped. See Preview in your language reference.
|
|
@@ -6,3 +6,20 @@ Use this reference in the React frontend workspace, independent of which SDK hos
|
|
|
6
6
|
- [Native keyboard checks and live submission](typescript-browser.md) — use browser-driven keys for actual Tab order or held-key behavior. Use the authenticated application only when the proof needs the live page, such as a command's result appearing without a reload.
|
|
7
7
|
|
|
8
8
|
Not supported by a story: real command acceptance or live query delivery — do those checks against the owning application instead. For Arc server tests, use `cratis-specifications-exercise-backend`; for view-model decisions, use `cratis-specifications-test-application-ui`.
|
|
9
|
+
|
|
10
|
+
## What ships and what the application owns
|
|
11
|
+
|
|
12
|
+
| Need | Where it comes from |
|
|
13
|
+
| --- | --- |
|
|
14
|
+
| Showcase layout: `StoryContainer`, `StorySection`, `StoryGrid`, `StoryDivider`, `StoryBadge` | `@cratis/arc.react/stories`, with `@cratis/arc.react/stories/styles.css`. These five are the whole story kit. |
|
|
15
|
+
| Refusal and result fixtures | Arc's own result types: `CommandResult` from `@cratis/arc/commands`, `QueryResult` from `@cratis/arc/queries`, `ValidationResult` from `@cratis/arc/validation` |
|
|
16
|
+
| Command, query, identity and transport fixtures; preview decorators; request interception | The application. No Cratis package ships them. |
|
|
17
|
+
| Play-function helpers and assertions | `storybook/test` |
|
|
18
|
+
| Native keys and the live check | The project's browser runner |
|
|
19
|
+
|
|
20
|
+
Do not import these; they do not exist or are for something else:
|
|
21
|
+
|
|
22
|
+
- `@cratis/components/testing`, `@cratis/components/stories` and `@cratis/arc.react/testing`: no such entry points.
|
|
23
|
+
- `@cratis/arc.testing` in a frontend story or browser check: it holds the Arc Node server's command and query scenarios and renders nothing.
|
|
24
|
+
- A Cratis mock backend, fake command proxy or story decorator for Arc: build the fixture as a subclass of the generated proxy or a fixed provider value, as the Storybook reference shows.
|
|
25
|
+
|
|
@@ -10,6 +10,7 @@ compatibility: Requires the application's frontend test project and its installe
|
|
|
10
10
|
|
|
11
11
|
- What it is
|
|
12
12
|
- When to use it
|
|
13
|
+
- What a spec proves
|
|
13
14
|
- How it behaves at runtime
|
|
14
15
|
- Default path
|
|
15
16
|
- Capability catalog
|
|
@@ -29,12 +30,19 @@ An application UI spec proves a decision a screen makes: what it keeps, closes,
|
|
|
29
30
|
- **Render the component** only for behavior the view model cannot show. Use static markup for an initial app-owned output contract; mount for provider-driven gating, routing or DOM interactions. Query by accessible role and name; use a browser when the assertion depends on browser behavior.
|
|
30
31
|
- **Not this skill**: browser evidence for focus, keyboard or portals, or live command-to-row delivery (see `cratis-specifications-observe-ui`); backend decisions; logic with no UI.
|
|
31
32
|
|
|
33
|
+
## What a spec proves
|
|
34
|
+
|
|
35
|
+
A UI spec proves what the screen does with the result the spec supplies. It does not prove that the backend returns that result, that a rule exists, or that the request is well formed. See What each spec proves in your language reference.
|
|
36
|
+
|
|
37
|
+
- The real execute first runs the command's client rules and required-property checks, returning a validation failure without a request; on success it resets change tracking. A stubbed execute does neither.
|
|
38
|
+
- To prove what a form refuses with no backend, call the synchronous client-side validation on a real generated proxy. Asynchronous validate and execute contact the server once local checks pass; never call them unstubbed.
|
|
39
|
+
- A rule only the server can evaluate belongs in a backend spec, not behind a canned refusal.
|
|
40
|
+
|
|
32
41
|
## How it behaves at runtime
|
|
33
42
|
|
|
34
43
|
- Generated command proxies post over HTTP. Query proxies fetch over HTTP; observable queries receive pushes (the Arc host defaults to Server-Sent Events; WebSocket and polling are configurable). A spec replaces the proxy's execute, perform or subscribe, so nothing goes over the wire.
|
|
35
44
|
- Command outcomes and caught request failures resolve as results: branch on flags for refusals, server exceptions, unknown routes and failed fetches. Setup can throw before the request is caught (for example, a missing origin or a throwing headers callback); a collaborator can also throw. Test rejection separately when the screen handles it.
|
|
36
45
|
- The client takes a result's flags exactly as given and derives none. A hand-built failure must also say it did not succeed, or success callbacks run.
|
|
37
|
-
- Before sending, the real execute runs the command's client rules and required-property checks and returns a validation failure without a request. On success it resets change tracking. A stubbed execute does neither.
|
|
38
46
|
- Validation results carry `members` (field paths). A command form shows a message on a field when a member equals the field's property name or is a dotted path under it, case-sensitive.
|
|
39
47
|
- An unauthorized result whose reason is `NotAvailable` or `Suspended` is the availability signal; any other unauthorized result is a plain authorization failure. Unauthorized callbacks fire for all three.
|
|
40
48
|
- Query results carry data, success, authorized, valid, exception and ready flags, validation results, paging and, for observable list queries, an optional change set. Observable queries deliver each result through a subscription callback.
|
|
@@ -177,7 +185,6 @@ Done when the affected specs, lint and type check pass and inverting a faked res
|
|
|
177
185
|
- Do not use a rejection to simulate a resolved refusal or fetch failure; separate the two paths.
|
|
178
186
|
- A validation result whose member differs in case or name from the property shows on no field.
|
|
179
187
|
- A hand-built failure left marked successful runs success callbacks.
|
|
180
|
-
- A stubbed execute lets a draft missing required values "succeed".
|
|
181
188
|
- Forgetting to clear caches or restore prototype stubs makes later spec files order-dependent.
|
|
182
189
|
- Mounting to test a decision the view model owns makes the spec slow and brittle.
|
|
183
190
|
- Application specs and Storybook builds do not run story `play` functions. The interactive preview can run them; use a browser story test run as the gate.
|
package/package/corpus/skills/cratis-specifications-test-application-ui/references/typescript.md
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
## Contents
|
|
4
4
|
|
|
5
5
|
- Packages and imports
|
|
6
|
+
- What each spec proves
|
|
6
7
|
- Runner and structure
|
|
7
8
|
- View-model spec
|
|
8
9
|
- Command results
|
|
@@ -37,6 +38,49 @@ Use this reference for the React frontend regardless of the backend SDK; a React
|
|
|
37
38
|
| `Navigation`, `INavigation`, `ILocalStorage` | `@cratis/arc.react.mvvm/browser` |
|
|
38
39
|
| `MVVM`, `IHandleProps`, `IHandleParams`, `IHandleQueryParams`, `IPropsChanged`, `IViewModelDetached` | `@cratis/arc.react.mvvm` |
|
|
39
40
|
|
|
41
|
+
## What each spec proves
|
|
42
|
+
|
|
43
|
+
Default: a view-model spec with the proxy methods stubbed. Pick another row only for the promise in its second column.
|
|
44
|
+
|
|
45
|
+
| Spec | Proves | Does not prove |
|
|
46
|
+
| --- | --- | --- |
|
|
47
|
+
| View model with `execute`, `perform` or `subscribe` stubbed | What the screen keeps, closes, navigates to, publishes or shows for that result | That the server returns that result, that the rule behind a refusal exists, local validation, the request |
|
|
48
|
+
| `validateClientSide()` on a real generated proxy | Which drafts are refused before any request | Server-only rules, or how the screen displays the failure |
|
|
49
|
+
| Real `execute` against a stubbed `fetch` | Local validation ahead of the request, the request itself, the change-tracking reset | Anything about the server: the envelope is the spec's own text |
|
|
50
|
+
| Static markup | The initial app-owned markup | Effects, state updates and event handling, which never run |
|
|
51
|
+
| Mounted component under the DOM test environment | Provider-driven gating, routing and the DOM events the component handles | Layout, native Tab order, held keys, and live command-to-row delivery |
|
|
52
|
+
|
|
53
|
+
Combinations to avoid:
|
|
54
|
+
|
|
55
|
+
- **A canned refusal as proof of a rule.** A stubbed `execute` or `fetch` that answers "not certified" proves the screen's reaction, not the rule. The rule is proven in a backend spec (`cratis-specifications-exercise-backend`, or `cratis-arc-testing-typescript` for an Arc Node server).
|
|
56
|
+
- **`validate()` or an unstubbed `execute()` in a suite with no backend.** Both send a request for every draft the local checks accept.
|
|
57
|
+
- **The same case at two layers.** Mount only for what the view-model spec cannot show.
|
|
58
|
+
- **A status code as a result.** For command calls and query `perform()`, model unauthorized outcomes with a complete result envelope containing `isAuthorized: false` and `isSuccess: false`, not a bare `401` or `403`. Polling subscriptions are different: they recognize those statuses and can synthesize an unauthorized result. Commands special-case `404`; queries using Auto can retry `405` or `501` with GET. Build the unauthorized result with the envelope helper in Command results.
|
|
59
|
+
|
|
60
|
+
### Client validation in a UI spec
|
|
61
|
+
|
|
62
|
+
Use a real proxy and the synchronous call; nothing is stubbed and nothing is sent. This proxy carries a mirrored `notEmpty()` rule for `name`:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const command = new RegisterInspector();
|
|
66
|
+
command.name = 'Kari Nordmann';
|
|
67
|
+
command.validateClientSide().isValid.should.be.true;
|
|
68
|
+
|
|
69
|
+
command.name = '';
|
|
70
|
+
|
|
71
|
+
const result = command.validateClientSide();
|
|
72
|
+
result.isValid.should.be.false;
|
|
73
|
+
result.validationResults.flatMap(_ => _.members).should.contain('name');
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- `validateClientSide()` runs the generated rules, then the required-property check, and returns a `CommandResult` synchronously.
|
|
77
|
+
- `await command.validate()` runs the same local steps and returns without a request only when one of them blocks. For a draft they accept, it POSTs to the command's route with `/validate` appended. It is the wrong call for a spec that must pass with no backend.
|
|
78
|
+
- The required-property check refuses only `null` and `undefined`. A cleared text field holds `''`, which passes it; `''` is refused only when the proxy carries a mirrored rule such as `notEmpty()`. Spec the cleared field and the never-set field as separate cases when both matter.
|
|
79
|
+
- `command.validation.validate(command)` runs the rules alone, without the required-property check. Do not use it in place of `validateClientSide()`.
|
|
80
|
+
- Rules that need the server (`Must`, `MustAsync`, `When`, `Unless`, custom validators, anything that reads state) are not on the proxy. For those, the UI spec stubs `execute` to resolve `CommandResult.validationFailed([...])` and proves only what the screen does next.
|
|
81
|
+
|
|
82
|
+
The result shape, the severity behaviour and the full list of what is mirrored are in `cratis-specifications-test-typescript-behavior`, Generated command client validation.
|
|
83
|
+
|
|
40
84
|
## Runner and structure
|
|
41
85
|
|
|
42
86
|
Dev dependencies of the frontend project: `vitest`, `chai`, `chai-as-promised`, `sinon`, `sinon-chai`, typings for the Mocha-style globals (`@types/mocha`), typings for the assertion libraries that do not bundle their own (`@types/chai`, `@types/chai-as-promised`, `@types/sinon`, `@types/sinon-chai`), and a reflect-metadata polyfill (`reflect-metadata` or `@cratis/fundamentals/reflection`). View models carry `tsyringe` decorators, and `tsyringe` throws on import without the polyfill. Mounted specs also need `@testing-library/react`, its peer `@testing-library/dom` (the package manager does not add it for you) and `jsdom`. Use what the app already has.
|
|
@@ -298,7 +342,7 @@ export const commandResult = (overrides: Partial<CommandEnvelope>, responseType:
|
|
|
298
342
|
- `severity` is a `ValidationResultSeverity`: `Unknown`, `Information`, `Warning` or `Error`.
|
|
299
343
|
- `members` names the fields. A command form attributes a result to a field when a member equals the property name exactly (case-sensitive) or is a dotted path that starts with it (`startsAt.Value`).
|
|
300
344
|
- `reason` defaults to `ValidationResultReason.Rule`. The others are `ConcurrencyViolation`, `ConstraintViolation`, `ValidatorFailed`, `DependencyUnavailable`, `MalformedRequest` and `FrameworkFailure`. `ValidationResultReasonDetail.Required` marks a missing required value.
|
|
301
|
-
- Warning-confirmation flows: `execute(allowedSeverity?, ignoreWarnings?)`. Without
|
|
345
|
+
- Warning-confirmation flows: `execute(allowedSeverity?, ignoreWarnings?)`. Without a declared blocking severity and with default caller options, only `Error` blocks locally. With a declared floor, findings at or above it and `Unknown` block; caller options cannot weaken that floor. `validateClientSide()` lists advisory findings without marking the draft invalid. Assert that the re-submit passed `ValidationResultSeverity.Warning` or `ignoreWarnings` `true` (`context.execute.secondCall.args`).
|
|
302
346
|
|
|
303
347
|
What you give up by stubbing `execute`: the real `execute` first runs the command's client rules and required-property checks. If either fails, it returns a validation failure without sending a request; a missing required property gets the message `<name> is required` with the property as its member. On success it also resets the change-tracking baseline (`hasChanges`). To prove either behaviour, keep the real `execute` and stub `fetch` (see Isolation and reset), or call `validateClientSide()`, which returns the client result synchronously. The other command members you can drive or assert are `validate()`, `clear()`, `setInitialValues(values)`, `setInitialValuesFromCurrentValues()`, `revertChanges()`, `hasChanges` and `onPropertyChanged(callback, thisArg)`.
|
|
304
348
|
|
|
@@ -9,6 +9,7 @@ description: Use when writing or repairing an isolated TypeScript spec for a cal
|
|
|
9
9
|
|
|
10
10
|
- What an isolated spec is
|
|
11
11
|
- Choose the boundary
|
|
12
|
+
- What each spec proves
|
|
12
13
|
- How a given context behaves
|
|
13
14
|
- Default path
|
|
14
15
|
- Capability catalog
|
|
@@ -34,6 +35,26 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
|
|
|
34
35
|
|
|
35
36
|
A direct call bypasses Arc's pipeline. Cover the decision's branches directly and prove the wiring at the pipeline layer, not the same rule at both layers. Skip getters, forwarding, and other trivial code with no consequential behavior of its own.
|
|
36
37
|
|
|
38
|
+
## What each spec proves
|
|
39
|
+
|
|
40
|
+
Default: call the behavior directly with explicit inputs. Reach for the other rows only when the promise is the one named in their first column.
|
|
41
|
+
|
|
42
|
+
| Spec | Proves | Does not prove |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| Direct call of a function, view model or handler | The decision for those inputs | Validation, authorization, binding or encoding around it |
|
|
45
|
+
| `validateClientSide()` on a real generated command proxy | Which drafts the browser refuses before any request | That the server accepts the draft, or any rule that exists only on the server |
|
|
46
|
+
| Real proxy call against a stubbed `fetch` | The request the proxy sends, and how the caller treats the envelope the stub returns | That a server would return that envelope: the rule, status code, authorization and route are the stub's invention |
|
|
47
|
+
| Stubbed proxy method (execute, perform, subscribe) | What the caller does with that result | Local validation, the request and change tracking, which the stub skips |
|
|
48
|
+
|
|
49
|
+
Do not combine them into a false proof:
|
|
50
|
+
|
|
51
|
+
- A canned refusal from a stubbed `fetch` or a stubbed proxy method is not evidence that the rule exists. Prove the rule where it runs.
|
|
52
|
+
- The proxy's asynchronous validate and its execute reach the server for every draft the local rules accept. Neither belongs in a spec that must pass with no backend unless `fetch` is stubbed.
|
|
53
|
+
- A stubbed `fetch` does not feed an observable query's subscription over a socket or event source. Stub the subscription.
|
|
54
|
+
- Do not assert the same rule at two layers. The client mirror gets one case per rule the screen depends on; the server rule is proven once in the pipeline.
|
|
55
|
+
|
|
56
|
+
See Generated command client validation and Proxies against a stubbed fetch in your language reference for the exact calls, what the client reads from a response, and the members that do not exist.
|
|
57
|
+
|
|
37
58
|
## How a given context behaves
|
|
38
59
|
|
|
39
60
|
The `given` helper takes a context type and a callback and returns the body of a suite. See Given context lifetime in your language reference when a spec passes alone but fails with its siblings, when a context constructor receives `undefined`, or when choosing between per-test and per-suite setup.
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
- Fake time
|
|
13
13
|
- Arc command decision
|
|
14
14
|
- Generated command client validation
|
|
15
|
+
- Proxies against a stubbed fetch
|
|
15
16
|
- Specs without globals
|
|
16
17
|
- Common mistakes and recovery
|
|
17
18
|
|
|
@@ -345,14 +346,68 @@ Start from a draft the rules accept, prove it passes, then change exactly one fi
|
|
|
345
346
|
|
|
346
347
|
What the local result covers:
|
|
347
348
|
|
|
348
|
-
- **Mirrored rules.** With the default generation setting the proxy carries the backend validator's translatable rules, for example `NotEmpty()` as `notEmpty()` and `LessThanOrEqualTo(12)` as `lessThanOrEqual(12)`. `notEmpty()` rejects `null`, `undefined`, a blank string and an empty array.
|
|
349
|
-
- **Required properties.** A non-optional property fails only when it is `null` or `undefined`. An empty string `''` passes this check but can fail a mirrored rule such as `notEmpty()` or `minLength(1)`.
|
|
350
|
-
- **Not translated.** `Must`, `MustAsync`, custom validators, conditional rules (`When`, `Unless`) and any rule that needs a dependency exist only on the server. A project generated with client validation set to `server` carries no generated rules at all.
|
|
349
|
+
- **Mirrored rules.** With the default generation setting the proxy carries the backend validator's translatable rules, for example `NotEmpty()` as `notEmpty()` and `LessThanOrEqualTo(12)` as `lessThanOrEqual(12)`. Data-annotation attributes such as `[Required]` (as `notEmpty()`), `[StringLength]`, `[Range]` and `[RegularExpression]` are mirrored the same way. `notEmpty()` rejects `null`, `undefined`, a blank string and an empty array.
|
|
350
|
+
- **Required properties.** A non-optional property fails only when it is `null` or `undefined`. An empty string `''` passes this check but can fail a mirrored rule such as `notEmpty()` or `minLength(1)`. A property bound to a route parameter is not checked.
|
|
351
|
+
- **Not translated.** `Must`, `MustAsync`, custom validators, conditional rules (`When`, `Unless`), a rule whose severity is computed per request, and any rule that needs a dependency exist only on the server. A project generated with client validation set to `server` carries no generated rules at all.
|
|
352
|
+
|
|
353
|
+
How the result is shaped:
|
|
354
|
+
|
|
355
|
+
- **Rules run first.** When a mirrored rule blocks, the result holds only the rule failures; the required-property check has not run. Do not expect `<name> is required` next to a rule failure in the same result.
|
|
356
|
+
- **Only blocking results make it invalid.** A rule with warning or information severity leaves `isValid` and `isSuccess` `true` and is still listed in `validationResults`. Assert `isValid` for a refusal and the member for the field; a non-empty `validationResults` alone is not a refusal. Without a declared blocking severity and with default caller options, only `Error` blocks locally. With a declared floor, findings at or above it and `Unknown` block; caller options cannot weaken that floor. `validateClientSide()` lists advisory findings without marking the draft invalid.
|
|
357
|
+
- **A draft with nothing to report** returns `CommandResult.empty`.
|
|
358
|
+
- **`validate()` merges.** When the request is sent and succeeds, the returned result also lists the local non-blocking results.
|
|
359
|
+
|
|
360
|
+
Members that do not exist or do something else:
|
|
361
|
+
|
|
362
|
+
| Tempting | Reality |
|
|
363
|
+
| --- | --- |
|
|
364
|
+
| `command.isValid`, `command.errors`, `command.validationResults` | None is on the proxy. Read `isValid` and `validationResults` from the returned `CommandResult`; it has no `errors` member. |
|
|
365
|
+
| `command.validation.validate(command)` | Runs only the generated rules and returns a `ValidationResult[]`: no required-property check, no severity filtering. `validation` is `undefined` on a proxy without rules. Call `validateClientSide()` instead. |
|
|
366
|
+
| `validateClientSide(severity)` | Takes no arguments. Only `execute(allowedSeverity?, ignoreWarnings?)` takes the warning arguments. |
|
|
367
|
+
| `query.validateClientSide()`, `query.validate()` | Query proxies have neither. Their local checks run inside `perform` and `subscribe`; see Proxies against a stubbed fetch. |
|
|
351
368
|
|
|
352
369
|
A passing local result is therefore not proof that the server accepts the command. Prove each server-only rule in a backend spec through the command pipeline (see `cratis-specifications-exercise-backend`). Do not stub `fetch` with a canned failure and call that proof of the rule: it proves only how the caller handles a refusal.
|
|
353
370
|
|
|
354
371
|
To see which rules a proxy carries, read the generated file; never edit it. How a screen uses the two calls is in `cratis-arc-react-bind-slice`.
|
|
355
372
|
|
|
373
|
+
## Proxies against a stubbed fetch
|
|
374
|
+
|
|
375
|
+
Stub `fetch` only to prove what a real proxy sends or how it reads an answer. To prove what a screen does with a result, stub the proxy's `execute`, `perform` or `subscribe` instead (see `cratis-specifications-test-application-ui`); to prove what the server answers, use `cratis-arc-testing-typescript` for an Arc Node server or `cratis-specifications-exercise-backend` for a C# backend.
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
const fetchStub = sinon.stub(globalThis, 'fetch').resolves({ status: 200, json: async () => envelope } as Response);
|
|
379
|
+
command.setOrigin('http://localhost');
|
|
380
|
+
|
|
381
|
+
const result = await command.execute();
|
|
382
|
+
|
|
383
|
+
fetchStub.should.have.been.calledOnce;
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
Under the node environment there is no document to take the origin from, so set it on the proxy before the call. Set a valid origin in Node before testing the request. Without it, URL construction fails before `fetch`: command calls and observable-query `perform()` reject; snapshot-query `perform()` returns an exception result. Restore the stub in `afterEach`.
|
|
387
|
+
|
|
388
|
+
What the proxy does before it calls `fetch`:
|
|
389
|
+
|
|
390
|
+
| Proxy call | Local outcome without a request |
|
|
391
|
+
| --- | --- |
|
|
392
|
+
| `command.execute()`, `command.validate()` | A blocking rule or a missing required property resolves a validation failure. |
|
|
393
|
+
| `query.perform(args)` | A failing generated rule resolves `QueryResult.validationFailed`. A required request parameter that is absent, `null`, `undefined` or `''` resolves an unsuccessful result whose data is the query's default value, and logs a warning. |
|
|
394
|
+
| `observableQuery.subscribe(callback, args)` | A failing generated rule delivers the validation failure to the callback. A missing required parameter delivers a successful empty result holding the default value. No connection opens in either case. |
|
|
395
|
+
|
|
396
|
+
Assert `fetchStub.should.not.have.been.called` to prove a local refusal sent nothing.
|
|
397
|
+
|
|
398
|
+
What the proxy reads from the answer:
|
|
399
|
+
|
|
400
|
+
- **The body is the result.** The flags (`isSuccess`, `isAuthorized`, `isValid`, `hasExceptions`) and `validationResults` come from the JSON envelope exactly as written. For command calls and query `perform()`, model unauthorized outcomes with a complete result envelope containing `isAuthorized: false` and `isSuccess: false`, not a bare `401` or `403`. Polling subscriptions are different: they recognize those statuses and can synthesize an unauthorized result. Commands special-case `404`; queries using Auto can retry `405` or `501` with GET.
|
|
401
|
+
- **A status code alone models nothing.** A stub answering `401` or `403` with an empty body does not produce an unauthorized result. The body cannot be parsed, so a command resolves a failed result with an exception message and a query resolves an unsuccessful result with its default value. For an unauthorized result, put `isAuthorized: false` and `isSuccess: false` in the envelope. Whether a real server answers `401` or `403` is a server-pipeline fact a stub cannot establish.
|
|
402
|
+
- **A rejected `fetch`.** A command resolves `CommandResult.failed` with the error in `exceptionMessages`. A snapshot query's `perform` resolves a result with `hasExceptions` `true` and the default value as data; an abort is rethrown. An observable query's `perform` rejects.
|
|
403
|
+
- **Query HTTP method.** A query is sent with `GET` unless the application configures another method or the spec calls `setHttpMethod`. Assert the method only when the spec set it.
|
|
404
|
+
|
|
405
|
+
What a stubbed `fetch` cannot stand in for:
|
|
406
|
+
|
|
407
|
+
- **Observable delivery.** `subscribe` receives results over a WebSocket or an event source, not from `fetch`; only the polling transport reads them with `fetch`. Stub `subscribe`, capture its callback and push results through it.
|
|
408
|
+
- **The server's decision.** The envelope is the spec's own text. It shows the client handles that shape, not that any command, validator, policy or route produces it.
|
|
409
|
+
- **Shared transport state.** A spec that lets a query reach the stub leaves module-level state behind; call `resetSharedMultiplexer()` and `resetQueryHttpMethodResolution()` from `@cratis/arc/queries` in `afterEach`.
|
|
410
|
+
|
|
356
411
|
## Specs without globals
|
|
357
412
|
|
|
358
413
|
When the package does not expose global suite functions, import them from the runner. The example uses Vitest matchers; keep the package's assertion style and naming regardless of how the suite functions are bound:
|