rspec-openapi 0.35.0 → 0.37.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 +4 -4
- data/README.md +131 -3
- data/lib/rspec/openapi/components_updater.rb +16 -9
- data/lib/rspec/openapi/extractors/shared_extractor.rb +58 -11
- data/lib/rspec/openapi/hash_helper.rb +62 -13
- data/lib/rspec/openapi/key_transformer.rb +17 -7
- data/lib/rspec/openapi/minitest_hooks.rb +2 -1
- data/lib/rspec/openapi/parallel_records.rb +59 -4
- data/lib/rspec/openapi/partial_run.rb +84 -0
- data/lib/rspec/openapi/record.rb +2 -0
- data/lib/rspec/openapi/result_recorder.rb +21 -8
- data/lib/rspec/openapi/rspec_hooks.rb +11 -3
- data/lib/rspec/openapi/schema_builder/build_context.rb +19 -4
- data/lib/rspec/openapi/schema_builder/variation_merger.rb +74 -32
- data/lib/rspec/openapi/schema_builder.rb +116 -63
- data/lib/rspec/openapi/schema_cleaner.rb +89 -56
- data/lib/rspec/openapi/schema_file.rb +27 -20
- data/lib/rspec/openapi/schema_merger.rb +24 -6
- data/lib/rspec/openapi/schema_sorter.rb +24 -4
- data/lib/rspec/openapi/stream_parser.rb +4 -5
- data/lib/rspec/openapi/version.rb +1 -1
- data/lib/rspec/openapi/yaml_dumper.rb +103 -0
- data/lib/rspec/openapi/yaml_loader.rb +118 -0
- data/lib/rspec/openapi.rb +19 -7
- metadata +5 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 147cf0a6b1b7bdb8131d9fd7ef937175d12c987b8556ac7f15da40eed0306b11
|
|
4
|
+
data.tar.gz: 36eea5596e9be414348eab608b0d6aaa4a888191585ec3fe67787d74122fc18f
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: d62deb3d4d3ea2503dafd4ecb7fcf936894b710334b98fbe35131569856f992fe20e8c59259921b5c91eb711644713e4d4899205c87c50992b38006723bed67c
|
|
7
|
+
data.tar.gz: 257d8b54b1c1bab4753e105b0f10293ae5ad7525b89e2c5259065f32d8b6ac7afbabf30d0661e37299fb09b16941ce2f5d0892f3e9b8af88cbacb3c20de3de8f
|
data/README.md
CHANGED
|
@@ -228,6 +228,10 @@ RSpec::OpenAPI.tags_builder = -> (example) { example.metadata.dig(:example_group
|
|
|
228
228
|
# This example assigns 'date-time' format to properties with names ending in '_at'
|
|
229
229
|
RSpec::OpenAPI.formats_builder = ->(_example, key) { key.end_with?('_at') ? 'date-time' : nil }
|
|
230
230
|
|
|
231
|
+
# Mark server-assigned properties as `readOnly`. Off by default.
|
|
232
|
+
# A builder of your own gets the RSpec example and a property name. See "Can I mark `id` and timestamps as `readOnly`?" below.
|
|
233
|
+
RSpec::OpenAPI.read_only_builder = RSpec::OpenAPI::DEFAULT_READ_ONLY_BUILDER
|
|
234
|
+
|
|
231
235
|
# Change the example type(s) that will generate schema
|
|
232
236
|
RSpec::OpenAPI.example_types = %i[request]
|
|
233
237
|
|
|
@@ -242,6 +246,10 @@ RSpec::OpenAPI.ignored_path_params = %i[controller action format]
|
|
|
242
246
|
# String or Regexp is acceptable.
|
|
243
247
|
RSpec::OpenAPI.ignored_paths = ["/admin/full/path/", Regexp.new("^/_internal/")]
|
|
244
248
|
|
|
249
|
+
# Whether a run adds and updates without removing anything. `nil` (default) lets each run decide,
|
|
250
|
+
# see "Can I run a subset of specs?" below. `true` or `false` forces it, as does `OPENAPI_PARTIAL_UPDATE=1` or `=0`.
|
|
251
|
+
RSpec::OpenAPI.partial_update = nil
|
|
252
|
+
|
|
245
253
|
# Your custom post-processing hook (like unrandomizing IDs)
|
|
246
254
|
RSpec::OpenAPI.post_process_hook = -> (path, records, spec) do
|
|
247
255
|
RSpec::OpenAPI::HashHelper.matched_paths(spec, 'paths.*.*.responses.*.content.*.*.*.id').each do |paths|
|
|
@@ -396,11 +404,66 @@ components:
|
|
|
396
404
|
Note that automatic `schemas` update feature is still new and may not work in complex scenario.
|
|
397
405
|
If you find a room for improvement, open an issue.
|
|
398
406
|
|
|
407
|
+
### Can I mark `id` and timestamps as `readOnly`?
|
|
408
|
+
|
|
409
|
+
Yes, with `read_only_builder`. It is off by default.
|
|
410
|
+
|
|
411
|
+
```rb
|
|
412
|
+
RSpec::OpenAPI.read_only_builder = RSpec::OpenAPI::DEFAULT_READ_ONLY_BUILDER
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
`DEFAULT_READ_ONLY_BUILDER` picks the names in `DEFAULT_READ_ONLY_KEYS`: `id`, `uuid`, `created_at`
|
|
416
|
+
and `updated_at`. Foreign keys such as `user_id` are not in it, since clients usually send them. A
|
|
417
|
+
builder of your own gets the RSpec example and a property name, and may return `true` for any name.
|
|
418
|
+
The names can also be listed per example, as whole names or patterns.
|
|
419
|
+
|
|
420
|
+
```rb
|
|
421
|
+
describe 'GET /posts', openapi: { read_only: ['id', /_count\z/] } do
|
|
422
|
+
# `read_only: false` turns it off for an example, and `read_only: true` hands it back to the builder.
|
|
423
|
+
end
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
A property the builder picks gets `readOnly: true` in response schemas. Keep in mind what that
|
|
427
|
+
means. A client should not send the property (OpenAPI 3.0), or the server may ignore or reject it
|
|
428
|
+
(3.1 and later). So a request that sends the property says the opposite, and the request wins.
|
|
429
|
+
That holds under `read_only: false` too, which only stops an example from marking.
|
|
430
|
+
In a schema shared by a request and a response through `$ref`, the component then keeps
|
|
431
|
+
`readOnly: false`. That explicit `false` lets partial runs (see "Can I run a subset of specs?"
|
|
432
|
+
below), such as `parallel_tests` workers, agree whichever order they run in. A full run decides
|
|
433
|
+
it anew. Inline request schemas never carry `readOnly`.
|
|
434
|
+
|
|
399
435
|
### How can I add information which can't be generated from RSpec?
|
|
400
436
|
|
|
401
437
|
rspec-openapi tries to preserve manual modifications as much as possible when generating specs.
|
|
402
438
|
You can directly edit `doc/openapi.yaml` as you like without spoiling the automatic generation capability.
|
|
403
439
|
|
|
440
|
+
### Can I run a subset of specs?
|
|
441
|
+
|
|
442
|
+
Yes. A run over part of the suite adds and updates what it records and removes nothing.
|
|
443
|
+
It prints a notice when it updates the file this way.
|
|
444
|
+
|
|
445
|
+
```bash
|
|
446
|
+
$ OPENAPI=1 bundle exec rspec spec/requests/tables_spec.rb
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
A run counts as partial in two cases.
|
|
450
|
+
|
|
451
|
+
- The examples are narrowed, by `-e`, `--tag`, a line number, `--only-failures` or a leftover `fit`.
|
|
452
|
+
An exclusion such as `--tag ~slow` does not count.
|
|
453
|
+
- A spec file next to one that recorded a request was left out. So `rspec spec/requests/tables_spec.rb`
|
|
454
|
+
is partial, while `rspec spec/requests` and `rspec spec/requests/*_spec.rb` are not.
|
|
455
|
+
|
|
456
|
+
Every other run also removes the paths, operations, parameters and properties it did not record.
|
|
457
|
+
This is how removed endpoints disappear from the file, so run all specs for that.
|
|
458
|
+
|
|
459
|
+
A `parallel_tests` worker sees only part of the files, so it never removes anything, whichever files it got.
|
|
460
|
+
rspec-openapi knows a worker by the `TEST_ENV_NUMBER` variable that `parallel_tests` sets.
|
|
461
|
+
Run the suite in one process when stale entries should go.
|
|
462
|
+
|
|
463
|
+
Set `RSpec::OpenAPI.partial_update` to `true` or `false`, or `OPENAPI_PARTIAL_UPDATE=1` or `=0`, to force one mode.
|
|
464
|
+
Minitest has no run information to decide from. It removes nothing in a `parallel_tests` worker or when the
|
|
465
|
+
option is `true`, and removes stale entries otherwise.
|
|
466
|
+
|
|
404
467
|
### Can I exclude specific specs from OpenAPI generation?
|
|
405
468
|
|
|
406
469
|
Yes, you can specify `openapi: false` to disable the automatic generation.
|
|
@@ -419,6 +482,44 @@ RSpec.describe '/resources', type: :request do
|
|
|
419
482
|
end
|
|
420
483
|
```
|
|
421
484
|
|
|
485
|
+
### How can I keep the generated file stable across runs?
|
|
486
|
+
|
|
487
|
+
rspec-openapi sorts `paths`, HTTP methods, response status codes, content types and the names of `examples`.
|
|
488
|
+
So the structure of the file does not depend on the order in which RSpec runs your tests.
|
|
489
|
+
|
|
490
|
+
The values inside `example` are different. They are copied from the real requests and responses
|
|
491
|
+
in your tests. Anything random in your app or test data shows up as a diff on every run.
|
|
492
|
+
Common sources are Faker, `SecureRandom`, `Time.now` and auto-increment IDs.
|
|
493
|
+
|
|
494
|
+
One option is to make the values stable in your test setup. This is plain RSpec configuration
|
|
495
|
+
and is not specific to rspec-openapi. For example:
|
|
496
|
+
|
|
497
|
+
```rb
|
|
498
|
+
if ENV['OPENAPI']
|
|
499
|
+
seed = ENV.fetch('OPENAPI_SEED', 1234).to_i
|
|
500
|
+
srand(seed)
|
|
501
|
+
Faker::Config.random = Random.new(seed) if defined?(Faker)
|
|
502
|
+
|
|
503
|
+
RSpec.configure do |config|
|
|
504
|
+
config.include ActiveSupport::Testing::TimeHelpers
|
|
505
|
+
|
|
506
|
+
config.around do |example|
|
|
507
|
+
travel_to(Time.zone.local(2024, 1, 1, 12, 0, 0)) { example.run }
|
|
508
|
+
end
|
|
509
|
+
end
|
|
510
|
+
end
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
The other option is to keep the random values out of the file. Set `RSpec::OpenAPI.enable_example = false`
|
|
514
|
+
to drop `example` everywhere, use `example_mode: :none` on the noisy tests only, or rewrite the values
|
|
515
|
+
in `RSpec::OpenAPI.post_process_hook`. See [Configuration](#configuration) for both.
|
|
516
|
+
|
|
517
|
+
One more thing to know. When several tests hit the same endpoint in the default `:single` mode,
|
|
518
|
+
the `example` comes from the test that ran last. With `config.order = :random` the winner changes
|
|
519
|
+
from run to run. Run with `--order defined` while generating the file, or switch those tests to
|
|
520
|
+
`example_mode: :multiple` so that each test writes its own named example.
|
|
521
|
+
See [Multiple Examples Mode](#multiple-examples-mode).
|
|
522
|
+
|
|
422
523
|
## Customizations
|
|
423
524
|
|
|
424
525
|
Some examples' attributes can be overwritten via RSpec metadata options. Example:
|
|
@@ -554,6 +655,29 @@ it 'returns items with status', openapi: {
|
|
|
554
655
|
end
|
|
555
656
|
```
|
|
556
657
|
|
|
658
|
+
For an array of strings, use the array's own name. The enum is applied to its items, so this also works for a
|
|
659
|
+
repeated query parameter such as `sort[]`, which Rack parses into a `sort` array:
|
|
660
|
+
|
|
661
|
+
```rb
|
|
662
|
+
it 'sorts tasks', openapi: {
|
|
663
|
+
request_enum: {
|
|
664
|
+
'sort' => %w[name -name created_at -created_at],
|
|
665
|
+
},
|
|
666
|
+
} do
|
|
667
|
+
get '/tasks', params: { sort: ['-created_at'] }
|
|
668
|
+
# Parameter schema: { type: array, items: { type: string, enum: [name, -name, created_at, -created_at] } }
|
|
669
|
+
expect(response.status).to eq(200)
|
|
670
|
+
end
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
The parameter is recorded as `sort`, without the brackets. A client generated from the document sends it the OpenAPI
|
|
674
|
+
default way, `sort=name&sort=-name`, and Rack reads that as the last value alone. Make the client send
|
|
675
|
+
`sort[]=name&sort[]=-name`.
|
|
676
|
+
|
|
677
|
+
rspec-openapi 0.36.0 and earlier also put the enum on the array itself. Merging keeps keys the new schema doesn't set, so
|
|
678
|
+
a schema file generated by one of those versions keeps that array-level `enum`. Delete it once, or regenerate the file
|
|
679
|
+
from scratch.
|
|
680
|
+
|
|
557
681
|
#### Request vs Response Enums
|
|
558
682
|
|
|
559
683
|
By default, `enum` applies to both request and response bodies. If you need different enum values for request and
|
|
@@ -573,6 +697,9 @@ it 'creates a task', openapi: {
|
|
|
573
697
|
end
|
|
574
698
|
```
|
|
575
699
|
|
|
700
|
+
When a value with an enum is also recorded as `null`, the enum gets `null` too. A null type or `nullable: true`
|
|
701
|
+
does not allow a value the enum leaves out.
|
|
702
|
+
|
|
576
703
|
### Dynamic-key Object Support (`additionalProperties`)
|
|
577
704
|
|
|
578
705
|
When an endpoint returns (or accepts) an object whose keys are not part of its
|
|
@@ -1014,9 +1141,10 @@ Existing RSpec plugins which have OpenAPI integration:
|
|
|
1014
1141
|
2. In GitHub Actions, run the `prepare release` workflow manually. It bumps `lib/rspec/openapi/version.rb`, pushes
|
|
1015
1142
|
`release/v<version>` to origin, and opens a PR.
|
|
1016
1143
|
3. Review and merge the release PR into the default branch.
|
|
1017
|
-
4.
|
|
1018
|
-
|
|
1019
|
-
|
|
1144
|
+
4. In the GitHub UI, create a release with a new tag `v<version>` on the merged commit. Use "Generate release notes"
|
|
1145
|
+
for the body. Publishing the release triggers the `Publish to RubyGems` workflow, which publishes the gem.
|
|
1146
|
+
5. If the workflow fails after the gem is pushed, do not delete and recreate the release or the tag. RubyGems rejects
|
|
1147
|
+
a second push of the same version.
|
|
1020
1148
|
|
|
1021
1149
|
## License
|
|
1022
1150
|
|
|
@@ -7,7 +7,8 @@ class << RSpec::OpenAPI::ComponentsUpdater = Object.new
|
|
|
7
7
|
|
|
8
8
|
# @param [Hash] base
|
|
9
9
|
# @param [Hash] fresh
|
|
10
|
-
|
|
10
|
+
# @param [Boolean] partial add to the schemas without removing anything
|
|
11
|
+
def update!(base, fresh, partial: false)
|
|
11
12
|
# Top-level schema: Used as the body of request or response
|
|
12
13
|
top_level_refs = paths_to_top_level_refs(base)
|
|
13
14
|
fresh_schemas = build_fresh_schemas(top_level_refs, base, fresh)
|
|
@@ -22,8 +23,9 @@ class << RSpec::OpenAPI::ComponentsUpdater = Object.new
|
|
|
22
23
|
|
|
23
24
|
return if fresh_schemas.empty?
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
RSpec::OpenAPI::
|
|
26
|
+
fresh_components = { components: { schemas: fresh_schemas } }
|
|
27
|
+
RSpec::OpenAPI::SchemaMerger.merge_normalized!(base, fresh_components)
|
|
28
|
+
RSpec::OpenAPI::SchemaCleaner.cleanup_components_schemas!(base, fresh_components) unless partial
|
|
27
29
|
end
|
|
28
30
|
|
|
29
31
|
private
|
|
@@ -87,6 +89,10 @@ class << RSpec::OpenAPI::ComponentsUpdater = Object.new
|
|
|
87
89
|
ref_link = dig_schema(base, paths)[:$ref]
|
|
88
90
|
schema_name = extract_schema_name(ref_link)
|
|
89
91
|
schema_body = dig_schema(fresh, paths.grep_v(Integer))
|
|
92
|
+
# Nothing was recorded for this body, so there is nothing to fill the
|
|
93
|
+
# schema from. A partial run leaves such operations in base, and so does
|
|
94
|
+
# a status code no example produces any more.
|
|
95
|
+
next if schema_body.nil?
|
|
90
96
|
|
|
91
97
|
merge_schema!(fresh_schemas, schema_name, schema_body)
|
|
92
98
|
end
|
|
@@ -98,14 +104,15 @@ class << RSpec::OpenAPI::ComponentsUpdater = Object.new
|
|
|
98
104
|
RSpec::OpenAPI::SchemaMerger.merge_normalized!({ schemas: fresh_schemas }, { schemas: { schema_name => schema } })
|
|
99
105
|
end
|
|
100
106
|
|
|
107
|
+
# The paths come from matched_paths, so their segments are symbols and the
|
|
108
|
+
# indexes of oneOf variants. A path to a media type ends in the content
|
|
109
|
+
# type, one to a variant in its index under the oneOf of the schema.
|
|
101
110
|
def dig_schema(obj, paths)
|
|
102
|
-
|
|
103
|
-
paths
|
|
104
|
-
item_schema = obj.dig(*paths, :schema, :items)
|
|
105
|
-
object_schema = obj.dig(*paths, :schema)
|
|
106
|
-
one_of_schema = obj.dig(*paths.take(paths.size - 1), :schema, :oneOf, paths.last)
|
|
111
|
+
media_type = obj.dig(*paths)
|
|
112
|
+
return obj.dig(*paths[0...-1], :schema, :oneOf, paths.last) unless media_type.is_a?(Hash)
|
|
107
113
|
|
|
108
|
-
|
|
114
|
+
schema = media_type[:schema]
|
|
115
|
+
(schema.is_a?(Hash) && schema[:items]) || schema
|
|
109
116
|
end
|
|
110
117
|
|
|
111
118
|
def paths_to_top_level_refs(base)
|
|
@@ -20,28 +20,27 @@ class SharedExtractor
|
|
|
20
20
|
|
|
21
21
|
def self.attributes(example)
|
|
22
22
|
metadata = merge_openapi_metadata(example.metadata)
|
|
23
|
-
request_example_mode, response_example_mode = normalize_example_mode(metadata[:example_mode], example)
|
|
24
23
|
response_additional_properties, request_additional_properties = resolve_additional_properties(metadata)
|
|
25
24
|
response_hybrid_additional_properties, request_hybrid_additional_properties =
|
|
26
25
|
resolve_hybrid_additional_properties(metadata)
|
|
27
26
|
# Enum support: response_enum and request_enum can override the general enum
|
|
28
|
-
base_enum = normalize_enum(metadata
|
|
27
|
+
base_enum = normalize_enum(metadata, :enum, example)
|
|
29
28
|
|
|
30
29
|
{
|
|
31
30
|
summary: metadata[:summary] || RSpec::OpenAPI.summary_builder.call(example),
|
|
32
31
|
tags: metadata[:tags] || RSpec::OpenAPI.tags_builder.call(example),
|
|
33
32
|
formats: metadata[:formats] || RSpec::OpenAPI.formats_builder.curry.call(example),
|
|
33
|
+
**read_only_lookups(metadata, example),
|
|
34
34
|
operation_id: metadata[:operation_id],
|
|
35
35
|
required_request_params: metadata[:required_request_params] || [],
|
|
36
36
|
security: metadata[:security],
|
|
37
37
|
description: metadata[:description] || RSpec::OpenAPI.description_builder.call(example),
|
|
38
38
|
deprecated: metadata[:deprecated],
|
|
39
|
-
|
|
40
|
-
response_example_mode: response_example_mode,
|
|
39
|
+
**example_modes(metadata, example),
|
|
41
40
|
example_key: resolve_example_key(metadata, example),
|
|
42
41
|
example_name: metadata[:example_name] || RSpec::OpenAPI.example_name_builder.call(example),
|
|
43
|
-
response_enum: normalize_enum(metadata
|
|
44
|
-
request_enum: normalize_enum(metadata
|
|
42
|
+
response_enum: normalize_enum(metadata, :response_enum, example) || base_enum,
|
|
43
|
+
request_enum: normalize_enum(metadata, :request_enum, example) || base_enum,
|
|
45
44
|
response_additional_properties: response_additional_properties,
|
|
46
45
|
request_additional_properties: request_additional_properties,
|
|
47
46
|
response_hybrid_additional_properties: response_hybrid_additional_properties,
|
|
@@ -71,13 +70,58 @@ class SharedExtractor
|
|
|
71
70
|
[response, request]
|
|
72
71
|
end
|
|
73
72
|
|
|
74
|
-
def self.
|
|
75
|
-
|
|
73
|
+
def self.example_modes(metadata, example)
|
|
74
|
+
request_example_mode, response_example_mode = normalize_example_mode(metadata[:example_mode], example)
|
|
75
|
+
{ request_example_mode: request_example_mode, response_example_mode: response_example_mode }
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The metadata wins over the builder for what a response marks. `false` marks
|
|
79
|
+
# nothing, and `true` hands it back to the builder, for a group that turned it
|
|
80
|
+
# off. A request that sends a property is evidence whatever its example
|
|
81
|
+
# marks, so its side takes the builder's candidates as well.
|
|
82
|
+
def self.read_only_lookups(metadata, example)
|
|
83
|
+
builder = RSpec::OpenAPI.read_only_builder&.curry&.call(example)
|
|
84
|
+
value = metadata.fetch(:read_only, true)
|
|
85
|
+
return { response_read_only: builder, request_read_only: builder } if value == true
|
|
86
|
+
|
|
87
|
+
listed = normalize_read_only(value, example)
|
|
88
|
+
request = listed && builder ? ->(key) { listed[key] || builder[key] } : listed || builder
|
|
89
|
+
{ response_read_only: listed, request_read_only: request }
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
READ_ONLY_PATTERN_CLASSES = [String, Symbol, Regexp].freeze
|
|
93
|
+
|
|
94
|
+
def self.normalize_read_only(value, example)
|
|
95
|
+
return nil unless value
|
|
96
|
+
|
|
97
|
+
patterns = Array(value)
|
|
98
|
+
unless patterns.all? { |pattern| READ_ONLY_PATTERN_CLASSES.any? { |klass| pattern.is_a?(klass) } }
|
|
99
|
+
raise ArgumentError, 'read_only must be true, false, or property names as Strings, Symbols or Regexps, ' \
|
|
100
|
+
"got #{value.inspect}#{example_context(example)}"
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
patterns = patterns.map { |pattern| pattern.is_a?(Regexp) ? pattern : pattern.to_s }
|
|
104
|
+
->(key) { patterns.any? { |pattern| pattern.is_a?(Regexp) ? pattern.match?(key) : pattern == key } }
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def self.normalize_enum(metadata, name, example)
|
|
108
|
+
enum_hash = metadata[name]
|
|
109
|
+
return nil if enum_hash.nil? || enum_hash == {}
|
|
110
|
+
unless enum_hash.is_a?(Hash) && enum_hash.each_value.all? { |values| scalars?(values) }
|
|
111
|
+
raise ArgumentError, "#{name} must be a Hash of property paths to Arrays of scalar values, " \
|
|
112
|
+
"got #{enum_hash.inspect}#{example_context(example)}"
|
|
113
|
+
end
|
|
76
114
|
|
|
77
115
|
# Convert all keys to strings for consistent lookup
|
|
78
116
|
enum_hash.transform_keys(&:to_s)
|
|
79
117
|
end
|
|
80
118
|
|
|
119
|
+
# Pairs such as `Order.statuses.to_a` or `pluck(:name, :id)` are a mistake for
|
|
120
|
+
# the values alone, and would allow nothing.
|
|
121
|
+
def self.scalars?(values)
|
|
122
|
+
values.is_a?(Array) && values.none? { |value| value.is_a?(Array) || value.is_a?(Hash) }
|
|
123
|
+
end
|
|
124
|
+
|
|
81
125
|
def self.normalize_additional_properties(hash)
|
|
82
126
|
return nil if hash.nil? || hash.empty?
|
|
83
127
|
|
|
@@ -153,9 +197,12 @@ class SharedExtractor
|
|
|
153
197
|
end
|
|
154
198
|
|
|
155
199
|
def self.example_mode_error(value, example)
|
|
156
|
-
context = example&.full_description
|
|
157
|
-
context = " (example: #{context})" if context
|
|
158
200
|
"example_mode must be a Symbol/String in #{VALID_EXAMPLE_MODES.inspect} " \
|
|
159
|
-
"or a Hash with :request/:response keys, got #{value.inspect}#{
|
|
201
|
+
"or a Hash with :request/:response keys, got #{value.inspect}#{example_context(example)}"
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def self.example_context(example)
|
|
205
|
+
context = example&.full_description
|
|
206
|
+
context ? " (example: #{context})" : ''
|
|
160
207
|
end
|
|
161
208
|
end
|
|
@@ -12,6 +12,15 @@ class << RSpec::OpenAPI::HashHelper = Object.new
|
|
|
12
12
|
matches
|
|
13
13
|
end
|
|
14
14
|
|
|
15
|
+
# Yields each match of selector in obj as its parent, the matching key and
|
|
16
|
+
# the value, with the value at the same path in other (nil when other has
|
|
17
|
+
# none). Callers that only edit the matched nodes, or compare them with a
|
|
18
|
+
# fresh document, get them without a path to dig back up from the root for
|
|
19
|
+
# every match.
|
|
20
|
+
def each_matched(obj, other, selector, &block)
|
|
21
|
+
walk_matched(obj, other, split_selector(selector), 0, &block)
|
|
22
|
+
end
|
|
23
|
+
|
|
15
24
|
# Paths that start with a match of begin_selector and end with a match of an
|
|
16
25
|
# end selector, with any number of keys in between: the matches of the first
|
|
17
26
|
# end selector sorted by length, then those of the next, each length in
|
|
@@ -34,22 +43,27 @@ class << RSpec::OpenAPI::HashHelper = Object.new
|
|
|
34
43
|
# named `type` or `nullable` would be silently mangled.
|
|
35
44
|
DATA_KEYS = [:example, :examples, :default, :enum, :const].freeze
|
|
36
45
|
|
|
37
|
-
#
|
|
38
|
-
#
|
|
39
|
-
|
|
40
|
-
|
|
46
|
+
# Keys of maps whose entries the document names, so an entry named like
|
|
47
|
+
# `default`, `nullable` or `x-mode` is never taken for a keyword.
|
|
48
|
+
NAMED_MAP_KEYS = [:properties, :schemas, :headers].freeze
|
|
49
|
+
|
|
50
|
+
# Yields every hash in obj outside the data subtrees in DATA_KEYS and the
|
|
51
|
+
# `x-` extensions, each after its descendants, with the key it sits under,
|
|
52
|
+
# directly or as a list element. The entries of a map in NAMED_MAP_KEYS are
|
|
53
|
+
# yielded whatever their names, and the map itself is not.
|
|
54
|
+
def each_schema(obj, under: nil, &block)
|
|
41
55
|
case obj
|
|
42
56
|
when Hash
|
|
43
57
|
obj.each do |key, value|
|
|
44
|
-
if key
|
|
45
|
-
value.each_value { |
|
|
46
|
-
elsif
|
|
47
|
-
each_schema(value, &block)
|
|
58
|
+
if NAMED_MAP_KEYS.include?(key) && value.is_a?(Hash)
|
|
59
|
+
value.each_value { |entry| each_schema(entry, &block) }
|
|
60
|
+
elsif walk?(key, under)
|
|
61
|
+
each_schema(value, under: key, &block)
|
|
48
62
|
end
|
|
49
63
|
end
|
|
50
|
-
yield obj
|
|
64
|
+
yield obj, under
|
|
51
65
|
when Array
|
|
52
|
-
obj.each { |value| each_schema(value, &block) }
|
|
66
|
+
obj.each { |value| each_schema(value, under: under, &block) }
|
|
53
67
|
end
|
|
54
68
|
end
|
|
55
69
|
|
|
@@ -59,10 +73,20 @@ class << RSpec::OpenAPI::HashHelper = Object.new
|
|
|
59
73
|
(schema[:oneOf] || [schema]).find { |variant| variant.is_a?(Hash) && variant[:type] == type }
|
|
60
74
|
end
|
|
61
75
|
|
|
76
|
+
# The selectors are a fixed set of literals, some of them matched once per
|
|
77
|
+
# media type of the document, so each is split once.
|
|
78
|
+
SELECTOR_PARTS = Hash.new { |cache, selector| cache[selector] = selector.split('.').map(&:to_sym).freeze }
|
|
79
|
+
private_constant :SELECTOR_PARTS
|
|
80
|
+
|
|
62
81
|
private
|
|
63
82
|
|
|
83
|
+
# A response may be named `default`, and the responses may carry extensions.
|
|
84
|
+
def walk?(key, under)
|
|
85
|
+
!key.start_with?('x-') && (under == :responses || !DATA_KEYS.include?(key))
|
|
86
|
+
end
|
|
87
|
+
|
|
64
88
|
def split_selector(selector)
|
|
65
|
-
selector
|
|
89
|
+
SELECTOR_PARTS[selector]
|
|
66
90
|
end
|
|
67
91
|
|
|
68
92
|
# `path` is the stack of keys from the root to obj, pushed and popped in
|
|
@@ -84,15 +108,40 @@ class << RSpec::OpenAPI::HashHelper = Object.new
|
|
|
84
108
|
end
|
|
85
109
|
end
|
|
86
110
|
|
|
111
|
+
def walk_matched(obj, other, selector_parts, depth, &block)
|
|
112
|
+
part = selector_parts[depth]
|
|
113
|
+
last = depth == selector_parts.size - 1
|
|
114
|
+
|
|
115
|
+
each_child(obj) do |key, value|
|
|
116
|
+
next unless part == :* || part == key
|
|
117
|
+
|
|
118
|
+
if last
|
|
119
|
+
yield obj, key, value, child_of(other, key)
|
|
120
|
+
else
|
|
121
|
+
walk_matched(value, child_of(other, key), selector_parts, depth + 1, &block)
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def child_of(obj, key)
|
|
127
|
+
case obj
|
|
128
|
+
when Hash, Array then obj[key]
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
87
132
|
# The loops below run once per node of the document, so they index by hand:
|
|
88
|
-
# each_with_index and Integer#times allocate per call.
|
|
133
|
+
# each_with_index and Integer#times allocate per call. Most nodes fail on
|
|
134
|
+
# their own key, which is checked before the rest of the suffix.
|
|
89
135
|
def collect_suffix_matches(obj, end_parts, path, prefix_size, matches)
|
|
90
136
|
each_child(obj) do |key, value|
|
|
91
137
|
path.push(key)
|
|
92
138
|
index = 0
|
|
93
139
|
while index < end_parts.size
|
|
94
140
|
parts = end_parts[index]
|
|
95
|
-
|
|
141
|
+
last = parts[-1]
|
|
142
|
+
if (last == :* || last == key) && path.size >= prefix_size + parts.size && suffix_matches?(path, parts)
|
|
143
|
+
matches[index] << path.dup
|
|
144
|
+
end
|
|
96
145
|
index += 1
|
|
97
146
|
end
|
|
98
147
|
collect_suffix_matches(value, end_parts, path, prefix_size, matches)
|
|
@@ -34,16 +34,26 @@ class << RSpec::OpenAPI::KeyTransformer = Object.new
|
|
|
34
34
|
result
|
|
35
35
|
end
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
# Normalizes the names of examples in place, for a document that already
|
|
38
|
+
# holds symbol keys.
|
|
39
|
+
def normalize_example_names!(value)
|
|
38
40
|
case value
|
|
39
41
|
when Hash
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
value.each do |k, v|
|
|
43
|
+
rename_examples!(v) if k == :examples && v.is_a?(Hash)
|
|
44
|
+
normalize_example_names!(v)
|
|
45
|
+
end
|
|
43
46
|
when Array
|
|
44
|
-
value.
|
|
45
|
-
else
|
|
46
|
-
value
|
|
47
|
+
value.each { |v| normalize_example_names!(v) }
|
|
47
48
|
end
|
|
49
|
+
value
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
private
|
|
53
|
+
|
|
54
|
+
def rename_examples!(examples)
|
|
55
|
+
renamed = {}
|
|
56
|
+
examples.each { |name, example| renamed[RSpec::OpenAPI::ExampleKey.normalize(name).to_sym] = example }
|
|
57
|
+
examples.replace(renamed)
|
|
48
58
|
end
|
|
49
59
|
end
|
|
@@ -53,7 +53,8 @@ if ENV['OPENAPI']
|
|
|
53
53
|
|
|
54
54
|
Minitest.after_run do
|
|
55
55
|
RSpec::OpenAPI::ParallelRecords.merge!
|
|
56
|
-
|
|
56
|
+
partial = RSpec::OpenAPI::PartialRun.minitest?
|
|
57
|
+
result_recorder = RSpec::OpenAPI::ResultRecorder.new(RSpec::OpenAPI.path_records, partial: partial)
|
|
57
58
|
result_recorder.record_results!
|
|
58
59
|
puts result_recorder.error_message if result_recorder.errors?
|
|
59
60
|
end
|
|
@@ -30,6 +30,16 @@ module RSpec::OpenAPI::ParallelRecords
|
|
|
30
30
|
# its content, so the file itself does not need to survive the trip.
|
|
31
31
|
UPLOADED_FILE_MARKER = '__rspec_openapi_uploaded_file'
|
|
32
32
|
|
|
33
|
+
# Members that hold a builder's lookup, a Proc when a builder is set.
|
|
34
|
+
LOOKUP_MEMBERS = [:formats, :response_read_only, :request_read_only].freeze
|
|
35
|
+
|
|
36
|
+
# Tags an error a lookup raised in a worker. It travels in place of the
|
|
37
|
+
# answers as [LOOKUP_ERROR_MARKER, message], a shape no answer Hash can take.
|
|
38
|
+
LOOKUP_ERROR_MARKER = '__rspec_openapi_lookup_error'
|
|
39
|
+
|
|
40
|
+
# Raised in the main process for an error a lookup raised in a worker.
|
|
41
|
+
class LookupError < StandardError; end
|
|
42
|
+
|
|
33
43
|
class << self
|
|
34
44
|
def worker?
|
|
35
45
|
Process.pid != MAIN_PID
|
|
@@ -52,7 +62,7 @@ module RSpec::OpenAPI::ParallelRecords
|
|
|
52
62
|
|
|
53
63
|
FileUtils.mkdir_p(dump_dir, mode: 0o700)
|
|
54
64
|
encoded = RSpec::OpenAPI.path_records.transform_values do |records|
|
|
55
|
-
records.map { |record|
|
|
65
|
+
records.map { |record| encode_record(answer_lookups(record)) }
|
|
56
66
|
end
|
|
57
67
|
File.write(File.join(dump_dir, "#{Process.pid}.yaml"), YAML.dump(encoded))
|
|
58
68
|
end
|
|
@@ -61,7 +71,7 @@ module RSpec::OpenAPI::ParallelRecords
|
|
|
61
71
|
Dir.glob(File.join(dump_dir, '*.yaml')).sort.each do |file|
|
|
62
72
|
records_by_path = YAML.safe_load(File.read(file), permitted_classes: permitted_classes, aliases: true)
|
|
63
73
|
records_by_path.each do |path, records|
|
|
64
|
-
decoded = records.map { |record|
|
|
74
|
+
decoded = records.map { |record| decode_record(record) }
|
|
65
75
|
RSpec::OpenAPI.path_records[path].concat(decoded)
|
|
66
76
|
end
|
|
67
77
|
end
|
|
@@ -83,8 +93,53 @@ module RSpec::OpenAPI::ParallelRecords
|
|
|
83
93
|
classes
|
|
84
94
|
end
|
|
85
95
|
|
|
86
|
-
def
|
|
87
|
-
RSpec::OpenAPI::Record.new(**record.to_h.transform_values(
|
|
96
|
+
def encode_record(record)
|
|
97
|
+
RSpec::OpenAPI::Record.new(**record.to_h.transform_values { |value| encode(value) })
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Only a lookup member can hold a lookup error, so only there is one looked for.
|
|
101
|
+
def decode_record(record)
|
|
102
|
+
members = record.to_h.to_h do |member, value|
|
|
103
|
+
[member, LOOKUP_MEMBERS.include?(member) ? decode_lookup(value) : decode(value)]
|
|
104
|
+
end
|
|
105
|
+
RSpec::OpenAPI::Record.new(**members)
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def decode_lookup(value)
|
|
109
|
+
return value unless value.is_a?(Array) && value.first == LOOKUP_ERROR_MARKER
|
|
110
|
+
|
|
111
|
+
message = value.last
|
|
112
|
+
->(*) { raise LookupError, message }
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# No serializer can carry a Proc. Building the schema here asks each lookup
|
|
116
|
+
# about every key the main process will ask about, and the answers travel
|
|
117
|
+
# as a Hash, which the builder reads the same way.
|
|
118
|
+
def answer_lookups(record)
|
|
119
|
+
lookups = LOOKUP_MEMBERS.select { |member| record[member].is_a?(Proc) }
|
|
120
|
+
return record if lookups.empty?
|
|
121
|
+
|
|
122
|
+
answers = lookups.to_h { |member| [member, {}] }
|
|
123
|
+
probe = record.dup
|
|
124
|
+
lookups.each { |member| probe[member] = recording_lookup(member, record[member], answers) }
|
|
125
|
+
begin
|
|
126
|
+
RSpec::OpenAPI::SchemaBuilder.build(probe)
|
|
127
|
+
rescue StandardError, NotImplementedError
|
|
128
|
+
# A value the builder cannot type, or a lookup error kept below. The
|
|
129
|
+
# main process builds this record again and reports the error itself.
|
|
130
|
+
end
|
|
131
|
+
record.dup.tap { |answered| answers.each { |member, value| answered[member] = value } }
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# The main process cannot call the lookup again, so an error it raises
|
|
135
|
+
# travels in place of its answers, and decode_lookup raises it there.
|
|
136
|
+
def recording_lookup(member, lookup, answers)
|
|
137
|
+
lambda do |key|
|
|
138
|
+
answers[member][key] = lookup.call(key)
|
|
139
|
+
rescue StandardError, NotImplementedError => e
|
|
140
|
+
answers[member] = [LOOKUP_ERROR_MARKER, "#{member} lookup raised #{e.class}: #{e.message}"]
|
|
141
|
+
raise
|
|
142
|
+
end
|
|
88
143
|
end
|
|
89
144
|
|
|
90
145
|
# Uploads hold an open Tempfile, which no serializer can represent, so
|