Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Shipped the rswag helpers so extensions can document their Admin API (V-3779) (#15095)

Damian Legawiec383228be97de
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 0af2bb6e33..92dbf7b418 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -26974,7 +26974,6 @@ paths:
Puts a product a seller submitted for review on sale, and closes the
submission. Only a product awaiting review can be approved.
-
**Required scope:** `write_products` (for API-key authentication).
parameters:
- name: x-spree-api-key
diff --git a/spree/api/lib/spree/api/testing_support/deterministic_openapi.rb b/spree/api/lib/spree/api/testing_support/deterministic_openapi.rb
new file mode 100644
index 0000000000..42a840cf85
--- /dev/null
+++ b/spree/api/lib/spree/api/testing_support/deterministic_openapi.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+# The OpenAPI specs in docs/api-reference/ embed real response bodies captured
+# while the integration suite runs, so anything the suite generates at random
+# lands in a checked-in file. Two runs of unchanged code used to produce a
+# ~1,800 line diff, which buried real API changes in noise during review.
+#
+# Under OPENAPI=true (set by the swaggerize rake task) every source of that
+# noise is pinned, so regenerating the specs yields a byte-identical file
+# unless the API itself changed. Nothing here is loaded by a normal spec run —
+# the suite keeps its random names and real clock.
+if ENV['OPENAPI'] == 'true'
+ require 'securerandom'
+ require 'digest/md5'
+ require 'ffaker'
+
+ module Spree
+ module OpenAPIDeterminism
+ # The instant every generated example is stamped with. Anything derived
+ # from it — an expiry fourteen days out, a promotion window — lands on a
+ # stable value too, so a whole run reduces to this one timestamp. Bump it
+ # only when the dates in the published examples start looking stale; each
+ # bump rewrites every timestamp in the checked-in specs.
+ FROZEN_TIME = Time.utc(2026, 1, 15, 12, 0, 0)
+
+ # Base seed for the two pseudo-random generators in play: Ruby's global
+ # one, which Kernel.rand draws from, and FFaker's own, which is separate
+ # and needs seeding through its own API. Both are mixed with the example's
+ # identity for the same reason the token seeds are: a run-wide constant
+ # would hand every example the same "random" name and email, and the
+ # unique ones then collide on a real index.
+ RANDOM_SEED = 20_260_115
+
+ # Signing secret for the JWTs shown in the examples. It signs nothing
+ # real — these tokens are documentation, generated against a throwaway
+ # dummy app — but it has to be the same everywhere for the signatures
+ # to match across machines.
+ JWT_SECRET = 'openapi-example-signing-secret'
+
+ # SecureRandom bypasses the global PRNG (it reads from the OS), so seeding
+ # alone leaves API keys, invitation tokens and JWT ids churning. These
+ # counter-backed replacements produce values with the right shape and
+ # length for anything that stores or displays them.
+ module PredictableSecureRandom
+ HEX_ALPHABET = '0123456789abcdef'
+ BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
+ BASE36_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'
+ URL_SAFE_ALPHABET = "#{BASE36_ALPHABET}ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
+
+ class << self
+ # Values must be unique across the whole run (they back columns with
+ # unique indexes, such as a store's setup token) while still being
+ # reproducible. Deriving the seed from the current example's id plus a
+ # per-example counter gives both: unique because no two examples share
+ # an id, reproducible because an example's id does not change between
+ # runs, and stable under edits because adding one spec cannot shift
+ # the values another spec produces.
+ def scope!(example_key)
+ @example_key = example_key
+ @sequence = 0
+ end
+
+ # Digest rather than String#hash: Ruby randomizes String#hash per
+ # process, which is exactly the churn this file exists to remove.
+ def next_seed
+ @sequence = (@sequence || 0) + 1
+ Digest::MD5.hexdigest("#{@example_key}/#{@sequence}")[0, 15].to_i(16)
+ end
+
+ def string_from(alphabet, length)
+ generator = Random.new(next_seed)
+ Array.new(length) { alphabet[generator.rand(alphabet.length)] }.join
+ end
+ end
+
+ # Callers pass nil to mean "the default length", so every override
+ # normalizes it rather than doing arithmetic on it.
+ def hex(length = nil)
+ PredictableSecureRandom.string_from(HEX_ALPHABET, (length || 16) * 2)
+ end
+
+ def base58(length = nil)
+ PredictableSecureRandom.string_from(BASE58_ALPHABET, length || 16)
+ end
+
+ def base36(length = nil)
+ PredictableSecureRandom.string_from(BASE36_ALPHABET, length || 16)
+ end
+
+ def alphanumeric(length = nil, chars: nil)
+ return super if chars
+
+ PredictableSecureRandom.string_from(BASE58_ALPHABET, length || 16)
+ end
+
+ def urlsafe_base64(length = nil, _padding = false)
+ PredictableSecureRandom.string_from(URL_SAFE_ALPHABET, ((length || 16) * 4 / 3.0).ceil)
+ end
+
+ def uuid
+ digits = PredictableSecureRandom.string_from(HEX_ALPHABET, 32)
+ [digits[0, 8], digits[8, 4], "4#{digits[13, 3]}", "a#{digits[17, 3]}", digits[20, 12]].join('-')
+ end
+
+ def bytes(length)
+ PredictableSecureRandom.string_from(HEX_ALPHABET, (length || 16) * 2)[0, length || 16]
+ end
+ end
+ end
+ end
+
+ SecureRandom.singleton_class.prepend(Spree::OpenAPIDeterminism::PredictableSecureRandom)
+
+ RSpec.configure do |config|
+ config.before do
+ travel_to(Spree::OpenAPIDeterminism::FROZEN_TIME)
+ end
+
+ # Reset before each example rather than once for the run, so a value shown
+ # in one example does not depend on how many records the examples before it
+ # happened to create. Without this, adding a spec shifts every random value
+ # generated after it and the diff spreads across unrelated endpoints.
+ #
+ # FactoryBot's own sequences are deliberately left alone: they already count
+ # from one per process, so they are stable, and rewinding them mid-run would
+ # hand out an SKU or email that another example already claimed.
+ config.before do |example|
+ example_key = example.metadata[:full_description]
+ example_seed = Spree::OpenAPIDeterminism::RANDOM_SEED ^ Digest::MD5.hexdigest(example_key)[0, 15].to_i(16)
+
+ srand(example_seed)
+ FFaker::Random.seed = example_seed
+ Spree::OpenAPIDeterminism::PredictableSecureRandom.scope!(example_key)
+
+ # The examples include signed JWTs. Their payloads are already stable
+ # (a frozen clock fixes `exp`, the SecureRandom override fixes `jti`),
+ # but the signature also depends on the signing secret, which otherwise
+ # falls through to the dummy app's `secret_key_base` — generated when
+ # that app is built and so different on every machine. Without this the
+ # specs reproduce for whoever generated them and for nobody else.
+ #
+ # Set per example, not once for the suite: the suite resets Spree's
+ # preferences before every example, which would wipe a one-off value.
+ Spree::Api::Config[:jwt_secret_key] = Spree::OpenAPIDeterminism::JWT_SECRET
+ end
+ end
+end
diff --git a/spree/api/lib/spree/api/testing_support/openapi.rb b/spree/api/lib/spree/api/testing_support/openapi.rb
new file mode 100644
index 0000000000..a3b77bb551
--- /dev/null
+++ b/spree/api/lib/spree/api/testing_support/openapi.rb
@@ -0,0 +1,198 @@
+require 'spree/api/testing_support/v3/base'
+require 'spree/api/testing_support/deterministic_openapi'
+
+module Spree
+ module Api
+ module TestingSupport
+ # Documents a write endpoint's request body from the controller's
+ # `request_params` declaration, so no integration spec describes a body by hand.
+ #
+ # path '/api/v3/admin/products' do
+ # post 'Create a product' do
+ # request_body_for
+ #
+ # The body references the `<Resource>CreateParams` / `<Resource>UpdateParams`
+ # component, registered with every shared shape it uses under the spec's
+ # `components.schemas`. The SDK request types are generated from those
+ # components.
+ module RequestBody
+ # @param action [Symbol, nil] the controller action; read from the route
+ # when omitted
+ # @param controller [Class, nil] resolved from the path when omitted
+ # @param required [Boolean] false for an endpoint that accepts no body
+ def request_body_for(action = nil, controller: nil, required: true)
+ route = request_body_route
+ action ||= route[:action].to_sym
+ controller ||= "#{route[:controller]}_controller".camelize.constantize
+ schema = controller.request_params_schema(action)
+ raise "#{controller.name} does not declare request_params for #{action}" unless schema
+
+ name = schema.component_name(action)
+ register_request_schema(name, schema.json_schema(action.in?(%i[create update]) ? action : nil))
+ schema.shapes.each { |shape| register_request_schema(shape.name, shape.json_schema) }
+ schema.code_lists.each { |list_name, definition| register_request_schema(list_name, definition) }
+
+ parameter name: :body, in: :body, required: required, schema: { '$ref': "#/components/schemas/#{name}" }
+ end
+
+ # Documents a shape a read endpoint takes as query parameters, and publishes
+ # it as a component so the SDKs generate one type for it.
+ #
+ # @param shape [Spree::Api::V3::RequestSchema] a named shape
+ def query_parameters_for(shape)
+ register_request_schema(shape.name, shape.json_schema)
+ shape.shapes.each { |nested| register_request_schema(nested.name, nested.json_schema) }
+ shape.code_lists.each { |list_name, definition| register_request_schema(list_name, definition) }
+
+ shape.json_schema[:properties].each do |name, property|
+ parameter name: name, in: :query, required: false, description: property[:description],
+ schema: property.except(:description)
+ end
+ end
+
+ private
+
+ def request_body_route
+ path = metadata[:path_item][:template].gsub(/\{[^}]+\}/, 'x1')
+ Rails.application.routes.recognize_path(path, method: metadata[:operation][:verb])
+ end
+
+ def register_request_schema(name, definition)
+ # rswag routes an operation with no document named to the first one.
+ specs = RSpec.configuration.openapi_specs
+ spec = specs.fetch(metadata[:openapi_spec] || metadata[:swagger_doc] || specs.keys.first)
+ schemas = (spec[:components] ||= {})[:schemas] ||= {}
+ definition = definition.deep_stringify_keys
+
+ if schemas.key?(name) && schemas[name].deep_stringify_keys != definition
+ raise "Two request schemas are named #{name}; " \
+ 'name one of the request_params declarations or shapes differently'
+ end
+
+ schemas[name] = definition
+ # Request schemas follow the response ones, sorted, so the written spec
+ # does not depend on the order specs ran in.
+ request, response = schemas.partition { |key, _| key.to_s.end_with?('Params') }
+ spec[:components][:schemas] = response.to_h.merge(request.sort_by { |key, _| key.to_s }.to_h)
+ end
+ end
+
+ # Appends a `**Required scope:**` line to the operation description, to
+ # surface scope requirements in the rendered docs without inventing a
+ # custom OpenAPI extension.
+ #
+ # admin_scope :read, :orders
+ # admin_scope :write, :customers
+ module AdminScope
+ def admin_scope(action, resource)
+ admin_scope_note("`#{action}_#{resource}`")
+ end
+
+ # Free-form variant for endpoints whose required scope is resolved at
+ # request time (e.g. exports — gated by the exported resource's scope).
+ def admin_scope_note(text)
+ line = "**Required scope:** #{text} (for API-key authentication)."
+ existing = metadata[:operation][:description].to_s
+ metadata[:operation][:description] = existing.empty? ? line : "#{existing}\n\n#{line}"
+ end
+ end
+
+ # What every admin operation in an rswag spec repeats, in one line: the
+ # content types, the two ways to authenticate, the scope note in the
+ # description, and a signed-in admin and secret key to call it with.
+ #
+ # patch 'Send a quote' do
+ # tags 'Quotes'
+ # admin_operation :write, :quotes, description: <<~DESC
+ # Sends the quote to the buyer. Use it once the prices are final.
+ # DESC
+ # request_body_for
+ #
+ # response('200', 'sent') { run_test! }
+ # end
+ #
+ # Pass the description here, or call it after `description`: the scope
+ # note is appended to whatever the description is at that point. A
+ # response block overrides either credential with its own `let`. The
+ # credentials come from the 'API v3 Admin' shared context, which
+ # Openapi.configure includes in every request spec.
+ module AdminOperation
+ BODY_VERBS = %i[post patch put].freeze
+
+ # @param kind [Symbol] :read or :write
+ # @param resource [Symbol] the controller's scoped resource
+ # @param description [String, nil]
+ # @return [void]
+ def admin_operation(kind, resource, description: nil)
+ verb = metadata[:operation][:verb].to_sym
+ consumes 'application/json' if BODY_VERBS.include?(verb)
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+
+ self.description(description.strip) if description
+ admin_scope(kind, resource)
+
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ end
+ end
+
+ # What an extension needs to generate the `openapi/admin.yaml` its gem
+ # ships, documenting its Admin API endpoints the way core documents its
+ # own. The extension can build its API docs or a client from the file. In the extension's swagger helper:
+ #
+ # require 'rswag/specs'
+ # require 'spree/api/testing_support/openapi'
+ #
+ # RSpec.configure do |config|
+ # Spree::Api::TestingSupport::Openapi.configure(
+ # config, engine: MyExtension::Engine, title: 'My Extension Admin API'
+ # )
+ # end
+ #
+ # and in its Rakefile, `require 'spree/api/testing_support/openapi_tasks'`
+ # for `rake spree:openapi:generate`.
+ module Openapi
+ HELPERS = [RequestBody, AdminScope, AdminOperation].freeze
+
+ class << self
+ # @param config [RSpec::Core::Configuration]
+ # @param engine [Class<Rails::Engine>]
+ # @param title [String]
+ # @param description [String, nil]
+ # @return [void]
+ def configure(config, engine:, title:, description: nil)
+ config.openapi_root = engine.root.to_s
+ config.openapi_specs = { 'openapi/admin.yaml' => admin_document(title, description) }
+ config.openapi_format = :yaml
+ HELPERS.each { |helper| config.extend helper, type: :request }
+ # The admin and secret key admin_operation authenticates with.
+ config.include_context 'API v3 Admin', type: :request
+ end
+
+ # The skeleton of an extension's admin document: the same security
+ # schemes as core's, so its operations authenticate the same way.
+ #
+ # @return [Hash]
+ def admin_document(title, description = nil)
+ {
+ openapi: '3.0.3',
+ info: { title: title, version: 'v3', description: description }.compact,
+ paths: {},
+ components: {
+ securitySchemes: {
+ api_key: { type: :apiKey, name: 'x-spree-api-key', in: :header,
+ description: 'Secret API key for admin access' },
+ bearer_auth: { type: :http, scheme: :bearer, bearerFormat: 'JWT',
+ description: 'JWT token for admin user authentication' }
+ }
+ }
+ }
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/lib/spree/api/testing_support/openapi_tasks.rb b/spree/api/lib/spree/api/testing_support/openapi_tasks.rb
new file mode 100644
index 0000000000..d4d5505e15
--- /dev/null
+++ b/spree/api/lib/spree/api/testing_support/openapi_tasks.rb
@@ -0,0 +1,17 @@
+# `rake spree:openapi:generate` for an extension: runs its integration specs
+# through rswag and writes the `openapi/admin.yaml` its gem ships. Under
+# OPENAPI=true the run is reproducible (see deterministic_openapi.rb), so a
+# diff in the file means the API changed.
+#
+# RSpec is started only when the task runs, so a Rakefile that loads this
+# keeps working in a bundle without rspec-core.
+namespace :spree do
+ namespace :openapi do
+ desc "Generate openapi/admin.yaml from this extension's integration specs"
+ task :generate do
+ pattern = ENV.fetch('PATTERN', 'spec/integration/**/*_spec.rb')
+ ENV['OPENAPI'] = 'true'
+ ruby '-S', 'rspec', '--pattern', pattern, '--format', 'Rswag::Specs::SwaggerFormatter', '--order', 'defined'
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
index d9fcce3619..f09e31e3a8 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
@@ -629,20 +629,12 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
patch 'Approve a submitted product' do
tags 'Products'
admin_sdk_example 'products/approve'
- consumes 'application/json'
- produces 'application/json'
- security [api_key: [], bearer_auth: []]
- description <<~DESC
+ admin_operation :write, :products, description: <<~DESC
Puts a product a seller submitted for review on sale, and closes the
submission. Only a product awaiting review can be approved.
DESC
- admin_scope :write, :products
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: :Authorization, in: :header, type: :string, required: true
response '200', 'product approved' do
- let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let(:submitted) { create(:product, store: store, status: 'proposed') }
let(:id) { submitted.prefixed_id }
@@ -654,7 +646,6 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
end
response '422', 'the product is not awaiting review' do
- let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let(:id) { product.prefixed_id }
schema '$ref' => '#/components/schemas/ErrorResponse'
diff --git a/spree/api/spec/support/code_samples_helper.rb b/spree/api/spec/support/code_samples_helper.rb
index 5c1fe9d309..84306fa95a 100644
--- a/spree/api/spec/support/code_samples_helper.rb
+++ b/spree/api/spec/support/code_samples_helper.rb
@@ -1,8 +1,11 @@
# frozen_string_literal: true
require 'json'
+require 'spree/api/testing_support/openapi'
module CodeSamplesHelper
+ include Spree::Api::TestingSupport::AdminScope
+
SDK_CLIENT_INIT = <<~JS.strip
import { createClient } from '@spree/sdk'
@@ -404,23 +407,6 @@ module CodeSamplesHelper
body.rstrip.strip_heredoc.strip
end
- # Appends a `**Required scope:**` line to the operation description.
- # Use in admin integration specs to surface scope requirements in the
- # rendered Mintlify docs without inventing a custom OpenAPI extension.
- #
- # admin_scope :read, :orders
- # admin_scope :write, :customers
- def admin_scope(action, resource)
- admin_scope_note("`#{action}_#{resource}`")
- end
-
- # Free-form variant for endpoints whose required scope is resolved at
- # request time (e.g. exports — gated by the exported resource's scope).
- def admin_scope_note(text)
- line = "**Required scope:** #{text} (for API-key authentication)."
- existing = metadata[:operation][:description].to_s
- metadata[:operation][:description] = existing.empty? ? line : "#{existing}\n\n#{line}"
- end
end
RSpec.configure do |config|
diff --git a/spree/api/spec/support/deterministic_openapi.rb b/spree/api/spec/support/deterministic_openapi.rb
index 42a840cf85..ba238b0dd9 100644
--- a/spree/api/spec/support/deterministic_openapi.rb
+++ b/spree/api/spec/support/deterministic_openapi.rb
@@ -1,147 +1 @@
-# frozen_string_literal: true
-
-# The OpenAPI specs in docs/api-reference/ embed real response bodies captured
-# while the integration suite runs, so anything the suite generates at random
-# lands in a checked-in file. Two runs of unchanged code used to produce a
-# ~1,800 line diff, which buried real API changes in noise during review.
-#
-# Under OPENAPI=true (set by the swaggerize rake task) every source of that
-# noise is pinned, so regenerating the specs yields a byte-identical file
-# unless the API itself changed. Nothing here is loaded by a normal spec run —
-# the suite keeps its random names and real clock.
-if ENV['OPENAPI'] == 'true'
- require 'securerandom'
- require 'digest/md5'
- require 'ffaker'
-
- module Spree
- module OpenAPIDeterminism
- # The instant every generated example is stamped with. Anything derived
- # from it — an expiry fourteen days out, a promotion window — lands on a
- # stable value too, so a whole run reduces to this one timestamp. Bump it
- # only when the dates in the published examples start looking stale; each
- # bump rewrites every timestamp in the checked-in specs.
- FROZEN_TIME = Time.utc(2026, 1, 15, 12, 0, 0)
-
- # Base seed for the two pseudo-random generators in play: Ruby's global
- # one, which Kernel.rand draws from, and FFaker's own, which is separate
- # and needs seeding through its own API. Both are mixed with the example's
- # identity for the same reason the token seeds are: a run-wide constant
- # would hand every example the same "random" name and email, and the
- # unique ones then collide on a real index.
- RANDOM_SEED = 20_260_115
-
- # Signing secret for the JWTs shown in the examples. It signs nothing
- # real — these tokens are documentation, generated against a throwaway
- # dummy app — but it has to be the same everywhere for the signatures
- # to match across machines.
- JWT_SECRET = 'openapi-example-signing-secret'
-
- # SecureRandom bypasses the global PRNG (it reads from the OS), so seeding
- # alone leaves API keys, invitation tokens and JWT ids churning. These
- # counter-backed replacements produce values with the right shape and
- # length for anything that stores or displays them.
- module PredictableSecureRandom
- HEX_ALPHABET = '0123456789abcdef'
- BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
- BASE36_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'
- URL_SAFE_ALPHABET = "#{BASE36_ALPHABET}ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
-
- class << self
- # Values must be unique across the whole run (they back columns with
- # unique indexes, such as a store's setup token) while still being
- # reproducible. Deriving the seed from the current example's id plus a
- # per-example counter gives both: unique because no two examples share
- # an id, reproducible because an example's id does not change between
- # runs, and stable under edits because adding one spec cannot shift
- # the values another spec produces.
- def scope!(example_key)
- @example_key = example_key
- @sequence = 0
- end
-
- # Digest rather than String#hash: Ruby randomizes String#hash per
- # process, which is exactly the churn this file exists to remove.
- def next_seed
- @sequence = (@sequence || 0) + 1
- Digest::MD5.hexdigest("#{@example_key}/#{@sequence}")[0, 15].to_i(16)
- end
-
- def string_from(alphabet, length)
- generator = Random.new(next_seed)
- Array.new(length) { alphabet[generator.rand(alphabet.length)] }.join
- end
- end
-
- # Callers pass nil to mean "the default length", so every override
- # normalizes it rather than doing arithmetic on it.
- def hex(length = nil)
- PredictableSecureRandom.string_from(HEX_ALPHABET, (length || 16) * 2)
- end
-
- def base58(length = nil)
- PredictableSecureRandom.string_from(BASE58_ALPHABET, length || 16)
- end
-
- def base36(length = nil)
- PredictableSecureRandom.string_from(BASE36_ALPHABET, length || 16)
- end
-
- def alphanumeric(length = nil, chars: nil)
- return super if chars
-
- PredictableSecureRandom.string_from(BASE58_ALPHABET, length || 16)
- end
-
- def urlsafe_base64(length = nil, _padding = false)
- PredictableSecureRandom.string_from(URL_SAFE_ALPHABET, ((length || 16) * 4 / 3.0).ceil)
- end
-
- def uuid
- digits = PredictableSecureRandom.string_from(HEX_ALPHABET, 32)
- [digits[0, 8], digits[8, 4], "4#{digits[13, 3]}", "a#{digits[17, 3]}", digits[20, 12]].join('-')
- end
-
- def bytes(length)
- PredictableSecureRandom.string_from(HEX_ALPHABET, (length || 16) * 2)[0, length || 16]
- end
- end
- end
- end
-
- SecureRandom.singleton_class.prepend(Spree::OpenAPIDeterminism::PredictableSecureRandom)
-
- RSpec.configure do |config|
- config.before do
- travel_to(Spree::OpenAPIDeterminism::FROZEN_TIME)
- end
-
- # Reset before each example rather than once for the run, so a value shown
- # in one example does not depend on how many records the examples before it
- # happened to create. Without this, adding a spec shifts every random value
- # generated after it and the diff spreads across unrelated endpoints.
- #
- # FactoryBot's own sequences are deliberately left alone: they already count
- # from one per process, so they are stable, and rewinding them mid-run would
- # hand out an SKU or email that another example already claimed.
- config.before do |example|
- example_key = example.metadata[:full_description]
- example_seed = Spree::OpenAPIDeterminism::RANDOM_SEED ^ Digest::MD5.hexdigest(example_key)[0, 15].to_i(16)
-
- srand(example_seed)
- FFaker::Random.seed = example_seed
- Spree::OpenAPIDeterminism::PredictableSecureRandom.scope!(example_key)
-
- # The examples include signed JWTs. Their payloads are already stable
- # (a frozen clock fixes `exp`, the SecureRandom override fixes `jti`),
- # but the signature also depends on the signing secret, which otherwise
- # falls through to the dummy app's `secret_key_base` — generated when
- # that app is built and so different on every machine. Without this the
- # specs reproduce for whoever generated them and for nobody else.
- #
- # Set per example, not once for the suite: the suite resets Spree's
- # preferences before every example, which would wipe a one-off value.
- Spree::Api::Config[:jwt_secret_key] = Spree::OpenAPIDeterminism::JWT_SECRET
- end
- end
-end
+require 'spree/api/testing_support/deterministic_openapi'
diff --git a/spree/api/spec/support/request_body_helper.rb b/spree/api/spec/support/request_body_helper.rb
index f4d7ee5cdd..03fac661cf 100644
--- a/spree/api/spec/support/request_body_helper.rb
+++ b/spree/api/spec/support/request_body_helper.rb
@@ -1,71 +1,6 @@
-# Documents a write endpoint's request body from the controller's
-# `request_params` declaration, so no integration spec describes a body by hand.
-#
-# path '/api/v3/admin/products' do
-# post 'Create a product' do
-# request_body_for
-#
-# The body references the `<Resource>CreateParams` / `<Resource>UpdateParams`
-# component, registered with every shared shape it uses under the spec's
-# `components.schemas`. The SDK request types are generated from those
-# components.
-module RequestBodyHelper
- # @param action [Symbol, nil] the controller action; read from the route
- # when omitted
- # @param controller [Class, nil] resolved from the path when omitted
- # @param required [Boolean] false for an endpoint that accepts no body
- def request_body_for(action = nil, controller: nil, required: true)
- route = request_body_route
- action ||= route[:action].to_sym
- controller ||= "#{route[:controller]}_controller".camelize.constantize
- schema = controller.request_params_schema(action)
- raise "#{controller.name} does not declare request_params for #{action}" unless schema
+require 'spree/api/testing_support/openapi'
- name = schema.component_name(action)
- register_request_schema(name, schema.json_schema(action.in?(%i[create update]) ? action : nil))
- schema.shapes.each { |shape| register_request_schema(shape.name, shape.json_schema) }
- schema.code_lists.each { |list_name, definition| register_request_schema(list_name, definition) }
-
- parameter name: :body, in: :body, required: required, schema: { '$ref': "#/components/schemas/#{name}" }
- end
-
- # Documents a shape a read endpoint takes as query parameters, and publishes
- # it as a component so the SDKs generate one type for it.
- #
- # @param shape [Spree::Api::V3::RequestSchema] a named shape
- def query_parameters_for(shape)
- register_request_schema(shape.name, shape.json_schema)
- shape.code_lists.each { |list_name, definition| register_request_schema(list_name, definition) }
-
- shape.json_schema[:properties].each do |name, property|
- parameter name: name, in: :query, required: false, description: property[:description],
- schema: property.except(:description)
- end
- end
-
- private
-
- def request_body_route
- path = metadata[:path_item][:template].gsub(/\{[^}]+\}/, 'x1')
- Rails.application.routes.recognize_path(path, method: metadata[:operation][:verb])
- end
-
- def register_request_schema(name, definition)
- spec = RSpec.configuration.openapi_specs.fetch(metadata[:openapi_spec] || metadata[:swagger_doc])
- schemas = (spec[:components] ||= {})[:schemas] ||= {}
- definition = definition.deep_stringify_keys
-
- if schemas.key?(name) && schemas[name].deep_stringify_keys != definition
- raise "Two request schemas are named #{name}; name one of the request_params declarations or shapes differently"
- end
-
- schemas[name] = definition
- # Request schemas follow the response ones, sorted, so the written spec
- # does not depend on the order specs ran in.
- request, response = schemas.partition { |key, _| key.to_s.end_with?('Params') }
- spec[:components][:schemas] = response.to_h.merge(request.sort_by { |key, _| key.to_s }.to_h)
- end
-end
+RequestBodyHelper = Spree::Api::TestingSupport::RequestBody
RSpec.configure do |config|
config.extend RequestBodyHelper, type: :request
diff --git a/spree/api/spec/swagger_helper.rb b/spree/api/spec/swagger_helper.rb
index 4e4ee4990e..e032beb683 100644
--- a/spree/api/spec/swagger_helper.rb
+++ b/spree/api/spec/swagger_helper.rb
@@ -6,6 +6,7 @@ require 'rswag/specs'
# Load OpenAPI helpers
require 'spree/api/openapi/schema_helper'
require 'spree/api/openapi/filter_documentation'
+require 'spree/api/testing_support/openapi'
RSpec.configure do |config|
# Output to the main spree docs directory at /docs/api-reference/
@@ -316,6 +317,8 @@ RSpec.configure do |config|
config.openapi_format = :yaml
+ config.extend Spree::Api::TestingSupport::AdminOperation, type: :request
+
# Auto-generate examples from actual test responses
# This captures real response data and embeds it in the OpenAPI spec
# Note: We need to modify the example_group's metadata, not the example's,
diff --git a/spree/core/lib/spree/testing_support/extension_rake.rb b/spree/core/lib/spree/testing_support/extension_rake.rb
index f2b580777f..fe69069805 100644
--- a/spree/core/lib/spree/testing_support/extension_rake.rb
+++ b/spree/core/lib/spree/testing_support/extension_rake.rb
@@ -1,5 +1,14 @@
require 'spree/testing_support/common_rake'
+# `rake spree:openapi:generate` writes the extension's openapi/admin.yaml from
+# its rswag specs.
+begin
+ require 'spree/api/testing_support/openapi_tasks'
+rescue LoadError
+ # An extension without spree_api has no admin operations to document. The
+ # file loads nothing else, so this is the only thing that can be missing.
+end
+
desc 'Generates a dummy app for testing an extension'
namespace :extension do
task :test_app, [:options] do |_t, args|