PowerShell / Intermediate: binding, errors, modules, data, and tests / Lesson 14
Validate JSON at an object boundary
Decode synthetic JSON, check required properties, and distinguish a serialized snapshot from a live object.
On this page
Lesson goals
- Separate JSON parsing from domain validation.
- Check required fields before consuming an object.
- Verify a serialization round trip without assuming live methods survive.
- Validate required JSON data against explicit type and range rules.
- Test snapshot values and shape without assuming live object identity or methods.
Define the external contract
JSON is text exchanged at a boundary; parsing it creates a PowerShell representation but does not establish the domain meaning of its fields. This example expects an item name and quantity, and uses synthetic data only. A real contract should also state types, permitted ranges, unknown-property policy, and whether null differs from absence. Decide how a malformed or incomplete response reaches the caller before processing it.
Decode and check required fields
The first block parses a small JSON string and rejects a null or missing required property. It then selects the two fields. This is a deliberately limited presence check, not complete validation: it does not prove that quantity is an integer within a useful range or that name is a nonempty string. Add those checks for a real application, and handle malformed JSON as a separate parsing failure.
$json = '{"name":"Pen","quantity":2}'
$item = $json | ConvertFrom-Json
if ($null -eq $item.name -or $null -eq $item.quantity) {
throw "Missing required field"
}
$item | Select-Object name, quantity
The presence check rejects null or missing fields; additional type and domain checks are still required.
Round-trip a snapshot
The second block serializes a simple object and parses it again before displaying its fields. It shows that data can cross a text boundary, not that object identity or live methods are preserved. More complex nested structures require an appropriate serialization depth and explicit tests for the intended representation. Keep both the serialized text and the restored object within a controlled fixture when experimenting.
$snapshot = [pscustomobject]@{ name = "Pen"; quantity = 2 }
$json = $snapshot | ConvertTo-Json
$restored = $json | ConvertFrom-Json
"{0}: {1}" -f $restored.name, $restored.quantity
The round trip restores data properties, not the original object identity or live methods.
Separate data from effects
Validate the decoded object before using it to update a file, issue an API request, or calculate a total. Keep the original input available for safe diagnosis without logging secrets or private fields. A successful parse is not authorization to act, and a valid quantity does not validate the rest of the record. Report a field-specific failure or integration error according to the command’s public contract.
Verify valid and invalid cases
Test valid input, malformed JSON, missing name, explicit null, wrong-type quantity, zero, and the allowed range boundaries. Verify that rejected input causes no downstream mutation and that a valid zero remains distinct from missing data when the domain allows it. For a round trip, assert the restored fields and values rather than comparing formatted console output. Run under each declared PowerShell edition and platform.
Define a precise domain contract
A JSON parser recognizes syntax but does not know whether a value is a valid inventory item. For this lesson’s synthetic contract, name must be a nonblank string and quantity must be an integer from 0 through 100 inclusive. Zero is valid; a missing field, null, a numeric-looking string, a fraction, and an out-of-range integer are different failures. Decide the treatment of unknown properties as well: this fixture rejects unexpected keys rather than silently extending its schema. These are example application rules, not universal JSON rules. A caller should receive a field-specific failure and no accepted item when validation fails. Check every required field before performing a calculation or side effect; successful parsing alone does not authorize a write. Preserve only safe diagnostic context, because the raw input can contain sensitive fields.
Walk through the validator
The following illustrative function parses an in-memory string as a hashtable and checks key presence separately from values. Its explicit type checks avoid accepting the string '2' simply because PowerShell can convert it in some contexts. The allowed integer representations in this example are Int32 and Int64; other numeric representations, including fractions, are rejected before the range comparison. IsNullOrWhiteSpace catches both an empty name and a name containing only whitespace, but it is called only after the string type check. The final object is created only after all checks pass. The valid fixture produces name Book and quantity 3; a value of -1 or 101 throws instead of producing a result. This exact source was run in isolated PowerShell 7.6.0 with the stated synthetic fixture. A real validator should also document numeric limits and input size and test each declared edition.
function Convert-LabItem {
param([string]$Text)
$item = $Text | ConvertFrom-Json -AsHashtable -ErrorAction Stop
if ($item -isnot [System.Collections.IDictionary]) { throw 'Expected object' }
foreach ($key in 'name','quantity') { if (-not $item.ContainsKey($key)) { throw "Missing $key" } }
foreach ($key in $item.Keys) { if ($key -cnotin 'name','quantity') { throw "Unknown $key" } }
if ($item['name'] -isnot [string] -or [string]::IsNullOrWhiteSpace($item['name'])) { throw 'Invalid name' }
$q = $item['quantity']
if (($q -isnot [int] -and $q -isnot [long]) -or $q -lt 0 -or $q -gt 100) { throw 'Invalid quantity' }
[pscustomobject]@{ name = $item['name']; quantity = $q }
}
Convert-LabItem '{"name":"Book","quantity":3}'
name quantity
---- --------
Book 3
The exact block ran in isolated PowerShell 7.6.0 and produced the displayed result; no external resources were used.
Test boundaries and failure order
Validation is a sequence of separate decisions. First handle malformed JSON as a parsing failure; then require an object-like representation and the named keys; then check null, types, domain range, and any cross-field rules. Rejecting at a boundary does not imply that later checks passed. Test a valid record, each missing key, explicit null, zero, 100, -1, 101, a fractional quantity, and a string quantity. Check that no effectful adapter was called for each rejected input. If the application must accumulate multiple errors instead of stopping at the first, define that behavior explicitly and avoid publishing a partially validated record. Distinguish failure from a legitimate empty result, and avoid broad catch blocks that convert all errors to a successful default. Verify actual output types and cardinality as well as the error category.
Treat serialized data as a snapshot
ConvertTo-Json produces text containing a representation of object properties; methods and original object identity do not cross the boundary as live behavior. Parsing that text creates a new representation of the captured values. If the original object changes afterward, the previously created text remains a snapshot of the earlier state, not a live reference. Set serialization depth for the intended nested schema and inspect warnings: the documented default depth is 2, and PowerShell warns when an input exceeds the specified depth. Round-trip tests should parse the text and compare required values, types and collection shape instead of comparing console formatting or relying only on string equality. Singleton arrays can be affected by pipeline enumeration; use documented options and test zero, one, and multiple values. A snapshot is not proof that every object type round-trips losslessly.
Gate effects after validation
Keep parsing and validation separate from the adapter that writes a file or sends a request. A useful test substitutes a controlled adapter and asserts that invalid inputs invoke it zero times; a valid input may invoke it only under the documented policy. A parsed record can still be invalid, and a valid record is not by itself permission to modify an external resource. For actual integration, use an authorized isolated fixture, record the engine version, and verify both the effect and cleanup. If an external operation times out after validation, its state may be uncertain and needs reconciliation rather than blind repetition. Never log credentials or unredacted private input merely to make a test diagnosable. The worked code uses synthetic in-memory data and was checked in isolated PowerShell 7.6.0; no file, network call or provider action was executed.
20 worked examples
1. Accept a valid item
Problem: Validate a synthetic item with a name and permitted integer quantity.
- Book is a nonblank string and the JSON integer is within the declared range.
- The displayed checks accept the specified fixture; a full validator also checks key presence and unknown fields.
$item = '{"name":"Book","quantity":3}' | ConvertFrom-Json -AsHashtable; $valid = $item['name'] -is [string] -and $item['quantity'] -is [long] -and $item['quantity'] -ge 0 -and $item['quantity'] -le 100; $valid
True
A valid fixture must meet every declared rule, not merely parse. Qualified in isolated PowerShell 7.6.0 without external resources.
Expected result: True for these checks under the 7.6 integer representation.
Why this result follows: A valid fixture must meet every declared rule, not merely parse.
2. Detect a missing field
Problem: A decoded object has name but omits quantity.
- The fixture contains only the name key.
- The explicit key-presence check returns false for quantity.
$item = '{"name":"Book"}' | ConvertFrom-Json -AsHashtable; $item.ContainsKey('quantity')
False
Presence checks distinguish a missing key from an explicit null value. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: Presence checks distinguish a missing key from an explicit null value.
3. Reject explicit null
Problem: A quantity key exists but its value is null.
- The quantity key is present in this fixture.
- Its value is null and therefore violates the non-null integer rule.
$item = '{"name":"Book","quantity":null}' | ConvertFrom-Json -AsHashtable; $item.ContainsKey('quantity'); $null -eq $item['quantity']
True
True
A present key is not sufficient when its value is invalid. Qualified in isolated PowerShell 7.6.0 without external resources.
Expected result: True then True; reject the item.
Why this result follows: A present key is not sufficient when its value is invalid.
4. Accept zero at the lower boundary
Problem: The quantity is zero under the inclusive range contract.
- Zero is an integer and equals the inclusive lower bound.
- It also lies below the upper bound, so the range checks return true.
$q = 0; ($q -is [int]) -and ($q -ge 0) -and ($q -le 100)
True
An explicit range check does not mistake valid zero for missing data. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: An explicit range check does not mistake valid zero for missing data.
5. Reject a negative quantity
Problem: A synthetic item has quantity minus one.
- Negative one is less than the minimum zero.
- The selected branch reports below range before any effect is attempted.
$q = -1; if ($q -lt 0) { 'below range' } else { 'in range' }
below range
The domain range excludes negative inventory under this example contract. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: The domain range excludes negative inventory under this example contract.
6. Accept the upper boundary
Problem: Check whether quantity 100 is allowed by the inclusive rule.
- The value is at least zero and equals the upper bound.
- The inclusive less-than-or-equal comparison therefore accepts it.
$q = 100; $q -ge 0 -and $q -le 100
True
An inclusive bound includes the endpoint rather than rejecting it. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: An inclusive bound includes the endpoint rather than rejecting it.
7. Reject above the maximum
Problem: Check a quantity of 101 against the maximum.
- The quantity 101 exceeds the maximum of 100.
- The branch produces too large and the item must not proceed to the adapter.
$item = @{ name='Book'; quantity=101 }; if ($item.quantity -gt 100) { 'too large' }
too large
A separate upper-bound check protects the declared domain limit. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: A separate upper-bound check protects the declared domain limit.
8. Reject a fractional quantity
Problem: The JSON quantity is 2.5 where an integer is required.
- The parsed decimal value is not an Int32 or Int64 integer.
- The integer-type predicate returns false before any range acceptance.
$item = '{"name":"Book","quantity":2.5}' | ConvertFrom-Json -AsHashtable; $q = $item['quantity']; ($q -is [int]) -or ($q -is [long])
False
A value inside the numeric range can still violate the integer requirement. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: A value inside the numeric range can still violate the integer requirement.
9. Reject a numeric-looking string
Problem: The quantity is the JSON string "2" rather than a number.
- JSON quotes make quantity a string even though its characters resemble a number.
- The string type check is true, so the strict integer contract rejects it.
$item = '{"name":"Book","quantity":"2"}' | ConvertFrom-Json -AsHashtable; $item['quantity'] -is [string]
True
Implicit conversion should not silently change a declared wire type. Qualified in isolated PowerShell 7.6.0 without external resources.
Expected result: True; reject the string quantity.
Why this result follows: Implicit conversion should not silently change a declared wire type.
10. Reject a whitespace name
Problem: A name containing only spaces is invalid under the contract.
- The string is present but contains no non-whitespace characters.
- IsNullOrWhiteSpace returns true, so the validator rejects the name.
$name = ' '; [string]::IsNullOrWhiteSpace($name)
True
Presence alone is not a nonblank-name validation. Qualified in isolated PowerShell 7.6.0 without external resources.
Expected result: True; reject the name.
Why this result follows: Presence alone is not a nonblank-name validation.
11. Reject malformed input
Problem: A quantity document is missing its closing brace.
- The text is not complete JSON because its object never closes.
- The parsing error enters catch and no accepted record is emitted.
try { '{"name":"Book","quantity":3' | ConvertFrom-Json -ErrorAction Stop; 'accepted' } catch { 'parse failed' }
parse failed
Syntax failure occurs before domain validation can accept an item. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: Syntax failure occurs before domain validation can accept an item.
12. Reject an unknown property
Problem: The strict schema allows only name and quantity, but color is supplied.
- The key color is outside the declared allowlist.
- The filtered key list contains color, which the strict policy rejects.
$item = @{ name='Book'; quantity=3; color='blue' }; @($item.Keys | Where-Object { $_ -cnotin 'name','quantity' })
color
An explicit unknown-field policy prevents silent schema expansion. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: An explicit unknown-field policy prevents silent schema expansion.
13. Round-trip a simple record
Problem: Serialize a different item and read both restored fields.
- Serialization captures the name and quantity as JSON data.
- Parsing creates a representation containing Pencil and 5.
$original = [pscustomobject]@{ name='Pencil'; quantity=5 }; $text = $original | ConvertTo-Json; $copy = $text | ConvertFrom-Json; $copy.name; $copy.quantity
Pencil
5
A simple round trip preserves these declared values in the intended fixture. Qualified in isolated PowerShell 7.6.0 without external resources.
Expected result: Pencil then 5
Why this result follows: A simple round trip preserves these declared values in the intended fixture.
14. Verify nested snapshot depth
Problem: A snapshot contains a nested warehouse label; verify its value.
- Depth 4 includes the nested warehouse structure in this fixture.
- Parsing the serialized snapshot exposes the label North.
$item = @{ name='Book'; stock=@{ warehouse=@{ label='North' } } }; $json = $item | ConvertTo-Json -Depth 4; ($json | ConvertFrom-Json).stock.warehouse.label
North
The depth setting and round-trip assertion protect the nested field. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: The depth setting and round-trip assertion protect the nested field.
15. Preserve one-element shape
Problem: An item list has exactly one value and must remain an array.
- NoEnumerate retains the parsed array as one pipeline object.
- The subsequent conversion preserves the surrounding array brackets.
'["Book"]' | ConvertFrom-Json -NoEnumerate | ConvertTo-Json -Compress
["Book"]
A singleton collection and a scalar have different JSON shapes. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: A singleton collection and a scalar have different JSON shapes.
16. Distinguish object identity
Problem: A record is serialized and parsed; compare it with the original reference.
- Parsing constructs a new object representation from the JSON text.
- The new object is not the same reference as the original.
$original = [pscustomobject]@{name='Book'; quantity=3}; $copy = $original | ConvertTo-Json | ConvertFrom-Json; [object]::ReferenceEquals($original,$copy)
False
A snapshot carries values, not the original live object identity. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: A snapshot carries values, not the original live object identity.
17. Do not expect methods to survive
Problem: A live object has a custom method; identify the snapshot boundary.
- ConvertTo-Json serializes data properties rather than the custom live method.
- The parsed representation has no Label script method, so the check is true.
$record = [pscustomobject]@{ name='Book' }; $record | Add-Member -MemberType ScriptMethod -Name Label -Value { $this.name }; $text = $record | ConvertTo-Json; $copy = $text | ConvertFrom-Json; $null -eq $copy.PSObject.Methods['Label']
True
Serialization is not a transport for executable object behavior. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: Serialization is not a transport for executable object behavior.
18. Observe snapshot timing
Problem: A quantity changes after serialization; inspect the stored text.
- The text was created while quantity was 3.
- Changing the original object afterward does not change the saved text.
$item = [pscustomobject]@{quantity=3}; $text = $item | ConvertTo-Json; $item.quantity = 8; ($text | ConvertFrom-Json).quantity
3
A serialized snapshot represents the state at the time it was made. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: A serialized snapshot represents the state at the time it was made.
19. Gate the adapter on validation
Problem: A negative quantity must not reach the synthetic effect adapter.
- The negative fixture fails the range condition.
- The guarded adapter counter remains zero.
$quantity = -2; $calls = 0; if ($quantity -ge 0 -and $quantity -le 100) { $calls++ }; $calls
0
Validation must finish before any external effect is permitted. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: Validation must finish before any external effect is permitted.
20. Redact diagnostic input
Problem: A record contains a token; produce a safe diagnostic identifier.
- The diagnostic contains only a field name and reason, not the token.
- Its token-key presence check is false for this fixture.
$item = @{ name='Book'; quantity=3; token='secret-fixture' }; $diagnostic = @{ field='quantity'; reason='out of range' }; $diagnostic.ContainsKey('token')
False
Minimal diagnostic context avoids unnecessarily exposing sensitive input. Qualified in isolated PowerShell 7.6.0 without external resources.
Why this result follows: Minimal diagnostic context avoids unnecessarily exposing sensitive input.
Common errors and fixes
Malformed JSON reaches business logic
- Why it happens
- Parsing failures were caught and replaced with an apparently valid empty object.
- How to fix it
- Propagate a clear parsing failure and stop processing the record.
- Prevent it next time
- Test malformed text and assert that no mutation occurs.
A wrong-type quantity passes a presence check
- Why it happens
- A field’s existence was treated as proof of its domain type.
- How to fix it
- Validate type and range after checking presence.
- Prevent it next time
- Test a numeric string, null, fraction, and out-of-range value.
A deserialized object is expected to retain live methods
- Why it happens
- Serialization was treated as preserving the original runtime object.
- How to fix it
- Use the restored data to construct a suitable local object or operate at the original boundary.
- Prevent it next time
- Test the actual round trip and document required properties.
20 practice exercises
1. Does the first example fully validate quantity?
Show hint
Compare a presence check with type and range checks.
Show worked solution
No. It only rejects a missing or null value. A complete domain validator must check the intended type, integer requirement, and allowed range before the quantity reaches a calculation.
The original example rejects missing or null name and quantity, but it does not establish that quantity is an integer in an allowed range or that name is nonblank text. Add those domain checks and test zero, bounds, fractional values and numeric-looking strings before performing any calculation.
Check your solution
- The answer identifies the missing integer and range checks.
- A valid zero remains distinct from a missing value.
2. What is preserved by the second example?
Show hint
Separate the data properties from the live object that held them.
Show worked solution
The simple name and quantity data can be read after the round trip. It does not establish that object identity, live methods, or every nested representation survives; those requirements need separate design and tests.
The original snapshot example restores the simple name Pen and quantity 2 as data properties. It does not preserve the original object reference or its live methods, and it does not prove every nested shape survives; those require explicit design and round-trip tests.
Check your solution
- The restored simple fields are name Pen and quantity 2.
- Object identity and methods are not claimed to survive.
3. A validated Ruler costs 6 per unit and has quantity 12. Design the validation gate and calculate the total.
Show hint
The multiplication is allowed only after the item passes the domain checks.
Show worked solution
Validate the nonblank name and integer quantity 12 against 0–100, then calculate 12 times 6 for a total of 72. Reject an invalid item before calling the calculation adapter; a correct arithmetic result alone does not validate the input.
Check your solution
- The validated total is 72.
- An invalid item never reaches the calculation adapter.
4. Field note is optional with default "none" in schema v1 but required in v2. Classify a record with no note.
Show hint
The same payload can have different validity by version.
Show worked solution
Under v1 use the documented default none; under v2 reject the missing required note. Record the schema version and block effects for the v2 failure.
Check your solution
- Version 1 yields default none.
- Version 2 rejects the missing note.
5. A record has blank name and quantity -1 under the nonblank and 0–100 rules. Define accumulated errors.
Show hint
Both fields violate separate rules.
Show worked solution
Return errors for name and quantity, publish no accepted object, and test a fully valid record separately. The invalid record must not reach an effect adapter even if one field is repaired later.
Check your solution
- Both name and quantity errors are reported.
- No invalid object is published.
6. A reviewer changes the maximum comparison from -le 100 to -lt 100. Construct a regression that detects the change.
Show hint
Choose the exact declared upper boundary.
Show worked solution
Submit an otherwise valid item with integer quantity 100 and assert acceptance. The changed comparison rejects 100, so the test fails; also assert 101 remains rejected to protect the upper side.
Check your solution
- Quantity 100 must be accepted.
- Quantity 101 must be rejected.
7. A batch contains quantities 2, 2.5, and 3. Design an independent-item validation report.
Show hint
Type is checked for each record before range.
Show worked solution
Report 2 and 3 as accepted integers and 2.5 as rejected for a non-integer type. Include each record’s identity and an aggregate partial status; do not round the fraction or hide the failure.
Check your solution
- Two integer records are accepted.
- The fractional record is identified as rejected.
8. Compare strict and coercing policies for a quoted quantity "12" and state one risk of coercion.
Show hint
The wire type is a string before any conversion.
Show worked solution
The strict policy rejects the string; an explicitly documented coercion policy may convert it to integer 12 after validation. Coercion can hide a producer schema change, so report or monitor conversion and test failure for nonnumeric text.
Check your solution
- Strict mode rejects the string.
- Coercion, if allowed, yields 12 and is observable.
9. A name may contain internal spaces but cannot begin or end with whitespace. Design a validation and error-reporting policy.
Show hint
Nonblank and normalized input are different rules.
Show worked solution
Accept a documented trimmed name such as "Blue Pen", but reject or explicitly normalize a value with leading or trailing whitespace according to policy. Preserve the original safely for diagnostics and test internal spaces separately.
Check your solution
- Internal spaces remain valid.
- Leading or trailing whitespace follows an explicit rule.
10. An input repeats the exact quantity key with values 3 and 9. Define a policy before parsing loses information.
Show hint
A resulting object may not retain both duplicate entries.
Show worked solution
Reject duplicate keys at a parsing or validation boundary capable of detecting them before collapsing the object. Test that boundary with both values; do not silently select one as the authoritative quantity.
Check your solution
- The duplicated key is detected before collapse.
- Neither quantity is silently accepted as authoritative.
11. A record adds an unknown supplier field to name and quantity. Choose a strict and a forward-compatible policy.
Show hint
Both policies must be deliberate and testable.
Show worked solution
A strict schema rejects supplier as unexpected; a forward-compatible schema can retain or ignore it while still validating required fields. Choose one policy for the application and test it explicitly rather than letting parser behavior decide.
Check your solution
- The strict policy rejects supplier.
- The compatible policy states whether supplier is retained or ignored.
12. A JSON document is syntactically valid but its root is an array rather than the required object. Define the error boundary.
Show hint
Parsing can succeed while the root shape fails.
Show worked solution
Report a root-shape schema error after parsing and before field access or effects. Test a valid object and malformed syntax separately so the caller can distinguish parser failure from a wrong-shaped value.
Check your solution
- The array root is rejected as a schema failure.
- Malformed syntax remains a separate parse failure.
13. A snapshot contains items with IDs A and B. Design a round-trip test that catches a missing item.
Show hint
Check nested cardinality and identity.
Show worked solution
Serialize and parse the synthetic snapshot, then assert exactly two nested items with IDs A and B. Fail if either is absent or duplicated even when the enclosing items property exists.
Check your solution
- Exactly IDs A and B survive.
- The nested item count is two.
14. A batch envelope has items [] in one case and IDs A,B in another. Define the outer and inner cardinality checks.
Show hint
The envelope and array have distinct counts.
Show worked solution
Assert one outer object in each case; its items array has count zero in the first and two with IDs A and B in the second. Do not flatten the inner records into unrelated top-level objects.
Check your solution
- Each case has one outer object.
- The inner counts are zero and two.
15. Two snapshots are taken before and after an approved change. Design a comparison that retains both versions.
Show hint
Each snapshot represents a distinct point in time.
Show worked solution
Store the first and second serialized values separately with timestamps or version IDs, then assert the first contains the old quantity and the second the new quantity. Do not overwrite the first artifact when preserving change history is required.
Check your solution
- Both snapshots remain available.
- Each snapshot matches its recorded version.
16. Restored quantity 3 and unit price 4 must produce a local total. Define a safe calculation boundary.
Show hint
Use trusted code on validated data.
Show worked solution
Validate both values as permitted numeric types, then call a trusted local calculation to obtain 12. Reject malformed or missing values and do not execute method text supplied by the serialized payload.
Check your solution
- The validated total is 12.
- Payload text is not executed as code.
17. An adapter is allowed only after validation and explicit authorization. Design a four-case gate test.
Show hint
Both conditions are required.
Show worked solution
Test valid/authorized, valid/unauthorized, invalid/authorized and invalid/unauthorized fixtures. Only the first may invoke the controlled adapter; record separate validation and authorization outcomes without accessing real resources.
Check your solution
- Only the valid and authorized case invokes the adapter.
- Each rejection reason remains distinguishable.
18. A validator receives an array containing one valid and one invalid item. Define atomic and independent-item policies.
Show hint
The application must choose publication semantics.
Show worked solution
Under an atomic policy reject the whole array and publish no items; under an independent policy return the valid item with an identified failure for the other. Test both policies explicitly rather than inferring success from one good record.
Check your solution
- Atomic mode publishes no items.
- Independent mode preserves both the success and failure identity.
19. A validation error should expose a field path but not the submitted value. Design a diagnostic schema.
Show hint
Field location and payload content are separate.
Show worked solution
Emit the non-secret field path and a stable error code, omit the submitted value and credentials, and test with a synthetic sensitive marker. Check all actual diagnostic channels before extending the secrecy claim.
Check your solution
- The field path and error code are retained.
- The submitted value and marker are absent.
20. A validator must support two declared PowerShell editions. Define a versioned boundary test plan.
Show hint
Run the same public contract against each target environment.
Show worked solution
In isolated environments for each supported edition, test valid and invalid types, zero and maximum boundaries, malformed input, and nested snapshot round trips. Record engine versions and actual results, including unsupported behavior; do not infer one edition’s behavior from another.
Check your solution
- Both editions receive the same boundary cases.
- The receipt records actual versions and results.
Key takeaways
- Parse external JSON and validate its domain separately.
- Treat serialized objects as data snapshots, not live identities.
- Parsing and presence checks do not replace domain validation.
- Zero, null, missing values and wrong types require distinct decisions.
- JSON snapshots carry data representations rather than live object behavior.