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.
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'set'
4
+
5
+ # Decides whether a run adds and updates the document without removing anything.
6
+ #
7
+ # A run over part of the suite cannot tell an endpoint that was removed from
8
+ # one whose spec did not run, so it removes nothing. Only a run over the whole
9
+ # suite does. RSpec::OpenAPI.partial_update forces either mode.
10
+ module RSpec::OpenAPI::PartialRun
11
+ class << self
12
+ # The spec file of an example that recorded a request. The run is partial
13
+ # when a spec file next to one of these was left out.
14
+ def record_file(path)
15
+ recorded_files << path
16
+ end
17
+
18
+ def rspec?
19
+ configured = RSpec::OpenAPI.partial_update
20
+ return configured unless configured.nil?
21
+
22
+ parallel_worker? || filtered? || files_left_out?
23
+ end
24
+
25
+ # Minitest tells nothing about the run, so only the option and the
26
+ # parallel_tests marker count.
27
+ def minitest?
28
+ configured = RSpec::OpenAPI.partial_update
29
+ configured == true || (configured.nil? && parallel_worker?)
30
+ end
31
+
32
+ # Printed when the run decided on its own, since the user may expect the
33
+ # removals of a full run.
34
+ def notice(partial)
35
+ return unless partial && RSpec::OpenAPI.partial_update.nil? && recorded_files.any?
36
+
37
+ 'rspec-openapi: this run covered part of the suite, so nothing was removed from the document. ' \
38
+ 'Run all specs to remove what no longer exists.'
39
+ end
40
+
41
+ private
42
+
43
+ def recorded_files
44
+ @recorded_files ||= Set.new
45
+ end
46
+
47
+ # parallel_tests marks each worker with TEST_ENV_NUMBER, an empty string
48
+ # for the first one. A worker sees part of the files, whichever files it
49
+ # got, so the directory check below cannot tell it from a full run.
50
+ def parallel_worker?
51
+ ENV.key?('TEST_ENV_NUMBER')
52
+ end
53
+
54
+ # -e, --tag, a line number, --only-failures, and a `fit` once an example
55
+ # carries it. An exclusion such as `--tag ~slow` does not narrow the run.
56
+ def filtered?
57
+ RSpec.configuration.inclusion_filter.rules.any?
58
+ end
59
+
60
+ # `rspec spec/requests/users_spec.rb` leaves out the other files of
61
+ # spec/requests. `rspec spec/requests` and `rspec spec/requests/*_spec.rb`
62
+ # do not, nor does a run that leaves out files of a directory that
63
+ # recorded nothing.
64
+ def files_left_out?
65
+ running = RSpec.configuration.files_to_run
66
+ recorded_files.map { |file| File.dirname(file) }.uniq.any? do |dir|
67
+ (spec_files_in(dir) - running).any?
68
+ end
69
+ end
70
+
71
+ # The spec files directly in dir, by the pattern and exclude pattern of
72
+ # the run.
73
+ def spec_files_in(dir)
74
+ config = RSpec.configuration
75
+ files = Dir[glob(dir, config.pattern)] - Dir[glob(dir, config.exclude_pattern)]
76
+ files.map { |file| File.expand_path(file) }.select { |file| File.dirname(file) == dir }
77
+ end
78
+
79
+ # A pattern may list alternatives, which glob as a brace group like RSpec does.
80
+ def glob(dir, pattern)
81
+ File.join(dir, "{#{pattern.to_s.gsub(/\s*,\s*/, ',')}}")
82
+ end
83
+ end
84
+ end
@@ -13,6 +13,8 @@ RSpec::OpenAPI::Record = Struct.new(
13
13
  :summary, # @param [String] - "v1/statuses #show"
14
14
  :tags, # @param [Array] - ["Status"]
15
15
  :formats, # @param [Proc] - ->(key) { key.end_with?('_at') ? 'date-time' : nil }
16
+ :response_read_only, # @param [Proc] - ->(key) { key == 'id' }, what a response marks readOnly
17
+ :request_read_only, # @param [Proc] - ->(key) { key == 'id' }, what a request may cancel
16
18
  :operation_id, # @param [String] - "request-1234"
17
19
  :description, # @param [String] - "returns a status"
18
20
  :example_key, # @param [String] - "with_flat_query_parameters"
@@ -1,8 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class RSpec::OpenAPI::ResultRecorder
4
- def initialize(path_records)
4
+ # @param [Boolean] partial add and update without removing anything
5
+ def initialize(path_records, partial: false)
5
6
  @path_records = path_records
7
+ @partial = partial
6
8
  @error_records = {}
7
9
  end
8
10
 
@@ -45,6 +47,10 @@ class RSpec::OpenAPI::ResultRecorder
45
47
  def build_spec(primary, records)
46
48
  title = records.first.title
47
49
  RSpec::OpenAPI::SchemaFile.new(primary).edit do |spec|
50
+ # The cleanup compares the document with one built from this run alone.
51
+ # Without an existing document nothing can be stale, so the document is
52
+ # that one and the records are merged once.
53
+ new_from_zero = spec.empty? ? spec : {}
48
54
  # Normalize an existing file back to the internal form so merge/cleanup is
49
55
  # version-agnostic; cleanup_schema! re-applies the target form.
50
56
  RSpec::OpenAPI::NullableConverter.normalize!(spec)
@@ -54,11 +60,11 @@ class RSpec::OpenAPI::ResultRecorder
54
60
  # SchemaFile#read already symbolized the document, so no merge here needs
55
61
  # to normalize it again.
56
62
  RSpec::OpenAPI::SchemaMerger.merge_normalized!(spec, schema)
57
- new_from_zero = {}
58
63
  records.each do |record|
59
64
  record_schema = RSpec::OpenAPI::SchemaBuilder.build(record)
60
- RSpec::OpenAPI::SchemaMerger.merge_normalized!(spec, record_schema)
61
- RSpec::OpenAPI::SchemaMerger.merge_normalized!(new_from_zero, record_schema)
65
+ # The document takes the schema over, so the fresh one gets a copy.
66
+ RSpec::OpenAPI::SchemaMerger.merge_normalized!(new_from_zero, record_schema) unless new_from_zero.equal?(spec)
67
+ RSpec::OpenAPI::SchemaMerger.merge_built!(spec, record_schema)
62
68
  rescue StandardError, NotImplementedError => e # e.g. SchemaBuilder raises a NotImplementedError
63
69
  @error_records[e] = record # Avoid failing the build
64
70
  end
@@ -68,14 +74,21 @@ class RSpec::OpenAPI::ResultRecorder
68
74
  end
69
75
 
70
76
  def execute_post_process_hook(path, records, spec)
71
- RSpec::OpenAPI.post_process_hook.call(path, records, spec) if RSpec::OpenAPI.post_process_hook.is_a?(Proc)
77
+ return unless RSpec::OpenAPI.post_process_hook.is_a?(Proc)
78
+
79
+ RSpec::OpenAPI.post_process_hook.call(path, records, spec)
80
+ # The hook may add string keys beside the symbol ones, and the files are
81
+ # written from the keys as they are. Folding them keeps one entry per name.
82
+ spec.replace(RSpec::OpenAPI::KeyTransformer.symbolize(spec))
72
83
  end
73
84
 
74
85
  def cleanup_schema!(new_from_zero, spec)
75
86
  RSpec::OpenAPI::SchemaCleaner.cleanup_conflicting_security_parameters!(spec)
76
- RSpec::OpenAPI::SchemaCleaner.cleanup!(spec, new_from_zero)
77
- RSpec::OpenAPI::ComponentsUpdater.update!(spec, new_from_zero)
78
- RSpec::OpenAPI::SchemaCleaner.cleanup_empty_required_array!(spec)
87
+ RSpec::OpenAPI::SchemaCleaner.cleanup!(spec, new_from_zero) unless @partial
88
+ RSpec::OpenAPI::ComponentsUpdater.update!(spec, new_from_zero, partial: @partial)
89
+ # After the update, which reads the request side's readOnly: false from
90
+ # new_from_zero, the very spec when there was no document yet.
91
+ RSpec::OpenAPI::SchemaCleaner.cleanup_schemas!(spec)
79
92
  RSpec::OpenAPI::OperationConverter.to_additional_operations!(spec) if RSpec::OpenAPI.supports_additional_operations?
80
93
  RSpec::OpenAPI::SchemaSorter.deep_sort!(spec)
81
94
  RSpec::OpenAPI::NullableConverter.to_json_schema!(spec) if RSpec::OpenAPI.json_schema_based?
@@ -10,16 +10,24 @@ RSpec.configuration.after(:each) do |example|
10
10
  if RSpec::OpenAPI.example_types.include?(example.metadata[:type]) && example.metadata[:openapi] != false
11
11
  path = RSpec::OpenAPI.path.then { |p| p.is_a?(Proc) ? p.call(example) : p }
12
12
  record = RSpec::OpenAPI::RecordBuilder.build(self, example: example, extractor: SharedHooks.find_extractor)
13
- RSpec::OpenAPI.path_records[path] << record if record
13
+ if record
14
+ RSpec::OpenAPI.path_records[path] << record
15
+ RSpec::OpenAPI::PartialRun.record_file(example.metadata[:absolute_file_path])
16
+ end
14
17
  end
15
18
  end
16
19
 
17
20
  RSpec.configuration.after(:suite) do
18
- result_recorder = RSpec::OpenAPI::ResultRecorder.new(RSpec::OpenAPI.path_records)
21
+ partial = RSpec::OpenAPI::PartialRun.rspec?
22
+ result_recorder = RSpec::OpenAPI::ResultRecorder.new(RSpec::OpenAPI.path_records, partial: partial)
19
23
  result_recorder.record_results!
24
+ reporter = RSpec.configuration.reporter
25
+ if (notice = RSpec::OpenAPI::PartialRun.notice(partial))
26
+ reporter.message notice
27
+ end
20
28
  if result_recorder.errors?
21
29
  error_message = result_recorder.error_message
22
30
  colorizer = RSpec::Core::Formatters::ConsoleCodes
23
- RSpec.configuration.reporter.message colorizer.wrap(error_message, :failure)
31
+ reporter.message colorizer.wrap(error_message, :failure)
24
32
  end
25
33
  end
@@ -6,14 +6,29 @@ class << RSpec::OpenAPI::SchemaBuilder
6
6
  # a value at a given path under a record's request/response side.
7
7
  #
8
8
  # Positional members: one is built per property of every body, and
9
- # keyword_init would add a keyword hash to each.
10
- BuildContext = Struct.new(:record, :context, :path, :key) do
9
+ # keyword_init would add a keyword hash to each. The path is only ever looked
10
+ # up in the enum and additionalProperties maps of the record, so it is built
11
+ # for a side of a record that holds one.
12
+ BuildContext = Struct.new(:record, :context, :path, :key, :lookups) do
13
+ def self.root(record, context, path = nil, key = nil)
14
+ lookups = record[ENUM_MEMBERS.fetch(context)] ||
15
+ OVERRIDE_MEMBERS.any? { |_kind, members| record[members.fetch(context)] }
16
+ new(record, context, path, key, lookups)
17
+ end
18
+
11
19
  def descend(child_key)
12
- self.class.new(record, context, path ? "#{path}.#{child_key}" : child_key.to_s, child_key)
20
+ self.class.new(record, context, child_path(child_key), child_key, lookups)
21
+ end
22
+
23
+ def child_path(child_key)
24
+ return nil unless lookups
25
+
26
+ path ? "#{path}.#{child_key}" : child_key.to_s
13
27
  end
14
28
 
29
+ # Items take the format and enum of their array, so they share its path and key.
15
30
  def for_array_items
16
- self.class.new(record, context, path, nil)
31
+ self.class.new(record, context, path, key, lookups)
17
32
  end
18
33
  end
19
34
  private_constant :BuildContext
@@ -12,50 +12,74 @@ class << RSpec::OpenAPI::SchemaBuilder
12
12
  # Drop empty `{}` schemas (e.g. items of an empty array) — they carry no
13
13
  # type info and would otherwise spuriously mark every property of their
14
14
  # populated siblings as nullable via the missing-key nullable rule.
15
- non_empty = widen_integers(variations.reject(&:empty?))
15
+ non_empty = variations.reject(&:empty?)
16
16
  return {} if non_empty.empty?
17
- return non_empty.first if non_empty.size == 1
18
17
 
19
- types = non_empty.map { |v| v[:type] }.compact.uniq
20
- return one_of_schema(non_empty) if types.size > 1
18
+ typed = non_empty.reject { |v| nullable_only?(v) }
19
+ return { nullable: true } if typed.empty?
21
20
 
22
- case types.first
23
- when 'object' then merge_object_variations(non_empty)
24
- when 'array' then merge_array_item_variations(non_empty)
25
- else non_empty.first
26
- end
21
+ with_nullable_from(non_empty, merge_typed_variations(widen_integers(typed)))
27
22
  end
28
23
 
29
24
  def merge_non_object_item_variations(schemas)
30
- nullable_only = ->(schema) { schema.keys == [:nullable] }
31
- typed = schemas.reject(&nullable_only)
25
+ typed = schemas.reject { |schema| nullable_only?(schema) }
26
+ return { nullable: true } if typed.empty?
32
27
 
33
28
  merged = typed.size == 1 ? typed.first.dup : merge_multi(typed)
34
- merged[:nullable] = true if schemas.any?(&nullable_only) && merged.is_a?(Hash)
29
+ merged[:nullable] = true if typed.size < schemas.size
35
30
  merged
36
31
  end
37
32
 
38
33
  # Merge the per-key property schemas of multiple object variations.
39
- # When `allow_recursive_merge` is true, objects are recursively merged via
40
- # merge_variations and existing oneOf entries are flattened.
41
- # When false (callsite: array-items merging), divergent property variations
42
- # become oneOf without recursive descent.
34
+ # `allow_recursive_merge` only decides which signals make a property
35
+ # nullable. Both modes merge the property schemas themselves alike.
43
36
  def merge_property_variations(variations, allow_recursive_merge:)
44
37
  property_keys(variations).each_with_object({}) do |key, merged_props|
45
38
  all = variations.map { |v| v[:properties]&.[](key) }
46
- prop_variations = all.reject { |p| p.nil? || p.keys == [:nullable] }
39
+ read_only = lift_read_only!(all)
40
+ prop_variations = all.reject { |p| p.nil? || nullable_only?(p) }
47
41
  has_nullable = nullable_present?(all, recursive: allow_recursive_merge)
48
42
 
49
43
  next if prop_variations.empty? && !has_nullable
50
44
 
51
- merged_props[key] = merge_single_property(prop_variations, has_nullable,
52
- variations_total: variations.size,
53
- allow_recursive_merge: allow_recursive_merge,)
45
+ merged = merge_single_property(prop_variations, has_nullable,
46
+ variations_total: variations.size,
47
+ allow_recursive_merge: allow_recursive_merge,)
48
+ merged[:readOnly] = read_only unless read_only.nil?
49
+ merged_props[key] = merged
54
50
  end
55
51
  end
56
52
 
57
53
  private
58
54
 
55
+ def merge_typed_variations(variations)
56
+ return variations.first if variations.size == 1
57
+ return merge_one_of_variations(variations) if variations.any? { |v| v.key?(:oneOf) }
58
+
59
+ types = variations.map { |v| v[:type] }.compact.uniq
60
+ return merge_one_of_variations(variations) if types.size > 1
61
+
62
+ case types.first
63
+ when 'object' then merge_object_variations(variations)
64
+ when 'array' then merge_array_item_variations(variations)
65
+ else variations.first
66
+ end
67
+ end
68
+
69
+ def with_nullable_from(variations, merged)
70
+ variations.any? { |v| v[:nullable] } ? merged.merge(nullable: true) : merged
71
+ end
72
+
73
+ # The variations of one property come from one side of one exchange, so
74
+ # they agree on readOnly. The merge rebuilds the schema, so the caller puts
75
+ # it back on the result, beside a oneOf like nullable. The schemas are the
76
+ # builder's own, so the flag comes off them in place.
77
+ def lift_read_only!(all)
78
+ read_only = all.find { |p| p.is_a?(Hash) && p.key?(:readOnly) }&.[](:readOnly)
79
+ all.each { |p| p&.delete(:readOnly) } unless read_only.nil?
80
+ read_only
81
+ end
82
+
59
83
  def merge_object_variations(variations)
60
84
  merged = { type: 'object' }
61
85
  if variations.any? { |v| v.key?(:properties) }
@@ -68,13 +92,22 @@ class << RSpec::OpenAPI::SchemaBuilder
68
92
  merged
69
93
  end
70
94
 
71
- # Merge multiple array schemas by merging their `items` schemas.
95
+ # Merge multiple array schemas by merging their `items` schemas. A constraint
96
+ # seen in a single sample must not spread to its siblings.
72
97
  def merge_array_item_variations(variations)
73
- { type: 'array', items: merge_variations(variations.map { |v| v[:items] }.compact) }
98
+ merged = variations.first.select do |key, value|
99
+ key == :type || key == :items ||
100
+ variations.all? { |variation| variation.key?(key) && variation[key] == value }
101
+ end
102
+ merged[:items] = merge_variations(variations.map { |v| v[:items] }.compact)
103
+ merged
74
104
  end
75
105
 
76
106
  def property_keys(variations)
77
- variations.flat_map { |v| v[:properties]&.keys || [] }.uniq
107
+ keys = []
108
+ variations.each { |v| v[:properties]&.each_key { |key| keys << key } }
109
+ keys.uniq!
110
+ keys
78
111
  end
79
112
 
80
113
  # `recursive` mirrors merge_variations' original rule that also treats
@@ -82,10 +115,15 @@ class << RSpec::OpenAPI::SchemaBuilder
82
115
  # looks at outright nil or `{ nullable: true }` markers.
83
116
  def nullable_present?(all_props, recursive:)
84
117
  all_props.any? do |p|
85
- p.nil? || (p.is_a?(Hash) && (p.keys == [:nullable] || (recursive && p[:nullable] == true)))
118
+ p.nil? || (p.is_a?(Hash) && (nullable_only?(p) || (recursive && p[:nullable] == true)))
86
119
  end
87
120
  end
88
121
 
122
+ # A nil builds `{ nullable: true }`.
123
+ def nullable_only?(schema)
124
+ schema[:nullable] == true && !schema.key?(:type) && !schema.key?(:oneOf)
125
+ end
126
+
89
127
  def merge_single_property(prop_variations, has_nullable, variations_total:, allow_recursive_merge:)
90
128
  return { nullable: true } if prop_variations.empty?
91
129
 
@@ -96,8 +134,6 @@ class << RSpec::OpenAPI::SchemaBuilder
96
134
  merge_multi(prop_variations)
97
135
  end
98
136
 
99
- return merged unless merged.is_a?(Hash)
100
-
101
137
  # In recursive mode, multi-variation merges also flag nullable when the key
102
138
  # only appeared in some of the source variations.
103
139
  needs_nullable =
@@ -114,11 +150,11 @@ class << RSpec::OpenAPI::SchemaBuilder
114
150
  # entries, recurse into objects and arrays, and combine divergent types into
115
151
  # oneOf. Scalar variations of a single type collapse to the first schema.
116
152
  def merge_multi(prop_variations)
117
- return { oneOf: flatten_one_of(prop_variations) } if prop_variations.any? { |p| p.key?(:oneOf) }
153
+ return merge_one_of_variations(prop_variations) if prop_variations.any? { |p| p.key?(:oneOf) }
118
154
 
119
155
  prop_variations = widen_integers(prop_variations)
120
156
  prop_types = prop_variations.map { |p| p[:type] }.compact.uniq
121
- return one_of_schema(prop_variations) if prop_types.size > 1
157
+ return merge_one_of_variations(prop_variations) if prop_types.size > 1
122
158
 
123
159
  case prop_types.first
124
160
  when 'array' then merge_array_item_variations(prop_variations)
@@ -127,6 +163,16 @@ class << RSpec::OpenAPI::SchemaBuilder
127
163
  end
128
164
  end
129
165
 
166
+ def merge_one_of_variations(variations)
167
+ { oneOf: merge_structured_alternatives(widen_integers(flatten_one_of(variations))) }
168
+ end
169
+
170
+ def merge_structured_alternatives(alternatives)
171
+ alternatives.group_by { |alternative| alternative[:type] }.flat_map do |type, group|
172
+ ['array', 'object'].include?(type) && group.size > 1 ? [merge_variations(group)] : group
173
+ end
174
+ end
175
+
130
176
  # Every integer is a number, so integers seen beside numbers are numbers.
131
177
  def widen_integers(variations)
132
178
  return variations unless variations.any? { |v| v[:type] == 'number' }
@@ -150,10 +196,6 @@ class << RSpec::OpenAPI::SchemaBuilder
150
196
  prop.reject { |k, _| k == :nullable }
151
197
  end
152
198
 
153
- def one_of_schema(variations)
154
- { oneOf: sort_by_type(variations.map { |p| without_nullable(p) }.uniq) }
155
- end
156
-
157
199
  # The same order the merger keeps, so the document does not depend on which
158
200
  # example ran first.
159
201
  def sort_by_type(options)