fhir_stub_server 0.1.0 → 0.2.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5fb4014444b1e91bdc898632088e20b41be964c7e6547a363161dc0c9a076178
4
- data.tar.gz: 736e595de5081963c0bcceb0c69c84a3dcc4efd00794ef9a3a896ffda3ceff8c
3
+ metadata.gz: c2b243c22a60b4c693f27d74bb3ce3426c0adf8b7f0e1246688a56c402a316d6
4
+ data.tar.gz: f9b5a8350318a1a91e591279674e1259d7643ced0a9b4080a0259dc4de9036cb
5
5
  SHA512:
6
- metadata.gz: f3064fad6f3c0d9c1df734e28601d5609e44053f8d614d4dc05a05af6a06fd3a9068717dddf24fb22825d0e4ca2b637f5b46fc56f3dfabe758659fa4c94909e5
7
- data.tar.gz: c4860c941b476456c2d2bd010796dcaa81de9f2e93e29402392f5bce19e2fdbcb74899cb734281825ffb394184e5526753a111cb242bf61be2aff8fbfe0c3c42
6
+ metadata.gz: b25ee68f053f4b877b1acee5369e1eb705e42b0f344fdcc246b7699caf15f8db99e7a14df8f00725b9b08bee52f723676b1c6f801c8e96bb27772986ef8c04b1
7
+ data.tar.gz: '08c895abc5db6b7d63b5fc6eebb731024392da2e3a9e91620019a2f4288744113ca071a7b250f9e2a9cdef12323815b068afe0029c2f4b85ee204fa2d1639a2c'
data/CHANGELOG.md CHANGED
@@ -5,6 +5,31 @@ follow [Semantic Versioning](https://semver.org/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.2.0] - 2026-11-26
9
+
10
+ ### Added
11
+
12
+ - Write Pairs: `request.method` takes `GET`, `POST`, `PUT`, `PATCH` or `DELETE` (any
13
+ case); another method is a config error. On `POST` (except `POST .../_search`), `PUT` and
14
+ `PATCH`, `request.body` is the expected JSON body, an object or array (a JSON Patch
15
+ included), compared with the parsed request body regardless of key order and
16
+ whitespace. A write Pair without `body` still matches any body. A differing body is one
17
+ `body` entry in a miss's `differences`, and `suggested_request` and `unused_pairs` carry
18
+ the parsed body.
19
+ - A response with `status: 204` may have no body kind; it answers with an empty body and
20
+ no `content-type`.
21
+ - `dictionary: <path>`: a YAML mapping of names to strings whose values replace each
22
+ `${name}` in Pairs when the Stub is built, so a shared Pair file serves Scenarios with
23
+ different values. It applies in a FHIR Pair's `path`, `query` and form `body` values and
24
+ expressions, and a validator Pair's `profile` and `resource`, including Pairs spliced
25
+ through `from:`. An undefined `${name}` and an invalid dictionary are config errors;
26
+ reports show the substituted values.
27
+
28
+ ### Changed
29
+
30
+ - A `${...}` in those Pair strings, formerly literal, must name a dictionary entry.
31
+ - A `body` on a `GET` or `DELETE` Pair, formerly ignored, is a config error.
32
+
8
33
  ## [0.1.0] - 2026-11-25
9
34
 
10
35
  Initial release.
data/README.md CHANGED
@@ -21,7 +21,7 @@ adapters you use:
21
21
 
22
22
  ```ruby
23
23
  group :development, :test do
24
- gem 'fhir_stub_server', '~> 0.1'
24
+ gem 'fhir_stub_server', '~> 0.2'
25
25
  gem 'webmock' # FHIRStubServer::WebMockAdapter
26
26
  gem 'puma' # FHIRStubServer::HTTPServer and fhir-stub-server
27
27
  gem 'rackup' # only for `bundle exec rackup`
@@ -53,6 +53,7 @@ validator: # optional
53
53
  pairs:
54
54
  - { profile: au-core-patient|1.0.0, resource: Patient/p1, issues: [] }
55
55
  expected_context: { sv: 4.0.1 }
56
+ dictionary: dictionary.yml # optional: values for ${name} in Pairs (see Dictionary)
56
57
  ```
57
58
 
58
59
  Quote dates and times (`birthdate: '1970-01-01'`): unquoted, YAML reads them as dates,
@@ -66,10 +67,13 @@ directory).
66
67
  Every config error raises a `FHIRStubServer::Error` naming the file or Pair when the
67
68
  Stub is built, never when a request arrives: a missing or invalid file, the same
68
69
  `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.
70
+ model for, several server CapabilityStatements, a Pair request method other than GET,
71
+ POST, PUT, PATCH or DELETE, a `body` on a GET or DELETE, a JSON `body` that is no object or
72
+ array, a Pair response with zero (except for `status: 204`) or several body kinds,
73
+ `include` or `page_size` without `select`, a `page_size` that is no positive integer, a
74
+ `resource` expression yielding zero or several resources, an included file that is no
75
+ list, an include cycle, a dictionary that is no mapping of valid names to strings, a
76
+ `${name}` the dictionary does not define (or any `${name}` without a dictionary).
73
77
 
74
78
  ### Sources and Demo Data
75
79
 
@@ -86,13 +90,17 @@ included file that is no list, an include cycle.
86
90
 
87
91
  A Pair is one expected request and the response configured for it.
88
92
 
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.
93
+ - `request`: `path` (relative to the FHIR base, required), `method` (`GET`, `POST`, `PUT`,
94
+ `PATCH` or `DELETE`, in any case; default `GET`), `query` and `body`. `query` and, for
95
+ `POST .../_search`, the form `body` each map a name to a value or a list of values. On
96
+ other POSTs, `PUT` and `PATCH`, `body` is the expected JSON body (see
97
+ [Writes](#writes)); GET and DELETE take none.
92
98
  - 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:
99
+ multiset of exact values. Headers, `Content-Type` included, are ignored. The first
100
+ matching Pair answers, and a Pair wins over a Demo Data read, so it can force a 404 or
101
+ an altered resource.
102
+ - `response`: optional `status` (default 200) and exactly one body kind, or none for
103
+ `status: 204`, which answers with an empty body and no `content-type`:
96
104
  - `body_file`: a file sent as it is;
97
105
  - `resource: <fhirpath>`: the one resource the expression yields;
98
106
  - `select: <fhirpath>`, optionally with `include: <fhirpath>`: a `searchset` Bundle of
@@ -126,14 +134,38 @@ A Pair is one expected request and the response configured for it.
126
134
  select: "Bundle.entry.resource.ofType(Patient).where(name.family = 'Nobody')"
127
135
  expect_empty: true
128
136
  ```
129
- - Writes (`POST`, `PUT`) get their Pair's response and never change Demo Data.
137
+ - Writes get their Pair's response and never change Demo Data (see [Writes](#writes)).
130
138
  - Any other request gets a 404 OperationOutcome and is recorded in `#unmatched`.
131
139
 
140
+ #### Writes
141
+
142
+ On `POST` (except `POST .../_search`), `PUT` and `PATCH`, a Pair's `body` is the JSON
143
+ object or array the request must send, written inline: a resource, or a JSON Patch array.
144
+ Quote its dates (`birthDate: '1970-01-01'`), as everywhere in the config. It is compared
145
+ with the parsed request body: key order and whitespace are ignored, array order counts. A
146
+ Pair without `body` matches any body. A body that is not JSON, or empty, misses a Pair
147
+ that declares one.
148
+
149
+ ```yaml
150
+ - request:
151
+ method: PUT
152
+ path: /Patient/p1
153
+ body: { resourceType: Patient, id: p1, active: true }
154
+ response: { body_file: patient_p1_updated.json }
155
+ - request:
156
+ method: PATCH
157
+ path: /Patient/p1
158
+ body: [{ op: replace, path: /active, value: false }]
159
+ response: { resource: "Bundle.entry.resource.ofType(Patient).where(id = 'p1')" }
160
+ - request: { method: DELETE, path: /Patient/p1 }
161
+ response: { status: 204 }
162
+ ```
163
+
132
164
  Pairs that several Scenarios share go in their own file. An entry `- from: <path>` in
133
165
  `fhir.pairs` or `validator.pairs` is replaced by the Pairs of that file, a YAML list that
134
166
  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.
167
+ Only splicing: a Scenario that needs a different Pair writes its own, or attaches a
168
+ [Dictionary](#dictionary) when only values differ; the first matching Pair still answers.
137
169
 
138
170
  ```yaml
139
171
  # scenario.yml
@@ -150,6 +182,50 @@ fhir:
150
182
  response: { body_file: smith.json } # ../_shared/smith.json
151
183
  ```
152
184
 
185
+ ### Dictionary
186
+
187
+ Pairs that several Scenarios share but with different values (a patient id, a family
188
+ name, a code) are written once against named variables, and each Scenario attaches a
189
+ Dictionary with its values. `dictionary: <path>` sits beside `fhir:` and `validator:` (in
190
+ a `scenario.yml`, inside `server:`); the file is a YAML mapping of names
191
+ (`[A-Za-z_][A-Za-z0-9_]*`) to strings, so quote numbers and dates:
192
+
193
+ ```yaml
194
+ # scenario.yml
195
+ server:
196
+ dictionary: dictionary.yml
197
+ fhir:
198
+ sources:
199
+ - bundle: patients.json # holds Patient p1, family Smith
200
+ pairs:
201
+ - from: ../_shared/patient_reads.yml
202
+ ```
203
+
204
+ ```yaml
205
+ # dictionary.yml
206
+ patient_id: p1
207
+ family: Smith
208
+ ```
209
+
210
+ ```yaml
211
+ # ../_shared/patient_reads.yml
212
+ - request: { path: "/Patient/${patient_id}" }
213
+ response: { resource: "Bundle.entry.resource.ofType(Patient).where(id = '${patient_id}')" }
214
+ - request: { path: /Patient, query: { family: "${family}" } }
215
+ response: { select: "Bundle.entry.resource.ofType(Patient).where(name.family = '${family}')" }
216
+ ```
217
+
218
+ - `${name}` is replaced, anywhere inside the string, in a FHIR Pair's `request.path`,
219
+ `query` values and form `body` values (`POST .../_search`) and in `select`, `include` and
220
+ `resource`; in a validator Pair's `profile` and `resource`. Nowhere else: not in query
221
+ names, a JSON `body`, `body_file`, `from` or `sources` paths, or numbers.
222
+ - It is plain text, done once when the Stub is built: no escaping (a value with a `'`
223
+ breaks a FHIRPath string), and never a value from a request, so matching stays exact.
224
+ - One Dictionary serves the Scenario's own Pairs and every Pair spliced through `from:`,
225
+ however deep. Unused entries are fine; a `${name}` it does not define is a config error,
226
+ as is any `${name}` in a config without `dictionary:`.
227
+ - Reports show the substituted values; a Pair is still named by where it is written.
228
+
153
229
  ### Validator
154
230
 
155
231
  The Stub can stand in for Inferno's validator wrapper. `POST /validate` is matched on
@@ -185,11 +261,14 @@ After a run, each in arrival order and the same for both adapters:
185
261
  - `stub.unmatched`: `{ request:, nearest_pair:, differences:, suggested_request: }` per
186
262
  unanswered request. `nearest_pair` names the Pair with the same method and path and the
187
263
  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.
264
+ `{ expected:, actual: }` (`nil` for a parameter missing on one side), and a differing
265
+ JSON body to one `body` entry, `actual` the parsed request body (the raw string when it
266
+ is not JSON, `nil` when it is empty). `suggested_request` is what to paste as the
267
+ `request` of a new Pair, as the config writes it: `method` only when not GET, `path`,
268
+ `query` and `body`: the form body of `POST .../_search`, a single value unwrapped, or the
269
+ parsed JSON body of another write (left out when it is not a JSON object or array). For
270
+ a validator miss it is `{ 'profile' =>, 'resource' => }` (add `issues`), or `nil` when
271
+ the request is no validate call.
193
272
  - `stub.context_mismatches`: `{ request:, key:, expected:, actual: }`.
194
273
  - `stub.served`: `{ kind: :load, skipped:, reason: }` for each skipped resource, then
195
274
  `{ kind: :request, request:, answered_by: }` per request, `answered_by` naming the
@@ -291,6 +370,8 @@ An agent maintaining a kit's Scenarios works in a loop:
291
370
  When the nearest Pair is in a shared file (`nearest fhir.pairs[0] (../_shared/x.yml[7])`)
292
371
  and the change holds for every Scenario that includes it, edit the shared file;
293
372
  otherwise add the Pair to the Scenario, above the `from:` entry so that it answers first.
373
+ A suggested request holds the substituted values: pasted into a shared file, put its
374
+ `${name}`s back by hand.
294
375
  4. Rerun until the report is empty; check `stub.context_mismatches` too.
295
376
  5. Assert `expect(stub.unused_pairs).to be_empty, stub.unused_pairs_report`: each line
296
377
  names a Pair no request used and its request:
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FHIRStubServer
4
+ # The `dictionary:` file, names to strings, replacing each `${name}` in a Pair's strings as plain
5
+ # text when the Stub is built. Every `${...}` must name an entry; one Dictionary serves the
6
+ # config's Pairs and those of every file they include.
7
+ # @api private
8
+ class Dictionary
9
+ NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/
10
+ VARIABLE = /\$\{([^}]*)\}/
11
+ EXPRESSIONS = %w[select include resource].freeze
12
+
13
+ # Without a path the Dictionary is empty, so any `${name}` is undefined.
14
+ def self.load(path, dir)
15
+ new(path ? values(File.expand_path(path, dir)) : {})
16
+ end
17
+
18
+ def self.values(file)
19
+ values = FHIRStubServer.parse_file(file, :yaml)
20
+ raise Error, "#{file}: the dictionary must be a mapping of names to strings" unless values.is_a?(Hash)
21
+
22
+ values.each { |name, value| check(file, name, value) }
23
+ end
24
+
25
+ def self.check(file, name, value)
26
+ raise Error, "#{file}: #{name} is no valid variable name" unless NAME.match?(name.to_s)
27
+ raise Error, "#{file}: #{name} must be a string" unless value.is_a?(String)
28
+ end
29
+
30
+ private_class_method :values, :check
31
+
32
+ # A `fhir.pairs` Pair, substituted in its request's `path`, `query` values and form `body`
33
+ # values, and in its expressions; not in query names, a JSON `body` or a `body_file`.
34
+ def self.fhir_pair(pair, resolve)
35
+ request = resolved(pair['request'].to_h, %w[path query], resolve)
36
+ form = Request.search?(method: request['method'].to_s.upcase, path: request['path'].to_s)
37
+ pair.merge('request' => resolved(request, form ? %w[body] : [], resolve),
38
+ 'response' => resolved(pair['response'].to_h, EXPRESSIONS, resolve))
39
+ end
40
+
41
+ def self.resolved(config, keys, resolve) = config.merge(resolve.call(config.slice(*keys)))
42
+
43
+ def initialize(values)
44
+ @values = values
45
+ end
46
+
47
+ def fhir_pair(pair, where) = Dictionary.fhir_pair(pair, resolver(where))
48
+
49
+ def validator_key(pair, where) = resolver(where).call(pair.values_at('profile', 'resource'))
50
+
51
+ private
52
+
53
+ # Hash keys (query names) are left as written; `where` names the Pair in an undefined-variable error.
54
+ def resolver(where)
55
+ resolve = lambda do |value|
56
+ case value
57
+ when String then substitute(value, where)
58
+ when Array then value.map(&resolve)
59
+ when Hash then value.transform_values(&resolve)
60
+ else value
61
+ end
62
+ end
63
+ end
64
+
65
+ def substitute(string, where)
66
+ string.gsub(VARIABLE) do
67
+ name = ::Regexp.last_match(1).to_s
68
+ @values.fetch(name) { raise Error, "#{where}: undefined variable #{name}" }
69
+ end
70
+ end
71
+ end
72
+ end
@@ -5,8 +5,9 @@ module FHIRStubServer
5
5
  # [answered_by, response, { report name => entries }].
6
6
  # @api private
7
7
  class FHIRRole
8
- def initialize(config, demo_data, model, dir)
9
- @pairs = Pairs.load(config['pairs'].to_a, Pairs.fhirpath(demo_data, model), dir)
8
+ def initialize(config, demo_data, model, dir, dictionary)
9
+ spliced = Includes.splice(config['pairs'].to_a, 'fhir.pairs', dir)
10
+ @pairs = Pairs.load(spliced, Pairs.fhirpath(demo_data, model), dictionary)
10
11
  @reads = Sources.reads(demo_data)
11
12
  end
12
13
 
@@ -32,11 +33,13 @@ module FHIRStubServer
32
33
  end
33
34
 
34
35
  # A key as the config writes a Pair's `request`: `method` only when not GET, a single value
35
- # unwrapped, the form `body` only for `POST .../_search`.
36
+ # unwrapped, `body` the form of `POST .../_search` or the JSON of another write (none when
37
+ # it is no JSON object or array).
36
38
  def self.config(key)
37
39
  method = key[:method]
38
- { 'method' => (method unless method == 'GET'), 'path' => key[:path],
39
- 'query' => config_values(key[:query]), 'body' => config_values(key[:form]) }.compact
40
+ json = key[:json]
41
+ { 'method' => (method unless method == 'GET'), 'path' => key[:path], 'query' => config_values(key[:query]),
42
+ 'body' => config_values(key[:form]) || (json unless json.is_a?(String)) }.compact
40
43
  end
41
44
 
42
45
  def self.config_values(params)
@@ -12,7 +12,7 @@ module FHIRStubServer
12
12
  # [index, page] of the first Pair whose request the key matches (page 1) or of the Pair and
13
13
  # page a continuation URL names; nil for neither.
14
14
  def self.locate(pairs, key)
15
- index = pairs.index { |pair| pair[:key] == key }
15
+ index = pairs.index { |pair| Request.match?(pair[:key], key) }
16
16
  index ? page(index, 1) : continued(key)
17
17
  end
18
18
 
@@ -9,22 +9,25 @@ module FHIRStubServer
9
9
  # The response has exactly one body kind: `body_file` (literal JSON), `resource` (a FHIRPath
10
10
  # expression yielding exactly one resource) or `select` (FHIRPath, answered as a searchset;
11
11
  # an optional `include` adds resources with search.mode include, an optional `page_size` pages
12
- # the matches, see Paging). Expressions run once, over a collection Bundle of all Demo Data
13
- # with the FHIR model of its version (see Sources), when the Stub is built. An empty `select`
14
- # or `include` is listed in Stub#empty_selects, unless the response says `expect_empty: true`.
12
+ # the matches, see Paging); a `status: 204` may have none and answers an empty body.
13
+ # Expressions run once, over a collection Bundle of all Demo Data with the FHIR model of its
14
+ # version (see Sources), when the Stub is built. An empty `select` or `include` is listed in
15
+ # Stub#empty_selects, unless the response says `expect_empty: true`.
15
16
  #
16
- # `path` is relative to the FHIR base and required; `method` defaults to GET, `status` to 200.
17
- # `query` and `body` map names to a value or a list of values. `body` is the form body and
18
- # only counts for `POST .../_search`; other writes match whatever body they send.
19
- # When several Pairs match a request, the first one answers. An entry `{ from: <path> }` is
20
- # replaced by the Pairs of that file (see Includes).
17
+ # `path` is relative to the FHIR base and required; `method` (GET, POST, PUT, PATCH or DELETE)
18
+ # defaults to GET, `status` to 200. `query` maps names to a value or a list of values, and so
19
+ # does `body` for `POST .../_search`, the form body. On other POSTs, PUT and PATCH, `body` is a
20
+ # JSON object or array, compared with the parsed request body (key order and whitespace
21
+ # ignored); without it any body matches. GET and DELETE take no `body`.
22
+ # When several Pairs match a request, the first one answers. They come spliced (see Includes),
23
+ # each with the Dictionary substituted (see Dictionary#fhir_pair).
21
24
  # @api private
22
25
  module Pairs
23
26
  BODY_KINDS = %w[body_file select resource].freeze
24
27
 
25
- def self.load(pairs, fhirpath, dir)
26
- Includes.splice(pairs, 'fhir.pairs', dir).map do |pair, pair_dir, where|
27
- build(with_dir(pair, pair_dir), fhirpath, where)
28
+ def self.load(spliced, fhirpath, dictionary)
29
+ spliced.map do |pair, dir, where|
30
+ build(with_dir(dictionary.fhir_pair(pair, where), dir), fhirpath, where)
28
31
  end
29
32
  end
30
33
 
@@ -67,9 +70,15 @@ module FHIRStubServer
67
70
  end
68
71
  end
69
72
 
70
- # Query and form body differences in one Hash; a name differing in both keeps the form body's.
73
+ # Query and form body differences in one Hash, a name differing in both keeping the form
74
+ # body's, and a `body` entry for a differing JSON body.
71
75
  def self.differences(pair_key, request_key)
72
76
  diff(pair_key[:query], request_key[:query]).merge(diff(pair_key[:form].to_h, request_key[:form].to_h))
77
+ .merge(json_diff(pair_key[:json], request_key[:json]))
78
+ end
79
+
80
+ def self.json_diff(expected, actual)
81
+ expected && expected != actual ? { 'body' => { expected:, actual: } } : {}
73
82
  end
74
83
 
75
84
  def self.diff(expected, actual)
@@ -80,23 +89,12 @@ module FHIRStubServer
80
89
  end
81
90
 
82
91
  def self.build(pair, fhirpath, where)
83
- key = Request.key(request(pair['request'].to_h, where))
92
+ key = Request.key(Request.pair(pair['request'].to_h, where))
84
93
  response = pair['response'].to_h
85
94
  body, empty_selects = body(response, fhirpath, where)
86
95
  { key:, status: response.fetch('status', 200), body:, where:, empty_selects: }
87
96
  end
88
97
 
89
- # The Pair's request, normalized exactly like an incoming one.
90
- def self.request(config, where)
91
- path = config['path'].to_s
92
- raise Error, "#{where}: the request needs a path starting with /" unless path.start_with?('/')
93
-
94
- Request.build(
95
- role: :fhir, method: config.fetch('method', 'GET').upcase, base_url: '', path:,
96
- query: URI.encode_www_form(config['query'].to_h), body: URI.encode_www_form(config['body'].to_h)
97
- )
98
- end
99
-
100
98
  # A lambda building the body of a matched request's page (from 1; nil past the last), and its
101
99
  # Stub#empty_selects entries. Only a searchset needs the request: its URLs use its base URL.
102
100
  def self.body(config, fhirpath, where)
@@ -114,19 +112,22 @@ module FHIRStubServer
114
112
  results.filter_map { |name, found| { role: :fhir, pair: where, expression: config[name] } if found.empty? }
115
113
  end
116
114
 
117
- # The fixed body of a `body_file` or `resource` response.
115
+ # The fixed body of a `body_file` or `resource` response, empty for a 204 without either.
118
116
  def self.literal_body(config, fhirpath, where)
119
117
  body = if config.key?('body_file')
120
118
  FHIRStubServer.read_file(config['body_file'])
121
- else
119
+ elsif config.key?('resource')
122
120
  JSON.generate(one_resource(evaluate(config['resource'], fhirpath, where), where))
121
+ else
122
+ ''
123
123
  end
124
124
  ->(_request, page) { body if page[:number] == 1 }
125
125
  end
126
126
 
127
127
  def self.body_kind(config, where)
128
128
  kinds = BODY_KINDS & config.keys
129
- raise Error, "#{where}: the response needs exactly one of #{BODY_KINDS.join(', ')}" unless kinds.one?
129
+ raise Error, "#{where}: the response needs exactly one of #{BODY_KINDS.join(', ')}" unless
130
+ kinds.one? || (kinds.empty? && config['status'] == 204)
130
131
 
131
132
  searchset_only = (%w[include page_size] & config.compact.keys).first unless kinds == ['select']
132
133
  raise Error, "#{where}: #{searchset_only} needs select" if searchset_only
@@ -156,7 +157,7 @@ module FHIRStubServer
156
157
  raise Error, "#{where}: resource must yield exactly one resource, got #{results.size}"
157
158
  end
158
159
 
159
- private_class_method :with_dir, :candidates, :differences, :diff, :build, :request, :body, :empty_selects,
160
+ private_class_method :with_dir, :candidates, :differences, :diff, :json_diff, :build, :body, :empty_selects,
160
161
  :literal_body, :body_kind, :evaluate, :resources_only, :one_resource
161
162
  end
162
163
  end
@@ -5,6 +5,10 @@ module FHIRStubServer
5
5
  # and what a request and a Pair must share to match.
6
6
  # @api private
7
7
  module Request
8
+ # The methods a Pair may declare; a JSON body counts for the writes among them.
9
+ METHODS = %w[GET POST PUT PATCH DELETE].freeze
10
+ JSON_WRITES = %w[POST PUT PATCH].freeze
11
+
8
12
  # Turns the raw values an adapter reads (query and body as strings) into a request: path
9
13
  # percent-decoded, query as { name => sorted values } (repeats kept, order ignored), the body
10
14
  # as UTF-8 (Rack hands it over as binary) and an empty body as nil.
@@ -17,6 +21,30 @@ module FHIRStubServer
17
21
  }
18
22
  end
19
23
 
24
+ # A Pair's `request`, normalized exactly like an incoming one.
25
+ def self.pair(config, where)
26
+ path = config['path'].to_s
27
+ raise Error, "#{where}: the request needs a path starting with /" unless path.start_with?('/')
28
+
29
+ method = config.fetch('method', 'GET').to_s.upcase
30
+ raise Error, "#{where}: the request method must be one of #{METHODS.join(', ')}, not #{method}" unless
31
+ METHODS.include?(method)
32
+
33
+ build(role: :fhir, method:, base_url: '', path:, query: URI.encode_www_form(config['query'].to_h),
34
+ body: pair_body(config['body'], { method:, path: }, where))
35
+ end
36
+
37
+ # A Pair's `body` as a request sends it: a form for `POST .../_search`, JSON for other writes.
38
+ def self.pair_body(body, request, where)
39
+ return URI.encode_www_form(body.to_h) if !body || search?(request)
40
+
41
+ method = request[:method]
42
+ raise Error, "#{where}: a #{method} request has no body" unless JSON_WRITES.include?(method)
43
+ raise Error, "#{where}: the body must be a JSON object or array" unless body.is_a?(Hash) || body.is_a?(Array)
44
+
45
+ JSON.generate(body)
46
+ end
47
+
20
48
  # Raw non-ASCII bytes (a form body sent as UTF-8) are percent-encoded first:
21
49
  # URI.decode_www_form rejects them.
22
50
  def self.parse_query(query)
@@ -24,12 +52,32 @@ module FHIRStubServer
24
52
  URI.decode_www_form(ascii).group_by(&:first).sort.to_h { |name, pairs| [name, pairs.map(&:last).sort] }
25
53
  end
26
54
 
27
- # Method, path, query and, for `POST .../_search`, the form body (nil otherwise).
55
+ # Method, path, query, and the form body of `POST .../_search` or the JSON body of another write.
28
56
  def self.key(request)
29
57
  method = request[:method]
30
- path = request[:path]
31
- form = parse_query(request[:body].to_s) if method == 'POST' && path.end_with?('/_search')
32
- { method:, path:, query: request[:query], form: }
58
+ body = request[:body]
59
+ search = search?(request)
60
+ { method:, path: request[:path], query: request[:query], form: (parse_query(body.to_s) if search),
61
+ json: (json(body) if !search && JSON_WRITES.include?(method)) }
62
+ end
63
+
64
+ # Whether a request's key matches a Pair's: a Pair without a JSON body takes any.
65
+ def self.match?(pair_key, key)
66
+ pair_key == (pair_key[:json] ? key : key.merge(json: nil))
33
67
  end
68
+
69
+ def self.search?(request) = request[:method] == 'POST' && request[:path].end_with?('/_search')
70
+
71
+ # The body parsed when it is a JSON object or array, else the body as it is. Invalid UTF-8
72
+ # is not parsed: JSON.parse accepts it, JSON.generate (in the reports) raises on it.
73
+ def self.json(body)
74
+ text = body.to_s
75
+ parsed = JSON.parse(text) if text.valid_encoding?
76
+ parsed.is_a?(Hash) || parsed.is_a?(Array) ? parsed : body
77
+ rescue JSON::ParserError
78
+ body
79
+ end
80
+
81
+ private_class_method :pair_body, :json
34
82
  end
35
83
  end
@@ -10,8 +10,9 @@ module FHIRStubServer
10
10
  raw(status, JSON.generate(resource))
11
11
  end
12
12
 
13
+ # Rack::Lint (run by `rackup` in development) rejects a content-type on a 204.
13
14
  def self.raw(status, body)
14
- [status, { 'content-type' => CONTENT_TYPE }, body]
15
+ [status, status == 204 ? {} : { 'content-type' => CONTENT_TYPE }, body]
15
16
  end
16
17
 
17
18
  # The JSON body of a searchset's `page` (see Paging), nil past the last one. `total` counts the
@@ -8,9 +8,11 @@ module FHIRStubServer
8
8
  def initialize(config, dir: '.')
9
9
  fhir = config['fhir'].to_h
10
10
  demo_data, served, model = Sources.load(fhir['sources'].to_a, dir)
11
+ dictionary = Dictionary.load(config['dictionary'], dir)
11
12
  validator = config['validator']
12
13
  @validator = validator ? true : false
13
- @roles = { fhir: FHIRRole.new(fhir, demo_data, model, dir), validator: Validator.new(validator.to_h, dir) }
14
+ @roles = { fhir: FHIRRole.new(fhir, demo_data, model, dir, dictionary),
15
+ validator: Validator.new(validator.to_h, dir, dictionary) }
14
16
  @reports = { served:, unmatched: [], context_mismatches: [] }
15
17
  end
16
18
 
@@ -7,12 +7,13 @@ module FHIRStubServer
7
7
  # expected_context: { sv: 4.0.1 }
8
8
  #
9
9
  # A call is matched on the profile (`filesToValidate[0].fileName` without `.json`) and the
10
- # `Type/id` of the file's content; `sessionId` is ignored. `pairs` may include files (see Includes).
10
+ # `Type/id` of the file's content; `sessionId` is ignored. `pairs` may include files (see Includes),
11
+ # each with the Dictionary substituted (see Dictionary#validator_key).
11
12
  # @api private
12
13
  class Validator
13
- def initialize(config, dir)
14
+ def initialize(config, dir, dictionary)
14
15
  @pairs = Includes.splice(config['pairs'].to_a, 'validator.pairs', dir).map do |pair, _dir, where|
15
- [pair.values_at('profile', 'resource'), pair['issues'].to_a, where]
16
+ [dictionary.validator_key(pair, where), pair['issues'].to_a, where]
16
17
  end
17
18
  @expected_context = config['expected_context'].to_h
18
19
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FHIRStubServer
4
- VERSION = '0.1.0'
4
+ VERSION = '0.2.0'
5
5
  end
@@ -52,6 +52,7 @@ module FHIRStubServer
52
52
  autoload :HTTPServer, 'fhir_stub_server/http_server'
53
53
  end
54
54
 
55
+ require_relative 'fhir_stub_server/dictionary'
55
56
  require_relative 'fhir_stub_server/fhir_role'
56
57
  require_relative 'fhir_stub_server/includes'
57
58
  require_relative 'fhir_stub_server/pairs'
@@ -65,7 +65,7 @@ module FHIRStubServer
65
65
  @pairs: Array[Pairs::pair]
66
66
  @reads: Hash[String, resource]
67
67
 
68
- def initialize: (Hash[String, untyped] config, Hash[String, resource] demo_data, String model, String dir) -> void
68
+ def initialize: (Hash[String, untyped] config, Hash[String, resource] demo_data, String model, String dir, Dictionary dictionary) -> void
69
69
  def answer: (request request) -> answer
70
70
  def pairs: () -> Array[unused_pair]
71
71
  def empty_selects: () -> Array[empty_select]
@@ -84,11 +84,12 @@ module FHIRStubServer
84
84
  type pair = { key: Request::key, status: Integer, body: body, where: String, empty_selects: Array[empty_select] }
85
85
  # Evaluates a FHIRPath expression over all Demo Data.
86
86
  type fhirpath = ^(String expression) -> Array[untyped]
87
- type differences = Hash[String, { expected: Array[String]?, actual: Array[String]? }]
87
+ # Query and form values, or (for `body`) JSON bodies.
88
+ type differences = Hash[String, { expected: Array[String] | Request::json | nil, actual: Array[String] | Request::json | nil }]
88
89
 
89
90
  BODY_KINDS: Array[String]
90
91
 
91
- def self.load: (Array[Hash[String, untyped]] pairs, fhirpath fhirpath, String dir) -> Array[pair]
92
+ def self.load: (Array[Includes::spliced] spliced, fhirpath fhirpath, Dictionary dictionary) -> Array[pair]
92
93
  def self.fhirpath: (Hash[String, resource] demo_data, String model) -> fhirpath
93
94
  def self.with_dir: (Hash[String, untyped] pair, String dir) -> Hash[String, untyped]
94
95
  def self.answer: (Array[pair] pairs, request request) -> [String, response]?
@@ -96,8 +97,8 @@ module FHIRStubServer
96
97
  def self.candidates: (Array[pair] pairs, Request::key key) -> Array[[String, differences]]
97
98
  def self.differences: (Request::key pair_key, Request::key request_key) -> differences
98
99
  def self.diff: (Hash[String, Array[String]] expected, Hash[String, Array[String]] actual) -> differences
100
+ def self.json_diff: (Request::json? expected, Request::json? actual) -> differences
99
101
  def self.build: (Hash[String, untyped] pair, fhirpath fhirpath, String where) -> pair
100
- def self.request: (Hash[String, untyped] config, String where) -> request
101
102
  def self.body: (Hash[String, untyped] config, fhirpath fhirpath, String where) -> [body, Array[empty_select]]
102
103
  def self.empty_selects: (Hash[String, untyped] config, Hash[String, Array[resource]] results, String where) -> Array[empty_select]
103
104
  def self.literal_body: (Hash[String, untyped] config, fhirpath fhirpath, String where) -> body
@@ -107,6 +108,31 @@ module FHIRStubServer
107
108
  def self.one_resource: (Array[resource] results, String where) -> resource
108
109
  end
109
110
 
111
+ class Dictionary
112
+ # Substitutes the Dictionary in a value's strings, an Array's items and a Hash's values.
113
+ type resolver = ^(untyped value) -> untyped
114
+
115
+ NAME: Regexp
116
+ VARIABLE: Regexp
117
+ EXPRESSIONS: Array[String]
118
+
119
+ @values: Hash[String, String]
120
+
121
+ def self.load: (String? path, String dir) -> Dictionary
122
+ def self.values: (String file) -> Hash[String, String]
123
+ def self.check: (String file, untyped name, untyped value) -> void
124
+ def self.fhir_pair: (Hash[String, untyped] pair, resolver resolve) -> Hash[String, untyped]
125
+ def self.resolved: (Hash[String, untyped] config, Array[String] keys, resolver resolve) -> Hash[String, untyped]
126
+ def initialize: (Hash[String, String] values) -> void
127
+ def fhir_pair: (Hash[String, untyped] pair, String where) -> Hash[String, untyped]
128
+ def validator_key: (Hash[String, untyped] pair, String where) -> Validator::key
129
+
130
+ private
131
+
132
+ def resolver: (String where) -> resolver
133
+ def substitute: (String string, String where) -> String
134
+ end
135
+
110
136
  class Includes
111
137
  # [pair as written, dir of its file, where it is written]
112
138
  type spliced = [untyped, String, String]
@@ -131,12 +157,23 @@ module FHIRStubServer
131
157
  end
132
158
 
133
159
  module Request
134
- # What a request and a Pair must share to match; queries are { name => sorted values }.
135
- type key = { method: String, path: String, query: Hash[String, Array[String]], form: Hash[String, Array[String]]? }
160
+ # What a request and a Pair must share to match; queries are { name => sorted values }, `json`
161
+ # a JSON object or array, or the body as it is when it is neither.
162
+ type key = { method: String, path: String, query: Hash[String, Array[String]], form: Hash[String, Array[String]]?,
163
+ json: json? }
164
+ type json = Hash[String, untyped] | Array[untyped] | String
165
+
166
+ METHODS: Array[String]
167
+ JSON_WRITES: Array[String]
136
168
 
137
169
  def self.build: (raw_request raw) -> request
170
+ def self.pair: (Hash[String, untyped] config, String where) -> request
171
+ def self.pair_body: (untyped body, { method: String, path: String } request, String where) -> String
138
172
  def self.parse_query: (String query) -> Hash[String, Array[String]]
139
173
  def self.key: (request request) -> key
174
+ def self.match?: (key pair_key, key key) -> bool
175
+ def self.search?: (request | { method: String, path: String } request) -> bool
176
+ def self.json: (String? body) -> json?
140
177
  end
141
178
 
142
179
  module Paging
@@ -201,7 +238,7 @@ module FHIRStubServer
201
238
  @pairs: Array[[key, Array[untyped], String]]
202
239
  @expected_context: Hash[String, untyped]
203
240
 
204
- def initialize: (Hash[String, untyped] config, String dir) -> void
241
+ def initialize: (Hash[String, untyped] config, String dir, Dictionary dictionary) -> void
205
242
  def answer: (request request) -> answer
206
243
  def pairs: () -> Array[unused_pair]
207
244
  def self.call: (request request) -> [key, Hash[String, untyped]]?
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fhir_stub_server
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Pavel Rozhkov
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-25 00:00:00.000000000 Z
11
+ date: 2026-11-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: fhirpath-rb
@@ -46,6 +46,7 @@ files:
46
46
  - config.ru
47
47
  - exe/fhir-stub-server
48
48
  - lib/fhir_stub_server.rb
49
+ - lib/fhir_stub_server/dictionary.rb
49
50
  - lib/fhir_stub_server/fhir_role.rb
50
51
  - lib/fhir_stub_server/http_server.rb
51
52
  - lib/fhir_stub_server/includes.rb