fhir_stub_server 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5fb4014444b1e91bdc898632088e20b41be964c7e6547a363161dc0c9a076178
4
+ data.tar.gz: 736e595de5081963c0bcceb0c69c84a3dcc4efd00794ef9a3a896ffda3ceff8c
5
+ SHA512:
6
+ metadata.gz: f3064fad6f3c0d9c1df734e28601d5609e44053f8d614d4dc05a05af6a06fd3a9068717dddf24fb22825d0e4ca2b637f5b46fc56f3dfabe758659fa4c94909e5
7
+ data.tar.gz: c4860c941b476456c2d2bd010796dcaa81de9f2e93e29402392f5bce19e2fdbcb74899cb734281825ffb394184e5526753a111cb242bf61be2aff8fbfe0c3c42
data/.rubocop.yml ADDED
@@ -0,0 +1,20 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.3
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+ Exclude:
6
+ - 'vendor/**/*'
7
+ - 'tmp/**/*'
8
+
9
+ # Example groups, shared examples above all, grow past the default length.
10
+ Metrics/BlockLength:
11
+ Exclude:
12
+ - 'spec/**/*'
13
+
14
+ # Reek rejects one-letter names such as `e`.
15
+ Naming/RescuedExceptionsVariableName:
16
+ PreferredName: error
17
+
18
+ # Steep reads `#: Type` assertions where it cannot infer a tuple's type.
19
+ Layout/LeadingCommentSpace:
20
+ AllowRBSInlineAnnotation: true
data/.yardopts ADDED
@@ -0,0 +1,3 @@
1
+ --markup markdown
2
+ --hide-api private
3
+ --readme README.md
data/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions
4
+ follow [Semantic Versioning](https://semver.org/).
5
+
6
+ ## [Unreleased]
7
+
8
+ ## [0.1.0] - 2026-11-25
9
+
10
+ Initial release.
11
+
12
+ ### Added
13
+
14
+ - Demo Data from FHIR NPM packages and Bundles, answering built-in reads
15
+ (`GET /<Type>/<id>`, `GET /metadata`).
16
+ - Pairs matched on method, path, query and form body, answered from a file or with
17
+ FHIRPath (`resource`, `select` with `include`). Expressions are evaluated with the FHIR
18
+ model of the packages' `fhirVersions` (R4 when no package states one), so choice
19
+ elements resolve (`effective` finds an `effectiveDateTime`).
20
+ - `page_size: n` on a `select` response: the searchset comes in pages of n matches, each
21
+ but the last with a `next` link to a Stub-served continuation URL (`<base>/_page/...`).
22
+ - `- from: <path>` entries in `fhir.pairs` and `validator.pairs`: the Pairs of a shared
23
+ YAML file, spliced in at that position, its paths relative to it.
24
+ - A validator role: canned issues per profile and resource, and `expected_context` checks.
25
+ - Reports: `#served`, `#context_mismatches` and `#unmatched`, each miss with its nearest
26
+ Pair, the differences and a paste-ready `suggested_request`; `Stub#unmatched_report`.
27
+ They name a Pair by where it is written (`fhir.pairs[1]`, `fhir.pairs[0] (shared.yml[7])`).
28
+ - `Stub#unused_pairs` and `Stub#unused_pairs_report`: the Pairs no request used, in config
29
+ order.
30
+ - `Stub#empty_selects`: each `select` or `include` that yielded nothing at build time,
31
+ but for Pairs whose response says `expect_empty: true`.
32
+ - Adapters: in process through WebMock (`WebMockAdapter.install`, and `uninstall` to
33
+ restore the query notation `install` replaced), over HTTP through `RackApp` and
34
+ `HTTPServer` (Puma).
35
+ - YAML configs through `FHIRStubServer.load`, and Scenario replay with `fhir-stub-server`
36
+ and `config.ru`: load-time skips and empty selects are logged at start, each miss as it
37
+ arrives and, by `fhir-stub-server`, the unused Pairs on shutdown.
@@ -0,0 +1,10 @@
1
+ # Code of Conduct
2
+
3
+ "fhir_stub_server" follows [The Ruby Community Conduct Guideline](https://www.ruby-lang.org/en/conduct) in all "collaborative space", which is defined as community communications channels (such as mailing lists, submitted patches, commit comments, etc.):
4
+
5
+ * Participants will be tolerant of opposing views.
6
+ * Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
7
+ * When interpreting the words and actions of others, participants should always assume good intentions.
8
+ * Behaviour which can be reasonably considered harassment will not be tolerated.
9
+
10
+ If you have any concerns about behaviour within this project, please contact us at ["TODO: Write your email address"](mailto:"TODO: Write your email address").
data/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,352 @@
1
+ # fhir_stub_server
2
+
3
+ [![CI](https://github.com/projkov/fhir_stub_server/actions/workflows/ci.yml/badge.svg)](https://github.com/projkov/fhir_stub_server/actions/workflows/ci.yml)
4
+ [![Gem Version](https://img.shields.io/gem/v/fhir_stub_server)](https://rubygems.org/gems/fhir_stub_server)
5
+ [![codecov](https://codecov.io/gh/projkov/fhir_stub_server/branch/main/graph/badge.svg)](https://codecov.io/gh/projkov/fhir_stub_server)
6
+ [![API reference](https://img.shields.io/badge/docs-rubydoc.info-blue)](https://rubydoc.info/gems/fhir_stub_server)
7
+
8
+ A strict stub for the FHIR server under test and for Inferno's validator, for regression
9
+ tests of FHIR test kits. It answers only the requests a Scenario declares, serves IG
10
+ examples as Demo Data without copying them, and reports every request it could not
11
+ answer with a diff against the nearest declared one. It behaves the same in the rspec
12
+ process (through WebMock) and over HTTP (for a child `inferno execute` process).
13
+
14
+ It is IG-agnostic: it knows FHIR packages, Bundles and FHIRPath, nothing about a
15
+ specific IG.
16
+
17
+ ## Install
18
+
19
+ Add it to the test kit's Gemfile, never to its gemspec, together with the gems of the
20
+ adapters you use:
21
+
22
+ ```ruby
23
+ group :development, :test do
24
+ gem 'fhir_stub_server', '~> 0.1'
25
+ gem 'webmock' # FHIRStubServer::WebMockAdapter
26
+ gem 'puma' # FHIRStubServer::HTTPServer and fhir-stub-server
27
+ gem 'rackup' # only for `bundle exec rackup`
28
+ end
29
+ ```
30
+
31
+ For changes not released yet, use
32
+ `gem 'fhir_stub_server', github: 'projkov/fhir_stub_server', ref: '<sha>'` instead.
33
+
34
+ The core needs only `fhirpath-rb`. An adapter whose gem is missing raises a
35
+ `FHIRStubServer::Error` naming it. To work on the kit and this gem together:
36
+ `bundle config local.fhir_stub_server <path>`.
37
+
38
+ ## Config
39
+
40
+ One YAML file per Scenario. It has no URLs or base paths, so it works in both modes.
41
+ Paths are relative to the file.
42
+
43
+ ```yaml
44
+ fhir:
45
+ sources: # Demo Data, in order: a later Source wins on the same Type/id
46
+ - package: ../igs/1.0.0.tgz # a FHIR NPM package archive
47
+ - bundle: overrides.json # a Bundle of any type: its entry.resource items
48
+ pairs:
49
+ - request: { path: /Patient, query: { family: Smith } }
50
+ response:
51
+ select: "Bundle.entry.resource.ofType(Patient).where(name.family = 'Smith')"
52
+ validator: # optional
53
+ pairs:
54
+ - { profile: au-core-patient|1.0.0, resource: Patient/p1, issues: [] }
55
+ expected_context: { sv: 4.0.1 }
56
+ ```
57
+
58
+ Quote dates and times (`birthdate: '1970-01-01'`): unquoted, YAML reads them as dates,
59
+ which the config does not accept.
60
+
61
+ `FHIRStubServer.load(path)` reads such a file, or the `server:` block of a kit's
62
+ `scenario.yml`, and returns a `FHIRStubServer::Stub`. `FHIRStubServer::Stub.new(hash, dir: '.')`
63
+ takes the same config as a Hash, its paths relative to `dir` (by default the working
64
+ directory).
65
+
66
+ Every config error raises a `FHIRStubServer::Error` naming the file or Pair when the
67
+ Stub is built, never when a request arrives: a missing or invalid file, the same
68
+ `Type/id` twice in one package, packages that share no FHIR version fhirpath-rb has a
69
+ model for, several server CapabilityStatements, a Pair response
70
+ with zero or several body kinds, `include` or `page_size` without `select`, a `page_size`
71
+ that is no positive integer, a `resource` expression yielding zero or several resources, an
72
+ included file that is no list, an include cycle.
73
+
74
+ ### Sources and Demo Data
75
+
76
+ - A package contributes every `*.json` with a `resourceType` key, conformance resources
77
+ included. Files without one (`package.json`, `.index.json`, `openapi/`) and `xml/` are
78
+ ignored. A Bundle in a package stays whole, as `Bundle/<id>`.
79
+ - A resource without an `id` is skipped and recorded as a load-time entry in `#served`.
80
+ - Without any Pair, Demo Data answers `GET /<Type>/<id>`, and `GET /metadata` with the
81
+ one CapabilityStatement whose `rest.mode` is `server` (an IG's responder). Only a read
82
+ without query parameters is answered; `GET /Patient/p1?x=1` is a miss unless a Pair
83
+ declares it.
84
+
85
+ ### Pairs
86
+
87
+ A Pair is one expected request and the response configured for it.
88
+
89
+ - `request`: `path` (relative to the FHIR base, required), `method` (default `GET`),
90
+ `query` and, for `POST .../_search`, the form `body`: each maps a name to a value or a
91
+ list of values.
92
+ - A request matches on method, path and its query (and form body) as an unordered
93
+ multiset of exact values. Headers are ignored. The first matching Pair answers, and a
94
+ Pair wins over a Demo Data read, so it can force a 404 or an altered resource.
95
+ - `response`: optional `status` (default 200) and exactly one body kind:
96
+ - `body_file`: a file sent as it is;
97
+ - `resource: <fhirpath>`: the one resource the expression yields;
98
+ - `select: <fhirpath>`, optionally with `include: <fhirpath>`: a `searchset` Bundle of
99
+ the matches (`search.mode: match`, counted in `total`) and includes
100
+ (`search.mode: include`), with `fullUrl`s and a `self` link built from the request's
101
+ base URL.
102
+ - `page_size: n` on a `select` response pages its matches, n per page; `total` counts all
103
+ of them and the includes come on the first page. Each page but the last has a `next` link
104
+ to a Stub-served continuation URL, `<base>/_page/<index>/<page>`, where `<index>` is the
105
+ Pair's position in the list once `from:` files are spliced in. Clients follow `next` and
106
+ do not build the URL. Its GET is answered and recorded like any request, `answered_by` the
107
+ Pair; a page past the last is a miss:
108
+
109
+ ```yaml
110
+ - request: { path: /Observation, query: { patient: p1 } }
111
+ response:
112
+ select: "Bundle.entry.resource.ofType(Observation).where(subject.reference = 'Patient/p1')"
113
+ page_size: 2
114
+ ```
115
+ - Expressions are literal FHIRPath, evaluated once over a `collection` Bundle of all
116
+ Demo Data (after overrides), with the FHIR model of the packages' `fhirVersions`
117
+ (R4 when no package states one), so choice elements resolve: `effective` finds an
118
+ `effectiveDateTime`.
119
+ - A `select` or `include` that yields nothing still builds, and is listed in
120
+ `stub.empty_selects` (see [Reports](#reports)). For a search meant to find nothing, add
121
+ `expect_empty: true` to the response; it leaves out the Pair's `include` too:
122
+
123
+ ```yaml
124
+ - request: { path: /Patient, query: { family: Nobody } }
125
+ response:
126
+ select: "Bundle.entry.resource.ofType(Patient).where(name.family = 'Nobody')"
127
+ expect_empty: true
128
+ ```
129
+ - Writes (`POST`, `PUT`) get their Pair's response and never change Demo Data.
130
+ - Any other request gets a 404 OperationOutcome and is recorded in `#unmatched`.
131
+
132
+ Pairs that several Scenarios share go in their own file. An entry `- from: <path>` in
133
+ `fhir.pairs` or `validator.pairs` is replaced by the Pairs of that file, a YAML list that
134
+ may itself have `from:` entries; paths in it (`from`, `body_file`) are relative to it.
135
+ Only splicing: a Scenario that needs a different Pair writes its own, and the first
136
+ matching Pair still answers.
137
+
138
+ ```yaml
139
+ # scenario.yml
140
+ fhir:
141
+ pairs:
142
+ - from: ../_shared/patient_searches.yml
143
+ - request: { path: /Observation }
144
+ response: { select: "Bundle.entry.resource.ofType(Observation)" }
145
+ ```
146
+
147
+ ```yaml
148
+ # ../_shared/patient_searches.yml
149
+ - request: { path: /Patient, query: { family: Smith } }
150
+ response: { body_file: smith.json } # ../_shared/smith.json
151
+ ```
152
+
153
+ ### Validator
154
+
155
+ The Stub can stand in for Inferno's validator wrapper. `POST /validate` is matched on
156
+ the profile (`filesToValidate[0].fileName` without `.json`) and the `Type/id` of the
157
+ file's content; `sessionId` is ignored. Inferno names the file after the last segment
158
+ of the profile URL, version included, so a Pair for
159
+ `http://example.org/StructureDefinition/au-core-patient|1.0.0` says
160
+ `profile: au-core-patient|1.0.0`. Two cases follow from that rule:
161
+
162
+ - A suite that validates against a base resource passes its core URL, usually without a
163
+ version (`http://hl7.org/fhir/StructureDefinition/CapabilityStatement`), so the Pair
164
+ says `profile: CapabilityStatement`.
165
+ - A suite may validate one resource against both `au-core-patient|1.0.0` and the
166
+ unversioned `au-core-patient` (AU Core's reference-resolution tests do): each needs its
167
+ own Pair.
168
+
169
+ A matching Pair answers `{ "sessionId": "stub", "outcomes": [{ "issues": issues }] }`.
170
+
171
+ `expected_context` lists the validator settings to check: each key is compared exactly
172
+ with the request's `cliContext` (or `validationContext`), and other keys are ignored. A
173
+ mismatch is recorded in `#context_mismatches`, and the call is still answered. Without a
174
+ `validator:` block (`stub.validator?` is false) the adapters route only the FHIR role, so
175
+ the real validator can be used.
176
+
177
+ ## Reports
178
+
179
+ Reports name a Pair by where it is written: `fhir.pairs[1]`, `validator.pairs[0]`, or,
180
+ for a Pair from an included file, the entry that includes it and its place in each file
181
+ along the way, paths relative to the config: `fhir.pairs[0] (../_shared/patient_searches.yml[7])`.
182
+
183
+ After a run, each in arrival order and the same for both adapters:
184
+
185
+ - `stub.unmatched`: `{ request:, nearest_pair:, differences:, suggested_request: }` per
186
+ unanswered request. `nearest_pair` names the Pair with the same method and path and the
187
+ fewest differing parameters; `differences` maps each differing parameter to
188
+ `{ expected:, actual: }` (`nil` for a parameter missing on one side).
189
+ `suggested_request` is what to paste as the `request` of a new Pair, as the config
190
+ writes it: `method` only when not GET, `path`, `query` and, for `POST .../_search`, the
191
+ form `body`, a single value unwrapped. For a validator miss it is `{ 'profile' =>,
192
+ 'resource' => }` (add `issues`), or `nil` when the request is no validate call.
193
+ - `stub.context_mismatches`: `{ request:, key:, expected:, actual: }`.
194
+ - `stub.served`: `{ kind: :load, skipped:, reason: }` for each skipped resource, then
195
+ `{ kind: :request, request:, answered_by: }` per request, `answered_by` naming the
196
+ answering Pair, or `:demo_data` or `:miss`.
197
+
198
+ `stub.unused_pairs` lists, in config order (`fhir.pairs`, then `validator.pairs`), the
199
+ Pairs no request was answered by: `{ role:, pair:, request: }`, `pair` naming where it
200
+ is written and `request` the request it matches, shaped like a `suggested_request`
201
+ (`{ 'profile' =>, 'resource' => }` for a validator Pair). As a kit changes, Pairs stop being requested;
202
+ assert `expect(stub.unused_pairs).to be_empty, stub.unused_pairs_report` to notice.
203
+
204
+ `stub.empty_selects` lists, in config order, each `select` or `include` that yielded
205
+ nothing when the Stub was built: `{ role: :fhir, pair:, expression: }`. It is usually a
206
+ typo, or an expression fhirpath-rb evaluates wrongly, and the search then answers an empty
207
+ searchset that a test may skip or even pass on. A Pair whose response says
208
+ `expect_empty: true` is left out, so assert `expect(stub.empty_selects).to be_empty`.
209
+
210
+ ## In process: WebMock
211
+
212
+ ```ruby
213
+ stub = FHIRStubServer.load('spec/fixtures/scenario.yml')
214
+ FHIRStubServer::WebMockAdapter.install(stub, fhir_base_url: 'http://fhir.stub.test/fhir',
215
+ validator_base_url: 'http://validator.stub.test')
216
+ # run the suite against http://fhir.stub.test/fhir, then:
217
+ expect(stub.unmatched).to be_empty, stub.unmatched_report
218
+ expect(stub.unused_pairs).to be_empty, stub.unused_pairs_report
219
+ ```
220
+
221
+ `install` registers one catch-all WebMock stub per base URL. Requests outside them
222
+ still raise through `WebMock.disable_net_connect!`.
223
+
224
+ - `install` sets `WebMock::Config.instance.query_values_notation = :flat_array`
225
+ globally, so repeated query parameters are kept. Until `uninstall` restores the
226
+ previous notation, `hash_including` and `hash_excluding` query stubs stop matching;
227
+ plain Hash and URL-string queries still work. `uninstall` leaves the catch-all stubs in
228
+ place until WebMock resets. In RSpec:
229
+ `config.after { FHIRStubServer::WebMockAdapter.uninstall }`.
230
+ - `webmock/rspec` resets stubs after every example, so install per example.
231
+
232
+ ## Over HTTP: Rack and Puma
233
+
234
+ ```ruby
235
+ server = FHIRStubServer::HTTPServer.new(stub)
236
+ base_url = server.start # e.g. http://127.0.0.1:53214, FHIR under /fhir, validator under /validator
237
+ # run `inferno execute` against "#{base_url}/fhir"
238
+ server.stop
239
+ ```
240
+
241
+ `HTTPServer` serves the Stub with Puma on a random free port of `127.0.0.1`, in a
242
+ background thread. `FHIRStubServer::RackApp.new(stub, fhir_base_path: '/fhir',
243
+ validator_base_path: '/validator')` is the Rack app behind it, for any Rack server;
244
+ `HTTPServer.new(stub, fhir_base_path: '/r4')` passes these options on to it.
245
+ It reads only the Rack env and needs no rack gem; CI runs the specs on Rack 2.2 and 3.2.
246
+ Requests outside both base paths get a plain 404 and are not recorded.
247
+ `HTTPServer.new` also takes any other Rack app (such as a `Replay`) and serves it as it is;
248
+ `#wait` blocks until `#stop`.
249
+
250
+ ## Scenario replay
251
+
252
+ To point Inferno's UI at one Scenario's Stub:
253
+
254
+ ```bash
255
+ bundle exec fhir-stub-server spec/fixtures/scenario.yml
256
+ # FHIR base URL: http://127.0.0.1:53214/fhir
257
+ # Validator base URL: http://127.0.0.1:53214/validator (only with a validator: block)
258
+ ```
259
+
260
+ or, with Rack tooling and a port of your choice:
261
+
262
+ ```bash
263
+ STUB_SERVER_CONFIG=spec/fixtures/scenario.yml bundle exec rackup "$(bundle info --path fhir_stub_server)/config.ru" -p 9292
264
+ ```
265
+
266
+ Both log load-time skips and empty selects (`Empty fhir.pairs[2]: <expression>`) at
267
+ start, and each unmatched request with its nearest Pair and differences; nothing fails on
268
+ a miss. `fhir-stub-server` also logs the unused Pairs on shutdown.
269
+
270
+ Both serve a `FHIRStubServer::Replay`, the Rack app that writes these lines. To replay from
271
+ Ruby, serve `replay = FHIRStubServer::Replay.new(stub, log)` (`log` defaults to `$stderr`)
272
+ with `HTTPServer.new(replay)`, and call `replay.log_unused_pairs` once it has stopped.
273
+
274
+ ## Working with LLM agents
275
+
276
+ An agent maintaining a kit's Scenarios works in a loop:
277
+
278
+ 1. Run the kit's specs. Assert with `expect(stub.unmatched).to be_empty, stub.unmatched_report`:
279
+ a failure then lists one line per request the Stub could not answer, with its nearest
280
+ Pair, the differences and a suggested request:
281
+
282
+ ```text
283
+ Unmatched fhir GET /Observation?_count=10&code=8867-4&patient=p2; nearest fhir.pairs[1]: _count expected nil, got ["10"]; patient expected ["p1"], got ["p2"]; request: {"path":"/Observation","query":{"_count":"10","code":"8867-4","patient":"p2"}}
284
+ ```
285
+
286
+ 2. Decide for each line whether the kit changed on purpose or regressed. A regression is
287
+ fixed in the kit, never by declaring the request: the Stub is strict so that drift shows.
288
+ 3. For an intended request, paste the JSON after `request:` into `fhir.pairs` as
289
+ `- request: <JSON>` (JSON is valid YAML) and write its `response`. A validator line ends
290
+ with `pair: <JSON>`: paste it into `validator.pairs` as `- <JSON>` and add `issues`.
291
+ When the nearest Pair is in a shared file (`nearest fhir.pairs[0] (../_shared/x.yml[7])`)
292
+ and the change holds for every Scenario that includes it, edit the shared file;
293
+ otherwise add the Pair to the Scenario, above the `from:` entry so that it answers first.
294
+ 4. Rerun until the report is empty; check `stub.context_mismatches` too.
295
+ 5. Assert `expect(stub.unused_pairs).to be_empty, stub.unused_pairs_report`: each line
296
+ names a Pair no request used and its request:
297
+
298
+ ```text
299
+ Unused fhir.pairs[0] (../_shared/x.yml[7]): {"path":"/Observation","query":{"patient":"p1"}}
300
+ ```
301
+
302
+ Remove the Pair, or fix it when the kit still sends that request in another form (an
303
+ `Unmatched` line then names it as the nearest Pair). Remove a Pair from a shared file
304
+ only when no Scenario that includes it uses it.
305
+
306
+ Pitfalls:
307
+
308
+ - Quote dates and times in the YAML (`birthdate: '1970-01-01'`).
309
+ - Built-in reads (`GET /<Type>/<id>`, `GET /metadata`) answer only without query
310
+ parameters; a read that sends one needs a Pair.
311
+ - When several Pairs match a request, the first answers, and a Pair wins over Demo Data.
312
+ - `package`, `bundle`, `body_file` and `from` paths are relative to the file that names them.
313
+ - fhirpath-rb (0.1.7) has defects that change what a `select` or `include` matches,
314
+ mostly without an error, so check `stub.empty_selects`:
315
+ - `in` and `contains` are always false for elements read from the resource. Add
316
+ `.toString()`: `where(status.toString() in ('final' | 'amended'))`.
317
+ - A primitive that has only an extension (`_birthDate` with a data-absent-reason) is
318
+ empty, yet `exists()` is true and a comparison raises. Guard it in a `where` of its
319
+ own, since `and` evaluates both sides:
320
+ `where(birthDate.extension.empty()).where(birthDate > @1975-05-02)`.
321
+
322
+ To point a kit's own agents here, add a line to its `AGENTS.md`:
323
+
324
+ ```markdown
325
+ - Stub configs use fhir_stub_server: read "Working with LLM agents" in its README (`bundle info --path fhir_stub_server`) before changing them.
326
+ ```
327
+
328
+ ## Development
329
+
330
+ ```bash
331
+ bin/setup
332
+ bundle exec rake # specs, then rubocop, reek, flay, flog and steep
333
+ ```
334
+
335
+ CI runs the same `bundle exec rake` on Ruby 3.3 and 4.0 for every push to `main` and every
336
+ pull request.
337
+
338
+ To release:
339
+
340
+ 1. Set `VERSION` in `lib/fhir_stub_server/version.rb`, run `bundle install` to update
341
+ `Gemfile.lock`, and rename `## [Unreleased]` in `CHANGELOG.md` to
342
+ `## [<VERSION>] - <date>` above a new, empty `## [Unreleased]`. Commit and push.
343
+ 2. Publish a GitHub release tagged `v<VERSION>` whose notes link to that `CHANGELOG.md`
344
+ section. The Release workflow checks the tag and the changelog, runs `bundle exec rake`
345
+ and pushes the gem to RubyGems through trusted publishing.
346
+
347
+ Whether RubyGems treats it as a prerelease depends on `VERSION` (`0.2.0.rc1`), not on
348
+ GitHub's pre-release checkbox.
349
+
350
+ ## License
351
+
352
+ Apache-2.0. See [LICENSE.txt](LICENSE.txt).