repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/branch.rb
lib/puppet/parser/ast/branch.rb
# frozen_string_literal: true # The parent class of all AST objects that contain other AST objects. # Everything but the really simple objects descend from this. It is # important to note that Branch objects contain other AST objects only -- # if you want to contain values, use a descendant of the AST::Leaf class. # # @api private class Puppet::Parser::AST::Branch < Puppet::Parser::AST include Enumerable attr_accessor :pin, :children def each @children.each { |child| yield child } end def initialize(children: [], **args) @children = children super(**args) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/compiler/catalog_validator.rb
lib/puppet/parser/compiler/catalog_validator.rb
# frozen_string_literal: true # Abstract class for a catalog validator that can be registered with the compiler to run at # a certain stage. class Puppet::Parser::Compiler class CatalogValidator PRE_FINISH = :pre_finish FINAL = :final # Returns true if the validator should run at the given stage. The default # implementation will only run at stage `FINAL` # # @param stage [Symbol] One of the stage constants defined in this class # @return [Boolean] true if the validator should run at the given stage # def self.validation_stage?(stage) FINAL.equal?(stage) end attr_reader :catalog # @param catalog [Puppet::Resource::Catalog] The catalog to validate def initialize(catalog) @catalog = catalog end # Validate some aspect of the catalog and raise a `CatalogValidationError` on failure def validate end end class CatalogValidationError < Puppet::Error include Puppet::ExternalFileError end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/compiler/catalog_validator/relationship_validator.rb
lib/puppet/parser/compiler/catalog_validator/relationship_validator.rb
# frozen_string_literal: true class Puppet::Parser::Compiler # Validator that asserts relationship metaparameters refer to valid resources class CatalogValidator::RelationshipValidator < CatalogValidator def validate catalog.resources.each do |resource| next unless resource.is_a?(Puppet::Parser::Resource) next if resource.virtual? resource.eachparam do |param| pclass = Puppet::Type.metaparamclass(param.name) validate_relationship(param) if !pclass.nil? && pclass < Puppet::Type::RelationshipMetaparam end end nil end private def validate_relationship(param) # the referenced resource must exist refs = param.value.is_a?(Array) ? param.value.flatten : [param.value] refs.each do |r| next if r.nil? || r == :undef res = r.to_s begin found = catalog.resource(res) rescue ArgumentError => e # Raise again but with file and line information raise CatalogValidationError.new(e.message, param.file, param.line) end unless found msg = _("Could not find resource '%{res}' in parameter '%{param}'") % { res: res, param: param.name.to_s } raise CatalogValidationError.new(msg, param.file, param.line) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/context/trusted_information.rb
lib/puppet/context/trusted_information.rb
# frozen_string_literal: true require_relative '../../puppet/trusted_external' # @api private class Puppet::Context::TrustedInformation # one of 'remote', 'local', or false, where 'remote' is authenticated via cert, # 'local' is trusted by virtue of running on the same machine (not a remote # request), and false is an unauthenticated remote request. # # @return [String, Boolean] attr_reader :authenticated # The validated certificate name used for the request # # @return [String] attr_reader :certname # Extra information that comes from the trusted certificate's extensions. # # @return [Hash{Object => Object}] attr_reader :extensions # The domain name derived from the validated certificate name # # @return [String] attr_reader :domain # The hostname derived from the validated certificate name # # @return [String] attr_reader :hostname def initialize(authenticated, certname, extensions, external = {}) @authenticated = authenticated.freeze @certname = certname.freeze @extensions = extensions.freeze if @certname hostname, domain = @certname.split('.', 2) else hostname = nil domain = nil end @hostname = hostname.freeze @domain = domain.freeze @external = external.is_a?(Proc) ? external : external.freeze end def self.remote(authenticated, node_name, certificate) external = proc { retrieve_trusted_external(node_name) } if authenticated extensions = {} if certificate.nil? Puppet.info(_('TrustedInformation expected a certificate, but none was given.')) else extensions = certificate.custom_extensions.to_h do |ext| [ext['oid'].freeze, ext['value'].freeze] end end new('remote', node_name, extensions, external) else new(false, nil, {}, external) end end def self.local(node) # Always trust local data by picking up the available parameters. client_cert = node ? node.parameters['clientcert'] : nil external = proc { retrieve_trusted_external(client_cert) } new('local', client_cert, {}, external) end # Additional external facts loaded through `trusted_external_command`. # # @return [Hash] def external if @external.is_a?(Proc) @external = @external.call.freeze end @external end def self.retrieve_trusted_external(certname) deep_freeze(Puppet::TrustedExternal.retrieve(certname) || {}) end private_class_method :retrieve_trusted_external # Deeply freezes the given object. The object and its content must be of the types: # Array, Hash, Numeric, Boolean, Regexp, NilClass, or String. All other types raises an Error. # (i.e. if they are assignable to Puppet::Pops::Types::Data type). def self.deep_freeze(object) case object when Array object.each { |v| deep_freeze(v) } object.freeze when Hash object.each { |k, v| deep_freeze(k); deep_freeze(v) } object.freeze when NilClass, Numeric, TrueClass, FalseClass # do nothing when String object.freeze else raise Puppet::Error, _("Unsupported data type: '%{klass}'") % { klass: object.class } end object end private_class_method :deep_freeze def to_h { 'authenticated' => authenticated, 'certname' => certname, 'extensions' => extensions, 'hostname' => hostname, 'domain' => domain, 'external' => external, }.freeze end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/session.rb
lib/puppet/http/session.rb
# frozen_string_literal: true # The session is the mechanism by which services may be connected to and accessed. # # @api public class Puppet::HTTP::Session # capabilities for a site CAP_LOCALES = 'locales' CAP_JSON = 'json' # puppet version where locales mount was added SUPPORTED_LOCALES_MOUNT_AGENT_VERSION = Gem::Version.new("5.3.4") # puppet version where JSON was enabled by default SUPPORTED_JSON_DEFAULT = Gem::Version.new("5.0.0") # Create a new HTTP session. The session is the mechanism by which services # may be connected to and accessed. Sessions should be created using # `Puppet::HTTP::Client#create_session`. # # @param [Puppet::HTTP::Client] client the container for this session # @param [Array<Puppet::HTTP::Resolver>] resolvers array of resolver strategies # to implement. # # @api private def initialize(client, resolvers) @client = client @resolvers = resolvers @resolved_services = {} @server_versions = {} end # If an explicit server and port are specified on the command line or # configuration file, this method always returns a Service with that host and # port. Otherwise, we walk the list of resolvers in priority order: # - DNS SRV # - Server List # - Puppet server/port settings # If a given resolver fails to connect, it tries the next available resolver # until a successful connection is found and returned. The successful service # is cached and returned if `route_to` is called again. # # @param [Symbol] name the service to resolve # @param [URI] url optional explicit url to use, if it is already known # @param [Puppet::SSL::SSLContext] ssl_context ssl context to be # used for connections # # @return [Puppet::HTTP::Service] the resolved service # # @api public def route_to(name, url: nil, ssl_context: nil) raise ArgumentError, "Unknown service #{name}" unless Puppet::HTTP::Service.valid_name?(name) # short circuit if explicit URL host & port given if url && !url.host.nil? && !url.host.empty? service = Puppet::HTTP::Service.create_service(@client, self, name, url.host, url.port) service.connect(ssl_context: ssl_context) return service end cached = @resolved_services[name] return cached if cached canceled = false canceled_handler = ->(cancel) { canceled = cancel } @resolvers.each do |resolver| Puppet.debug("Resolving service '#{name}' using #{resolver.class}") service = resolver.resolve(self, name, ssl_context: ssl_context, canceled_handler: canceled_handler) if service @resolved_services[name] = service Puppet.debug("Resolved service '#{name}' to #{service.url}") return service elsif canceled break end end raise Puppet::HTTP::RouteError, "No more routes to #{name}" end # Collect per-site server versions. This will allow us to modify future # requests based on the version of puppetserver we are talking to. # # @param [Puppet::HTTP::Response] response the request response containing headers # # @api private def process_response(response) version = response[Puppet::HTTP::HEADER_PUPPET_VERSION] if version site = Puppet::HTTP::Site.from_uri(response.url) @server_versions[site] = version end end # Determine if a session supports a capability. Depending on the server version # we are talking to, we know certain features are available or not. These # specifications are defined here so we can modify our requests appropriately. # # @param [Symbol] name name of the service to check # @param [String] capability the capability, ie `locales` or `json` # # @return [Boolean] # # @api public def supports?(name, capability) raise ArgumentError, "Unknown service #{name}" unless Puppet::HTTP::Service.valid_name?(name) service = @resolved_services[name] return false unless service site = Puppet::HTTP::Site.from_uri(service.url) server_version = @server_versions[site] case capability when CAP_LOCALES !server_version.nil? && Gem::Version.new(server_version) >= SUPPORTED_LOCALES_MOUNT_AGENT_VERSION when CAP_JSON server_version.nil? || Gem::Version.new(server_version) >= SUPPORTED_JSON_DEFAULT else false end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/errors.rb
lib/puppet/http/errors.rb
# frozen_string_literal: true module Puppet::HTTP # A base class for puppet http errors # @api public class HTTPError < Puppet::Error; end # A connection error such as if the server refuses the connection. # @api public class ConnectionError < HTTPError; end # A failure to route to the server such as if the `server_list` is exhausted. # @api public class RouteError < HTTPError; end # An HTTP protocol error, such as the server's response missing a required header. # @api public class ProtocolError < HTTPError; end # An error serializing or deserializing an object via REST. # @api public class SerializationError < HTTPError; end # An error due to an unsuccessful HTTP response, such as HTTP 500. # @api public class ResponseError < HTTPError attr_reader :response def initialize(response) super(response.reason) @response = response end end # An error if asked to follow too many redirects (such as HTTP 301). # @api public class TooManyRedirects < HTTPError def initialize(addr) super(_("Too many HTTP redirections for %{addr}") % { addr: addr }) end end # An error if asked to retry (such as HTTP 503) too many times. # @api public class TooManyRetryAfters < HTTPError def initialize(addr) super(_("Too many HTTP retries for %{addr}") % { addr: addr }) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/pool.rb
lib/puppet/http/pool.rb
# frozen_string_literal: true # A pool for persistent `Net::HTTP` connections. Connections are # stored in the pool indexed by their {Site}. # Connections are borrowed from the pool, yielded to the caller, and # released back into the pool. If a connection is expired, it will be # closed either when a connection to that site is requested, or when # the pool is closed. The pool can store multiple connections to the # same site, and will be reused in MRU order. # # @api private class Puppet::HTTP::Pool attr_reader :factory, :keepalive_timeout def initialize(keepalive_timeout) @pool = {} @factory = Puppet::HTTP::Factory.new @keepalive_timeout = keepalive_timeout end def with_connection(site, verifier, &block) reuse = true http = borrow(site, verifier) begin if http.use_ssl? && http.verify_mode != OpenSSL::SSL::VERIFY_PEER reuse = false end yield http rescue => detail reuse = false raise detail ensure if reuse && http.started? release(site, verifier, http) else close_connection(site, http) end end end def close @pool.each_pair do |site, entries| entries.each do |entry| close_connection(site, entry.connection) end end @pool.clear end # @api private def pool @pool end # Start a persistent connection # # @api private def start(site, verifier, http) Puppet.debug("Starting connection for #{site}") if site.use_ssl? verifier.setup_connection(http) begin http.start print_ssl_info(http) if Puppet::Util::Log.sendlevel?(:debug) rescue OpenSSL::SSL::SSLError => error verifier.handle_connection_error(http, error) end else http.start end end # Safely close a persistent connection. # Don't try to close a connection that's already closed. # # @api private def close_connection(site, http) return false unless http.started? Puppet.debug("Closing connection for #{site}") http.finish true rescue => detail Puppet.log_exception(detail, _("Failed to close connection for %{site}: %{detail}") % { site: site, detail: detail }) nil end # Borrow and take ownership of a persistent connection. If a new # connection is created, it will be started prior to being returned. # # @api private def borrow(site, verifier) @pool[site] = active_entries(site) index = @pool[site].index do |entry| (verifier.nil? && entry.verifier.nil?) || (!verifier.nil? && verifier.reusable?(entry.verifier)) end entry = index ? @pool[site].delete_at(index) : nil if entry @pool.delete(site) if @pool[site].empty? Puppet.debug("Using cached connection for #{site}") entry.connection else http = @factory.create_connection(site) start(site, verifier, http) setsockopts(http.instance_variable_get(:@socket)) http end end # Set useful socket option(s) which lack from default settings in Net:HTTP # # @api private def setsockopts(netio) return unless netio socket = netio.io socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) end # Release a connection back into the pool. # # @api private def release(site, verifier, http) expiration = Time.now + @keepalive_timeout entry = Puppet::HTTP::PoolEntry.new(http, verifier, expiration) Puppet.debug("Caching connection for #{site}") entries = @pool[site] if entries entries.unshift(entry) else @pool[site] = [entry] end end # Returns an Array of entries whose connections are not expired. # # @api private def active_entries(site) now = Time.now entries = @pool[site] || [] entries.select do |entry| if entry.expired?(now) close_connection(site, entry.connection) false else true end end end private def print_ssl_info(http) buffered_io = http.instance_variable_get(:@socket) return unless buffered_io socket = buffered_io.io return unless socket cipher = if Puppet::Util::Platform.jruby? socket.cipher else socket.cipher.first end Puppet.debug("Using #{socket.ssl_version} with cipher #{cipher}") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/response_converter.rb
lib/puppet/http/response_converter.rb
# frozen_string_literal: true module Puppet::HTTP::ResponseConverter module_function # Borrowed from puppetserver, see https://github.com/puppetlabs/puppetserver/commit/a1ebeaaa5af590003ccd23c89f808ba4f0c89609 def to_ruby_response(response) str_code = response.code.to_s # Copied from Net::HTTPResponse because it is private there. clazz = Net::HTTPResponse::CODE_TO_OBJ[str_code] or Net::HTTPResponse::CODE_CLASS_TO_OBJ[str_code[0, 1]] or Net::HTTPUnknownResponse result = clazz.new(nil, str_code, nil) result.body = response.body # This is nasty, nasty. But apparently there is no way to create # an instance of Net::HttpResponse from outside of the library and have # the body be readable, unless you do stupid things like this. result.instance_variable_set(:@read, true) response.each_header do |k, v| result[k] = v end result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/proxy.rb
lib/puppet/http/proxy.rb
# frozen_string_literal: true require 'uri' require_relative '../../puppet/ssl/openssl_loader' module Puppet::HTTP::Proxy def self.proxy(uri) if http_proxy_host && !no_proxy?(uri) Net::HTTP.new(uri.host, uri.port, http_proxy_host, http_proxy_port, http_proxy_user, http_proxy_password) else http = Net::HTTP.new(uri.host, uri.port, nil, nil, nil, nil) # Net::HTTP defaults the proxy port even though we said not to # use one. Set it to nil so caller is not surprised http.proxy_port = nil http end end def self.http_proxy_env # Returns a URI object if proxy is set, or nil proxy_env = ENV.fetch("http_proxy", nil) || ENV.fetch("HTTP_PROXY", nil) begin return URI.parse(proxy_env) if proxy_env rescue URI::InvalidURIError return nil end nil end # The documentation around the format of the no_proxy variable seems # inconsistent. Some suggests the use of the * as a way of matching any # hosts under a domain, e.g.: # *.example.com # Other documentation suggests that just a leading '.' indicates a domain # level exclusion, e.g.: # .example.com # We'll accommodate both here. def self.no_proxy?(dest) no_proxy = self.no_proxy unless no_proxy return false end unless dest.is_a? URI begin dest = URI.parse(dest) rescue URI::InvalidURIError return false end end no_proxy.split(/\s*,\s*/).each do |d| host, port = d.split(':') host = Regexp.escape(host).gsub('\*', '.*') # If this no_proxy entry specifies a port, we want to match it against # the destination port. Otherwise just match hosts. if port no_proxy_regex = /#{host}:#{port}$/ dest_string = "#{dest.host}:#{dest.port}" else no_proxy_regex = /#{host}$/ dest_string = dest.host.to_s end if no_proxy_regex.match(dest_string) return true end end false end def self.http_proxy_host env = http_proxy_env if env and env.host return env.host end if Puppet.settings[:http_proxy_host] == 'none' return nil end Puppet.settings[:http_proxy_host] end def self.http_proxy_port env = http_proxy_env if env and env.port return env.port end Puppet.settings[:http_proxy_port] end def self.http_proxy_user env = http_proxy_env if env and env.user return env.user end if Puppet.settings[:http_proxy_user] == 'none' return nil end Puppet.settings[:http_proxy_user] end def self.http_proxy_password env = http_proxy_env if env and env.password return env.password end if Puppet.settings[:http_proxy_user] == 'none' or Puppet.settings[:http_proxy_password] == 'none' return nil end Puppet.settings[:http_proxy_password] end def self.no_proxy no_proxy_env = ENV.fetch("no_proxy", nil) || ENV.fetch("NO_PROXY", nil) if no_proxy_env return no_proxy_env end if Puppet.settings[:no_proxy] == 'none' return nil end Puppet.settings[:no_proxy] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/response.rb
lib/puppet/http/response.rb
# frozen_string_literal: true # Represents the response returned from the server from an HTTP request. # # @api abstract # @api public class Puppet::HTTP::Response # @return [URI] the response url attr_reader :url # Create a response associated with the URL. # # @param [URI] url # @param [Integer] HTTP status # @param [String] HTTP reason def initialize(url, code, reason) @url = url @code = code @reason = reason end # Return the response code. # # @return [Integer] Response code for the request # # @api public def code @code end # Return the response message. # # @return [String] Response message for the request # # @api public def reason @reason end # Returns the entire response body. Can be used instead of # `Puppet::HTTP::Response.read_body`, but both methods cannot be used for the # same response. # # @return [String] Response body for the request # # @api public def body raise NotImplementedError end # Streams the response body to the caller in chunks. Can be used instead of # `Puppet::HTTP::Response.body`, but both methods cannot be used for the same # response. # # @yield [String] Streams the response body in chunks # # @raise [ArgumentError] raise if a block is not given # # @api public def read_body(&block) raise NotImplementedError end # Check if the request received a response of success (HTTP 2xx). # # @return [Boolean] Returns true if the response indicates success # # @api public def success? 200 <= @code && @code < 300 end # Get a header case-insensitively. # # @param [String] name The header name # @return [String] The header value # # @api public def [](name) raise NotImplementedError end # Yield each header name and value. Returns an enumerator if no block is given. # # @yieldparam [String] header name # @yieldparam [String] header value # # @api public def each_header(&block) raise NotImplementedError end # Ensure the response body is fully read so that the server is not blocked # waiting for us to read data from the socket. Also if the caller streamed # the response, but didn't read the data, we need a way to drain the socket # before adding the connection back to the connection pool, otherwise the # unread response data would "leak" into the next HTTP request/response. # # @api public def drain body true end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/pool_entry.rb
lib/puppet/http/pool_entry.rb
# frozen_string_literal: true # An entry in the peristent HTTP pool that references the connection and # an expiration time for the connection. # # @api private class Puppet::HTTP::PoolEntry attr_reader :connection, :verifier def initialize(connection, verifier, expiration_time) @connection = connection @verifier = verifier @expiration_time = expiration_time end def expired?(now) @expiration_time <= now end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/response_net_http.rb
lib/puppet/http/response_net_http.rb
# frozen_string_literal: true # Adapts Net::HTTPResponse to Puppet::HTTP::Response # # @api public class Puppet::HTTP::ResponseNetHTTP < Puppet::HTTP::Response # Create a response associated with the URL. # # @param [URI] url # @param [Net::HTTPResponse] nethttp The response def initialize(url, nethttp) super(url, nethttp.code.to_i, nethttp.message) @nethttp = nethttp end # (see Puppet::HTTP::Response#body) def body @nethttp.body end # (see Puppet::HTTP::Response#read_body) def read_body(&block) raise ArgumentError, "A block is required" unless block_given? @nethttp.read_body(&block) end # (see Puppet::HTTP::Response#success?) def success? @nethttp.is_a?(Net::HTTPSuccess) end # (see Puppet::HTTP::Response#[]) def [](name) @nethttp[name] end # (see Puppet::HTTP::Response#each_header) def each_header(&block) @nethttp.each_header(&block) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/resolver.rb
lib/puppet/http/resolver.rb
# frozen_string_literal: true # Resolver base class. Each resolver represents a different strategy for # resolving a service name into a list of candidate servers and ports. # # @abstract Subclass and override {#resolve} to create a new resolver. # @api public class Puppet::HTTP::Resolver # # Create a new resolver. # # @param [Puppet::HTTP::Client] client def initialize(client) @client = client end # Return a working server/port for the resolver. This is the base # implementation and is meant to be a placeholder. # # @param [Puppet::HTTP::Session] session # @param [Symbol] name the service to resolve # @param [Puppet::SSL::SSLContext] ssl_context (nil) optional ssl context to # use when creating a connection # @param [Proc] canceled_handler (nil) optional callback allowing a resolver # to cancel resolution. # # @raise [NotImplementedError] this base class is not implemented # # @api public def resolve(session, name, ssl_context: nil, canceled_handler: nil) raise NotImplementedError end # Check a given connection to establish if it can be relied on for future use. # # @param [Puppet::HTTP::Session] session # @param [Puppet::HTTP::Service] service # @param [Puppet::SSL::SSLContext] ssl_context # # @return [Boolean] Returns true if a connection is successful, false otherwise # # @api public def check_connection?(session, service, ssl_context: nil) service.connect(ssl_context: ssl_context) true rescue Puppet::HTTP::ConnectionError => e Puppet.log_exception(e, "Connection to #{service.url} failed, trying next route: #{e.message}") false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/dns.rb
lib/puppet/http/dns.rb
# frozen_string_literal: true require 'resolv' module Puppet::HTTP class DNS class CacheEntry attr_reader :records, :ttl, :resolution_time def initialize(records) @records = records @resolution_time = Time.now @ttl = choose_lowest_ttl(records) end def choose_lowest_ttl(records) ttl = records.first.ttl records.each do |rec| if rec.ttl < ttl ttl = rec.ttl end end ttl end end def initialize(resolver = Resolv::DNS.new) @resolver = resolver # Stores DNS records per service, along with their TTL # and the time at which they were resolved, for cache # eviction. @record_cache = {} end # Iterate through the list of records for this service # and yield each server and port pair. Records are only fetched # via DNS query the first time and cached for the duration of their # service's TTL thereafter. # @param [String] domain the domain to search for # @param [Symbol] service_name the key of the service we are querying # @yields [String, Integer] server and port of selected record def each_srv_record(domain, service_name = :puppet, &block) if domain.nil? or domain.empty? Puppet.debug "Domain not known; skipping SRV lookup" return end Puppet.debug "Searching for SRV records for domain: #{domain}" case service_name when :puppet then service = '_x-puppet' when :file then service = '_x-puppet-fileserver' else service = "_x-puppet-#{service_name}" end record_name = "#{service}._tcp.#{domain}" if @record_cache.has_key?(service_name) && !expired?(service_name) records = @record_cache[service_name].records Puppet.debug "Using cached record for #{record_name}" else records = @resolver.getresources(record_name, Resolv::DNS::Resource::IN::SRV) if records.size > 0 @record_cache[service_name] = CacheEntry.new(records) end Puppet.debug "Found #{records.size} SRV records for: #{record_name}" end if records.size == 0 && service_name != :puppet # Try the generic :puppet service if no SRV records were found # for the specific service. each_srv_record(domain, :puppet, &block) else each_priority(records) do |recs| while next_rr = recs.delete(find_weighted_server(recs)) # rubocop:disable Lint/AssignmentInCondition Puppet.debug "Yielding next server of #{next_rr.target}:#{next_rr.port}" yield next_rr.target.to_s, next_rr.port end end end end # Given a list of records of the same priority, chooses a random one # from among them, favoring those with higher weights. # @param [[Resolv::DNS::Resource::IN::SRV]] records a list of records # of the same priority # @return [Resolv::DNS::Resource::IN:SRV] the chosen record def find_weighted_server(records) return nil if records.nil? || records.empty? return records.first if records.size == 1 # Calculate the sum of all weights in the list of resource records, # This is used to then select hosts until the weight exceeds what # random number we selected. For example, if we have weights of 1 8 and 3: # # |-|--------|---| # ^ # We generate a random number 5, and iterate through the records, adding # the current record's weight to the accumulator until the weight of the # current record plus previous records is greater than the random number. total_weight = records.inject(0) { |sum, record| sum + weight(record) } current_weight = 0 chosen_weight = 1 + Kernel.rand(total_weight) records.each do |record| current_weight += weight(record) return record if current_weight >= chosen_weight end end def weight(record) record.weight == 0 ? 1 : record.weight * 10 end # Returns TTL for the cached records for this service. # @param [String] service_name the service whose TTL we want # @return [Integer] the TTL for this service, in seconds def ttl(service_name) @record_cache[service_name].ttl end # Checks if the cached entry for the given service has expired. # @param [String] service_name the name of the service to check # @return [Boolean] true if the entry has expired, false otherwise. # Always returns true if the record had no TTL. def expired?(service_name) entry = @record_cache[service_name] if entry Time.now > (entry.resolution_time + entry.ttl) else true end end private # Groups the records by their priority and yields the groups # in order of highest to lowest priority (lowest to highest numbers), # one at a time. # { 1 => [records], 2 => [records], etc. } # # @param [[Resolv::DNS::Resource::IN::SRV]] records the list of # records for a given service # @yields [[Resolv::DNS::Resource::IN::SRV]] a group of records of # the same priority def each_priority(records) pri_hash = records.each_with_object({}) do |element, groups| groups[element.priority] ||= [] groups[element.priority] << element end pri_hash.keys.sort.each do |key| yield pri_hash[key] end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/client.rb
lib/puppet/http/client.rb
# frozen_string_literal: true # The HTTP client provides methods for making `GET`, `POST`, etc requests to # HTTP(S) servers. It also provides methods for resolving Puppetserver REST # service endpoints using SRV records and settings (such as `server_list`, # `server`, `ca_server`, etc). Once a service endpoint has been resolved, there # are methods for making REST requests (such as getting a node, sending facts, # etc). # # The client uses persistent HTTP connections by default unless the `Connection: # close` header is specified and supports streaming response bodies. # # By default the client only trusts the Puppet CA for HTTPS connections. However, # if the `include_system_store` request option is set to true, then Puppet will # trust certificates in the puppet-agent CA bundle. # # @example To access the HTTP client: # client = Puppet.runtime[:http] # # @example To make an HTTP GET request: # response = client.get(URI("http://www.example.com")) # # @example To make an HTTPS GET request, trusting the puppet CA and certs in Puppet's CA bundle: # response = client.get(URI("https://www.example.com"), options: { include_system_store: true }) # # @example To use a URL containing special characters, such as spaces: # response = client.get(URI(Puppet::Util.uri_encode("https://www.example.com/path to file"))) # # @example To pass query parameters: # response = client.get(URI("https://www.example.com"), query: {'q' => 'puppet'}) # # @example To pass custom headers: # response = client.get(URI("https://www.example.com"), headers: {'Accept-Content' => 'application/json'}) # # @example To check if the response is successful (2xx): # response = client.get(URI("http://www.example.com")) # puts response.success? # # @example To get the response code and reason: # response = client.get(URI("http://www.example.com")) # unless response.success? # puts "HTTP #{response.code} #{response.reason}" # end # # @example To read response headers: # response = client.get(URI("http://www.example.com")) # puts response['Content-Type'] # # @example To stream the response body: # client.get(URI("http://www.example.com")) do |response| # if response.success? # response.read_body do |data| # puts data # end # end # end # # @example To handle exceptions: # begin # client.get(URI("https://www.example.com")) # rescue Puppet::HTTP::ResponseError => e # puts "HTTP #{e.response.code} #{e.response.reason}" # rescue Puppet::HTTP::ConnectionError => e # puts "Connection error #{e.message}" # rescue Puppet::SSL::SSLError => e # puts "SSL error #{e.message}" # rescue Puppet::HTTP::HTTPError => e # puts "General HTTP error #{e.message}" # end # # @example To route to the `:puppet` service: # session = client.create_session # service = session.route_to(:puppet) # # @example To make a node request: # node = service.get_node(Puppet[:certname], environment: 'production') # # @example To submit facts: # facts = Puppet::Indirection::Facts.indirection.find(Puppet[:certname]) # service.put_facts(Puppet[:certname], environment: 'production', facts: facts) # # @example To submit a report to the `:report` service: # report = Puppet::Transaction::Report.new # service = session.route_to(:report) # service.put_report(Puppet[:certname], report, environment: 'production') # # @api public class Puppet::HTTP::Client attr_reader :pool # Create a new http client instance. Use `Puppet.runtime[:http]` to get # the current client instead of creating an instance of this class. # # @param [Puppet::HTTP::Pool] pool pool of persistent Net::HTTP # connections # @param [Puppet::SSL::SSLContext] ssl_context ssl context to be used for # connections # @param [Puppet::SSL::SSLContext] system_ssl_context the system ssl context # used if :include_system_store is set to true # @param [Integer] redirect_limit default number of HTTP redirections to allow # in a given request. Can also be specified per-request. # @param [Integer] retry_limit number of HTTP retries allowed in a given # request # def initialize(pool: Puppet::HTTP::Pool.new(Puppet[:http_keepalive_timeout]), ssl_context: nil, system_ssl_context: nil, redirect_limit: 10, retry_limit: 100) @pool = pool @default_headers = { 'X-Puppet-Version' => Puppet.version, 'User-Agent' => Puppet[:http_user_agent], }.freeze @default_ssl_context = ssl_context @default_system_ssl_context = system_ssl_context @default_redirect_limit = redirect_limit @retry_after_handler = Puppet::HTTP::RetryAfterHandler.new(retry_limit, Puppet[:runinterval]) end # Create a new HTTP session. A session is the object through which services # may be connected to and accessed. # # @return [Puppet::HTTP::Session] the newly created HTTP session # # @api public def create_session Puppet::HTTP::Session.new(self, build_resolvers) end # Open a connection to the given URI. It is typically not necessary to call # this method as the client will create connections as needed when a request # is made. # # @param [URI] uri the connection destination # @param [Hash] options # @option options [Puppet::SSL::SSLContext] :ssl_context (nil) ssl context to # be used for connections # @option options [Boolean] :include_system_store (false) if we should include # the system store for connection def connect(uri, options: {}, &block) start = Time.now verifier = nil connected = false site = Puppet::HTTP::Site.from_uri(uri) if site.use_ssl? ssl_context = options.fetch(:ssl_context, nil) include_system_store = options.fetch(:include_system_store, false) ctx = resolve_ssl_context(ssl_context, include_system_store) verifier = Puppet::SSL::Verifier.new(site.host, ctx) end @pool.with_connection(site, verifier) do |http| connected = true if block_given? yield http end end rescue Net::OpenTimeout => e raise_error(_("Request to %{uri} timed out connect operation after %{elapsed} seconds") % { uri: uri, elapsed: elapsed(start) }, e, connected) rescue Net::ReadTimeout => e raise_error(_("Request to %{uri} timed out read operation after %{elapsed} seconds") % { uri: uri, elapsed: elapsed(start) }, e, connected) rescue EOFError => e raise_error(_("Request to %{uri} interrupted after %{elapsed} seconds") % { uri: uri, elapsed: elapsed(start) }, e, connected) rescue Puppet::SSL::SSLError raise rescue Puppet::HTTP::HTTPError raise rescue => e raise_error(_("Request to %{uri} failed after %{elapsed} seconds: %{message}") % { uri: uri, elapsed: elapsed(start), message: e.message }, e, connected) end # These options apply to all HTTP request methods # # @!macro [new] request_options # @param [Hash] options HTTP request options. Options not recognized by the # HTTP implementation will be ignored. # @option options [Puppet::SSL::SSLContext] :ssl_context (nil) ssl context to # be used for connections # @option options [Boolean] :include_system_store (false) if we should include # the system store for connection # @option options [Integer] :redirect_limit (10) The maximum number of HTTP # redirections to allow for this request. # @option options [Hash] :basic_auth A map of `:username` => `String` and # `:password` => `String` # @option options [String] :metric_id The metric id used to track metrics # on requests. # Submits a GET HTTP request to the given url # # @param [URI] url the location to submit the http request # @param [Hash] headers merged with the default headers defined by the client # @param [Hash] params encoded and set as the url query # @!macro request_options # # @yield [Puppet::HTTP::Response] if a block is given yields the response # # @return [Puppet::HTTP::Response] the response # # @api public def get(url, headers: {}, params: {}, options: {}, &block) url = encode_query(url, params) request = Net::HTTP::Get.new(url, @default_headers.merge(headers)) execute_streaming(request, options: options, &block) end # Submits a HEAD HTTP request to the given url # # @param [URI] url the location to submit the http request # @param [Hash] headers merged with the default headers defined by the client # @param [Hash] params encoded and set as the url query # @!macro request_options # # @return [Puppet::HTTP::Response] the response # # @api public def head(url, headers: {}, params: {}, options: {}) url = encode_query(url, params) request = Net::HTTP::Head.new(url, @default_headers.merge(headers)) execute_streaming(request, options: options) end # Submits a PUT HTTP request to the given url # # @param [URI] url the location to submit the http request # @param [String] body the body of the PUT request # @param [Hash] headers merged with the default headers defined by the client. The # `Content-Type` header is required and should correspond to the type of data passed # as the `body` argument. # @param [Hash] params encoded and set as the url query # @!macro request_options # # @return [Puppet::HTTP::Response] the response # # @api public def put(url, body, headers: {}, params: {}, options: {}) raise ArgumentError, "'put' requires a string 'body' argument" unless body.is_a?(String) url = encode_query(url, params) request = Net::HTTP::Put.new(url, @default_headers.merge(headers)) request.body = body request.content_length = body.bytesize raise ArgumentError, "'put' requires a 'content-type' header" unless request['Content-Type'] execute_streaming(request, options: options) end # Submits a POST HTTP request to the given url # # @param [URI] url the location to submit the http request # @param [String] body the body of the POST request # @param [Hash] headers merged with the default headers defined by the client. The # `Content-Type` header is required and should correspond to the type of data passed # as the `body` argument. # @param [Hash] params encoded and set as the url query # @!macro request_options # # @yield [Puppet::HTTP::Response] if a block is given yields the response # # @return [Puppet::HTTP::Response] the response # # @api public def post(url, body, headers: {}, params: {}, options: {}, &block) raise ArgumentError, "'post' requires a string 'body' argument" unless body.is_a?(String) url = encode_query(url, params) request = Net::HTTP::Post.new(url, @default_headers.merge(headers)) request.body = body request.content_length = body.bytesize raise ArgumentError, "'post' requires a 'content-type' header" unless request['Content-Type'] execute_streaming(request, options: options, &block) end # Submits a DELETE HTTP request to the given url. # # @param [URI] url the location to submit the http request # @param [Hash] headers merged with the default headers defined by the client # @param [Hash] params encoded and set as the url query # @!macro request_options # # @return [Puppet::HTTP::Response] the response # # @api public def delete(url, headers: {}, params: {}, options: {}) url = encode_query(url, params) request = Net::HTTP::Delete.new(url, @default_headers.merge(headers)) execute_streaming(request, options: options) end # Close persistent connections in the pool. # # @return [void] # # @api public def close @pool.close @default_ssl_context = nil @default_system_ssl_context = nil end def default_ssl_context cert = Puppet::X509::CertProvider.new password = cert.load_private_key_password ssl = Puppet::SSL::SSLProvider.new ctx = ssl.load_context(certname: Puppet[:certname], password: password) ssl.print(ctx) ctx rescue => e # TRANSLATORS: `message` is an already translated string of why SSL failed to initialize Puppet.log_exception(e, _("Failed to initialize SSL: %{message}") % { message: e.message }) # TRANSLATORS: `puppet agent -t` is a command and should not be translated Puppet.err(_("Run `puppet agent -t`")) raise e end protected def encode_query(url, params) return url if params.empty? url = url.dup url.query = encode_params(params) url end private # Connect or borrow a connection from the pool to the host and port associated # with the request's URL. Then execute the HTTP request, retrying and # following redirects as needed, and return the HTTP response. The response # body will always be fully drained/consumed when this method returns. # # If a block is provided, then the response will be yielded to the caller, # allowing the response body to be streamed. # # If the request/response did not result in an exception and the caller did # not ask for the connection to be closed (via Connection: close), then the # connection will be returned to the pool. # # @yieldparam [Puppet::HTTP::Response] response The final response, after # following redirects and retrying # @return [Puppet::HTTP::Response] def execute_streaming(request, options: {}, &block) redirector = Puppet::HTTP::Redirector.new(options.fetch(:redirect_limit, @default_redirect_limit)) basic_auth = options.fetch(:basic_auth, nil) unless basic_auth if request.uri.user && request.uri.password basic_auth = { user: request.uri.user, password: request.uri.password } end end redirects = 0 retries = 0 response = nil done = false until done connect(request.uri, options: options) do |http| apply_auth(request, basic_auth) if redirects.zero? # don't call return within the `request` block close_and_sleep = nil http.request(request) do |nethttp| response = Puppet::HTTP::ResponseNetHTTP.new(request.uri, nethttp) begin Puppet.debug("HTTP #{request.method.upcase} #{request.uri} returned #{response.code} #{response.reason}") if redirector.redirect?(request, response) request = redirector.redirect_to(request, response, redirects) redirects += 1 next elsif @retry_after_handler.retry_after?(request, response) interval = @retry_after_handler.retry_after_interval(request, response, retries) retries += 1 if interval close_and_sleep = proc do if http.started? Puppet.debug("Closing connection for #{Puppet::HTTP::Site.from_uri(request.uri)}") http.finish end Puppet.warning(_("Sleeping for %{interval} seconds before retrying the request") % { interval: interval }) ::Kernel.sleep(interval) end next end end if block_given? yield response else response.body end ensure # we need to make sure the response body is fully consumed before # the connection is put back in the pool, otherwise the response # for one request could leak into a future response. response.drain end done = true end ensure # If a server responded with a retry, make sure the connection is closed and then # sleep the specified time. close_and_sleep.call if close_and_sleep end end response end def expand_into_parameters(data) data.inject([]) do |params, key_value| key, value = key_value expanded_value = case value when Array value.collect { |val| [key, val] } else [key_value] end params.concat(expand_primitive_types_into_parameters(expanded_value)) end end def expand_primitive_types_into_parameters(data) data.inject([]) do |params, key_value| key, value = key_value case value when nil params when true, false, String, Symbol, Integer, Float params << [key, value] else raise Puppet::HTTP::SerializationError, _("HTTP REST queries cannot handle values of type '%{klass}'") % { klass: value.class } end end end def encode_params(params) params = expand_into_parameters(params) params.map do |key, value| "#{key}=#{Puppet::Util.uri_query_encode(value.to_s)}" end.join('&') end def elapsed(start) (Time.now - start).to_f.round(3) end def raise_error(message, cause, connected) if connected raise Puppet::HTTP::HTTPError.new(message, cause) else raise Puppet::HTTP::ConnectionError.new(message, cause) end end def resolve_ssl_context(ssl_context, include_system_store) if ssl_context raise Puppet::HTTP::HTTPError, "The ssl_context and include_system_store parameters are mutually exclusive" if include_system_store ssl_context elsif include_system_store system_ssl_context else @default_ssl_context || Puppet.lookup(:ssl_context) end end def system_ssl_context return @default_system_ssl_context if @default_system_ssl_context cert_provider = Puppet::X509::CertProvider.new cacerts = cert_provider.load_cacerts || [] ssl = Puppet::SSL::SSLProvider.new @default_system_ssl_context = ssl.create_system_context(cacerts: cacerts, include_client_cert: true) ssl.print(@default_system_ssl_context) @default_system_ssl_context end def apply_auth(request, basic_auth) if basic_auth request.basic_auth(basic_auth[:user], basic_auth[:password]) end end def build_resolvers resolvers = [] if Puppet[:use_srv_records] resolvers << Puppet::HTTP::Resolver::SRV.new(self, domain: Puppet[:srv_domain]) end server_list_setting = Puppet.settings.setting(:server_list) if server_list_setting.value && !server_list_setting.value.empty? # use server list to resolve all services services = Puppet::HTTP::Service::SERVICE_NAMES.dup # except if it's been explicitly set if Puppet.settings.set_by_config?(:ca_server) services.delete(:ca) end if Puppet.settings.set_by_config?(:report_server) services.delete(:report) end resolvers << Puppet::HTTP::Resolver::ServerList.new(self, server_list_setting: server_list_setting, default_port: Puppet[:serverport], services: services) end resolvers << Puppet::HTTP::Resolver::Settings.new(self) resolvers.freeze end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/external_client.rb
lib/puppet/http/external_client.rb
# frozen_string_literal: true # Adapts an external http_client_class to the HTTP client API. The former # is typically registered by puppetserver and only implements a subset of # the Puppet::Network::HTTP::Connection methods. As a result, only the # `get` and `post` methods are supported. Calling `delete`, etc will # raise a NotImplementedError. # # @api private class Puppet::HTTP::ExternalClient < Puppet::HTTP::Client # Create an external http client. # # @param [Class] http_client_class The class to create to handle the request def initialize(http_client_class) @http_client_class = http_client_class end # (see Puppet::HTTP::Client#get) # @api private def get(url, headers: {}, params: {}, options: {}, &block) url = encode_query(url, params) options[:use_ssl] = url.scheme == 'https' client = @http_client_class.new(url.host, url.port, options) response = Puppet::HTTP::ResponseNetHTTP.new(url, client.get(url.request_uri, headers, options)) if block_given? yield response else response end rescue Puppet::HTTP::HTTPError raise rescue => e raise Puppet::HTTP::HTTPError.new(e.message, e) end # (see Puppet::HTTP::Client#post) # @api private def post(url, body, headers: {}, params: {}, options: {}, &block) raise ArgumentError, "'post' requires a string 'body' argument" unless body.is_a?(String) url = encode_query(url, params) options[:use_ssl] = url.scheme == 'https' client = @http_client_class.new(url.host, url.port, options) response = Puppet::HTTP::ResponseNetHTTP.new(url, client.post(url.request_uri, body, headers, options)) if block_given? yield response else response end rescue Puppet::HTTP::HTTPError, ArgumentError raise rescue => e raise Puppet::HTTP::HTTPError.new(e.message, e) end # (see Puppet::HTTP::Client#close) # @api private def close # This is a noop as puppetserver doesn't provide a way to close its http client. end # The following are intentionally not documented def create_session raise NotImplementedError end def connect(uri, options: {}, &block) raise NotImplementedError end def head(url, headers: {}, params: {}, options: {}) raise NotImplementedError end def put(url, headers: {}, params: {}, options: {}) raise NotImplementedError end def delete(url, headers: {}, params: {}, options: {}) raise NotImplementedError end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/factory.rb
lib/puppet/http/factory.rb
# frozen_string_literal: true require_relative '../../puppet/ssl/openssl_loader' require 'net/http' require_relative '../../puppet/http' # Factory for `Net::HTTP` objects. # # Encapsulates the logic for creating a `Net::HTTP` object based on the # specified {Site} and puppet settings. # # @api private class Puppet::HTTP::Factory @@openssl_initialized = false KEEP_ALIVE_TIMEOUT = 2**31 - 1 def initialize # PUP-1411, make sure that openssl is initialized before we try to connect unless @@openssl_initialized OpenSSL::SSL::SSLContext.new @@openssl_initialized = true end end def create_connection(site) Puppet.debug("Creating new connection for #{site}") http = Puppet::HTTP::Proxy.proxy(URI(site.addr)) http.use_ssl = site.use_ssl? if site.use_ssl? http.min_version = OpenSSL::SSL::TLS1_VERSION if http.respond_to?(:min_version) http.ciphers = Puppet[:ciphers] end http.read_timeout = Puppet[:http_read_timeout] http.open_timeout = Puppet[:http_connect_timeout] http.keep_alive_timeout = KEEP_ALIVE_TIMEOUT if http.respond_to?(:keep_alive_timeout=) # 0 means make one request and never retry http.max_retries = 0 if Puppet[:sourceaddress] Puppet.debug("Using source IP #{Puppet[:sourceaddress]}") http.local_host = Puppet[:sourceaddress] end if Puppet[:http_debug] http.set_debug_output($stderr) end http end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/service.rb
lib/puppet/http/service.rb
# frozen_string_literal: true # Represents an abstract Puppet web service. # # @abstract Subclass and implement methods for the service's REST APIs. # @api public class Puppet::HTTP::Service # @return [URI] the url associated with this service attr_reader :url # @return [Array<Symbol>] available services SERVICE_NAMES = [:ca, :fileserver, :puppet, :puppetserver, :report].freeze # @return [Array<Symbol>] format types that are unsupported EXCLUDED_FORMATS = [:yaml, :b64_zlib_yaml, :dot].freeze # Create a new web service, which contains the URL used to connect to the # service. The four services implemented are `:ca`, `:fileserver`, `:puppet`, # and `:report`. # # The `:ca` and `:report` services handle certs and reports, respectively. The # `:fileserver` service handles puppet file metadata and content requests. And # the default service, `:puppet`, handles nodes, facts, and catalogs. # # @param [Puppet::HTTP::Client] client the owner of the session # @param [Puppet::HTTP::Session] session the owner of the service # @param [Symbol] name the type of service to create # @param [<Type>] server optional, the server to connect to # @param [<Type>] port optional, the port to connect to # # @return [Puppet::HTTP::Service] an instance of the service type requested # # @api private def self.create_service(client, session, name, server = nil, port = nil) case name when :ca Puppet::HTTP::Service::Ca.new(client, session, server, port) when :fileserver Puppet::HTTP::Service::FileServer.new(client, session, server, port) when :puppet ::Puppet::HTTP::Service::Compiler.new(client, session, server, port) when :puppetserver ::Puppet::HTTP::Service::Puppetserver.new(client, session, server, port) when :report Puppet::HTTP::Service::Report.new(client, session, server, port) else raise ArgumentError, "Unknown service #{name}" end end # Check if the service named is included in the list of available services. # # @param [Symbol] name # # @return [Boolean] # # @api private def self.valid_name?(name) SERVICE_NAMES.include?(name) end # Create a new service. Services should be created by calling `Puppet::HTTP::Session#route_to`. # # @param [Puppet::HTTP::Client] client # @param [Puppet::HTTP::Session] session # @param [URI] url The url to connect to # # @api private def initialize(client, session, url) @client = client @session = session @url = url end # Return the url with the given path encoded and appended # # @param [String] path the string to append to the base url # # @return [URI] the URI object containing the encoded path # # @api public def with_base_url(path) u = @url.dup u.path += Puppet::Util.uri_encode(path) u end # Open a connection using the given ssl context. # # @param [Puppet::SSL::SSLContext] ssl_context An optional ssl context to connect with # @return [void] # # @api public def connect(ssl_context: nil) @client.connect(@url, options: { ssl_context: ssl_context }) end protected def add_puppet_headers(headers) modified_headers = headers.dup # Add 'X-Puppet-Profiling' to enable performance profiling if turned on modified_headers['X-Puppet-Profiling'] = 'true' if Puppet[:profile] # Add additional user-defined headers if they are defined Puppet[:http_extra_headers].each do |name, value| if modified_headers.keys.find { |key| key.casecmp(name) == 0 } Puppet.warning(_('Ignoring extra header "%{name}" as it was previously set.') % { name: name }) elsif value.nil? || value.empty? Puppet.warning(_('Ignoring extra header "%{name}" as it has no value.') % { name: name }) else modified_headers[name] = value end end modified_headers end def build_url(api, server, port) URI::HTTPS.build(host: server, port: port, path: api).freeze end def get_mime_types(model) network_formats = model.supported_formats - EXCLUDED_FORMATS network_formats.map { |f| model.get_format(f).mime } end def formatter_for_response(response) header = response['Content-Type'] raise Puppet::HTTP::ProtocolError, _("No content type in http response; cannot parse") unless header header.gsub!(/\s*;.*$/, '') # strip any charset formatter = Puppet::Network::FormatHandler.mime(header) raise Puppet::HTTP::ProtocolError, "Content-Type is unsupported" if EXCLUDED_FORMATS.include?(formatter.name) formatter end def serialize(formatter, object) formatter.render(object) rescue => err raise Puppet::HTTP::SerializationError.new("Failed to serialize #{object.class} to #{formatter.name}: #{err.message}", err) end def serialize_multiple(formatter, object) formatter.render_multiple(object) rescue => err raise Puppet::HTTP::SerializationError.new("Failed to serialize multiple #{object.class} to #{formatter.name}: #{err.message}", err) end def deserialize(response, model) formatter = formatter_for_response(response) begin formatter.intern(model, response.body.to_s) rescue => err raise Puppet::HTTP::SerializationError.new("Failed to deserialize #{model} from #{formatter.name}: #{err.message}", err) end end def deserialize_multiple(response, model) formatter = formatter_for_response(response) begin formatter.intern_multiple(model, response.body.to_s) rescue => err raise Puppet::HTTP::SerializationError.new("Failed to deserialize multiple #{model} from #{formatter.name}: #{err.message}", err) end end def process_response(response) @session.process_response(response) raise Puppet::HTTP::ResponseError, response unless response.success? end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/redirector.rb
lib/puppet/http/redirector.rb
# frozen_string_literal: true # Handle HTTP redirects # # @api private class Puppet::HTTP::Redirector # Create a new redirect handler # # @param [Integer] redirect_limit maximum number of redirects allowed # # @api private def initialize(redirect_limit) @redirect_limit = redirect_limit end # Determine of the HTTP response code indicates a redirect # # @param [Net::HTTP] request request that received the response # @param [Puppet::HTTP::Response] response # # @return [Boolean] true if the response code is 301, 302, or 307. # # @api private def redirect?(request, response) # Net::HTTPRedirection is not used because historically puppet # has only handled these, and we're not a browser case response.code when 301, 302, 307 true else false end end # Implement the HTTP request redirection # # @param [Net::HTTP] request request that has been redirected # @param [Puppet::HTTP::Response] response # @param [Integer] redirects the current number of redirects # # @return [Net::HTTP] A new request based on the original request, but with # the redirected location # # @api private def redirect_to(request, response, redirects) raise Puppet::HTTP::TooManyRedirects, request.uri if redirects >= @redirect_limit location = parse_location(response) url = request.uri.merge(location) new_request = request.class.new(url) new_request.body = request.body request.each do |header, value| unless Puppet[:location_trusted] # skip adding potentially sensitive header to other hosts next if header.casecmp('Authorization').zero? && request.uri.host.casecmp(location.host) != 0 next if header.casecmp('Cookie').zero? && request.uri.host.casecmp(location.host) != 0 end # Allow Net::HTTP to set its own Accept-Encoding header to avoid errors with HTTP compression. # See https://github.com/puppetlabs/puppet/issues/9143 next if header.casecmp('Accept-Encoding').zero? new_request[header] = value end # mimic private Net::HTTP#addr_port new_request['Host'] = if (location.scheme == 'https' && location.port == 443) || (location.scheme == 'http' && location.port == 80) location.host else "#{location.host}:#{location.port}" end new_request end private def parse_location(response) location = response['location'] raise Puppet::HTTP::ProtocolError, _("Location response header is missing") unless location URI.parse(location) rescue URI::InvalidURIError => e raise Puppet::HTTP::ProtocolError.new(_("Location URI is invalid: %{detail}") % { detail: e.message }, e) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/retry_after_handler.rb
lib/puppet/http/retry_after_handler.rb
# frozen_string_literal: true require 'date' require 'time' # Parse information relating to responses containing a Retry-After headers # # @api private class Puppet::HTTP::RetryAfterHandler # Create a handler to allow the system to sleep between HTTP requests # # @param [Integer] retry_limit number of retries allowed # @param [Integer] max_sleep maximum sleep time allowed def initialize(retry_limit, max_sleep) @retry_limit = retry_limit @max_sleep = max_sleep end # Does the response from the server tell us to wait until we attempt the next # retry? # # @param [Net::HTTP] request # @param [Puppet::HTTP::Response] response # # @return [Boolean] Return true if the response code is 429 or 503, return # false otherwise # # @api private def retry_after?(request, response) case response.code when 429, 503 true else false end end # The amount of time to wait before attempting a retry # # @param [Net::HTTP] request # @param [Puppet::HTTP::Response] response # @param [Integer] retries number of retries attempted so far # # @return [Integer] the amount of time to wait # # @raise [Puppet::HTTP::TooManyRetryAfters] raise if we have hit our retry # limit # # @api private def retry_after_interval(request, response, retries) raise Puppet::HTTP::TooManyRetryAfters, request.uri if retries >= @retry_limit retry_after = response['Retry-After'] return nil unless retry_after seconds = parse_retry_after(retry_after) # if retry-after is far in the future, we could end up sleeping repeatedly # for 30 minutes, effectively waiting indefinitely, seems like we should wait # in total for 30 minutes, in which case this upper limit needs to be enforced # by the client. [seconds, @max_sleep].min end private def parse_retry_after(retry_after) Integer(retry_after) rescue TypeError, ArgumentError begin tm = DateTime.rfc2822(retry_after) seconds = (tm.to_time - DateTime.now.to_time).to_i [seconds, 0].max rescue ArgumentError raise Puppet::HTTP::ProtocolError, _("Failed to parse Retry-After header '%{retry_after}' as an integer or RFC 2822 date") % { retry_after: retry_after } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/site.rb
lib/puppet/http/site.rb
# frozen_string_literal: true # Represents a site to which HTTP connections are made. It is a value # object, and is suitable for use in a hash. If two sites are equal, # then a persistent connection made to the first site, can be re-used # for the second. # # @api private class Puppet::HTTP::Site attr_reader :scheme, :host, :port def self.from_uri(uri) new(uri.scheme, uri.host, uri.port) end def initialize(scheme, host, port) @scheme = scheme @host = host @port = port.to_i end def addr "#{@scheme}://#{@host}:#{@port}" end alias to_s addr def ==(rhs) (@scheme == rhs.scheme) && (@host == rhs.host) && (@port == rhs.port) end alias eql? == def hash [@scheme, @host, @port].hash end def use_ssl? @scheme == 'https' end def move_to(uri) self.class.new(uri.scheme, uri.host, uri.port) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/service/report.rb
lib/puppet/http/service/report.rb
# frozen_string_literal: true # The Report service is used to submit run reports to the report server. # # @api public # class Puppet::HTTP::Service::Report < Puppet::HTTP::Service # @return [String] Default API for the report service API = '/puppet/v3' # Use `Puppet::HTTP::Session.route_to(:report)` to create or get an instance of this class. # # @param [Puppet::HTTP::Client] client # @param [Puppet::HTTP::Session] session # @param [String] server (Puppet[:ca_server]) If an explicit server is given, # create a service using that server. If server is nil, the default value # is used to create the service. # @param [Integer] port (Puppet[:ca_port]) If an explicit port is given, create # a service using that port. If port is nil, the default value is used to # create the service. # # @api private # def initialize(client, session, server, port) url = build_url(API, server || Puppet[:report_server], port || Puppet[:report_port]) super(client, session, url) end # Submit a report to the report server. # # @param [String] name the name of the report being submitted # @param [Puppet::Transaction::Report] report run report to be submitted # @param [String] environment name of the agent environment # # @return [Puppet::HTTP::Response] response returned by the server # # @api public # def put_report(name, report, environment:) formatter = Puppet::Network::FormatHandler.format_for(Puppet[:preferred_serialization_format]) headers = add_puppet_headers( 'Accept' => get_mime_types(Puppet::Transaction::Report).join(', '), 'Content-Type' => formatter.mime ) response = @client.put( with_base_url("/report/#{name}"), serialize(formatter, report), headers: headers, params: { environment: environment } ) # override parent's process_response handling @session.process_response(response) if response.success? response else raise Puppet::HTTP::ResponseError, response end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/service/compiler.rb
lib/puppet/http/service/compiler.rb
# frozen_string_literal: true # The Compiler service is used to submit and retrieve data from the # puppetserver. # # @api public class Puppet::HTTP::Service::Compiler < Puppet::HTTP::Service # @return [String] Default API for the Compiler service API = '/puppet/v3' # Use `Puppet::HTTP::Session.route_to(:puppet)` to create or get an instance of this class. # # @param [Puppet::HTTP::Client] client # @param [Puppet::HTTP::Session] session # @param [String] server (`Puppet[:server]`) If an explicit server is given, # create a service using that server. If server is nil, the default value # is used to create the service. # @param [Integer] port (`Puppet[:masterport]`) If an explicit port is given, create # a service using that port. If port is nil, the default value is used to # create the service. # def initialize(client, session, server, port) url = build_url(API, server || Puppet[:server], port || Puppet[:serverport]) super(client, session, url) end # Submit a GET request to retrieve a node from the server. # # @param [String] name The name of the node being requested # @param [String] environment The name of the environment we are operating in # @param [String] configured_environment Optional, the name of the configured # environment. If unset, `environment` is used. # @param [String] transaction_uuid An agent generated transaction uuid, used # for connecting catalogs and reports. # # @return [Array<Puppet::HTTP::Response, Puppet::Node>] An array containing # the request response and the deserialized requested node # # @api public def get_node(name, environment:, configured_environment: nil, transaction_uuid: nil) headers = add_puppet_headers('Accept' => get_mime_types(Puppet::Node).join(', ')) response = @client.get( with_base_url("/node/#{name}"), headers: headers, params: { environment: environment, configured_environment: configured_environment || environment, transaction_uuid: transaction_uuid, } ) process_response(response) [response, deserialize(response, Puppet::Node)] end # Submit a POST request to submit a catalog to the server. # # @param [String] name The name of the catalog to be submitted # @param [Puppet::Node::Facts] facts Facts for this catalog # @param [String] environment The name of the environment we are operating in # @param [String] configured_environment Optional, the name of the configured # environment. If unset, `environment` is used. # @param [Boolean] check_environment If true, request that the server check if # our `environment` matches the server-specified environment. If they do not # match, then the server may return an empty catalog in the server-specified # environment. # @param [String] transaction_uuid An agent generated transaction uuid, used # for connecting catalogs and reports. # @param [String] job_uuid A unique job identifier defined when the orchestrator # starts a puppet run via pxp-agent. This is used to correlate catalogs and # reports with the orchestrator job. # @param [Boolean] static_catalog Indicates if the file metadata(s) are inlined # in the catalog. This informs the agent if it needs to make a second request # to retrieve metadata in addition to the initial catalog request. # @param [Array<String>] checksum_type An array of accepted checksum types. # # @return [Array<Puppet::HTTP::Response, Puppet::Resource::Catalog>] An array # containing the request response and the deserialized catalog returned by # the server # # @api public def post_catalog(name, facts:, environment:, configured_environment: nil, check_environment: false, transaction_uuid: nil, job_uuid: nil, static_catalog: true, checksum_type: Puppet[:supported_checksum_types]) if Puppet[:preferred_serialization_format] == "pson" formatter = Puppet::Network::FormatHandler.format_for(:pson) # must use 'pson' instead of 'text/pson' facts_format = 'pson' else formatter = Puppet::Network::FormatHandler.format_for(:json) facts_format = formatter.mime end facts_as_string = serialize(formatter, facts) # query parameters are sent in the POST request body body = { facts_format: facts_format, facts: Puppet::Util.uri_query_encode(facts_as_string), environment: environment, configured_environment: configured_environment || environment, check_environment: !!check_environment, transaction_uuid: transaction_uuid, job_uuid: job_uuid, static_catalog: static_catalog, checksum_type: checksum_type.join('.') }.map do |key, value| "#{key}=#{Puppet::Util.uri_query_encode(value.to_s)}" end.join("&") headers = add_puppet_headers( 'Accept' => get_mime_types(Puppet::Resource::Catalog).join(', '), 'Content-Type' => 'application/x-www-form-urlencoded' ) response = @client.post( with_base_url("/catalog/#{name}"), body, headers: headers, # for legacy reasons we always send environment as a query parameter too params: { environment: environment } ) if (compiler = response['X-Puppet-Compiler-Name']) Puppet.notice("Catalog compiled by #{compiler}") end process_response(response) [response, deserialize(response, Puppet::Resource::Catalog)] end # # @api private # # Submit a POST request to request a catalog to the server using v4 endpoint # # @param [String] certname The name of the node for which to compile the catalog. # @param [Hash] persistent A hash containing two required keys, facts and catalog, # which when set to true will cause the facts and reports to be stored in # PuppetDB, or discarded if set to false. # @param [String] environment The name of the environment for which to compile the catalog. # @param [Hash] facts A hash with a required values key, containing a hash of all the # facts for the node. If not provided, Puppet will attempt to fetch facts for the node # from PuppetDB. # @param [Hash] trusted_facts A hash with a required values key containing a hash of # the trusted facts for a node # @param [String] transaction_uuid The id for tracking the catalog compilation and # report submission. # @param [String] job_id The id of the orchestrator job that triggered this run. # @param [Hash] options A hash of options beyond direct input to catalogs. Options: # - prefer_requested_environment Whether to always override a node's classified # environment with the one supplied in the request. If this is true and no environment # is supplied, fall back to the classified environment, or finally, 'production'. # - capture_logs Whether to return the errors and warnings that occurred during # compilation alongside the catalog in the response body. # - log_level The logging level to use during the compile when capture_logs is true. # Options are 'err', 'warning', 'info', and 'debug'. # # @return [Array<Puppet::HTTP::Response, Puppet::Resource::Catalog, Array<String>>] An array # containing the request response, the deserialized catalog returned by # the server and array containing logs (log array will be empty if capture_logs is false) # def post_catalog4(certname, persistence:, environment:, facts: nil, trusted_facts: nil, transaction_uuid: nil, job_id: nil, options: nil) unless persistence.is_a?(Hash) && (missing = [:facts, :catalog] - persistence.keys.map(&:to_sym)).empty? raise ArgumentError, "The 'persistence' hash is missing the keys: #{missing.join(', ')}" end raise ArgumentError, "Facts must be a Hash not a #{facts.class}" unless facts.nil? || facts.is_a?(Hash) body = { certname: certname, persistence: persistence, environment: environment, transaction_uuid: transaction_uuid, job_id: job_id, options: options } body[:facts] = { values: facts } unless facts.nil? body[:trusted_facts] = { values: trusted_facts } unless trusted_facts.nil? headers = add_puppet_headers( 'Accept' => get_mime_types(Puppet::Resource::Catalog).join(', '), 'Content-Type' => 'application/json' ) url = URI::HTTPS.build(host: @url.host, port: @url.port, path: Puppet::Util.uri_encode("/puppet/v4/catalog")) response = @client.post( url, body.to_json, headers: headers ) process_response(response) begin response_body = JSON.parse(response.body) catalog = Puppet::Resource::Catalog.from_data_hash(response_body['catalog']) rescue => err raise Puppet::HTTP::SerializationError.new("Failed to deserialize catalog from puppetserver response: #{err.message}", err) end logs = response_body['logs'] || [] [response, catalog, logs] end # # @api private # # Submit a GET request to retrieve the facts for the named node # # @param [String] name Name of the node to retrieve facts for # @param [String] environment Name of the environment we are operating in # # @return [Array<Puppet::HTTP::Response, Puppet::Node::Facts>] An array # containing the request response and the deserialized facts for the # specified node # # @api public def get_facts(name, environment:) headers = add_puppet_headers('Accept' => get_mime_types(Puppet::Node::Facts).join(', ')) response = @client.get( with_base_url("/facts/#{name}"), headers: headers, params: { environment: environment } ) process_response(response) [response, deserialize(response, Puppet::Node::Facts)] end # Submits a PUT request to submit facts for the node to the server. # # @param [String] name Name of the node we are submitting facts for # @param [String] environment Name of the environment we are operating in # @param [Puppet::Node::Facts] facts Facts for the named node # # @return [Puppet::HTTP::Response] The request response # # @api public def put_facts(name, environment:, facts:) formatter = Puppet::Network::FormatHandler.format_for(Puppet[:preferred_serialization_format]) headers = add_puppet_headers( 'Accept' => get_mime_types(Puppet::Node::Facts).join(', '), 'Content-Type' => formatter.mime ) response = @client.put( with_base_url("/facts/#{name}"), serialize(formatter, facts), headers: headers, params: { environment: environment } ) process_response(response) response end # Submit a GET request to retrieve a file stored with filebucket. # # @param [String] path The request path, formatted by `Puppet::FileBucket::Dipper` # @param [String] environment Name of the environment we are operating in. # This should not impact filebucket at all, but is included to be consistent # with legacy code. # @param [String] bucket_path # @param [String] diff_with a checksum to diff against if we are comparing # files that are both stored in the bucket # @param [String] list_all # @param [String] fromdate # @param [String] todate # # @return [Array<Puppet::HTTP::Response, Puppet::FileBucket::File>] An array # containing the request response and the deserialized file returned from # the server. # # @api public def get_filebucket_file(path, environment:, bucket_path: nil, diff_with: nil, list_all: nil, fromdate: nil, todate: nil) headers = add_puppet_headers('Accept' => 'application/octet-stream') response = @client.get( with_base_url("/file_bucket_file/#{path}"), headers: headers, params: { environment: environment, bucket_path: bucket_path, diff_with: diff_with, list_all: list_all, fromdate: fromdate, todate: todate } ) process_response(response) [response, deserialize(response, Puppet::FileBucket::File)] end # Submit a PUT request to store a file with filebucket. # # @param [String] path The request path, formatted by `Puppet::FileBucket::Dipper` # @param [String] body The contents of the file to be backed # @param [String] environment Name of the environment we are operating in. # This should not impact filebucket at all, but is included to be consistent # with legacy code. # # @return [Puppet::HTTP::Response] The response request # # @api public def put_filebucket_file(path, body:, environment:) headers = add_puppet_headers({ 'Accept' => 'application/octet-stream', 'Content-Type' => 'application/octet-stream' }) response = @client.put( with_base_url("/file_bucket_file/#{path}"), body, headers: headers, params: { environment: environment } ) process_response(response) response end # Submit a HEAD request to check the status of a file stored with filebucket. # # @param [String] path The request path, formatted by `Puppet::FileBucket::Dipper` # @param [String] environment Name of the environment we are operating in. # This should not impact filebucket at all, but is included to be consistent # with legacy code. # @param [String] bucket_path # # @return [Puppet::HTTP::Response] The request response # # @api public def head_filebucket_file(path, environment:, bucket_path: nil) headers = add_puppet_headers('Accept' => 'application/octet-stream') response = @client.head( with_base_url("/file_bucket_file/#{path}"), headers: headers, params: { environment: environment, bucket_path: bucket_path } ) process_response(response) response end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/service/ca.rb
lib/puppet/http/service/ca.rb
# frozen_string_literal: true # The CA service is used to handle certificate related REST requests. # # @api public class Puppet::HTTP::Service::Ca < Puppet::HTTP::Service # @return [Hash] default headers for the ca service HEADERS = { 'Accept' => 'text/plain' }.freeze # @return [String] default API for the ca service API = '/puppet-ca/v1' # Use `Puppet::HTTP::Session.route_to(:ca)` to create or get an instance of this class. # # @param [Puppet::HTTP::Client] client # @param [Puppet::HTTP::Session] session # @param [String] server (`Puppet[:ca_server]`) If an explicit server is given, # create a service using that server. If server is nil, the default value # is used to create the service. # @param [Integer] port (`Puppet[:ca_port]`) If an explicit port is given, create # a service using that port. If port is nil, the default value is used to # create the service. # def initialize(client, session, server, port) url = build_url(API, server || Puppet[:ca_server], port || Puppet[:ca_port]) super(client, session, url) end # Submit a GET request to retrieve the named certificate from the server. # # @param [String] name name of the certificate to request # @param [Time] if_modified_since If not nil, only download the cert if it has # been modified since the specified time. # @param [Puppet::SSL::SSLContext] ssl_context # # @return [Array<Puppet::HTTP::Response, String>] An array containing the # request response and the stringified body of the request response # # @api public def get_certificate(name, if_modified_since: nil, ssl_context: nil) headers = add_puppet_headers(HEADERS) headers['If-Modified-Since'] = if_modified_since.httpdate if if_modified_since response = @client.get( with_base_url("/certificate/#{name}"), headers: headers, options: { ssl_context: ssl_context } ) process_response(response) [response, response.body.to_s] end # Submit a GET request to retrieve the certificate revocation list from the # server. # # @param [Time] if_modified_since If not nil, only download the CRL if it has # been modified since the specified time. # @param [Puppet::SSL::SSLContext] ssl_context # # @return [Array<Puppet::HTTP::Response, String>] An array containing the # request response and the stringified body of the request response # # @api public def get_certificate_revocation_list(if_modified_since: nil, ssl_context: nil) headers = add_puppet_headers(HEADERS) headers['If-Modified-Since'] = if_modified_since.httpdate if if_modified_since response = @client.get( with_base_url("/certificate_revocation_list/ca"), headers: headers, options: { ssl_context: ssl_context } ) process_response(response) [response, response.body.to_s] end # Submit a PUT request to send a certificate request to the server. # # @param [String] name The name of the certificate request being sent # @param [OpenSSL::X509::Request] csr Certificate request to send to the # server # @param [Puppet::SSL::SSLContext] ssl_context # # @return [Puppet::HTTP::Response] The request response # # @api public def put_certificate_request(name, csr, ssl_context: nil) headers = add_puppet_headers(HEADERS) headers['Content-Type'] = 'text/plain' response = @client.put( with_base_url("/certificate_request/#{name}"), csr.to_pem, headers: headers, options: { ssl_context: ssl_context } ) process_response(response) response end # Submit a POST request to send a certificate renewal request to the server # # @param [Puppet::SSL::SSLContext] ssl_context # # @return [Array<Puppet::HTTP::Response, String>] The request response # # @api public def post_certificate_renewal(ssl_context) headers = add_puppet_headers(HEADERS) headers['Content-Type'] = 'text/plain' response = @client.post( with_base_url('/certificate_renewal'), '', # Puppet::HTTP::Client.post requires a body, the API endpoint does not headers: headers, options: { ssl_context: ssl_context } ) raise ArgumentError, _('SSL context must contain a client certificate.') unless ssl_context.client_cert process_response(response) [response, response.body.to_s] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/service/puppetserver.rb
lib/puppet/http/service/puppetserver.rb
# frozen_string_literal: true # The puppetserver service. # # @api public # class Puppet::HTTP::Service::Puppetserver < Puppet::HTTP::Service # Use `Puppet::HTTP::Session.route_to(:puppetserver)` to create or get an instance of this class. # # @param [Puppet::HTTP::Client] client # @param [Puppet::HTTP::Session] session # @param [String] server (`Puppet[:server]`) If an explicit server is given, # create a service using that server. If server is nil, the default value # is used to create the service. # @param [Integer] port (`Puppet[:masterport]`) If an explicit port is given, create # a service using that port. If port is nil, the default value is used to # create the service. # def initialize(client, session, server, port) url = build_url('', server || Puppet[:server], port || Puppet[:serverport]) super(client, session, url) end # Request the puppetserver's simple status. # # @param [Puppet::SSL::SSLContext] ssl_context to use when establishing # the connection. # @return Puppet::HTTP::Response The HTTP response # # @api public # def get_simple_status(ssl_context: nil) request_path = "/status/v1/simple/server" begin response = @client.get( with_base_url(request_path), headers: add_puppet_headers({}), options: { ssl_context: ssl_context } ) process_response(response) rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 && e.response.url.path == "/status/v1/simple/server" request_path = "/status/v1/simple/master" retry else raise e end end [response, response.body.to_s] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/service/file_server.rb
lib/puppet/http/service/file_server.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/metadata' # The FileServer service is used to retrieve file metadata and content. # # @api public # class Puppet::HTTP::Service::FileServer < Puppet::HTTP::Service # @return [String] Default API for the FileServer service API = '/puppet/v3' # @return [RegEx] RegEx used to determine if a path contains a leading slash PATH_REGEX = %r{^/} # Use `Puppet::HTTP::Session.route_to(:fileserver)` to create or get an instance of this class. # # @param [Puppet::HTTP::Client] client # @param [Puppet::HTTP::Session] session # @param [String] server (`Puppet[:server]`) If an explicit server is given, # create a service using that server. If server is nil, the default value # is used to create the service. # @param [Integer] port (`Puppet[:masterport]`) If an explicit port is given, create # a service using that port. If port is nil, the default value is used to # create the service. # def initialize(client, session, server, port) url = build_url(API, server || Puppet[:server], port || Puppet[:serverport]) super(client, session, url) end # Submit a GET request to the server to retrieve the metadata for a specified file. # # @param [String] path path to the file to retrieve data from # @param [String] environment the name of the environment we are operating in # @param [Symbol] links Can be one of either `:follow` or `:manage`, defines # how links are handled. # @param [String] checksum_type The digest algorithm used to verify the file. # Defaults to `sha256`. # @param [Symbol] source_permissions Can be one of `:use`, `:use_when_creating`, # or `:ignore`. This parameter tells the server if it should include the # file permissions in the response. If set to `:ignore`, the server will # return default permissions. # # @return [Array<Puppet::HTTP::Response, Puppet::FileServing::Metadata>] An # array with the request response and the deserialized metadata for the # file returned from the server # # @api public # def get_file_metadata(path:, environment:, links: :manage, checksum_type: Puppet[:digest_algorithm], source_permissions: :ignore) validate_path(path) headers = add_puppet_headers('Accept' => get_mime_types(Puppet::FileServing::Metadata).join(', ')) response = @client.get( with_base_url("/file_metadata#{path}"), headers: headers, params: { links: links, checksum_type: checksum_type, source_permissions: source_permissions, environment: environment } ) process_response(response) [response, deserialize(response, Puppet::FileServing::Metadata)] end # Submit a GET request to the server to retrieve the metadata for multiple files # # @param [String] path path to the file(s) to retrieve data from # @param [String] environment the name of the environment we are operating in # @param [Symbol] recurse Can be `:true`, `:false`, or `:remote`. Defines if # we recursively return the contents of the directory. Used in conjunction # with `:recurselimit`. See the reference documentation for the file type # for more details. # @param [Integer] recurselimit When `recurse` is set, `recurselimit` defines # how far Puppet should descend into subdirectories. `0` is effectively the # same as `recurse => false`, `1` will return files and directories directly # inside the defined directory, `2` will return the direct content of the # directory as well as the contents of the _first_ level of subdirectories. # The pattern continues for each incremental value. See the reference # documentation for the file type for more details. # @param [Array<String>] ignore An optional array of files to ignore, ie `['CVS', '.git', '.hg']` # @param [Symbol] links Can be one of either `:follow` or `:manage`, defines # how links are handled. # @param [String] checksum_type The digest algorithm used to verify the file. # Currently if fips is enabled, this defaults to `sha256`. Otherwise, it's `md5`. # @param [Symbol] source_permissions Can be one of `:use`, `:use_when_creating`, # or `:ignore`. This parameter tells the server if it should include the # file permissions in the report. If set to `:ignore`, the server will return # default permissions. # # @return [Array<Puppet::HTTP::Response, Array<Puppet::FileServing::Metadata>>] # An array with the request response and an array of the deserialized # metadata for each file returned from the server # # @api public # def get_file_metadatas(environment:, path: nil, recurse: :false, recurselimit: nil, max_files: nil, ignore: nil, links: :manage, checksum_type: Puppet[:digest_algorithm], source_permissions: :ignore) # rubocop:disable Lint/BooleanSymbol validate_path(path) headers = add_puppet_headers('Accept' => get_mime_types(Puppet::FileServing::Metadata).join(', ')) response = @client.get( with_base_url("/file_metadatas#{path}"), headers: headers, params: { recurse: recurse, recurselimit: recurselimit, max_files: max_files, ignore: ignore, links: links, checksum_type: checksum_type, source_permissions: source_permissions, environment: environment, } ) process_response(response) [response, deserialize_multiple(response, Puppet::FileServing::Metadata)] end # Submit a GET request to the server to retrieve content of a file. # # @param [String] path path to the file to retrieve data from # @param [String] environment the name of the environment we are operating in # # @yield [Sting] Yields the body of the response returned from the server # # @return [Puppet::HTTP::Response] The request response # # @api public # def get_file_content(path:, environment:, &block) validate_path(path) headers = add_puppet_headers('Accept' => 'application/octet-stream') response = @client.get( with_base_url("/file_content#{path}"), headers: headers, params: { environment: environment } ) do |res| if res.success? res.read_body(&block) end end process_response(response) response end # Submit a GET request to retrieve file content using the `static_file_content` API # uniquely identified by (`code_id`, `environment`, `path`). # # @param [String] path path to the file to retrieve data from # @param [String] environment the name of the environment we are operating in # @param [String] code_id Defines the version of the resource to return # # @yield [String] Yields the body of the response returned # # @return [Puppet::HTTP::Response] The request response # # @api public # def get_static_file_content(path:, environment:, code_id:, &block) validate_path(path) headers = add_puppet_headers('Accept' => 'application/octet-stream') response = @client.get( with_base_url("/static_file_content#{path}"), headers: headers, params: { environment: environment, code_id: code_id, } ) do |res| if res.success? res.read_body(&block) end end process_response(response) response end private def validate_path(path) raise ArgumentError, "Path must start with a slash" unless path =~ PATH_REGEX end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/resolver/srv.rb
lib/puppet/http/resolver/srv.rb
# frozen_string_literal: true # Resolve a service using DNS SRV records. # # @api public class Puppet::HTTP::Resolver::SRV < Puppet::HTTP::Resolver # Create an DNS SRV resolver. # # @param [Puppet::HTTP::Client] client # @param [String] domain srv domain # @param [Resolv::DNS] dns # def initialize(client, domain:, dns: Resolv::DNS.new) @client = client @srv_domain = domain @delegate = Puppet::HTTP::DNS.new(dns) end # Walk the available srv records and return the first that successfully connects # # @param [Puppet::HTTP::Session] session # @param [Symbol] name the service being resolved # @param [Puppet::SSL::SSLContext] ssl_context # @param [Proc] canceled_handler optional callback allowing a resolver # to cancel resolution. # # @return [Puppet::HTTP::Service] if an available service is found, return # it. Return nil otherwise. # # @api public def resolve(session, name, ssl_context: nil, canceled_handler: nil) # Here we pass our HTTP service name as the DNS SRV service name # This is fine for :ca, but note that :puppet and :file are handled # specially in `each_srv_record`. @delegate.each_srv_record(@srv_domain, name) do |server, port| service = Puppet::HTTP::Service.create_service(@client, session, name, server, port) return service if check_connection?(session, service, ssl_context: ssl_context) end nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/resolver/settings.rb
lib/puppet/http/resolver/settings.rb
# frozen_string_literal: true # Resolve a service using settings. This is the default resolver if none of the # other resolvers find a functional connection. # # @api public class Puppet::HTTP::Resolver::Settings < Puppet::HTTP::Resolver # Resolve a service using the default server and port settings for this service. # # @param [Puppet::HTTP::Session] session # @param [Symbol] name the name of the service to be resolved # @param [Puppet::SSL::SSLContext] ssl_context # @param [Proc] canceled_handler optional callback allowing a resolver # to cancel resolution. # # @return [Puppet::HTTP::Service] if the service successfully connects, # return it. Otherwise, return nil. # # @api public def resolve(session, name, ssl_context: nil, canceled_handler: nil) service = Puppet::HTTP::Service.create_service(@client, session, name) check_connection?(session, service, ssl_context: ssl_context) ? service : nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http/resolver/server_list.rb
lib/puppet/http/resolver/server_list.rb
# frozen_string_literal: true # Use the server_list setting to resolve a service. This resolver is only used # if server_list is set either on the command line or in the configuration file. # # @api public class Puppet::HTTP::Resolver::ServerList < Puppet::HTTP::Resolver # Create a server list resolver. # # @param [Puppet::HTTP::Client] client # @param [Array<String>] server_list_setting array of servers set via the # configuration or the command line # @param [Integer] default_port if a port is not set for a server in # server_list, use this port # @param [Array<Symbol>] services array of services that server_list can be # used to resolve. If a service is not included in this array, this resolver # will return nil. # def initialize(client, server_list_setting:, default_port:, services:) @client = client @server_list_setting = server_list_setting @default_port = default_port @services = services end # Walk the server_list to find a server and port that will connect successfully. # # @param [Puppet::HTTP::Session] session # @param [Symbol] name the name of the service being resolved # @param [Puppet::SSL::SSLContext] ssl_context # @param [Proc] canceled_handler optional callback allowing a resolver # to cancel resolution. # # @return [nil] return nil if the service to be resolved does not support # server_list # @return [Puppet::HTTP::Service] a validated service to use for future HTTP # requests # # @raise [Puppet::Error] raise if none of the servers defined in server_list # are available # # @api public def resolve(session, name, ssl_context: nil, canceled_handler: nil) # If we're configured to use an explicit service host, e.g. report_server # then don't use server_list to resolve the `:report` service. return nil unless @services.include?(name) # If we resolved the URL already, use its host & port for the service if @resolved_url return Puppet::HTTP::Service.create_service(@client, session, name, @resolved_url.host, @resolved_url.port) end # Return the first simple service status endpoint we can connect to @server_list_setting.value.each_with_index do |server, index| host = server[0] port = server[1] || @default_port service = Puppet::HTTP::Service.create_service(@client, session, :puppetserver, host, port) begin service.get_simple_status(ssl_context: ssl_context) @resolved_url = service.url return Puppet::HTTP::Service.create_service(@client, session, name, @resolved_url.host, @resolved_url.port) rescue Puppet::HTTP::ResponseError => detail if index < @server_list_setting.value.length - 1 Puppet.warning(_("Puppet server %{host}:%{port} is unavailable: %{code} %{reason}") % { host: service.url.host, port: service.url.port, code: detail.response.code, reason: detail.response.reason } + ' ' + _("Trying with next server from server_list.")) else Puppet.log_exception(detail, _("Puppet server %{host}:%{port} is unavailable: %{code} %{reason}") % { host: service.url.host, port: service.url.port, code: detail.response.code, reason: detail.response.reason }) end rescue Puppet::HTTP::HTTPError => detail if index < @server_list_setting.value.length - 1 Puppet.warning(_("Unable to connect to server from server_list setting: %{detail}") % { detail: detail } + ' ' + _("Trying with next server from server_list.")) else Puppet.log_exception(detail, _("Unable to connect to server from server_list setting: %{detail}") % { detail: detail }) end end end # don't fallback to other resolvers canceled_handler.call(true) if canceled_handler # not found nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/profile_steps.rb
features/lib/profile_steps.rb
# frozen_string_literal: true Given('the following profile(s) is/are defined:') do |profiles| write_file('cucumber.yml', profiles) end Then('the {word} profile should be used') do |profile| expect(command_line.all_output).to include_output(profile) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/parameter_types.rb
features/lib/support/parameter_types.rb
# frozen_string_literal: true ParameterType( name: 'list', regexp: /.*/, transformer: ->(s) { s.split(/,\s+/) }, use_for_snippets: false ) class ExecutionStatus def initialize(name) @passed = name == 'pass' end def validates?(exit_code) @passed ? exit_code.zero? : exit_code.positive? end end ParameterType( name: 'status', regexp: /pass|fail/, transformer: ->(s) { ExecutionStatus.new(s) } )
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/output.rb
features/lib/support/output.rb
# frozen_string_literal: true require 'rspec/expectations' def clean_output(output) output.split("\n").map do |line| next if line.include?(CUCUMBER_FEATURES_PATH) line .gsub(/\e\[([;\d]+)?m/, '') # Drop colors .gsub(/^.*cucumber_process\.rb.*$\n/, '') .gsub(/^\d+m\d+\.\d+s$/, '0m0.012s') # Make duration predictable .gsub(/Coverage report generated .+$\n/, '') # Remove SimpleCov message .sub(/\s*$/, '') # Drop trailing whitespaces end.compact.join("\n") end def remove_self_ref(output) output .split("\n") .reject { |line| line.include?(CUCUMBER_FEATURES_PATH) } .join("\n") end RSpec::Matchers.define :be_similar_output_than do |expected| match do |actual| @actual = clean_output(actual) @expected = clean_output(expected) @actual == @expected end diffable end RSpec::Matchers.define :start_with_output do |expected| match do |actual| @actual = clean_output(actual) @expected = clean_output(expected) @actual.start_with?(@expected) end diffable end RSpec::Matchers.define :include_output do |expected| match do |actual| @actual = clean_output(actual) @expected = clean_output(expected) @actual.include?(@expected) end diffable end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/json.rb
features/lib/support/json.rb
# frozen_string_literal: true module JSONWorld def normalise_json(json) json.each do |feature| elements = feature.fetch('elements') { [] } elements.each do |scenario| normalise_scenario_json(scenario) end end end private def normalise_scenario_json(scenario) scenario['steps']&.each do %w[steps before after].each do |type| next unless scenario[type] scenario[type].each do |step_or_hook| normalise_json_step_or_hook(step_or_hook) next unless step_or_hook['after'] step_or_hook['after'].each do |hook| normalise_json_step_or_hook(hook) end end end end end # make sure duration was captured (should be >= 0) # then set it to what is "expected" since duration is dynamic def normalise_json_step_or_hook(step_or_hook) update_json_step_or_hook_error_message(step_or_hook) if step_or_hook['result']['error_message'] return unless step_or_hook['result'] && step_or_hook['result']['duration'] raise 'Duration should always be positive' unless step_or_hook['result']['duration'].positive? step_or_hook['result']['duration'] = 1 end def update_json_step_or_hook_error_message(step_or_hook) step_or_hook['result']['error_message'] = step_or_hook['result']['error_message'].split("\n").reject { |line| line.include?(CUCUMBER_FEATURES_PATH) }.join("\n") end end World(JSONWorld)
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/env.rb
features/lib/support/env.rb
# frozen_string_literal: true require 'cucumber/formatter/ansicolor' require 'securerandom' require 'nokogiri' CUCUMBER_FEATURES_PATH = 'features/lib' Before do |scenario| @original_cwd = Dir.pwd # We limit the length to avoid issues on Windows where sometimes the creation # of the temporary directory fails due to the length of the scenario name. scenario_name = scenario.name.downcase.gsub(/[^a-z0-9]+/, '-')[0..100] @tmp_working_directory = File.join('tmp', "scenario-#{scenario_name}-#{SecureRandom.uuid}") FileUtils.rm_rf(@tmp_working_directory) FileUtils.mkdir_p(@tmp_working_directory) Dir.chdir(@tmp_working_directory) end After do |scenario| command_line&.destroy_mocks Dir.chdir(@original_cwd) FileUtils.rm_rf(@tmp_working_directory) unless scenario.failed? end Around do |_, block| original_publish_token = ENV.delete('CUCUMBER_PUBLISH_TOKEN') original_coloring = Cucumber::Term::ANSIColor.coloring? block.call Cucumber::Term::ANSIColor.coloring = original_coloring ENV['CUCUMBER_PUBLISH_TOKEN'] = original_publish_token end Around('@force_legacy_loader') do |_, block| original_loader = Cucumber.use_legacy_autoloader Cucumber.use_legacy_autoloader = true block.call Cucumber.use_legacy_autoloader = original_loader end Before('@global_state') do # Ok, this one is tricky but kinda make sense. # So, we need to share state between some sub-scenarios (the ones executed by # CucumberCommand). But we don't want those to leak between the "real" scenarios # (the ones ran by Cucumber itself). # This should reset data hopefully (and make clear why we do that) $global_state = nil $global_cukes = 0 $scenario_runs = 0 end After('@disable_fail_fast') do Cucumber.wants_to_quit = false end def snake_case(name) name.downcase.gsub(/\W/, '_') end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/feature_factory.rb
features/lib/support/feature_factory.rb
# frozen_string_literal: true module FeatureFactory def create_feature(name = generate_feature_name) gherkin = <<~GHERKIN Feature: #{name} #{yield} GHERKIN write_file filename(name), gherkin end def create_feature_ja(name = generate_feature_name) gherkin = <<~GHERKIN # language: ja ζ©Ÿθƒ½: #{name} #{yield} GHERKIN write_file filename(name), gherkin end def create_scenario(name = generate_scenario_name) <<-GHERKIN Scenario: #{name} #{yield} GHERKIN end def create_scenario_ja(name = generate_scenario_name) <<-GHERKIN γ‚·γƒŠγƒͺγ‚ͺ: #{name} #{yield} GHERKIN end def create_step_definition write_file generate_step_definition_filename, yield end def generate_feature_name "Test Feature #{next_increment(:feature)}" end def generate_scenario_name "Test Scenario #{next_increment(:scenario)}" end def next_increment(label) @increments ||= {} @increments[label] ||= 0 @increments[label] += 1 end def generate_step_definition_filename "features/step_definitions/steps#{next_increment(:step_defs)}.rb" end def filename(name) "features/#{name.downcase.tr(' ', '_')}.feature" end def features cd('.') do Dir['features/*.feature'] end end end World(FeatureFactory)
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/junit.rb
features/lib/support/junit.rb
# frozen_string_literal: true module JUnitWorld def replace_junit_time(time) time.gsub(/\d+\.\d\d+/m, '0.05') end end World(JUnitWorld)
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/command_line.rb
features/lib/support/command_line.rb
# frozen_string_literal: true require 'rspec/expectations' require 'rspec/mocks' require 'rake' require 'cucumber/rake/task' class MockKernel attr_reader :exit_status def exit(status) @exit_status = status status unless status.zero? end end class CommandLine include ::RSpec::Mocks::ExampleMethods def initialize ::RSpec::Mocks.setup @stdout = StringIO.new @stderr = StringIO.new @kernel = MockKernel.new end def stderr @stderr.string end def stdout(format: :string) case format when :lines then @stdout.string.split("\n") when :messages then @stdout.string.split("\n").map { |line| JSON.parse(line) } else @stdout.string end end def all_output [stdout, stderr].reject(&:empty?).join("\n") end def exit_status @kernel.exit_status || 0 end def capture_stdout capture_stream($stdout, @stdout) capture_stream($stderr, @stderr) yield end def destroy_mocks ::RSpec::Mocks.verify ensure ::RSpec::Mocks.teardown end private def capture_stream(stream, redirect) allow(stream) .to receive(:puts) .and_wrap_original do |_, *args| redirect.puts(*args) end allow(stream) .to receive(:print) .and_wrap_original do |_, *args| redirect.print(*args) end allow(stream) .to receive(:flush) .and_wrap_original do |_, *args| redirect.flush(*args) end end end class CucumberCommand < CommandLine attr_reader :args def execute(args) @args = args argument_list = make_arg_list(args) Cucumber::Cli::Main.new( argument_list, @stdout, @stderr, @kernel ).execute! end private def make_arg_list(args) index = -1 args.split(/'|"/).map do |chunk| index += 1 index.even? ? chunk.split(' ') : chunk end.flatten end end class RubyCommand < CommandLine def execute(file) capture_stdout { require file } rescue RuntimeError # no-op: this is raised when Cucumber fails rescue SystemExit # No-op: well, we are supposed to exit the rake task rescue StandardError @kernel.exit(1) end end class RakeCommand < CommandLine def execute(task) allow_any_instance_of(Cucumber::Rake::Task) .to receive(:fork) .and_return(false) allow(Cucumber::Cli::Main) .to receive(:execute) .and_wrap_original do |_, *args| Cucumber::Cli::Main.new( args[0], @stdout, @stderr, @kernel ).execute! end Rake.with_application do |rake| rake.load_rakefile capture_stdout { rake[task.strip].invoke } end rescue RuntimeError # no-op: this is raised when Cucumber fails rescue SystemExit # No-op: well, we are supposed to exit the rake task end end module CLIWorld def execute_cucumber(args) execute_command(CucumberCommand, args) end def execute_extra_cucumber(args) execute_extra_command(CucumberCommand, args) end def execute_ruby(filename) execute_command(RubyCommand, "#{Dir.pwd}/#{filename}") end def execute_rake(task) execute_command(RakeCommand, task) end def execute_command(cls, args) @command_line = cls.new @command_line.execute(args) end def execute_extra_command(cls, args) @extra_commands = [] @extra_commands << cls.new @extra_commands.last.execute(args) end def command_line @command_line end def last_extra_command @extra_commands&.last end end World(CLIWorld) RSpec::Matchers.define :have_succeded do match do |cli| @actual = cli.exit_status @expected = '0 exit code' @actual.zero? end end RSpec::Matchers.define :have_failed do match do |cli| @actual = cli.exit_status @expected = 'non-0 exit code' @actual.positive? end end RSpec::Matchers.define :have_exited_with do |expected| match do |cli| @actual = cli.exit_status if expected.is_a?(ExecutionStatus) expected.validates?(@actual) else @actual == expected end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/step_definitions.rb
features/lib/support/step_definitions.rb
# frozen_string_literal: true module StepDefinitionsWorld def step_definition(expression, content, keyword: 'Given') if content.is_a?(String) one_line_step_definition(keyword, expression, content) else block_step_definition(keyword, expression, content) end end def one_line_step_definition(keyword, expression, content) "#{keyword}(#{expression}) { #{content} }" end def block_step_definition(keyword, expression, content) indented_content = content .map { |line| " #{line}" } .join("\n") "#{keyword}(#{expression}) do\n#{indented_content}\nend" end end World(StepDefinitionsWorld)
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/support/filesystem.rb
features/lib/support/filesystem.rb
# frozen_string_literal: true def write_file(path, content) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') { |file| file.write(content) } end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/command_line_steps.rb
features/lib/step_definitions/command_line_steps.rb
# frozen_string_literal: true When('I run `cucumber{}`') do |args| execute_cucumber(args) end When('I run `bundle exec ruby {}`') do |filename| execute_ruby(filename) end When('I run `(bundle exec )rake {word}`') do |task| execute_rake(task) end When('I run the feature with the progress formatter') do execute_cucumber('features/ --format progress') end Then('the exit status should be {int}') do |exit_code| expect(command_line).to have_exited_with(exit_code) end Then('it should {status}') do |status| expect(command_line).to have_exited_with(status) end Then('it should {status} with:') do |status, output| expect(command_line).to have_exited_with(status) expect(command_line.all_output).to include_output(output) end Then('it should {status} with exactly:') do |status, output| expect(command_line).to have_exited_with(status) expect(command_line.all_output).to be_similar_output_than(output) end Then('the output should contain:') do |output| expect(command_line.all_output).to include_output(output) end Then('the output should contain {string}') do |output| expect(command_line.all_output).to include_output(output) end Then('the output includes the message {string}') do |message| expect(command_line.all_output).to include(message) end Then('the output should not contain:') do |output| expect(command_line.all_output).not_to include_output(output) end Then('the output should not contain {string}') do |output| expect(command_line.all_output).not_to include_output(output) end Then('the stdout should contain exactly:') do |output| expect(command_line.stdout).to be_similar_output_than(output) end Then('the stderr should contain:') do |output| expect(command_line.stderr).to include_output(output) end Then('the stderr should not contain:') do |output| expect(command_line.stderr).not_to include_output(output) end Then('the stderr should not contain anything') do expect(command_line.stderr).to be_empty end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/junit_steps.rb
features/lib/step_definitions/junit_steps.rb
# frozen_string_literal: true Then('the junit output file {string} should contain:') do |actual_file, text| actual = IO.read("#{File.expand_path('.')}/#{actual_file}") actual = remove_self_ref(replace_junit_time(actual)) expect(actual).to be_similar_output_than(text) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/message_steps.rb
features/lib/step_definitions/message_steps.rb
# frozen_string_literal: true Then('messages types should be:') do |expected_types| message_types = command_line.stdout(format: :messages).map(&:keys).flatten.compact expect(expected_types.split("\n")).to eq(message_types) end Then('output should be valid NDJSON') do expect { command_line.stdout(format: :messages) }.not_to raise_error end Then('the output should contain NDJSON with key {string}') do |key| expect(command_line.stdout(format: :messages)).to include(have_key(key)) end Then('the output should contain NDJSON with key {string} and value {string}') do |key, value| expect(command_line.stdout).to match(/"#{key}": ?"#{value}"/) end Then('the output should contain NDJSON {string} message with key {string} and value {string}') do |message_name, key, value| message_contents = command_line.stdout(format: :messages).detect { |msg| msg.keys == [message_name] }[message_name] expect(message_contents).to include(key => value) end Then('the output should contain NDJSON {string} message with key {string} and boolean value {word}') do |message_name, key, value| boolean = value == 'true' message_contents = command_line.stdout(format: :messages).detect { |msg| msg.keys == [message_name] }[message_name] expect(message_contents).to include(key => boolean) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/cucumber_steps.rb
features/lib/step_definitions/cucumber_steps.rb
# frozen_string_literal: true Given('a directory without standard Cucumber project directory structure') do FileUtils.cd('.') do FileUtils.rm_rf 'features' if File.directory?('features') end end Given('log only formatter is declared') do write_file('features/support/log_only_formatter.rb', [ 'class LogOnlyFormatter', ' attr_reader :io', '', ' def initialize(config)', ' @io = config.out_stream', ' end', '', ' def attach(src, media_type, _filename)', ' @io.puts(src)', ' end', 'end' ].join("\n")) end Then('exactly these files should be loaded: {list}') do |files| expect(command_line.stdout.scan(/^ \* (.*\.rb)$/).flatten).to eq files end Then('exactly these features should be run: {list}') do |files| expect(command_line.stdout.scan(/^ \* (.*\.feature)$/).flatten).to eq files end Then('{string} should not be required') do |file_name| expect(command_line.stdout).not_to include("* #{file_name}") end Then('{string} should be required') do |file_name| expect(command_line.stdout).to include("* #{file_name}") end Then('it fails before running features with:') do |expected| expect(command_line.all_output).to start_with_output(expected) expect(command_line).to have_failed end Then('the file {string} should contain:') do |path, content| expect(File.read(path)).to include(content) end When('I rerun the previous command with the same seed') do previous_seed = command_line.stdout.match(/with seed (\d+)/)[1] execute_extra_cucumber(command_line.args.gsub(/random/, "random:#{previous_seed}")) end Then('the output of both commands should be the same') do expect(command_line.stdout).to be_similar_output_than(last_extra_command.stdout) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/scenarios_and_steps.rb
features/lib/step_definitions/scenarios_and_steps.rb
# frozen_string_literal: true Given('the standard step definitions') do write_file( 'features/step_definitions/steps.rb', [ step_definition('/^this step passes$/', ''), step_definition('/^this step raises an error$/', "raise 'error'"), step_definition('/^this step is pending$/', 'pending'), step_definition('/^this step fails$/', 'fail'), step_definition('/^this step is a table step$/', '|t|') ].join("\n") ) end Given('a scenario with a step that looks like this:') do |string| create_feature do create_scenario { string } end end Given('a scenario with a step that looks like this in japanese:') do |string| create_feature_ja do create_scenario_ja { string } end end Given('a scenario {string} that passes') do |name| create_feature(name) do create_scenario(name) do " Given it passes in #{name}" end end write_file( "features/step_definitions/#{name}_steps.rb", step_definition("/^it passes in #{name}$/", 'expect(true).to be true') ) end Given('a scenario {string} that fails') do |name| create_feature(name) do create_scenario(name) do " Given it fails in #{name}" end end write_file( "features/step_definitions/#{name}_steps.rb", step_definition("/^it fails in #{name}$/", 'expect(false).to be true') ) end Given('a scenario {string} that fails once, then passes') do |full_name| name = snake_case(full_name) create_feature("#{full_name} feature") do create_scenario(full_name) do " Given it fails once, then passes in #{full_name}" end end write_file( "features/step_definitions/#{name}_steps.rb", step_definition( "/^it fails once, then passes in #{full_name}$/", [ "$#{name} += 1", "expect($#{name}).to be > 1" ] ) ) write_file( "features/support/#{name}_init.rb", " $#{name} = 0" ) end Given('a scenario {string} that fails twice, then passes') do |full_name| name = snake_case(full_name) create_feature("#{full_name} feature") do create_scenario(full_name) do " Given it fails twice, then passes in #{full_name}" end end write_file( "features/step_definitions/#{name}_steps.rb", step_definition( "/^it fails twice, then passes in #{full_name}$/", [ "$#{name} ||= 0", "$#{name} += 1", "expect($#{name}).to be > 2" ] ) ) write_file( "features/support/#{name}_init.rb", " $#{name} = 0" ) end Given('a step definition that looks like this:') do |content| write_file("features/step_definitions/steps#{SecureRandom.uuid}.rb", content) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/filesystem_steps.rb
features/lib/step_definitions/filesystem_steps.rb
# frozen_string_literal: true Given('a directory named {string}') do |path| FileUtils.mkdir_p(path) end Given('a file named {string} with:') do |path, content| write_file(path, content) end Given('an empty file named {string}') do |path| write_file(path, '') end Then('a file named {string} should exist') do |path| expect(File.file?(path)).to be true end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/json_steps.rb
features/lib/step_definitions/json_steps.rb
# frozen_string_literal: true Then('it should fail with JSON:') do |json| expect(command_line).to have_failed actual = normalise_json(JSON.parse(command_line.stdout)) expected = JSON.parse(json) expect(actual).to eq expected end Then('it should pass with JSON:') do |json| expect(command_line).to have_succeded actual = normalise_json(JSON.parse(command_line.stdout)) expected = JSON.parse(json) expect(actual).to eq expected end Then('file {string} should contain JSON:') do |filename, json| actual = normalise_json(JSON.parse(File.read(filename))) expected = JSON.parse(json) expect(actual).to eq expected end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/html_steps.rb
features/lib/step_definitions/html_steps.rb
# frozen_string_literal: true Then('output should be html with title {string}') do |title| document = Nokogiri::HTML.parse(command_line.stdout) expect(document.xpath('//title').text).to eq(title) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/features/lib/step_definitions/cucumber_cli_steps.rb
features/lib/step_definitions/cucumber_cli_steps.rb
# frozen_string_literal: true Then('I should see the CLI help') do expect(command_line.stdout).to include('Usage:') end Then('cucumber lists all the supported languages') do sample_languages = %w[Arabic Π±ΡŠΠ»Π³Π°Ρ€ΡΠΊΠΈ Pirate English ζ—₯本θͺž] sample_languages.each do |language| expect(command_line.stdout.force_encoding('utf-8')).to include(language) end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true ENV['CUCUMBER_COLORS'] = nil $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'simplecov_setup' require 'cucumber' RSpec.configure do |c| c.before { Cucumber::Term::ANSIColor.coloring = true } end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/support/standard_step_actions.rb
spec/support/standard_step_actions.rb
# frozen_string_literal: true # Filter that activates steps with obvious pass / fail behaviour class StandardStepActions < Cucumber::Core::Filter.new def test_case(test_case) test_steps = test_case.test_steps.map do |step| case step.text when /fail/ step.with_action { raise Failure } when /pass/ step.with_action {} else step end end test_case.with_steps(test_steps).describe_to(receiver) end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/support/fake_objects.rb
spec/support/fake_objects.rb
# frozen_string_literal: true require 'cucumber/core/filter' # The following fake objects was previously declared within `describe` scope. # Declaring into scope did not isolate them. # # Moving these into a dedicated support file explicitly states that these are available globally as soon as they are required once. module FakeObjects module ModuleOne def method_one 1 end end module ModuleTwo def method_one 2 end def method_two 2 end end module ModuleThree def method_three 3 end end class Actor attr_accessor :name def initialize(name) @name = name end end class FlakyStepActions < ::Cucumber::Core::Filter.new def test_case(test_case) failing_test_steps = test_case.test_steps.map do |step| step.with_action { raise Failure } end passing_test_steps = test_case.test_steps.map do |step| step.with_action {} end test_case.with_steps(failing_test_steps).describe_to(receiver) test_case.with_steps(passing_test_steps).describe_to(receiver) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/support/shared_context/http_server.rb
spec/support/shared_context/http_server.rb
RSpec.shared_context 'an HTTP server accepting file requests' do subject(:server) { http_server_class.new } let(:http_server_class) do Class.new do attr_reader :read_io, :write_io, :received_headers, :request_count attr_accessor :received_body_io def initialize @read_io, @write_io = IO.pipe @received_headers = [] @request_count = 0 @received_body_io = StringIO.new end def webrick_options @webrick_options ||= default_options end private def default_options { Port: 0, Logger: WEBrick::Log.new(File.open(File::NULL, 'w')), AccessLog: [], StartCallback: proc do write_io.write(1) # write "1", signal a server start message write_io.close end } end end end let(:putreport_returned_location) { URI('/s3').to_s } let(:success_banner) do [ 'View your Cucumber Report at:', 'https://reports.cucumber.io/reports/<some-random-uid>' ].join("\n") end let(:failure_banner) { 'Oh noooo, something went horribly wrong :(' } let(:server_url) { "http://localhost:#{@server.config[:Port]}" } before do @server = WEBrick::HTTPServer.new(server.webrick_options) @request_count = 0 mount_s3_endpoint mount_404_endpoint mount_401_endpoint mount_report_endpoint mount_redirect_endpoint Thread.new { @server.start } server.read_io.read(1) # read a byte for the server start signal server.read_io.close end after do @server&.shutdown end private def mount_s3_endpoint @server.mount_proc '/s3' do |req, res| @request_count += 1 IO.copy_stream(req.body_reader, server.received_body_io) server.received_headers << req.header if req['authorization'] res.status = 400 res.body = 'Do not send Authorization header to S3' end end end def mount_404_endpoint @server.mount_proc '/404' do |req, res| @request_count += 1 server.received_headers << req.header res.status = 404 res.header['Content-Type'] = 'text/plain;charset=utf-8' res.body = failure_banner end end def mount_401_endpoint @server.mount_proc '/401' do |req, res| @request_count += 1 server.received_headers << req.header res.status = 401 res.header['Content-Type'] = 'text/plain;charset=utf-8' res.body = failure_banner end end def mount_report_endpoint @server.mount_proc '/putreport' do |req, res| @request_count += 1 IO.copy_stream(req.body_reader, server.received_body_io) server.received_headers << req.header if req.request_method == 'GET' res.status = 202 # Accepted res.header['location'] = putreport_returned_location if putreport_returned_location res.header['Content-Type'] = 'text/plain;charset=utf-8' res.body = success_banner else res.set_redirect( WEBrick::HTTPStatus::TemporaryRedirect, '/s3' ) end end end def mount_redirect_endpoint @server.mount_proc '/loop_redirect' do |req, res| @request_count += 1 server.received_headers << req.header res.set_redirect( WEBrick::HTTPStatus::TemporaryRedirect, '/loop_redirect' ) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/hooks_spec.rb
spec/cucumber/hooks_spec.rb
# frozen_string_literal: true require 'cucumber/hooks' module Cucumber module Hooks shared_examples_for 'a source node' do it 'responds to text' do expect(subject.text).to be_a(String) end it 'responds to location' do expect(subject.location).to eq(location) end it 'responds to match_locations?' do expect(subject).to be_match_locations([location]) expect(subject).not_to be_match_locations([]) end end require 'cucumber/core/test/location' describe BeforeHook do subject { described_class.new(location) } let(:location) { Cucumber::Core::Test::Location.new('hooks.rb', 1) } it_behaves_like 'a source node' end describe AfterHook do subject { described_class.new(location) } let(:location) { Cucumber::Core::Test::Location.new('hooks.rb', 1) } it_behaves_like 'a source node' end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/cucumber_spec.rb
spec/cucumber/cucumber_spec.rb
# frozen_string_literal: true describe Cucumber do describe '.deprecate' do it 'outputs a message to $stderr' do allow(Kernel).to receive(:warn) expect(Kernel).to receive(:warn).with( a_string_including('WARNING: #some_method is deprecated and will be removed after version 1.0.0. Use #some_other_method instead.') ) described_class.deprecate('Use #some_other_method instead', '#some_method', '1.0.0') end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/query_spec.rb
spec/cucumber/query_spec.rb
# frozen_string_literal: true def source_names %w[attachments empty hooks minimal rules] end def sources source_names.map { |name| "#{Dir.pwd}/spec/support/#{name}.ndjson" } end def queries { 'findAllPickles' => ->(query) { query.find_all_pickles.length }, 'findAllTestCases' => ->(query) { query.find_all_test_cases.length }, 'findAllTestSteps' => ->(query) { query.find_all_test_steps.length }, 'findTestCaseBy' => lambda do |query| results = {} results['testCaseStarted'] = query.find_all_test_case_started.map { |message| query.find_test_case_by(message).id } results['testCaseFinished'] = query.find_all_test_case_finished.map { |message| query.find_test_case_by(message).id } results['testStepStarted'] = query.find_all_test_step_started.map { |message| query.find_test_case_by(message).id } results['testStepFinished'] = query.find_all_test_step_finished.map { |message| query.find_test_case_by(message).id } results end, 'findPickleBy' => lambda do |query| results = {} results['testCaseStarted'] = query.find_all_test_case_started.map { |message| query.find_pickle_by(message).name } results['testCaseFinished'] = query.find_all_test_case_finished.map { |message| query.find_pickle_by(message).name } results['testStepStarted'] = query.find_all_test_step_started.map { |message| query.find_pickle_by(message).name } results['testStepFinished'] = query.find_all_test_step_finished.map { |message| query.find_pickle_by(message).name } results end } end def list_of_tests sources.flat_map do |source| queries.map do |query_name, query_proc| { cck_spec: source, query_name:, query_proc: } end end end require 'cucumber/query' require 'cucumber/messages' require_relative '../../compatibility/support/cck/helpers' describe Cucumber::Query do include CCK::Helpers subject(:query) { described_class.new(repository) } let(:repository) { Cucumber::Repository.new } list_of_tests.each do |test| describe "executes the query '#{test[:query_name]}' against the CCK definition '#{test[:cck_spec]}'" do let(:cck_messages) { parse_ndjson_file(test[:cck_spec]).map.itself } let(:filename_to_check) { test[:cck_spec].sub('.ndjson', ".#{test[:query_name]}.results.json") } before { cck_messages.each { |message| repository.update(message) } } it 'returns the expected query result' do evaluated_query = test[:query_proc].call(query) expected_query_result = JSON.parse(File.read(filename_to_check)) expect(evaluated_query).to eq(expected_query_result) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/project_initializer_spec.rb
spec/cucumber/project_initializer_spec.rb
# frozen_string_literal: true describe Cucumber::ProjectInitializer do let(:command_line_config) { described_class.new } before { allow(command_line_config).to receive(:puts) } context 'when there are no existing files' do around(:example) do |example| dir = Dir.mktmpdir original_dir = Dir.pwd begin FileUtils.cd(dir) example.call ensure FileUtils.cd(original_dir) FileUtils.rm_rf(dir) end end it 'still creates a features directory' do expect(command_line_config).to receive(:puts).with('creating features') command_line_config.run end it 'still creates a step_definitions directory' do expect(command_line_config).to receive(:puts).with('creating features/step_definitions') command_line_config.run end it 'still creates a support directory' do expect(command_line_config).to receive(:puts).with('creating features/support') command_line_config.run end it 'still creates an env.rb file' do expect(command_line_config).to receive(:puts).with('creating features/support/env.rb') command_line_config.run end end context 'when there are existing files' do around(:example) do |example| dir = Dir.mktmpdir FileUtils.mkdir_p("#{dir}/features") FileUtils.mkdir_p("#{dir}/features/step_definitions") FileUtils.mkdir_p("#{dir}/features/support") FileUtils.touch("#{dir}/features/support/env.rb") original_dir = Dir.pwd begin FileUtils.cd(dir) example.call ensure FileUtils.cd(original_dir) FileUtils.rm_rf(dir) end end it 'does not create a features directory' do expect(command_line_config).to receive(:puts).with('features already exists') command_line_config.run end it 'does not create a step_definitions directory' do expect(command_line_config).to receive(:puts).with('features/step_definitions already exists') command_line_config.run end it 'does not create a support directory' do expect(command_line_config).to receive(:puts).with('features/support already exists') command_line_config.run end it 'does not create an env.rb file' do expect(command_line_config).to receive(:puts).with('features/support/env.rb already exists') command_line_config.run end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/configuration_spec.rb
spec/cucumber/configuration_spec.rb
# frozen_string_literal: true require 'spec_helper' module Cucumber describe Configuration do describe '.default' do subject { described_class.default } it 'has an autoload_code_paths containing the standard support and step_definitions folders' do expect(subject.autoload_code_paths).to include('features/support') expect(subject.autoload_code_paths).to include('features/step_definitions') end end describe 'with custom user options' do let(:user_options) { { autoload_code_paths: ['foo/bar/baz'] } } subject { described_class.new(user_options) } it 'allows you to override the defaults' do expect(subject.autoload_code_paths).to eq ['foo/bar/baz'] end end context 'when selecting the files to load' do def given_the_following_files(*files) allow(File).to receive(:directory?).and_return(true) allow(File).to receive(:file?).and_return(true) allow(Dir).to receive(:[]) { files } end it 'requires env.rb files first' do configuration = described_class.new given_the_following_files('/features/support/a_file.rb', '/features/support/env.rb') expect(configuration.support_to_load).to eq(%w[/features/support/env.rb /features/support/a_file.rb]) end it 'features/support/env.rb is loaded before any other features/**/support/env.rb file' do configuration = described_class.new given_the_following_files( '/features/foo/support/env.rb', '/features/foo/support/a_file.rb', '/features/foo/bar/support/env.rb', '/features/foo/bar/support/a_file.rb', '/features/support/a_file.rb', '/features/support/env.rb' ) expect(configuration.support_to_load).to eq( %w[ /features/support/env.rb /features/foo/support/env.rb /features/foo/bar/support/env.rb /features/support/a_file.rb /features/foo/support/a_file.rb /features/foo/bar/support/a_file.rb ] ) end it 'requires step defs in vendor/{plugins,gems}/*/cucumber/*.rb' do given_the_following_files('/vendor/gems/gem_a/cucumber/bar.rb', '/vendor/plugins/plugin_a/cucumber/foo.rb') configuration = described_class.new expect(configuration.step_defs_to_load).to eq(%w[/vendor/gems/gem_a/cucumber/bar.rb /vendor/plugins/plugin_a/cucumber/foo.rb]) end describe '--exclude' do it 'excludes a ruby file from requiring when the name matches exactly' do given_the_following_files('/features/support/a_file.rb', '/features/support/env.rb') configuration = described_class.new(excludes: [/a_file.rb/]) expect(configuration.all_files_to_load).to eq(['/features/support/env.rb']) end it 'excludes all ruby files that match the provided patterns from requiring' do given_the_following_files('/features/support/foof.rb', '/features/support/bar.rb', '/features/support/food.rb', '/features/blah.rb', '/features/support/fooz.rb') configuration = described_class.new(excludes: [/foo[df]/, /blah/]) expect(configuration.all_files_to_load).to eq(%w[/features/support/bar.rb /features/support/fooz.rb]) end end end context 'when selecting feature files' do it 'preserves the order of the feature files' do configuration = described_class.new(paths: %w[b.feature c.feature a.feature]) expect(configuration.feature_files).to eq ['b.feature', 'c.feature', 'a.feature'] end it 'searchs for all features in the specified directory' do allow(File).to receive(:directory?).and_return(true) allow(Dir).to receive(:[]).with('feature_directory/**/*.feature').and_return(['cucumber.feature']) configuration = described_class.new(paths: %w[feature_directory/]) expect(configuration.feature_files).to eq ['cucumber.feature'] end it 'defaults to the features directory when no feature file are provided' do allow(File).to receive(:directory?).and_return(true) allow(Dir).to receive(:[]).with('features/**/*.feature').and_return(['cucumber.feature']) configuration = described_class.new(paths: []) expect(configuration.feature_files).to eq ['cucumber.feature'] end it 'gets the feature files from the rerun file' do allow(File).to receive(:directory?).and_return(false) allow(File).to receive(:file?).and_return(true) allow(IO).to receive(:read).and_return( "cucumber.feature:1:3\ncucumber.feature:5 cucumber.feature:10\n"\ "domain folder/different cuke.feature:134 domain folder/cuke.feature:1\n"\ 'domain folder/different cuke.feature:4:5 bar.feature' ) configuration = described_class.new(paths: %w[@rerun.txt]) expect(configuration.feature_files).to eq [ 'cucumber.feature:1:3', 'cucumber.feature:5', 'cucumber.feature:10', 'domain folder/different cuke.feature:134', 'domain folder/cuke.feature:1', 'domain folder/different cuke.feature:4:5', 'bar.feature' ] end end describe '#with_options' do it 'returns a copy of the configuration with new options' do old_out_stream = double('Old out_stream') new_out_stream = double('New out_stream') config = described_class.new(out_stream: old_out_stream).with_options(out_stream: new_out_stream) expect(config.out_stream).to eq new_out_stream end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/runtime_spec.rb
spec/cucumber/runtime_spec.rb
# frozen_string_literal: true require 'spec_helper' module Cucumber describe Runtime do subject { described_class.new(options) } let(:options) { {} } describe '#features_paths' do let(:options) { { paths: ['foo/bar/baz.feature', 'foo/bar/features/baz.feature', 'other_features'] } } it 'returns the value from configuration.paths' do expect(subject.features_paths).to eq options[:paths] end end describe '#doc_string' do it 'is creates an object equal to a string' do expect(subject.doc_string('Text')).to eq 'Text' end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/constantize_spec.rb
spec/cucumber/constantize_spec.rb
# frozen_string_literal: true require 'spec_helper' module Html end module Cucumber describe Constantize do include described_class it 'loads pretty formatter' do clazz = constantize('Cucumber::Formatter::Pretty') expect(clazz.name).to eq 'Cucumber::Formatter::Pretty' end it 'fails to load a made up class' do expect { constantize('My::MadeUp::ClassName') }.to raise_error(LoadError) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/step_match_search_spec.rb
spec/cucumber/step_match_search_spec.rb
# frozen_string_literal: true require 'cucumber/step_match_search' require 'cucumber/glue/dsl' require 'cucumber/glue/registry_and_more' require 'cucumber/configuration' module Cucumber describe StepMatchSearch do let(:search) { described_class.new(registry.method(:step_matches), configuration) } let(:registry) { Glue::RegistryAndMore.new(double, configuration) } let(:configuration) { Configuration.new(options) } let(:options) { {} } let(:dsl) do # TODO: stop relying on implicit global state registry Object.new.extend(Glue::Dsl) end it 'caches step match results' do dsl.Given(/it (.*) in (.*)/) { |what, month| } step_match = search.call('it snows in april').first expect(registry).not_to receive(:step_matches) second_step_match = search.call('it snows in april').first expect(step_match).to equal(second_step_match) end describe 'resolving step definition matches' do let(:elongated_error_message) do %{Ambiguous match of "Three blind mice": spec/cucumber/step_match_search_spec.rb:\\d+:in `/Three (.*) mice/' spec/cucumber/step_match_search_spec.rb:\\d+:in `/Three blind (.*)/' You can run again with --guess to make Cucumber be more smart about it } end it 'raises Ambiguous error with guess hint when multiple step definitions match' do dsl.Given(/Three (.*) mice/) { |disability| } dsl.Given(/Three blind (.*)/) { |animal| } expect { search.call('Three blind mice').first }.to raise_error(Ambiguous, /#{elongated_error_message}/) end describe 'when --guess is used' do let(:options) { { guess: true } } let(:elongated_error_message) do %{Ambiguous match of "Three cute mice": spec/cucumber/step_match_search_spec.rb:\\d+:in `/Three (.*) mice/' spec/cucumber/step_match_search_spec.rb:\\d+:in `/Three cute (.*)/' } end it 'does not show --guess hint' do dsl.Given(/Three (.*) mice/) { |disability| } dsl.Given(/Three cute (.*)/) { |animal| } expect { search.call('Three cute mice').first }.to raise_error(Ambiguous, /#{elongated_error_message}/) end it 'does not raise Ambiguous error when multiple step definitions match' do dsl.Given(/Three (.*) mice/) { |disability| } dsl.Given(/Three (.*)/) { |animal| } expect { search.call('Three blind mice').first }.not_to raise_error end it 'picks right step definition when an equal number of capture groups' do right = dsl.Given(/Three (.*) mice/) { |disability| } _wrong = dsl.Given(/Three (.*)/) { |animal| } expect(search.call('Three blind mice').first.step_definition).to eq right end it 'picks right step definition when an unequal number of capture groups' do right = dsl.Given(/Three (.*) mice ran (.*)/) { |disability| } _wrong = dsl.Given(/Three (.*)/) { |animal| } expect(search.call('Three blind mice ran far').first.step_definition).to eq right end it 'picks most specific step definition when an unequal number of capture groups' do _general = dsl.Given(/Three (.*) mice ran (.*)/) { |disability| } _specific = dsl.Given(/Three blind mice ran far/) {} more_specific = dsl.Given(/^Three blind mice ran far$/) {} expect(search.call('Three blind mice ran far').first.step_definition).to eq more_specific end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/events_spec.rb
spec/cucumber/events_spec.rb
# frozen_string_literal: true module Cucumber describe Events do it 'builds a registry without failing' do expect { described_class.registry }.not_to raise_error end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/running_test_case_spec.rb
spec/cucumber/running_test_case_spec.rb
# frozen_string_literal: true require 'cucumber/running_test_case' require 'cucumber/core' require 'cucumber/core/gherkin/writer' module Cucumber describe RunningTestCase do include Core include Core::Gherkin::Writer attr_accessor :wrapped_test_case, :core_test_case let(:result) { double(:result, to_sym: :status_symbol) } before do receiver = double.as_null_object allow(receiver).to receive(:test_case) { |core_test_case| self.core_test_case = core_test_case self.wrapped_test_case = described_class.new(core_test_case).with_result(result) } compile [gherkin_doc], receiver end context 'with a regular scenario' do let(:gherkin_doc) do gherkin do feature 'feature name' do scenario 'scenario name' do step 'passing' end end end end it 'sets the scenario name correctly' do expect(wrapped_test_case.name).to eq 'scenario name' end it 'exposes properties of the test_case' do expect(wrapped_test_case.location).to eq core_test_case.location expect(wrapped_test_case.language).to eq core_test_case.language end it 'exposes properties of the result' do expect(wrapped_test_case.status).to eq result.to_sym end end context 'with a failing scenario' do let(:gherkin_doc) do gherkin do feature 'feature name' do scenario 'scenario name' do step 'failed' end end end end let(:exception) { StandardError.new } before do self.wrapped_test_case = wrapped_test_case.with_result(Core::Test::Result::Failed.new(0, exception)) end it 'is failed?' do expect(wrapped_test_case).to be_failed end it 'exposes the exception' do expect(wrapped_test_case.exception).to eq exception end end context 'with a passing scenario' do let(:gherkin_doc) do gherkin do feature 'feature name' do scenario 'scenario name' do step 'passing' end end end end before do self.wrapped_test_case = wrapped_test_case.with_result(Core::Test::Result::Passed.new(0)) end it 'is not failed?' do expect(wrapped_test_case).not_to be_failed end it '#exception is nil' do expect(wrapped_test_case.exception).to be_nil end end context 'when using a scenario outline' do let(:gherkin_doc) do gherkin do feature 'feature name' do scenario_outline 'scenario outline name' do step 'passing with <arg1> <arg2>' examples 'examples name' do row 'arg1', 'arg2' row 'a', 'b' end end end end end it "sets the test case's name correctly" do expect(wrapped_test_case.name).to eq('scenario outline name') end it 'exposes properties of the test_case' do expect(wrapped_test_case.location).to eq(core_test_case.location) expect(wrapped_test_case.language).to eq(core_test_case.language) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/step_match_spec.rb
spec/cucumber/step_match_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/glue/step_definition' require 'cucumber/glue/registry_and_more' module Cucumber describe StepMatch do let(:word) { '[[:word:]]' } before do @registry = Glue::RegistryAndMore.new(nil, Configuration.new) end def stepdef(string_or_regexp) Glue::StepDefinition.new('some-id', @registry, string_or_regexp, -> {}, {}) end def step_match(regexp, name) stepdef = stepdef(regexp) StepMatch.new(stepdef, name, stepdef.arguments_from(name)) end it 'formats step names' do m = step_match(/it (.*) in (.*)/, 'it snows in april') format = m.format_args('[%s]') expect(format).to eq 'it [snows] in [april]' end it 'formats one group when we use Unicode' do m = step_match(/I (#{word}+) ok/, 'I æøΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ… ok') expect(m.format_args('<span>%s</span>')).to eq 'I <span>æøΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…</span> ok' end it 'formats several groups when we use Unicode' do m = step_match(/I (#{word}+) (#{word}+) (#{word}+) this (#{word}+)/, 'I ate æøΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ… egg this morning') expect(m.format_args('<span>%s</span>')).to eq 'I <span>ate</span> <span>æøΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…Γ¦ΓΈΓ₯Γ†Γ˜Γ…</span> <span>egg</span> this <span>morning</span>' end it 'deals with Unicode both inside and outside arguments' do expect('JΓ¦ vΓΈ Γ₯lsker dΓΈtte lΓΈndet').to match(/JΓ¦ (.+) Γ₯lsker (.+) lΓΈndet/) m = step_match(/JΓ¦ (#{word}+) Γ₯lsker (#{word}+) lΓΈndet/, 'JΓ¦ vΓΈ Γ₯lsker dΓΈtte lΓΈndet') expect(m.format_args('<span>%s</span>')).to eq 'JΓ¦ <span>vΓΈ</span> Γ₯lsker <span>dΓΈtte</span> lΓΈndet' end it 'formats groups with format string' do m = step_match(/I (#{word}+) (\d+) (#{word}+) this (#{word}+)/, 'I ate 1 egg this morning') expect(m.format_args('<span>%s</span>')).to eq 'I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>' end it 'formats groups with format string when there are dupes' do m = step_match(/I (#{word}+) (\d+) (#{word}+) this (#{word}+)/, 'I bob 1 bo this bobs') expect(m.format_args('<span>%s</span>')).to eq 'I <span>bob</span> <span>1</span> <span>bo</span> this <span>bobs</span>' end it 'formats groups with block' do m = step_match(/I (#{word}+) (\d+) (#{word}+) this (#{word}+)/, 'I ate 1 egg this morning') expect(m.format_args(&->(msg) { "<span>#{msg}</span>" })).to eq 'I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>' end it 'formats groups with proc object' do m = step_match(/I (#{word}+) (\d+) (#{word}+) this (#{word}+)/, 'I ate 1 egg this morning') expect(m.format_args(->(msg) { "<span>#{msg}</span>" })).to eq 'I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>' end it 'formats groups even when first group is optional and not matched' do m = step_match(/should( not)? be flashed '([^']*?)'$/, "I should be flashed 'Login failed.'") expect(m.format_args('<span>%s</span>')).to eq "I should be flashed '<span>Login failed.</span>'" end it 'formats embedded groups' do m = step_match(/running( (\d+) times)? (\d+) meters/, 'running 5 times 10 meters') expect(m.format_args('<span>%s</span>')).to eq 'running<span> 5 times</span> <span>10</span> meters' end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/file_specs_spec.rb
spec/cucumber/file_specs_spec.rb
# frozen_string_literal: true require 'cucumber/file_specs' module Cucumber describe FileSpecs do let(:file_specs) { described_class.new(['features/foo.feature:1:2:3', 'features/bar.feature:4:5:6']) } let(:locations) { file_specs.locations } let(:files) { file_specs.files } it 'parses locations from multiple files' do expect(locations.length).to eq 6 expect(locations).to eq [ Cucumber::Core::Test::Location.new('features/foo.feature', 1), Cucumber::Core::Test::Location.new('features/foo.feature', 2), Cucumber::Core::Test::Location.new('features/foo.feature', 3), Cucumber::Core::Test::Location.new('features/bar.feature', 4), Cucumber::Core::Test::Location.new('features/bar.feature', 5), Cucumber::Core::Test::Location.new('features/bar.feature', 6) ] end it 'parses file names from multiple file specs' do expect(files.length).to eq 2 expect(files).to eq [ 'features/foo.feature', 'features/bar.feature' ] end context 'when files are not unique' do let(:file_specs) { described_class.new(['features/foo.feature:4', 'features/foo.feature:34']) } it 'parses unique file names' do expect(files.length).to eq 1 expect(files).to eq ['features/foo.feature'] end end context 'when no line number is specified' do let(:file_specs) { described_class.new(['features/foo.feature', 'features/bar.feature:34']) } it 'returns a wildcard location for that file' do expect(locations).to eq [ Cucumber::Core::Test::Location.new('features/foo.feature'), Cucumber::Core::Test::Location.new('features/bar.feature', 34) ] end end context 'when the same file is referenced more than once' do let(:file_specs) { described_class.new(['features/foo.feature:10', 'features/foo.feature:1']) } it 'returns locations in the order specified' do expect(locations).to eq [ Cucumber::Core::Test::Location.new('features/foo.feature', 10), Cucumber::Core::Test::Location.new('features/foo.feature', 1) ] end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/multiline_argument/data_table_spec.rb
spec/cucumber/multiline_argument/data_table_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/multiline_argument/data_table' module Cucumber module MultilineArgument describe DataTable do subject(:table) { described_class.from([%w[one four seven], %w[4444 55555 666666]]) } it 'has rows' do expect(table.cells_rows[0].map(&:value)).to eq(%w[one four seven]) end it 'has columns' do expect(table.columns[1].map(&:value)).to eq(%w[four 55555]) end it 'has same cell objects in rows and columns' do expect(table.cells_rows[1][2]).to eq(table.columns[2][1]) end it 'is convertible to an array of hashes' do expect(table.hashes).to eq([{ 'one' => '4444', 'four' => '55555', 'seven' => '666666' }]) end it 'accepts symbols as keys for the hashes' do expect(table.hashes.first[:one]).to eq('4444') end it 'returns the row values in order' do expect(table.rows.first).to eq(%w[4444 55555 666666]) end describe '#symbolic_hashes' do it 'converts data table to an array of hashes with symbols as keys' do ast_table = Cucumber::Core::Test::DataTable.new([['foo', 'Bar', 'Foo Bar'], %w[1 22 333]]) data_table = described_class.new(ast_table) expect(data_table.symbolic_hashes).to eq([{ foo: '1', bar: '22', foo_bar: '333' }]) end it 'is able to be accessed multiple times' do table.symbolic_hashes expect { table.symbolic_hashes }.not_to raise_error end it 'does not interfere with use of #hashes' do table.symbolic_hashes expect { table.hashes }.not_to raise_error end end describe '#map_column' do it 'allows mapping columns' do new_table = table.map_column('one', &:to_i) expect(new_table.hashes.first['one']).to eq(4444) end it 'applies the block once to each value when #rows are interrogated' do rows = ['value'] table = described_class.from [['header'], rows] count = 0 table.map_column('header') { count += 1 }.rows expect(count).to eq(rows.length) end it 'allows mapping columns taking a symbol as the column name' do new_table = table.map_column(:one, &:to_i) expect(new_table.hashes.first['one']).to eq 4444 end it 'allows mapping columns and modify the rows as well' do new_table = table.map_column(:one, &:to_i) expect(new_table.rows.first).to include(4444) expect(new_table.rows.first).not_to include('4444') end it 'passes silently once #hashes are interrogated if a mapped column does not exist in non-strict mode' do expect do new_table = table.map_column('two', strict: false, &:to_i) new_table.hashes end.not_to raise_error end it 'fails once #hashes are interrogated if a mapped column does not exist in strict mode' do expect do new_table = table.map_column('two', strict: true, &:to_i) new_table.hashes end.to raise_error('The column named "two" does not exist') end it 'returns a new table' do expect(table.map_column(:one, &:to_i)).not_to eq(table) end end describe '#match' do it 'returns nil if headers do not match' do expect(table.match('does,not,match')).to be_nil end it 'requires a table: prefix on match' do expect(table.match('table:one,four,seven')).not_to be_nil end it 'does not match if no table: prefix on match' do expect(table.match('one,four,seven')).to be_nil end end describe '#transpose' do it 'is convertible in to an array where each row is a hash' do expect(table.transpose.hashes[0]).to eq('one' => 'four', '4444' => '55555') end end describe '#rows_hash' do it 'returns a hash of the rows' do table = described_class.from([%w[one 1111], %w[two 22222]]) expect(table.rows_hash).to eq('one' => '1111', 'two' => '22222') end it "fails if the table doesn't have two columns" do faulty_table = described_class.from([%w[one 1111 abc], %w[two 22222 def]]) expect { faulty_table.rows_hash }.to raise_error('The table must have exactly 2 columns') end it 'supports header and column mapping' do table = described_class.from([%w[one 1111], %w[two 22222]]) t2 = table.map_headers({ 'two' => 'Two' }, &:upcase).map_column('two', strict: false, &:to_i) expect(t2.rows_hash).to eq('ONE' => '1111', 'Two' => 22_222) end end describe '#map_headers' do subject(:table) { described_class.from([%w[ANT ANTEATER], %w[4444 55555]]) } it 'renames the columns to the specified values in the provided hash' do table2 = table.map_headers('ANT' => :three) expect(table2.hashes.first[:three]).to eq('4444') end it 'allows renaming columns using regexp' do table2 = table.map_headers(/^ANT$|^BEE$/ => :three) expect(table2.hashes.first[:three]).to eq('4444') end it 'copies column mappings' do table2 = table.map_column('ANT', &:to_i) table3 = table2.map_headers('ANT' => 'three') expect(table3.hashes.first['three']).to eq(4444) end it 'takes a block and operates on all the headers with it' do table2 = table.map_headers(&:downcase) expect(table2.hashes.first.keys).to match %w[ant anteater] end it 'treats the mappings in the provided hash as overrides when used with a block' do table2 = table.map_headers('ANT' => 'foo', &:downcase) expect(table2.hashes.first.keys).to match %w[foo anteater] end end describe 'diff!' do it 'detects a complex diff' do t1 = described_class.from(%( | 1 | 22 | 333 | 4444 | | 55555 | 666666 | 7777777 | 88888888 | | 999999999 | 0000000000 | 01010101010 | 121212121212 | | 4000 | ABC | DEF | 50000 | )) t2 = described_class.from(%( | a | 4444 | 1 | | bb | 88888888 | 55555 | | ccc | xxxxxxxx | 999999999 | | dddd | 4000 | 300 | | e | 50000 | 4000 | )) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 14, color: false)).to eq %{ | 1 | (-) 22 | (-) 333 | 4444 | (+) a | | 55555 | (-) 666666 | (-) 7777777 | 88888888 | (+) bb | | (-) 999999999 | (-) 0000000000 | (-) 01010101010 | (-) 121212121212 | (+) | | (+) 999999999 | (+) | (+) | (+) xxxxxxxx | (+) ccc | | (+) 300 | (+) | (+) | (+) 4000 | (+) dddd | | 4000 | (-) ABC | (-) DEF | 50000 | (+) e | } end end it 'does not change table when diffed with identical' do t = described_class.from(%( |a|b|c| |d|e|f| |g|h|i| )) t.diff!(t.dup) expect(t.to_s(indent: 12, color: false)).to eq %( | a | b | c | | d | e | f | | g | h | i | ) end context 'with empty tables' do it 'allows diffing empty tables' do t1 = described_class.from([[]]) t2 = described_class.from([[]]) expect { t1.diff!(t2) }.not_to raise_error end it 'is able to diff when the right table is empty' do t1 = described_class.from(%( |a|b|c| |d|e|f| |g|h|i| )) t2 = described_class.from([[]]) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 16, color: false)).to eq %{ | (-) a | (-) b | (-) c | | (-) d | (-) e | (-) f | | (-) g | (-) h | (-) i | } end end it 'should be able to diff when the left table is empty' do t1 = described_class.from([[]]) t2 = described_class.from(%( |a|b|c| |d|e|f| |g|h|i| )) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 16, color: false)).to eq %{ | (+) a | (+) b | (+) c | | (+) d | (+) e | (+) f | | (+) g | (+) h | (+) i | } end end end context 'with duplicate header values' do it 'raises no error for two identical tables' do t = described_class.from(%( |a|a|c| |d|e|f| |g|h|i| )) t.diff!(t.dup) expect(t.to_s(indent: 12, color: false)).to eq %( | a | a | c | | d | e | f | | g | h | i | ) end it 'detects a diff in one cell' do t1 = described_class.from(%( |a|a|c| |d|e|f| |g|h|i| )) t2 = described_class.from(%( |a|a|c| |d|oops|f| |g|h|i| )) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 16, color: false)).to eq %{ | a | a | c | | (-) d | (-) e | (-) f | | (+) d | (+) oops | (+) f | | g | h | i | } end end it 'detects missing columns' do t1 = described_class.from(%( |a|a|b|c| |d|d|e|f| |g|g|h|i| )) t2 = described_class.from(%( |a|b|c| |d|e|f| |g|h|i| )) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 16, color: false)).to eq %{ | a | (-) a | b | c | | d | (-) d | e | f | | g | (-) g | h | i | } end end it 'detects surplus columns' do t1 = described_class.from(%( |a|b|c| |d|e|f| |g|h|i| )) t2 = described_class.from(%( |a|b|a|c| |d|e|d|f| |g|h|g|i| )) expect { t1.diff!(t2, surplus_col: true) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 16, color: false)).to eq %{ | a | b | c | (+) a | | d | e | f | (+) d | | g | h | i | (+) g | } end end end it 'inspects missing and surplus cells' do t1 = described_class.from([ %w[name male lastname swedish], %w[aslak true hellesΓΈy false] ]) t2 = described_class.from([ %w[name male lastname swedish], ['aslak', true, 'hellesΓΈy', false] ]) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 14, color: false)).to eq %{ | name | male | lastname | swedish | | (-) aslak | (-) (i) "true" | (-) hellesΓΈy | (-) (i) "false" | | (+) aslak | (+) (i) true | (+) hellesΓΈy | (+) (i) false | } end end it 'allows column mapping of target before diffing' do t1 = described_class.from([ %w[name male], %w[aslak true] ]) t2 = described_class.from([ %w[name male], ['aslak', true] ]) t1.map_column('male') { |m| m == 'true' }.diff!(t2) expect(t1.to_s(indent: 12, color: false)).to eq %( | name | male | | aslak | true | ) end it 'allows column mapping of argument before diffing' do t1 = described_class.from([ %w[name male], ['aslak', true] ]) t2 = described_class.from([ %w[name male], %w[aslak true] ]) t2.diff!(t1.map_column('male') { 'true' }) expect(t1.to_s(indent: 12, color: false)).to eq %( | name | male | | aslak | true | ) end it 'allows header mapping before diffing' do t1 = described_class.from([ %w[Name Male], %w[aslak true] ]) t1 = t1.map_headers('Name' => 'name', 'Male' => 'male') t1 = t1.map_column('male') { |m| m == 'true' } t2 = described_class.from([ %w[name male], ['aslak', true] ]) t1.diff!(t2) expect(t1.to_s(indent: 12, color: false)).to eq %( | name | male | | aslak | true | ) end it 'detects seemingly identical tables as different' do t1 = described_class.from([ %w[X Y], %w[2 1] ]) t2 = described_class.from([ %w[X Y], [2, 1] ]) expect { t1.diff!(t2) }.to raise_error(DataTable::Different) do |error| expect(error.table.to_s(indent: 14, color: false)).to eq %{ | X | Y | | (-) (i) "2" | (-) (i) "1" | | (+) (i) 2 | (+) (i) 1 | } end end it 'does not allow mappings that match more than 1 column' do t1 = described_class.from([ %w[Cuke Duke], %w[Foo Bar] ]) expect do t1 = t1.map_headers(/uk/ => 'u') t1.hashes end.to raise_error(%(2 headers matched /uk/: ["Cuke", "Duke"])) end describe 'raising' do before do @t = described_class.from(%( | a | b | | c | d | )) expect(@t).not_to eq nil end it 'raises on missing rows' do t = described_class.from(%( | a | b | )) expect { @t.dup.diff!(t) }.to raise_error(DataTable::Different) expect { @t.dup.diff!(t, missing_row: false) }.not_to raise_error end it 'does not raise on surplus rows when surplus is at the end' do t = described_class.from(%( | a | b | | c | d | | e | f | )) expect { @t.dup.diff!(t) }.to raise_error(DataTable::Different) expect { @t.dup.diff!(t, surplus_row: false) }.not_to raise_error end it 'does not raise on surplus rows when surplus is interleaved' do t1 = described_class.from(%( | row_1 | row_2 | | four | 4 | )) t2 = described_class.from(%( | row_1 | row_2 | | one | 1 | | two | 2 | | three | 3 | | four | 4 | | five | 5 | )) expect { t1.dup.diff!(t2) }.to raise_error(DataTable::Different) expect { t1.dup.diff!(t2, surplus_row: false) }.not_to raise_error end it 'raises on missing columns' do t = described_class.from(%( | a | | c | )) expect { @t.dup.diff!(t) }.to raise_error(DataTable::Different) expect { @t.dup.diff!(t, missing_col: false) }.not_to raise_error end it 'does not raise on surplus columns' do t = described_class.from(%( | a | b | x | | c | d | y | )) expect { @t.dup.diff!(t) }.not_to raise_error expect { @t.dup.diff!(t, surplus_col: true) }.to raise_error(DataTable::Different) end it 'does not raise on misplaced columns' do t = described_class.from(%( | b | a | | d | c | )) expect { @t.dup.diff!(t) }.not_to raise_error expect { @t.dup.diff!(t, misplaced_col: true) }.to raise_error(DataTable::Different) end end it 'can compare to an Array' do t = described_class.from(%( | b | a | | d | c | )) other = [%w[b a], %w[d c]] expect { t.diff!(other) }.not_to raise_error end end describe '#from' do it 'allows Array of Hash' do t1 = described_class.from([{ 'name' => 'aslak', 'male' => 'true' }]) expect(t1.to_s(indent: 12, color: false)).to eq %( | male | name | | true | aslak | ) end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/pretty_spec.rb
spec/cucumber/formatter/pretty_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/pretty' require 'cucumber/cli/options' module Cucumber module Formatter describe Pretty do extend SpecHelperDsl include SpecHelper context 'with no options' do before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out, source: false)) end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'outputs the scenario name' do expect(@out.string).to include('Scenario: Monkey eats banana') end it 'outputs the step' do expect(@out.string).to include('Given there are bananas') end end describe 'with a background' do define_feature <<~FEATURE Feature: Banana party Background: Given a tree Scenario: Monkey eats banana Given there are bananas FEATURE it 'outputs the gherkin' do expect(@out.string).to include(self.class.feature_content) end it 'outputs the scenario name' do expect(@out.string).to include('Scenario: Monkey eats banana') end it 'outputs the step' do expect(@out.string).to include('Given there are bananas') end end describe 'with a scenario outline' do define_feature <<-FEATURE Feature: Fud Pyramid Scenario Outline: Monkey eats a balanced diet Given there are <Things> Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | FEATURE it 'outputs the scenario outline' do lines = <<-OUTPUT Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | OUTPUT lines.split("\n").each do |line| expect(@out.string).to include(line.strip) end end it 'has 4 undefined scenarios' do expect(@out.string).to include('4 scenarios (4 undefined)') end it 'has 4 undefined steps' do expect(@out.string).to include('4 steps (4 undefined)') end context 'when the examples table header is wider than the rows' do define_feature <<-FEATURE Feature: Monkey Business Scenario Outline: Types of monkey Given there are <Types of monkey> Examples: | Types of monkey | | Hominidae | FEATURE it 'outputs the scenario outline' do lines = <<-OUTPUT Examples: | Types of monkey | | Hominidae | OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end end # To ensure https://rspec.lighthouseapp.com/projects/16211/tickets/475 remains fixed. describe 'with a scenario outline with a pystring' do define_feature <<-FEATURE Feature: Scenario Outline: Monkey eats a balanced diet Given a multiline string: """ Monkeys eat <things> """ Examples: | things | | apples | FEATURE it 'outputs the scenario outline' do lines = <<-OUTPUT Given a multiline string: """ Monkeys eat <things> """ Examples: | things | | apples | OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end describe 'with a step with a py string' do define_feature <<-FEATURE Feature: Traveling circus Scenario: Monkey goes to town Given there is a monkey called: """ foo """ FEATURE it 'displays the pystring nested' do expect(@out.string).to include <<OUTPUT """ foo """ OUTPUT end end describe 'with a multiline step arg' do define_feature <<-FEATURE Feature: Traveling circus Scenario: Monkey goes to town Given there are monkeys: | name | | foo | | bar | FEATURE it 'displays the multiline string' do expect(@out.string).to include <<OUTPUT Given there are monkeys: | name | | foo | | bar | OUTPUT end end describe 'with a table in the background and the scenario' do define_feature <<-FEATURE Feature: accountant monkey Background: Given table: | a | b | | c | d | Scenario: Given another table: | e | f | | g | h | FEATURE it 'displays the table for the background' do expect(@out.string).to include <<OUTPUT Given table: | a | b | | c | d | OUTPUT end it 'displays the table for the scenario' do expect(@out.string).to include <<OUTPUT Given another table: | e | f | | g | h | OUTPUT end end describe 'with a py string in the background and the scenario' do define_feature <<-FEATURE Feature: py strings Background: Given stuff: """ foo """ Scenario: Given more stuff: """ bar """ FEATURE it 'displays the background py string' do expect(@out.string).to include <<OUTPUT Given stuff: """ foo """ OUTPUT end it 'displays the scenario py string' do expect(@out.string).to include <<OUTPUT Given more stuff: """ bar """ OUTPUT end end describe 'with output from hooks' do define_feature <<-FEATURE Feature: Scenario: Given this step passes Scenario Outline: Given this step <status> Examples: | status | | passes | FEATURE define_steps do Before do log 'Before hook' end AfterStep do log 'AfterStep hook' end After do log 'After hook' end Given('this step passes') {} end it 'displays hook output appropriately ' do expect(@out.string).to include <<~OUTPUT Feature: Scenario: Before hook Given this step passes AfterStep hook After hook Scenario Outline: Given this step <status> Examples: | status | | passes | Before hook, AfterStep hook, After hook 2 scenarios (2 passed) 2 steps (2 passed) OUTPUT end end describe 'with background and output from hooks' do define_feature <<-FEATURE Feature: Background: Given this step passes Scenario: Given this step passes FEATURE define_steps do Before do log 'Before hook' end AfterStep do log 'AfterStep hook' end After do log 'After hook' end Given('this step passes') {} end it 'displays hook output appropriately' do expect(@out.string).to include <<~OUTPUT Feature: Background: Before hook Given this step passes AfterStep hook Scenario: Given this step passes AfterStep hook After hook 1 scenario (1 passed) 2 steps (2 passed) OUTPUT end end describe 'with tags on all levels' do define_feature <<-FEATURE @tag1 Feature: @tag2 Scenario: Given this step passes @tag3 Scenario Outline: Given this step passes @tag4 Examples: | dummy | | dummy | FEATURE it 'includes the tags in the output ' do expect(@out.string).to include <<~OUTPUT @tag1 Feature: @tag2 Scenario: Given this step passes @tag3 Scenario Outline: Given this step passes @tag4 Examples: | dummy | | dummy | OUTPUT end end describe 'with comments on all levels' do define_feature <<-FEATURE #comment1 Feature: #comment2 Background: #comment3 Given this step passes #comment4 Scenario: #comment5 Given this step passes #comment6 | dummy | #comment7 Scenario Outline: #comment8 Given this step passes #comment9 Examples: #comment10 | dummy | #comment11 | dummy | #comment12 FEATURE it 'includes the all comments in the output' do expect(@out.string).to include <<~OUTPUT #comment1 Feature: #comment2 Background: #comment3 Given this step passes #comment4 Scenario: #comment5 Given this step passes #comment6 | dummy | #comment7 Scenario Outline: #comment8 Given this step passes #comment9 Examples: #comment10 | dummy | #comment11 | dummy | #comment12 OUTPUT end end describe 'with the rule keyword' do define_feature <<-FEATURE Feature: Some rules Background: FB Given fb Rule: A The rule A description Background: AB Given ab Example: Example A Given a Rule: B The rule B description Example: Example B Given b FEATURE it 'ignores the rule keyword' do expect(@out.string).to include <<~OUTPUT Feature: Some rules Background: FB Given fb Given ab Example: Example A Given a Example: Example B Given b OUTPUT end end end end context 'with --no-multiline passed as an option' do before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out, source: false, no_multiline: true)) end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'outputs the scenario name' do expect(@out.string).to include 'Scenario: Monkey eats banana' end it 'outputs the step' do expect(@out.string).to include 'Given there are bananas' end end describe 'with a scenario outline' do define_feature <<-FEATURE Feature: Fud Pyramid Scenario Outline: Monkey eats a balanced diet Given there are <Things> Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | FEATURE it 'outputs the scenario outline' do lines = <<-OUTPUT Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end it 'has 4 undefined scenarios' do expect(@out.string).to include '4 scenarios (4 undefined)' end it 'has 4 undefined steps' do expect(@out.string).to include '4 steps (4 undefined)' end end describe 'with a step with a py string' do define_feature <<-FEATURE Feature: Traveling circus Scenario: Monkey goes to town Given there is a monkey called: """ foo """ FEATURE it 'does not display the pystring' do expect(@out.string).not_to include <<OUTPUT """ foo """ OUTPUT end end describe 'with a multiline step arg' do define_feature <<-FEATURE Feature: Traveling circus Scenario: Monkey goes to town Given there are monkeys: | name | | foo | | bar | FEATURE it 'does not display the multiline string' do expect(@out.string).not_to include <<OUTPUT | name | | foo | | bar | OUTPUT end end describe 'with a table in the background and the scenario' do define_feature <<-FEATURE Feature: accountant monkey Background: Given table: | a | b | | c | d | Scenario: Given another table: | e | f | | g | h | FEATURE it 'does not display the table for the background' do expect(@out.string).not_to include <<OUTPUT | a | b | | c | d | OUTPUT end it 'does not display the table for the scenario' do expect(@out.string).not_to include <<OUTPUT | e | f | | g | h | OUTPUT end end describe 'with a py string in the background and the scenario' do define_feature <<-FEATURE Feature: py strings Background: Given stuff: """ foo """ Scenario: Given more stuff: """ bar """ FEATURE it 'does not display the background py string' do expect(@out.string).not_to include <<OUTPUT """ foo """ OUTPUT end it 'does not display the scenario py string' do expect(@out.string).not_to include <<OUTPUT """ bar """ OUTPUT end end end end context 'when using --expand mode' do let(:options) { { expand: true } } before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out)) end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario outline' do define_feature <<-FEATURE Feature: Fud Pyramid Scenario Outline: Monkey eats a balanced diet Given there are <Things> Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | FEATURE it 'outputs the instantiated scenarios' do lines = <<-OUTPUT Examples: Fruit Example: | apples | Given there are apples Example: | bananas | Given there are bananas Examples: Vegetables Example: | broccoli | Given there are broccoli Example: | carrots | Given there are carrots OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end describe 'with a scenario outline in en-lol' do define_feature <<-FEATURE # language: en-lol OH HAI: STUFFING MISHUN SRSLY: CUCUMBR I CAN HAZ IN TEH BEGINNIN <BEGINNIN> CUCUMBRZ WEN I EAT <EAT> CUCUMBRZ DEN I HAS <EAT> CUCUMBERZ IN MAH BELLY AN IN TEH END <KTHXBAI> CUCUMBRZ KTHXBAI EXAMPLZ: | BEGINNIN | EAT | KTHXBAI | | 3 | 2 | 1 | FEATURE it 'outputs localized text' do lines = <<-OUTPUT OH HAI: STUFFING MISHUN SRSLY: CUCUMBR I CAN HAZ IN TEH BEGINNIN <BEGINNIN> CUCUMBRZ WEN I EAT <EAT> CUCUMBRZ DEN I HAS <EAT> CUCUMBERZ IN MAH BELLY AN IN TEH END <KTHXBAI> CUCUMBRZ KTHXBAI EXAMPLZ: MISHUN: | 3 | 2 | 1 | I CAN HAZ IN TEH BEGINNIN 3 CUCUMBRZ WEN I EAT 2 CUCUMBRZ DEN I HAS 2 CUCUMBERZ IN MAH BELLY AN IN TEH END 1 CUCUMBRZ KTHXBAI OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end end end context 'when using --expand mode with --source as an option' do let(:options) { { expand: true } } before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out, source: true)) end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario outline' do define_feature <<-FEATURE Feature: Fud Pyramid Scenario Outline: Monkey eats a balanced diet Given there are <Things> Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | FEATURE it 'includes the source in the output' do lines = <<-OUTPUT Scenario Outline: Monkey eats a balanced diet # spec.feature:3 Given there are <Things> # spec.feature:4 Examples: Fruit Example: | apples | # spec.feature:8 Given there are apples # spec.feature:8 Example: | bananas | # spec.feature:9 Given there are bananas # spec.feature:9 Examples: Vegetables Example: | broccoli | # spec.feature:12 Given there are broccoli # spec.feature:12 Example: | carrots | # spec.feature:13 Given there are carrots # spec.feature:13 OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end context 'with very wide cells' do define_feature <<-FEATURE Feature: Monkey Business Scenario Outline: Types of monkey Given there are <Types of monkey> Examples: | Types of monkey | Extra | | Hominidae | Very long cell content | FEATURE it 'the scenario line controls the source indentation' do lines = <<-OUTPUT Examples: Example: | Hominidae | Very long cell content | # spec.feature:8 Given there are Hominidae # spec.feature:8 OUTPUT lines.split("\n").each do |line| expect(@out.string).to include(line.strip) end end end end end end context 'with snippets that contain relevant keyword replacements' do before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out, snippets: true)) run_defined_feature end describe 'With a scenario that has undefined steps' do define_feature <<-FEATURE Feature: Banana party Scenario: many monkeys eat many things Given there are bananas and apples And other monkeys are around But there was only one chimpanzee When one monkey eats a banana And the other monkeys eat all the apples But the chimpanzee ate nothing Then bananas remain But there are no apples left And there was never any marshmallows FEATURE it "offers the exact snippet of a 'Given' step name" do expect(@out.string).to include("Given('there are bananas and apples')") end it "replaces snippets containing 'And' to the previous 'Given' step name" do expect(@out.string).to include("Given('other monkeys are around')") end it "replaces snippets containing 'But' to the previous 'Given' step name" do expect(@out.string).to include("Given('there was only one chimpanzee')") end it "offers the exact snippet of a 'When' step name" do expect(@out.string).to include("When('one monkey eats a banana')") end it "replaces snippets containing 'And' to the previous 'When' step name" do expect(@out.string).to include("When('the other monkeys eat all the apples')") end it "replaces snippets containing 'But' to the previous 'When' step name" do expect(@out.string).to include("When('the chimpanzee ate nothing')") end it "offers the exact snippet of a 'Then' step name" do expect(@out.string).to include("Then('bananas remain')") end it "replaces snippets containing 'But' to the previous 'Then' step name" do expect(@out.string).to include("Then('there are no apples left')") end it "replaces snippets containing 'And' to the previous 'Then' step name" do expect(@out.string).to include("Then('there was never any marshmallows')") end end describe "With a scenario that uses *" do define_feature <<-FEATURE Feature: Banana party Scenario: many monkeys eat many things * there are bananas and apples * other monkeys are around When one monkey eats a banana * the other monkeys eat all the apples Then bananas remain * there are no apples left FEATURE it "replaces the first step with 'Given'" do expect(@out.string).to include("Given('there are bananas and apples')") end it "uses actual keywords as the previous 'Given' keyword for future replacements" do expect(@out.string).to include("Given('other monkeys are around')") end it "uses actual keywords as the previous 'When' keyword for future replacements" do expect(@out.string).to include("When('the other monkeys eat all the apples')") end it "uses actual keywords as the previous 'Then' keyword for future replacements" do expect(@out.string).to include("Then('there are no apples left')") end end describe "With a scenario where the only undefined step uses 'And'" do define_feature <<-FEATURE Feature: Scenario: Given this step passes Then this step passes And this step is undefined FEATURE define_steps do Given('this step passes') {} end it 'uses actual keyword of the previous passing step for the undefined step' do expect(@out.string).to include("Then('this step is undefined')") end end describe "With scenarios where the first step is undefined and uses '*'" do define_feature <<-FEATURE Feature: Scenario: * this step is undefined Then this step passes Scenario: * this step is also undefined Then this step passes FEATURE define_steps do Given('this step passes') {} end it "uses 'Given' as the actual keyword for the step in the first scenario" do expect(@out.string).to include("Given('this step is undefined')") end it "uses 'Given' as the actual keyword for the step in the last scenario" do expect(@out.string).to include("Given('this step is also undefined')") end end describe 'with a scenario in en-lol' do define_feature <<-FEATURE # language: en-lol OH HAI: STUFFING MISHUN: CUCUMBR I CAN HAZ IN TEH BEGINNIN CUCUMBRZ AN I EAT CUCUMBRZ FEATURE it 'uses actual keyword of the previous passing step for the undefined step' do expect(@out.string).to include("ICANHAZ('I EAT CUCUMBRZ')") end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/http_io_spec.rb
spec/cucumber/formatter/http_io_spec.rb
# frozen_string_literal: true require 'stringio' require 'webrick' require 'webrick/https' require 'spec_helper' require 'cucumber/formatter/io' require 'support/shared_context/http_server' module Cucumber module Formatter class DummyFormatter include Io def initialize(config = nil); end def io(path_or_url_or_io, error_stream) ensure_io(path_or_url_or_io, error_stream) end end describe HTTPIO do include_context 'an HTTP server accepting file requests' # Close during the test so the request is done while server still runs after { io.close } let(:io) { DummyFormatter.new.io("#{server_url}/s3 -X GET -H 'Content-Type: text/json'", nil) } context 'created by Io#ensure_io' do it 'returns a IOHTTPBuffer' do expect(io).to be_a(Cucumber::Formatter::IOHTTPBuffer) end it 'uses CurlOptionParser to pass correct options to IOHTTPBuffer' do expect(io.uri).to eq(URI("#{server_url}/s3")) expect(io.method).to eq('GET') expect(io.headers).to eq('Content-Type' => 'text/json') end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/io_http_buffer_spec.rb
spec/cucumber/formatter/io_http_buffer_spec.rb
# frozen_string_literal: true require 'stringio' require 'webrick' require 'webrick/https' require 'spec_helper' require 'cucumber/formatter/io' require 'support/shared_context/http_server' module Cucumber module Formatter class DummyReporter def report(banner); end end describe IOHTTPBuffer do include_context 'an HTTP server accepting file requests' # JRuby seems to have some issues with huge reports. At least during tests # Maybe something to see with Webrick configuration. let(:report_size) { RUBY_PLATFORM == 'java' ? 8_000 : 10_000_000 } let(:sent_body) { 'X' * report_size } it 'raises an error on close when server in unreachable' do io = described_class.new("#{server_url}/404", 'PUT') expect { io.close }.to(raise_error("request to #{server_url}/404 failed with status 404")) end it 'raises an error on close when the server is unreachable' do io = described_class.new('http://localhost:9987', 'PUT') expect { io.close }.to(raise_error(/Failed to open TCP connection to localhost:9987/)) end it 'raises an error on close when there is too many redirect attempts' do io = described_class.new("#{server_url}/loop_redirect", 'PUT') expect { io.close }.to(raise_error("request to #{server_url}/loop_redirect failed (too many redirections)")) end it 'sends the content over HTTP' do io = described_class.new("#{server_url}/s3", 'PUT') io.write(sent_body) io.flush io.close server.received_body_io.rewind received_body = server.received_body_io.read expect(received_body).to eq(sent_body) end it 'sends the content over HTTPS' do io = described_class.new("#{server_url}/s3", 'PUT', {}, OpenSSL::SSL::VERIFY_NONE) io.write(sent_body) io.flush io.close server.received_body_io.rewind received_body = server.received_body_io.read expect(received_body).to eq(sent_body) end it 'follows redirections and sends body twice' do io = described_class.new("#{server_url}/putreport", 'PUT') io.write(sent_body) io.flush io.close server.received_body_io.rewind received_body = server.received_body_io.read expect(received_body).to eq("#{sent_body}#{sent_body}") end it 'only sends body once' do io = described_class.new("#{server_url}/putreport", 'GET') io.write(sent_body) io.flush io.close server.received_body_io.rewind received_body = server.received_body_io.read expect(received_body).to eq(sent_body) end it 'does not send headers to 2nd PUT request' do io = described_class.new("#{server_url}/putreport", 'GET', { Authorization: 'Bearer abcdefg' }) io.write(sent_body) io.flush io.close expect(server.received_headers[0]['authorization']).to eq(['Bearer abcdefg']) expect(server.received_headers[1]['authorization']).to eq([]) end it 'reports the body of the response to the reporter' do reporter = DummyReporter.new allow(reporter).to receive(:report) io = described_class.new("#{server_url}/putreport", 'GET', {}, nil, reporter) io.write(sent_body) io.flush io.close expect(reporter).to have_received(:report).with(success_banner) end it 'reports the body of the response to the reporter when request failed' do reporter = DummyReporter.new allow(reporter).to receive(:report) begin io = described_class.new("#{server_url}/401", 'GET', {}, nil, reporter) io.write(sent_body) io.flush io.close rescue StandardError # no-op end expect(reporter).to have_received(:report).with(failure_banner) end context 'when the location http header is not set on 202 response' do let(:putreport_returned_location) { nil } it 'does not follow the location' do io = described_class.new("#{server_url}/putreport", 'GET') io.write(sent_body) io.flush io.close server.received_body_io.rewind received_body = server.received_body_io.read expect(received_body).to eq('') end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/console_spec.rb
spec/cucumber/formatter/console_spec.rb
# frozen_string_literal: true require 'cucumber/configuration' require 'cucumber/formatter/console' module Cucumber module Formatter describe Console do include described_class it 'indents when padding is positive' do res = indent('a line', 2) expect(res).to eq ' a line' end it 'indents when padding is negative' do res = indent(' a line', -1) expect(res).to eq ' a line' end it 'handles excessive negative indentation properly' do res = indent(' a line', -10) expect(res).to eq 'a line' end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/rerun_spec.rb
spec/cucumber/formatter/rerun_spec.rb
# frozen_string_literal: true require 'cucumber/formatter/rerun' require 'cucumber/core' require 'cucumber/core/gherkin/writer' require 'support/standard_step_actions' require 'cucumber/configuration' require 'support/fake_objects' module Cucumber module Formatter describe Rerun do include Cucumber::Core::Gherkin::Writer include Cucumber::Core let(:config) { Cucumber::Configuration.new(out_stream: io) } let(:io) { StringIO.new } # after_test_case context 'when 2 scenarios fail in the same file' do it 'Prints the locations of the failed scenarios' do gherkin = gherkin('foo.feature') do feature do scenario do step 'failing' end scenario do step 'failing' end scenario do step 'passing' end end end described_class.new(config) execute [gherkin], [StandardStepActions.new], config.event_bus config.event_bus.test_run_finished expect(io.string).to eq 'foo.feature:3:6' end end context 'with failures in multiple files' do it 'prints the location of the failed scenarios in each file' do foo = gherkin('foo.feature') do feature do scenario do step 'failing' end scenario do step 'failing' end scenario do step 'passing' end end end bar = gherkin('bar.feature') do feature do scenario do step 'failing' end end end described_class.new(config) execute [foo, bar], [StandardStepActions.new], config.event_bus config.event_bus.test_run_finished expect(io.string).to eq "foo.feature:3:6\nbar.feature:3" end end context 'when there are no failing scenarios' do it 'prints nothing' do gherkin = gherkin('foo.feature') do feature do scenario do step 'passing' end end end described_class.new(config) execute [gherkin], [StandardStepActions.new], config.event_bus config.event_bus.test_run_finished expect(io.string).to eq '' end end context 'with only a flaky scenarios' do context 'with option --no-strict-flaky' do it 'prints nothing' do gherkin = gherkin('foo.feature') do feature do scenario do step 'flaky' end end end described_class.new(config) execute [gherkin], [FakeObjects::FlakyStepActions.new], config.event_bus config.event_bus.test_run_finished expect(io.string).to eq '' end end context 'with option --strict-flaky' do let(:config) { Configuration.new(out_stream: io, strict: Core::Test::Result::StrictConfiguration.new([:flaky])) } it 'prints the location of the flaky scenario' do foo = gherkin('foo.feature') do feature do scenario do step 'flaky' end end end described_class.new(config) execute [foo], [FakeObjects::FlakyStepActions.new], config.event_bus config.event_bus.test_run_finished expect(io.string).to eq 'foo.feature:3' end it 'does not include retried failing scenarios more than once' do foo = gherkin('foo.feature') do feature do scenario do step 'failing' end end end described_class.new(config) execute [foo, foo], [StandardStepActions.new], config.event_bus config.event_bus.test_run_finished expect(io.string).to eq 'foo.feature:3' end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/fail_fast_spec.rb
spec/cucumber/formatter/fail_fast_spec.rb
# frozen_string_literal: true require 'cucumber/formatter/fail_fast' require 'cucumber/core' require 'cucumber/core/gherkin/writer' require 'cucumber/core/test/result' require 'cucumber/core/filter' require 'cucumber' require 'support/standard_step_actions' module Cucumber module Formatter describe FailFast do include Cucumber::Core include Cucumber::Core::Gherkin::Writer let(:configuration) { Cucumber::Configuration.new } before { described_class.new(configuration) } context 'with a failing scenario' do before(:each) do @gherkin = gherkin('foo.feature') do feature do scenario do step 'failing' end scenario do step 'failing' end end end end after(:each) do Cucumber.wants_to_quit = false end it 'sets Cucumber.wants_to_quit' do execute [@gherkin], [StandardStepActions.new], configuration.event_bus expect(Cucumber.wants_to_quit).to be true end end context 'with a passing scenario' do before(:each) do @gherkin = gherkin('foo.feature') do feature do scenario do step 'passing' end end end end it "doesn't set Cucumber.wants_to_quit" do execute [@gherkin], [StandardStepActions.new], configuration.event_bus expect(Cucumber.wants_to_quit).to be_falsey end end context 'with an undefined scenario' do before(:each) do @gherkin = gherkin('foo.feature') do feature do scenario do step 'undefined' end end end end it "doesn't set Cucumber.wants_to_quit" do execute [@gherkin], [StandardStepActions.new], configuration.event_bus expect(Cucumber.wants_to_quit).to be_falsey end context 'when in strict mode' do let(:configuration) { Cucumber::Configuration.new strict: Cucumber::Core::Test::Result::StrictConfiguration.new([:undefined]) } it 'sets Cucumber.wants_to_quit' do execute [@gherkin], [StandardStepActions.new], configuration.event_bus expect(Cucumber.wants_to_quit).to be_truthy end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/ansicolor_spec.rb
spec/cucumber/formatter/ansicolor_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/ansicolor' module Cucumber module Formatter describe ANSIColor do include described_class it 'wraps passed_param with bold green and reset to green' do expect(passed_param('foo')).to eq "\e[32m\e[1mfoo\e[0m\e[0m\e[32m" end it 'wraps passed in green' do expect(passed('foo')).to eq "\e[32mfoo\e[0m" end it 'does not reset passed if there are no arguments' do expect(passed).to eq "\e[32m" end it 'wraps comments in grey' do expect(comment('foo')).to eq "\e[90mfoo\e[0m" end it 'does not generate ansi codes when colors are disabled' do ::Cucumber::Term::ANSIColor.coloring = false expect(passed('foo')).to eq 'foo' end it 'works with a block' do expect(passed { 'foo' }).to eq "\e[32mfoo\e[0m" end context 'with custom color scheme' do before do described_class.apply_custom_colors('passed=red,bold') end after do reset_colours_to_default end it 'works with custom colors' do expect(passed('foo')).to eq "\e[31m\e[1mfoo\e[0m\e[0m" end def reset_colours_to_default ANSIColor.apply_custom_colors('passed=green') end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/message_spec.rb
spec/cucumber/formatter/message_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/message' require 'cucumber/cli/options' module Cucumber module Formatter describe Message do extend SpecHelperDsl include SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out)) end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'outputs the undefined step' do expect(@out.string).to include '"status":"UNDEFINED"' end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/curl_option_parser_spec.rb
spec/cucumber/formatter/curl_option_parser_spec.rb
# frozen_string_literal: true require 'stringio' require 'webrick' require 'webrick/https' require 'spec_helper' require 'cucumber/formatter/io' require 'support/shared_context/http_server' describe Cucumber::Formatter::CurlOptionParser do describe '.parse' do context 'when a simple URL is given' do it 'returns the URL' do url, = described_class.parse('http://whatever.ltd') expect(url).to eq('http://whatever.ltd') end it 'uses PUT as the default method' do _, http_method = described_class.parse('http://whatever.ltd') expect(http_method).to eq('PUT') end it 'does not specify any header' do _, _, headers = described_class.parse('http://whatever.ltd') expect(headers).to eq({}) end end it 'detects the HTTP method with the flag -X' do expect(described_class.parse('http://whatever.ltd -X POST')).to eq( ['http://whatever.ltd', 'POST', {}] ) expect(described_class.parse('http://whatever.ltd -X PUT')).to eq( ['http://whatever.ltd', 'PUT', {}] ) end it 'detects the HTTP method with the flag --request' do expect(described_class.parse('http://whatever.ltd --request GET')).to eq( ['http://whatever.ltd', 'GET', {}] ) end it 'can recognize headers set with option -H and double quote' do expect(described_class.parse('http://whatever.ltd -H "Content-Type: text/json" -H "Authorization: Bearer abcde"')).to eq( [ 'http://whatever.ltd', 'PUT', { 'Content-Type' => 'text/json', 'Authorization' => 'Bearer abcde' } ] ) end it 'can recognize headers set with option -H and single quote' do expect(described_class.parse("http://whatever.ltd -H 'Content-Type: text/json' -H 'Content-Length: 12'")).to eq( [ 'http://whatever.ltd', 'PUT', { 'Content-Type' => 'text/json', 'Content-Length' => '12' } ] ) end it 'supports all options at once' do expect(described_class.parse('http://whatever.ltd -H "Content-Type: text/json" -X GET -H "Transfer-Encoding: chunked"')).to eq( [ 'http://whatever.ltd', 'GET', { 'Content-Type' => 'text/json', 'Transfer-Encoding' => 'chunked' } ] ) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/console_counts_spec.rb
spec/cucumber/formatter/console_counts_spec.rb
# frozen_string_literal: true require 'cucumber/configuration' require 'cucumber/formatter/console_counts' module Cucumber module Formatter describe ConsoleCounts do it 'works for zero' do config = Configuration.new counts = described_class.new(config) expect(counts.to_s).to eq "0 scenarios\n0 steps" end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/interceptor_spec.rb
spec/cucumber/formatter/interceptor_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/interceptor' describe Cucumber::Formatter::Interceptor::Pipe do let(:pipe) { instance_spy(IO) } describe '#wrap!' do it 'raises an ArgumentError if its not passed :stderr/:stdout' do expect { described_class.wrap(:nonsense) }.to raise_error(ArgumentError) end context 'when passed :stderr' do before { @stderr = $stderr } after { $stderr = @stderr } it 'wraps $stderr' do wrapped = described_class.wrap(:stderr) expect($stderr).to be_instance_of described_class expect($stderr).to be wrapped end end context 'when passed :stdout' do before { @stdout = $stdout } after { $stdout = @stdout } it 'wraps $stdout' do wrapped = described_class.wrap(:stdout) expect($stdout).to be_instance_of described_class expect($stdout).to be wrapped end end end describe '#unwrap!' do before :each do @stdout = $stdout $stdout = pipe @wrapped = described_class.wrap(:stdout) @stderr = $stderr end after :each do $stdout = @stdout $stderr = @stderr end it "raises an ArgumentError if it wasn't passed :stderr/:stdout" do expect { described_class.unwrap!(:nonsense) }.to raise_error(ArgumentError) end it 'resets $stdout when #unwrap! is called' do interceptor = described_class.unwrap! :stdout expect(interceptor).to be_instance_of described_class expect($stdout).not_to be interceptor end it 'noops if $stdout or $stderr has been overwritten' do $stdout = StringIO.new pipe = described_class.unwrap! :stdout expect(pipe).to eq($stdout) $stderr = StringIO.new pipe = described_class.unwrap! :stderr expect(pipe).to eq($stderr) end it 'disables the pipe bypass' do buffer = '(::)' described_class.unwrap!(:stdout) @wrapped.write(buffer) expect(@wrapped.buffer_string).not_to end_with(buffer) end it 'wraps $stderr' do wrapped = described_class.wrap(:stderr) expect($stderr).to be_instance_of described_class expect($stderr).to be wrapped end context 'when passed :stdout' do before :each do @stdout = $stdout end after :each do $stdout = @stdout end it 'wraps $stdout' do wrapped = described_class.wrap(:stdout) expect($stdout).to be_instance_of described_class expect($stdout).to be wrapped end end end describe '#write' do let(:buffer) { 'Some stupid buffer' } let(:pi) { described_class.new(pipe) } it 'writes arguments to the original pipe' do expect(pipe).to receive(:write).with(buffer) { buffer.size } expect(pi.write(buffer)).to eq(buffer.length) end it 'adds the buffer to its stored output' do expect(pipe).to receive(:write).with(buffer) pi.write(buffer) expect(pi.buffer_string).not_to be_empty expect(pi.buffer_string).to eq(buffer) end end describe '#method_missing' do before :each do @stdout = $stdout $stdout = pipe @wrapped = described_class.wrap(:stdout) @stderr = $stderr end after :each do $stdout = @stdout $stderr = @stderr end let(:pi) { described_class.new(pipe) } it 'passes #tty? to the original pipe' do expect(pipe).to receive(:tty?).and_return(true) expect(pi.tty?).to be true end end describe '#respond_to' do before :each do @stdout = $stdout $stdout = pipe @wrapped = described_class.wrap(:stdout) @stderr = $stderr end after :each do $stdout = @stdout $stderr = @stderr end let(:pi) { described_class.wrap(:stderr) } it 'responds to all methods $stderr has' do expect(pi).to respond_to(*$stderr.methods) end end describe 'when calling `methods` on the stream' do it 'does not raise errors' do allow($stderr).to receive(:puts) described_class.wrap(:stderr) expect { $stderr.puts('Oh, hi here !') }.not_to raise_error end it 'does not shadow errors when method do not exist on the stream' do described_class.wrap(:stderr) expect { $stderr.not_really_puts('Oh, hi here !') }.to raise_error(NoMethodError) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/duration_spec.rb
spec/cucumber/formatter/duration_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/duration' module Cucumber module Formatter describe Duration do include described_class it 'formats ms' do expect(format_duration(0.002103)).to eq '0m0.002s' end it 'formats m' do expect(format_duration(61.002503)).to eq '1m1.003s' end it 'formats h' do expect(format_duration(3661.002503)).to eq '61m1.003s' end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/url_reporter_spec.rb
spec/cucumber/formatter/url_reporter_spec.rb
# frozen_string_literal: true require 'stringio' require 'uri' require 'cucumber/formatter/url_reporter' module Cucumber module Formatter describe URLReporter do let(:io) { StringIO.new } subject { described_class.new(io) } describe '#report' do it 'displays the provided string' do banner = [ 'β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”', 'β”‚ View your Cucumber Report at: β”‚', 'β”‚ https://reports.cucumber.io/reports/<some-random-uid> β”‚', 'β”‚ β”‚', 'β”‚ This report will self-destruct in 24h unless it is claimed or deleted. β”‚', 'β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜' ].join("\n") subject.report(banner) io.rewind expect(io.read).to eq("#{banner}\n") end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/json_spec.rb
spec/cucumber/formatter/json_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/json' require 'cucumber/cli/options' require 'json' module Cucumber module Formatter describe Json do extend SpecHelperDsl include SpecHelper before(:each) do @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out)) run_defined_feature end describe 'with a scenario with an undefined step' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE it 'outputs the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec.feature:4"}, "result": {"status": "undefined"}}]}]}])) end end describe 'with a scenario with a passed step' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Given(/^there are bananas$/) {} end it 'outputs the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec/cucumber/formatter/json_spec.rb:62"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a scenario with a failed step' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Given(/^there are bananas$/) { raise 'no bananas' } end it 'outputs the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%{ [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec/cucumber/formatter/json_spec.rb:99"}, "result": {"status": "failed", "error_message": "no bananas (RuntimeError)\\n./spec/cucumber/formatter/json_spec.rb:99:in `/^there are bananas$/'\\nspec.feature:4:in `there are bananas'", "duration": 1}}]}]}]}) end end describe 'with a scenario with a pending step' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Given(/^there are bananas$/) { pending } end it 'outputs the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%{ [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec/cucumber/formatter/json_spec.rb:137"}, "result": {"status": "pending", "error_message": "TODO (Cucumber::Pending)\\n./spec/cucumber/formatter/json_spec.rb:137:in `/^there are bananas$/'\\nspec.feature:4:in `there are bananas'", "duration": 1}}]}]}]}) end end describe 'with a scenario outline with one example' do define_feature <<~FEATURE Feature: Banana party Scenario Outline: Monkey eats <fruit> Given there are <fruit> Examples: Fruit Table | fruit | | bananas | FEATURE define_steps do Given(/^there are bananas$/) {} end it 'outputs the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-<fruit>;fruit-table;2", "keyword": "Scenario Outline", "name": "Monkey eats bananas", "line": 8, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec/cucumber/formatter/json_spec.rb:179"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with tags in the feature file' do define_feature <<~FEATURE @f Feature: Banana party @s Scenario: Monkey eats bananas Given there are bananas @so Scenario Outline: Monkey eats bananas Given there are <fruit> @ex Examples: Fruit Table | fruit | | bananas | FEATURE define_steps do Given(/^there are bananas$/) {} end it 'the tags are included in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 2, "description": "", "tags": [{"name": "@f", "line": 1}], "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 5, "description": "", "tags": [{"name": "@f", "line": 1}, {"name": "@s", "line": 4}], "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 6, "match": {"location": "spec/cucumber/formatter/json_spec.rb:227"}, "result": {"status": "passed", "duration": 1}}]}, {"id": "banana-party;monkey-eats-bananas;fruit-table;2", "keyword": "Scenario Outline", "name": "Monkey eats bananas", "line": 15, "description": "", "tags": [{"name": "@f", "line": 1}, {"name": "@so", "line": 8}, {"name": "@ex", "line": 12}], "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 10, "match": {"location": "spec/cucumber/formatter/json_spec.rb:227"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with comments in the feature file' do define_feature <<~FEATURE #feature comment Feature: Banana party #background comment Background: There are bananas Given there are bananas #scenario comment Scenario: Monkey eats bananas #step comment1 Then the monkey eats bananas #scenario outline comment Scenario Outline: Monkey eats bananas #step comment2 Then the monkey eats <fruit> #examples table comment Examples: Fruit Table | fruit | #examples table row comment | bananas | FEATURE define_steps do Given(/^there are bananas$/) {} Then(/^the monkey eats bananas$/) {} end it 'the comments are not included in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 2, "description": "", "elements": [{"keyword": "Background", "name": "There are bananas", "line": 5, "description": "", "type": "background", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 6, "match": {"location": "spec/cucumber/formatter/json_spec.rb:307"}, "result": {"status": "passed", "duration": 1}}]}, {"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 9, "description": "", "type": "scenario", "steps": [{"keyword": "Then ", "name": "the monkey eats bananas", "line": 11, "match": {"location": "spec/cucumber/formatter/json_spec.rb:308"}, "result": {"status": "passed", "duration": 1}}]}, {"keyword": "Background", "name": "There are bananas", "line": 5, "description": "", "type": "background", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 6, "match": {"location": "spec/cucumber/formatter/json_spec.rb:307"}, "result": {"status": "passed", "duration": 1}}]}, {"id": "banana-party;monkey-eats-bananas;fruit-table;2", "keyword": "Scenario Outline", "name": "Monkey eats bananas", "line": 22, "description": "", "type": "scenario", "steps": [{"keyword": "Then ", "name": "the monkey eats bananas", "line": 16, "match": {"location": "spec/cucumber/formatter/json_spec.rb:308"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a scenario with a step with a doc string' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas """ the doc string """ FEATURE define_steps do Given(/^there are bananas$/) { |s| s } end it 'includes the doc string in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "doc_string": {"value": "the doc string", "content_type": "", "line": 5}, "match": {"location": "spec/cucumber/formatter/json_spec.rb:385"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a scenario with a step that use puts' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Given(/^there are bananas$/) { log 'from step' } end it 'includes the output from the step in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "output": ["from step"], "match": {"location": "spec/cucumber/formatter/json_spec.rb:425"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a background' do define_feature <<~FEATURE Feature: Banana party Background: There are bananas Given there are bananas Scenario: Monkey eats bananas Then the monkey eats bananas Scenario: Monkey eats more bananas Then the monkey eats more bananas FEATURE it 'includes the background in the json data each time it is executed' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"keyword": "Background", "name": "There are bananas", "line": 3, "description": "", "type": "background", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec.feature:4"}, "result": {"status": "undefined"}}]}, {"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 6, "description": "", "type": "scenario", "steps": [{"keyword": "Then ", "name": "the monkey eats bananas", "line": 7, "match": {"location": "spec.feature:7"}, "result": {"status": "undefined"}}]}, {"keyword": "Background", "name": "There are bananas", "line": 3, "description": "", "type": "background", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec.feature:4"}, "result": {"status": "undefined"}}]}, {"id": "banana-party;monkey-eats-more-bananas", "keyword": "Scenario", "name": "Monkey eats more bananas", "line": 9, "description": "", "type": "scenario", "steps": [{"keyword": "Then ", "name": "the monkey eats more bananas", "line": 10, "match": {"location": "spec.feature:10"}, "result": {"status": "undefined"}}]}]}])) end end describe 'with a scenario with a step that embeds data directly' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Given(/^there are bananas$/) { attach('YWJj', 'mime-type;base64') } end it 'includes the data from the step in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "embeddings": [{"mime_type": "mime-type", "data": "YWJj"}], "match": {"location": "spec/cucumber/formatter/json_spec.rb:535"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a scenario with a step that embeds a file' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Given(/^there are bananas$/) do RSpec::Mocks.allow_message(File, :file?) { true } RSpec::Mocks.allow_message(File, :read) { 'foo' } attach('out/snapshot.jpeg', 'image/png') end end it 'includes the file content in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "embeddings": [{"mime_type": "image/png", "data": "Zm9v"}], "match": {"location": "spec/cucumber/formatter/json_spec.rb:574"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a scenario with hooks' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Before() {} Before() {} After() {} After() {} AfterStep() {} AfterStep() {} Around() { |_scenario, block| block.call } Given(/^there are bananas$/) {} end it 'includes all hooks except the around hook in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "before": [{"match": {"location": "spec/cucumber/formatter/json_spec.rb:617"}, "result": {"status": "passed", "duration": 1}}, {"match": {"location": "spec/cucumber/formatter/json_spec.rb:618"}, "result": {"status": "passed", "duration": 1}}], "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec/cucumber/formatter/json_spec.rb:624"}, "result": {"status": "passed", "duration": 1}, "after": [{"match": {"location": "spec/cucumber/formatter/json_spec.rb:621"}, "result": {"status": "passed", "duration": 1}}, {"match": {"location": "spec/cucumber/formatter/json_spec.rb:622"}, "result": {"status": "passed", "duration": 1}}]}], "after": [{"match": {"location": "spec/cucumber/formatter/json_spec.rb:620"}, "result": {"status": "passed", "duration": 1}}, {"match": {"location": "spec/cucumber/formatter/json_spec.rb:619"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end describe 'with a scenario when only an around hook is failing' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas FEATURE define_steps do Around() do |_scenario, block| block.call raise 'error' end Given(/^there are bananas$/) {} end it 'includes the around hook result in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%{ [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "match": {"location": "spec/cucumber/formatter/json_spec.rb:686"}, "result": {"status": "passed", "duration": 1}}], "around": [{"match": {"location": "unknown_hook_location:1"}, "result": {"status": "failed", "error_message": "error (RuntimeError)\\n./spec/cucumber/formatter/json_spec.rb:684:in `Around'", "duration": 1}}]}]}]}) end end describe 'with a scenario with a step with a data table' do define_feature <<~FEATURE Feature: Banana party Scenario: Monkey eats bananas Given there are bananas | aa | bb | | cc | dd | FEATURE define_steps do Given(/^there are bananas$/) { |s| s } end it 'includes the doc string in the json data' do expect(load_normalised_json(@out)).to eq JSON.parse(%( [{"id": "banana-party", "uri": "spec.feature", "keyword": "Feature", "name": "Banana party", "line": 1, "description": "", "elements": [{"id": "banana-party;monkey-eats-bananas", "keyword": "Scenario", "name": "Monkey eats bananas", "line": 3, "description": "", "type": "scenario", "steps": [{"keyword": "Given ", "name": "there are bananas", "line": 4, "rows": [{"cells": ["aa", "bb"]}, {"cells": ["cc", "dd"]}], "match": {"location": "spec/cucumber/formatter/json_spec.rb:730"}, "result": {"status": "passed", "duration": 1}}]}]}])) end end def load_normalised_json(out) normalise_json(JSON.parse(out.string)) end def normalise_json(json) # make sure duration was captured (should be >= 0) # then set it to what is "expected" since duration is dynamic json.each do |feature| elements = feature.fetch('elements') { [] } elements.each do |scenario| %w[steps before after around].each do |type| next unless scenario[type] scenario[type].each do |step_or_hook| normalise_json_step_or_hook(step_or_hook) next unless step_or_hook['after'] step_or_hook['after'].each do |hook| normalise_json_step_or_hook(hook) end end end end end end def normalise_json_step_or_hook(step_or_hook) return unless step_or_hook['result'] && step_or_hook['result']['duration'] expect(step_or_hook['result']['duration']).to be >= 0 step_or_hook['result']['duration'] = 1 end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/backtrace_filter_spec.rb
spec/cucumber/formatter/backtrace_filter_spec.rb
# frozen_string_literal: true require 'cucumber/formatter/backtrace_filter' describe Cucumber::Formatter::BacktraceFilter do subject(:exception) { exception_klass.new } let(:exception_klass) do Class.new(StandardError) do def _trace static_trace + dynamic_trace + realistic_trace end private def static_trace %w[ a b _anything__/vendor/rails__anything_ _anything__lib/cucumber__anything_ _anything__bin/cucumber:__anything_ _anything__lib/rspec__anything_ _anything__gems/__anything_ _anything__minitest__anything_ _anything__test/unit__anything_ _anything__Xgem/ruby__anything_ _anything__.rbenv/versions/2.3/bin/bundle__anything_ ] end def dynamic_trace [].tap do |paths| paths << "_anything__#{RbConfig::CONFIG['rubyarchdir']}__anything_" if RbConfig::CONFIG['rubyarchdir'] paths << "_anything__#{RbConfig::CONFIG['rubylibdir']}__anything_" if RbConfig::CONFIG['rubylibdir'] end end def realistic_trace ["./vendor/bundle/ruby/3.4.0/gems/cucumber-9.2.1/lib/cucumber/glue/invoke_in_world.rb:37:in 'BasicObject#instance_exec'"] end end end describe '#exception' do before do exception.set_backtrace(exception._trace) end it 'filters unnecessary traces' do described_class.new(exception).exception expect(exception.backtrace).to eq(%w[a b]) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/junit_spec.rb
spec/cucumber/formatter/junit_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/junit' require 'nokogiri' module Cucumber module Formatter class TestDoubleJunitFormatter < ::Cucumber::Formatter::Junit attr_reader :written_files def initialize(config) super config.on_event :test_step_started, &method(:on_test_step_started) end def on_test_step_started(_event) Interceptor::Pipe.unwrap! :stdout @fake_io = $stdout = StringIO.new $stdout.sync = true @interceptedout = Interceptor::Pipe.wrap(:stdout) end def on_test_step_finished(event) super $stdout = STDOUT @fake_io.close end def write_file(feature_filename, data) @written_files ||= {} @written_files[feature_filename] = data end end describe Junit do extend SpecHelperDsl include SpecHelper context 'with --junit,fileattribute=true option' do before(:each) do allow(File).to receive(:directory?).and_return(true) @formatter = TestDoubleJunitFormatter.new( actual_runtime.configuration.with_options( out_stream: '', formats: [['junit', { 'fileattribute' => 'true' }]] ) ) end describe 'includes the file' do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end define_steps do Given('a passing scenario') do Kernel.puts 'foo' end end define_feature <<~FEATURE Feature: One passing feature Scenario: Passing Given a passing scenario FEATURE it 'contains the file attribute' do expect(@doc.xpath('//testsuite/testcase/@file').first.value).to eq('spec.feature') end end end context 'with --junit,fileattribute=different option' do before(:each) do allow(File).to receive(:directory?).and_return(true) @formatter = TestDoubleJunitFormatter.new( actual_runtime.configuration.with_options( out_stream: '', formats: [['junit', { 'fileattribute' => 'different' }]] ) ) end describe 'includes the file' do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end define_steps do Given('a passing scenario') do Kernel.puts 'foo' end end define_feature <<~FEATURE Feature: One passing feature Scenario: Passing Given a passing scenario FEATURE it 'does not contain the file attribute' do expect(@doc.xpath('//testsuite/testcase/@file')).to be_empty end end end context 'with --junit no fileattribute option' do before(:each) do allow(File).to receive(:directory?).and_return(true) @formatter = TestDoubleJunitFormatter.new(actual_runtime.configuration.with_options(out_stream: '')) end describe 'includes the file' do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end define_steps do Given('a passing scenario') do Kernel.puts 'foo' end end define_feature <<~FEATURE Feature: One passing feature Scenario: Passing Given a passing scenario FEATURE it 'does not contain the file attribute' do expect(@doc.xpath('//testsuite/testcase/@file')).to be_empty end end end context 'with no options' do before(:each) do allow(File).to receive(:directory?).and_return(true) @formatter = TestDoubleJunitFormatter.new(actual_runtime.configuration.with_options(out_stream: '')) end describe 'is able to strip control chars from cdata' do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end define_steps do Given('a passing ctrl scenario') do Kernel.puts "boo\b\cx\e\a\f boo " end end define_feature <<~FEATURE Feature: One passing scenario, one failing scenario Scenario: Passing Given a passing ctrl scenario FEATURE it { expect(@doc.xpath('//testsuite/testcase/system-out').first.content).to match(/\s+boo boo\s+/) } end describe 'a feature with no name' do define_feature <<~FEATURE Feature: Scenario: Passing Given a passing scenario FEATURE it 'raises an exception' do expect { run_defined_feature }.to raise_error(Junit::UnNamedFeatureError) end end describe 'given a single feature' do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end describe 'with a single scenario' do define_feature <<~FEATURE Feature: One passing scenario, one failing scenario Scenario: Passing Given a passing scenario FEATURE it { expect(@doc.to_s).to match(/One passing scenario, one failing scenario/) } it 'has not a root system-out node' do expect(@doc.xpath('//testsuite/system-out')).to be_empty end it 'has not a root system-err node' do expect(@doc.xpath('//testsuite/system-err')).to be_empty end it 'has a system-out node under <testcase/>' do expect(@doc.xpath('//testcase/system-out').length).to eq(1) end it 'has a system-err node under <testcase/>' do expect(@doc.xpath('//testcase/system-err').length).to eq(1) end end describe 'with a scenario in a subdirectory' do define_feature %( Feature: One passing scenario, one failing scenario Scenario: Passing Given a passing scenario ), File.join('features', 'some', 'path', 'spec.feature') it 'writes the filename with absolute path' do expect(@formatter.written_files.keys.first).to eq(File.absolute_path('TEST-features-some-path-spec.xml')) end end describe 'with a scenario outline table' do define_steps do Given('{word}') {} end define_feature <<~FEATURE Feature: Eat things when hungry Scenario Outline: Eat variety of things Given <things> And stuff: | foo | | bar | Examples: Good | things | | Cucumber | Examples: Evil | things | | Burger | | Whisky | FEATURE it { expect(@doc.to_s).to match(/Eat things when hungry/) } it { expect(@doc.to_s).to match(/Cucumber/) } it { expect(@doc.to_s).to match(/Burger/) } it { expect(@doc.to_s).to match(/Whisky/) } it { expect(@doc.to_s).not_to match(/Cake/) } it { expect(@doc.to_s).not_to match(/Good|Evil/) } it { expect(@doc.to_s).not_to match(/type="skipped"/) } end describe 'scenario with skipped test in junit report' do define_feature <<~FEATURE Feature: junit report with skipped test Scenario Outline: skip a test and junit report of the same Given a <skip> scenario Examples: | skip | | undefined | | still undefined | FEATURE it { expect(@doc.to_s).to match(/skipped="2"/) } end describe 'with a regular data table scenario' do define_steps do Given(/the following items on a shortlist/) { |table| } When(/I go.*/) {} Then(/I should have visited at least/) { |table| } end define_feature <<~FEATURE Feature: Shortlist Scenario: Procure items Given the following items on a shortlist: | item | | milk | | cookies | When I get some.. Then I'll eat 'em FEATURE # these type of tables shouldn't crash (or generate test cases) it { expect(@doc.to_s).not_to match(/milk/) } it { expect(@doc.to_s).not_to match(/cookies/) } end context 'with failing hooks' do describe 'with a failing before hook' do define_steps do Before do raise 'Before hook failed' end Given('a passing step') do end end define_feature <<~FEATURE Feature: One passing scenario Scenario: Passing Given a passing step FEATURE it { expect(@doc.to_s).to match(/Before hook at spec\/cucumber\/formatter\/junit_spec.rb:(\d+)/) } end describe 'with a failing after hook' do define_steps do After do raise 'After hook failed' end Given('a passing step') do end end define_feature <<~FEATURE Feature: One passing scenario Scenario: Passing Given a passing step FEATURE it { expect(@doc.to_s).to match(/After hook at spec\/cucumber\/formatter\/junit_spec.rb:(\d+)/) } end describe 'with a failing after step hook' do define_steps do AfterStep do raise 'AfterStep hook failed' end Given('a passing step') do end end define_feature <<~FEATURE Feature: One passing scenario Scenario: Passing Given a passing step FEATURE it { expect(@doc.to_s).to match(/AfterStep hook at spec\/cucumber\/formatter\/junit_spec.rb:(\d+)/) } end describe 'with a failing around hook' do define_steps do Around do |_scenario, block| block.call raise 'Around hook failed' end Given('a passing step') do end end define_feature <<~FEATURE Feature: One passing scenario Scenario: Passing Given a passing step FEATURE it { expect(@doc.to_s).to match(/Around hook\n\nMessage:/) } end end end end context 'In --expand mode' do let(:runtime) { Runtime.new(expand: true) } before(:each) do allow(File).to receive(:directory?).and_return(true) @formatter = TestDoubleJunitFormatter.new(actual_runtime.configuration.with_options(out_stream: '', expand: true)) end describe 'given a single feature' do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end describe 'with a scenario outline table' do define_steps do Given('{word}') {} end define_feature <<~FEATURE Feature: Eat things when hungry Scenario Outline: Eat things Given <things> And stuff: | foo | | bar | Examples: Good | things | | Cucumber | Examples: Evil | things | | Burger | | Whisky | FEATURE it { expect(@doc.to_s).to match(/Eat things when hungry/) } it { expect(@doc.to_s).to match(/Cucumber/) } it { expect(@doc.to_s).to match(/Whisky/) } it { expect(@doc.to_s).to match(/Burger/) } it { expect(@doc.to_s).not_to match(/Things/) } it { expect(@doc.to_s).not_to match(/Good|Evil/) } it { expect(@doc.to_s).not_to match(/type="skipped"/) } end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/progress_spec.rb
spec/cucumber/formatter/progress_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/progress' require 'cucumber/cli/options' module Cucumber module Formatter describe Progress do extend SpecHelperDsl include SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(out_stream: @out)) end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'outputs the undefined step' do expect(@out.string).to include "U\n" end end describe 'with a background' do define_feature <<-FEATURE Feature: Banana party Background: Given a tree Scenario: Monkey eats banana Given there are bananas FEATURE it 'outputs the two undefined steps' do expect(@out.string).to include "UU\n" end end describe 'with a scenario outline' do define_feature <<-FEATURE Feature: Fud Pyramid Scenario Outline: Monkey eats a balanced diet Given there are <Things> Examples: Fruit | Things | | apples | | bananas | Examples: Vegetables | Things | | broccoli | | carrots | FEATURE it 'outputs each undefined step' do expect(@out.string).to include "UUUU\n" end it 'has 4 undefined scenarios' do expect(@out.string).to include '4 scenarios (4 undefined)' end it 'has 4 undefined steps' do expect(@out.string).to include '4 steps (4 undefined)' end end describe 'with hooks' do describe 'all hook passes' do define_feature <<-FEATURE Feature: Scenario: Given this step passes FEATURE define_steps do Before do end AfterStep do end After do end Given(/^this step passes$/) {} end it 'only steps generate output' do lines = <<-OUTPUT . 1 scenario (1 passed) 1 step (1 passed) OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end describe 'with a failing before hook' do define_feature <<-FEATURE Feature: Scenario: Given this step passes FEATURE define_steps do Before do raise 'hook failed' end Given(/^this step passes$/) {} end it 'the failing hook generate output' do lines = <<-OUTPUT F- 1 scenario (1 failed) 1 step (1 skipped) OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end describe 'with a failing after hook' do define_feature <<-FEATURE Feature: Scenario: Given this step passes FEATURE define_steps do After do raise 'hook failed' end Given(/^this step passes$/) {} end it 'the failing hook generate output' do lines = <<-OUTPUT .F 1 scenario (1 failed) 1 step (1 passed) OUTPUT lines.split("\n").each do |line| expect(@out.string).to include line.strip end end end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/publish_banner_printer_spec.rb
spec/cucumber/formatter/publish_banner_printer_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/publish_banner_printer' module Cucumber module Formatter describe PublishBannerPrinter do extend SpecHelperDsl include SpecHelper before do Cucumber::Term::ANSIColor.coloring = false @err = StringIO.new @formatter = described_class.new(actual_runtime.configuration.with_options(error_stream: @err)) end context 'passing scenario' do define_feature <<-FEATURE Feature: Banana party FEATURE it 'prints banner' do run_defined_feature expect(@err.string).to include(<<~BANNER) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Share your Cucumber Report with your team at https://reports.cucumber.io β”‚ β”‚ β”‚ β”‚ Command line option: --publish β”‚ β”‚ Environment variable: CUCUMBER_PUBLISH_ENABLED=true β”‚ β”‚ cucumber.yml: default: --publish β”‚ β”‚ β”‚ β”‚ More information at https://cucumber.io/docs/cucumber/environment-variables/ β”‚ β”‚ β”‚ β”‚ To disable this message, specify CUCUMBER_PUBLISH_QUIET=true or use the β”‚ β”‚ --publish-quiet option. You can also add this to your cucumber.yml: β”‚ β”‚ default: --publish-quiet β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ BANNER end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/spec_helper.rb
spec/cucumber/formatter/spec_helper.rb
# frozen_string_literal: true module Cucumber module Formatter module SpecHelperDsl attr_reader :feature_content, :step_defs, :feature_filename def define_feature(string, feature_file = 'spec.feature') @feature_content = string @feature_filename = feature_file end def define_steps(&block) @step_defs = block end end require 'cucumber/core' module SpecHelper include Core def run_defined_feature define_steps actual_runtime.visitor = Fanout.new([@formatter]) receiver = Test::Runner.new(event_bus) event_bus.gherkin_source_read(gherkin_doc.uri, gherkin_doc.body) compile [gherkin_doc], receiver, filters, event_bus event_bus.test_run_finished end def filters # TODO: Remove duplication with runtime.rb#filters [ Filters::ActivateSteps.new( StepMatchSearch.new(actual_runtime.support_code.registry.method(:step_matches), actual_runtime.configuration), actual_runtime.configuration ), Filters::ApplyAfterStepHooks.new(actual_runtime.support_code), Filters::ApplyBeforeHooks.new(actual_runtime.support_code), Filters::ApplyAfterHooks.new(actual_runtime.support_code), Filters::ApplyAroundHooks.new(actual_runtime.support_code), Filters::BroadcastTestRunStartedEvent.new(actual_runtime.configuration), Filters::BroadcastTestCaseReadyEvent.new(actual_runtime.configuration), Filters::PrepareWorld.new(actual_runtime) ] end require 'cucumber/core/gherkin/document' def gherkin_doc Core::Gherkin::Document.new(self.class.feature_filename, gherkin) end def gherkin self.class.feature_content || raise('No feature content defined!') end def actual_runtime @actual_runtime ||= Runtime.new(options) end def event_bus actual_runtime.configuration.event_bus end def define_steps step_defs = self.class.step_defs return unless step_defs dsl = Object.new dsl.extend Glue::Dsl dsl.instance_exec(&step_defs) end def options {} end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/query/pickle_step_by_test_step_spec.rb
spec/cucumber/formatter/query/pickle_step_by_test_step_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/query/pickle_step_by_test_step' module Cucumber module Formatter module Query describe PickleStepByTestStep do extend SpecHelperDsl include SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @test_cases = [] @out = StringIO.new @config = actual_runtime.configuration.with_options(out_stream: @out) @formatter = described_class.new(@config) @config.on_event :test_case_created do |event| @test_cases << event.test_case end @pickle_step_ids = [] @config.on_event :envelope do |event| next unless event.envelope.pickle event.envelope.pickle.steps.each do |step| @pickle_step_ids << step.id end end end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario' do describe '#pickle_step_id' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'provides the ID of the PickleStep used to generate the Test::Step' do test_case = @test_cases.first test_step = test_case.test_steps.first expect(@formatter.pickle_step_id(test_step)).to eq(@pickle_step_ids.first) end it 'raises an exception when the test_step is unknown' do test_step = double allow(test_step).to receive(:id).and_return('whatever-id') expect { @formatter.pickle_step_id(test_step) }.to raise_error(Cucumber::Formatter::TestStepUnknownError) end end end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/query/step_definitions_by_test_step_spec.rb
spec/cucumber/formatter/query/step_definitions_by_test_step_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/query/step_definitions_by_test_step' module Cucumber module Formatter module Query describe StepDefinitionsByTestStep do extend SpecHelperDsl include SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @test_cases = [] @out = StringIO.new @config = actual_runtime.configuration.with_options(out_stream: @out) @formatter = described_class.new(@config) @config.on_event :test_case_created do |event| @test_cases << event.test_case end @step_definition_ids = [] @config.on_event :envelope do |event| next unless event.envelope.step_definition @step_definition_ids << event.envelope.step_definition.id end end describe 'given a single feature' do before(:each) do run_defined_feature end describe '#step_definition_ids' do context 'with a matching step' do define_steps do Given(/^there are bananas$/) {} end define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'provides the ID of the StepDefinition that matches Test::Step' do test_case = @test_cases.first test_step = test_case.test_steps.first expect(@formatter.step_definition_ids(test_step)).to eq([@step_definition_ids.first]) end end context 'with a step that was not activated' do context 'when there is no match' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'returns an empty array' do test_case = @test_cases.first test_step = test_case.test_steps.first expect(@formatter.step_definition_ids(test_step)).to be_empty end end context 'when there are multiple matches' do define_steps do Given(/^there are bananas$/) {} Given(/^there .* bananas$/) {} end define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'returns an empty array as the step is not activated' do test_case = @test_cases.first test_step = test_case.test_steps.first expect(@formatter.step_definition_ids(test_step)).to be_empty end end end context 'with an unknown step' do define_feature 'Feature: Banana party' it 'raises an exception' do test_step = double allow(test_step).to receive(:id).and_return('whatever-id') expect { @formatter.step_definition_ids(test_step) }.to raise_error(Cucumber::Formatter::TestStepUnknownError) end end end describe '#step_match_arguments' do context 'with a matching step without arguments' do define_steps do Given(/^there are bananas$/) {} end define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'returns an empty list' do test_case = @test_cases.first test_step = test_case.test_steps.first expect(@formatter.step_match_arguments(test_step)).to be_empty end end context 'with a matching step with arguments' do define_steps do Given(/^there are (.*)$/) {} end define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'returns an empty list' do test_case = @test_cases.first test_step = test_case.test_steps.first matches = @formatter.step_match_arguments(test_step) expect(matches.count).to eq(1) expect(matches.first).to be_a(Cucumber::CucumberExpressions::Argument) expect(matches.first.group.value).to eq('bananas') end end context 'with an unknown step' do define_feature 'Feature: Banana party' it 'raises an exception' do test_step = double allow(test_step).to receive(:id).and_return('whatever-id') expect { @formatter.step_match_arguments(test_step) }.to raise_error(Cucumber::Formatter::TestStepUnknownError) end end end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/query/hook_by_test_step_spec.rb
spec/cucumber/formatter/query/hook_by_test_step_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/query/hook_by_test_step' describe Cucumber::Formatter::Query::HookByTestStep do extend Cucumber::Formatter::SpecHelperDsl include Cucumber::Formatter::SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @test_cases = [] @out = StringIO.new @config = actual_runtime.configuration.with_options(out_stream: @out) @formatter = described_class.new(@config) @config.on_event :test_case_started do |event| @test_cases << event.test_case end @hook_ids = [] @config.on_event :envelope do |event| next unless event.envelope.hook @hook_ids << event.envelope.hook.id end end context 'given a single feature' do before(:each) do run_defined_feature end context 'with a scenario' do describe '#pickle_step_id' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE define_steps do Before() {} After() {} end it 'provides the ID of the Before Hook used to generate the Test::Step' do test_case = @test_cases.first expect(@formatter.hook_id(test_case.test_steps.first)).to eq(@hook_ids.first) end it 'provides the ID of the After Hook used to generate the Test::Step' do test_case = @test_cases.first expect(@formatter.hook_id(test_case.test_steps.last)).to eq(@hook_ids.last) end it 'returns nil if the step was not generated from a hook' do test_case = @test_cases.first expect(@formatter.hook_id(test_case.test_steps[1])).to be_nil end it 'raises an exception when the test_step is unknown' do test_step = double allow(test_step).to receive(:id).and_return('whatever-id') expect { @formatter.hook_id(test_step) }.to raise_error(Cucumber::Formatter::TestStepUnknownError) end end end context 'with AfterStep hooks' do describe '#pickle_step_id' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE define_steps do AfterStep() {} end it 'provides the ID of the AfterStepHook used to generate the Test::Step' do test_case = @test_cases.first expect(@formatter.hook_id(test_case.test_steps.last)).to eq(@hook_ids.first) end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/query/pickle_by_test_spec.rb
spec/cucumber/formatter/query/pickle_by_test_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/query/pickle_by_test' module Cucumber module Formatter module Query describe PickleByTest do extend SpecHelperDsl include SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @test_cases = [] @out = StringIO.new @config = actual_runtime.configuration.with_options(out_stream: @out) @formatter = described_class.new(@config) @config.on_event :test_case_created do |event| @test_cases << event.test_case end @pickle_ids = [] @config.on_event :envelope do |event| next unless event.envelope.pickle @pickle_ids << event.envelope.pickle.id end end describe 'given a single feature' do before(:each) do run_defined_feature end describe 'with a scenario' do describe '#pickle_id' do define_feature <<-FEATURE Feature: Banana party Scenario: Monkey eats banana Given there are bananas FEATURE it 'provides the ID of the pickle used to generate the Test::Case' do expect(@formatter.pickle_id(@test_cases.first)).to eq(@pickle_ids.first) end it 'raises an error when the Test::Case is unknown' do test_case = double allow(test_case).to receive(:id).and_return('whatever-id') expect { @formatter.pickle_id(test_case) }.to raise_error(Cucumber::Formatter::TestCaseUnknownError) end end end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/formatter/query/test_case_started_by_test_case_spec.rb
spec/cucumber/formatter/query/test_case_started_by_test_case_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/query/test_case_started_by_test_case' module Cucumber module Formatter module Query describe TestCaseStartedByTestCase do extend SpecHelperDsl include SpecHelper before(:each) do Cucumber::Term::ANSIColor.coloring = false @out = StringIO.new @config = actual_runtime.configuration.with_options(out_stream: @out) @formatter = described_class.new(@config) end let(:unknown_test_case) do test_case = double allow(test_case).to receive(:id).and_return('whatever-id') test_case end describe '#attempt_by_test_case' do it 'raises an exception when the TestCase is unknown' do expect { @formatter.attempt_by_test_case(unknown_test_case) }.to raise_exception(TestCaseUnknownError) end context 'when the test case has been declared' do before do @test_case = double allow(@test_case).to receive(:id).and_return('some-valid-id') @config.notify :test_case_created, @test_case, nil end it 'returns 0 if no test_case_started event has been fired' do expect(@formatter.attempt_by_test_case(@test_case)).to eq(0) end it 'increments the attemp on every test_case_started event' do @config.notify :test_case_started, @test_case expect(@formatter.attempt_by_test_case(@test_case)).to eq(1) @config.notify :test_case_started, @test_case expect(@formatter.attempt_by_test_case(@test_case)).to eq(2) end end end describe '#test_case_started_id_by_test_case' do it 'raises an exception when the TestCase is unknown' do expect { @formatter.test_case_started_id_by_test_case(unknown_test_case) }.to raise_exception(TestCaseUnknownError) end context 'when the test case has been declared' do before do @test_case = double allow(@test_case).to receive(:id).and_return('some-valid-id') @config.notify :test_case_created, @test_case, nil end it 'returns nil if no test_case_started event has been fired' do expect(@formatter.test_case_started_id_by_test_case(@test_case)).to be_nil end it 'gives a new id when a test_case_started event is fired' do @config.notify :test_case_started, @test_case first_attempt_id = @formatter.test_case_started_id_by_test_case(@test_case) expect(first_attempt_id).not_to be_nil @config.notify :test_case_started, @test_case second_attempt_id = @formatter.test_case_started_id_by_test_case(@test_case) expect(second_attempt_id).not_to be_nil expect(second_attempt_id).not_to eq(first_attempt_id) end end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/runtime/before_hooks_spec.rb
spec/cucumber/runtime/before_hooks_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/runtime/hooks_examples' require 'cucumber/runtime/before_hooks' module Cucumber class Runtime describe BeforeHooks do let(:subject) { described_class.new(id_generator, hooks, scenario, event_bus) } describe '#apply_to' do include_examples 'events are fired when applying hooks' end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/runtime/hooks_examples.rb
spec/cucumber/runtime/hooks_examples.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/messages/helpers/id_generator' RSpec.shared_examples 'events are fired when applying hooks' do let(:id_generator) { Cucumber::Messages::Helpers::IdGenerator::Incrementing.new } let(:scenario) { double } let(:event_bus) { double } let(:hooks) { [hook] } let(:hook) { double } let(:test_case) { double } before do allow(test_case).to receive(:with_steps) allow(test_case).to receive(:test_steps).and_return([]) allow(hook).to receive(:location) allow(event_bus).to receive(:hook_test_step_created) end it 'fires a :hook_test_step_created event for each created step' do subject.apply_to(test_case) expect(event_bus).to have_received(:hook_test_step_created) end context 'when multiple hooks are applied' do let(:hooks) { [hook, hook, hook] } it 'fires a :hook_test_step_created event for each step' do subject.apply_to(test_case) expect(event_bus).to have_received(:hook_test_step_created).exactly(3).times end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/runtime/meta_message_builder_spec.rb
spec/cucumber/runtime/meta_message_builder_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/runtime/meta_message_builder' describe Cucumber::Runtime::MetaMessageBuilder do describe '.build_meta_message' do subject { described_class.build_meta_message } it { is_expected.to be_a(Cucumber::Messages::Meta) } it 'has a protocol version' do expect(subject.protocol_version).to eq(Cucumber::Messages::VERSION) end it 'has an implementation name' do expect(subject.implementation.name).to eq('cucumber-ruby') end it 'has an implementation version' do expect(subject.implementation.version).to eq(Cucumber::VERSION) end it 'has a runtime name' do expect(subject.runtime.name).to eq(RUBY_ENGINE) end it 'has a runtime version' do expect(subject.runtime.version).to eq(RUBY_VERSION) end it 'has an os name' do expect(subject.os.name).to eq(RbConfig::CONFIG['target_os']) end it 'has an os version' do expect(subject.os.version).to eq(Sys::Uname.uname.version) end it 'has a cpu name' do expect(subject.cpu.name).to eq(RbConfig::CONFIG['target_cpu']) end context 'with an overridden ENV hash' do subject { described_class.build_meta_message(env) } let(:env) { {} } it 'detects CI environment using the given env' do expect(Cucumber::CiEnvironment).to receive(:detect_ci_environment).with(env) subject end end context 'when running on a CI system without git data' do subject { described_class.build_meta_message.ci } before { expect(Cucumber::CiEnvironment).to receive(:detect_ci_environment).and_return(ci_data) } let(:ci_data) do { name: 'Jenkins', url: 'http://localhost:8080', buildNumber: '123' } end it { is_expected.to be_a(Cucumber::Messages::Ci) } it 'has a populated CI name from the ci input hash' do expect(subject.name).to eq(ci_data[:name]) end it 'has a populated CI url from the ci input hash' do expect(subject.url).to eq(ci_data[:url]) end it 'has a populated CI build number from the ci input hash' do expect(subject.build_number).to eq(ci_data[:buildNumber]) end end context 'when running on a CI system with git data' do subject { described_class.build_meta_message.ci.git } before { expect(Cucumber::CiEnvironment).to receive(:detect_ci_environment).and_return(ci_data) } let(:ci_data) do { git: { remote: 'origin', revision: '1234567890', branch: 'main', tag: 'v1.0.0' } } end it { is_expected.to be_a(Cucumber::Messages::Git) } it 'has a populated git remote from the git field of the ci input hash' do expect(subject.remote).to eq(ci_data[:git][:remote]) end it 'has a populated git revision from the git field of the ci input hash' do expect(subject.revision).to eq(ci_data[:git][:revision]) end it 'has a populated git branch from the git field of the ci input hash' do expect(subject.branch).to eq(ci_data[:git][:branch]) end it 'has a populated git tag from the git field of the ci input hash' do expect(subject.tag).to eq(ci_data[:git][:tag]) end end context 'when not running on a CI system' do subject { described_class.build_meta_message.ci } before { expect(Cucumber::CiEnvironment).to receive(:detect_ci_environment).and_return(ci_data) } let(:ci_data) { nil } it { is_expected.to be_nil } end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/runtime/after_hooks_spec.rb
spec/cucumber/runtime/after_hooks_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/runtime/hooks_examples' require 'cucumber/runtime/after_hooks' module Cucumber class Runtime describe AfterHooks do let(:subject) { described_class.new(id_generator, hooks, scenario, event_bus) } describe '#apply_to' do include_examples 'events are fired when applying hooks' end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/runtime/support_code_spec.rb
spec/cucumber/runtime/support_code_spec.rb
# frozen_string_literal: true require 'spec_helper' module Cucumber describe Runtime::SupportCode do let(:user_interface) { double('user interface') } subject { described_class.new(user_interface, configuration) } let(:configuration) { Configuration.new(options) } let(:options) { {} } let(:dsl) do @rb = subject.ruby Object.new.extend(RbSupport::RbDsl) end subject { described_class.new(user_interface, configuration) } describe '#apply_before_hooks' do let(:test_case) { double } let(:test_step) { double } it 'applies before hooks to test cases with steps' do allow(test_case).to receive(:test_steps).and_return([test_step]) allow(test_case).to receive(:with_steps).and_return(double) expect(subject.apply_before_hooks(test_case)).not_to equal(test_case) end it 'does not apply before hooks to test cases with no steps' do allow(test_case).to receive(:test_steps).and_return([]) expect(subject.apply_before_hooks(test_case)).to equal(test_case) end end describe '#apply_after_hooks' do let(:test_case) { double } let(:test_step) { double } it 'applies after hooks to test cases with steps' do allow(test_case).to receive(:test_steps).and_return([test_step]) allow(test_case).to receive(:with_steps).and_return(double) expect(subject.apply_after_hooks(test_case)).not_to equal(test_case) end it 'does not apply after hooks to test cases with no steps' do allow(test_case).to receive(:test_steps).and_return([]) expect(subject.apply_after_hooks(test_case)).to equal(test_case) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/world/pending_spec.rb
spec/cucumber/world/pending_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'cucumber/glue/registry_and_more' require 'cucumber/configuration' module Cucumber describe 'Pending' do before(:each) do registry = Glue::RegistryAndMore.new(Runtime.new, Configuration.new) registry.begin_scenario(double('scenario').as_null_object) @world = registry.current_world end it 'raises a Pending if no block is supplied' do expect { @world.pending 'TODO' }.to raise_error(Cucumber::Pending, /TODO/) end it 'raises a Pending if a supplied block fails as expected' do expect do @world.pending 'TODO' do raise 'oops' end end.to raise_error(Cucumber::Pending, /TODO/) end it 'raises a Pending if a supplied block fails as expected with a double' do expect do @world.pending 'TODO' do m = double('thing') expect(m).to receive(:foo) RSpec::Mocks.verify end end.to raise_error(Cucumber::Pending, /TODO/) # The teardown is needed so that the message expectation does not bubble up. RSpec::Mocks.teardown end it 'raises a Pending if a supplied block starts working' do expect { @world.pending 'TODO' }.to raise_error(Cucumber::Pending, /TODO/) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/term/banner_spec.rb
spec/cucumber/term/banner_spec.rb
# frozen_string_literal: true require 'cucumber/term/banner' describe Cucumber::Term::Banner do include described_class describe '.display_banner' do let(:io) { StringIO.new } context 'when a string is provided' do it 'outputs a nice banner to IO surrounded by a bold green border' do display_banner('Oh, this is a banner', io) io.rewind expect(io.read).to eq(<<~BANNER) \e[1m\e[32mβ”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”\e[0m\e[0m \e[1m\e[32mβ”‚\e[0m\e[0m Oh, this is a banner \e[1m\e[32mβ”‚\e[0m\e[0m \e[1m\e[32mβ””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\e[0m\e[0m BANNER end it 'supports multi-lines' do display_banner("Oh, this is a banner\nwhich spreads on\nmultiple lines", io, []) io.rewind expect(io.read).to eq(<<~BANNER) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Oh, this is a banner β”‚ β”‚ which spreads on β”‚ β”‚ multiple lines β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ BANNER end end context 'when an array is provided' do it 'outputs a nice banner with each item on a line' do display_banner(['Oh, this is a banner', 'It has two lines'], io, []) io.rewind expect(io.read).to eq(<<~BANNER) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Oh, this is a banner β”‚ β”‚ It has two lines β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ BANNER end it 'can render special characters inside the lines' do display_banner(['Oh, this is a banner', ['It has ', ['two', :bold, :blue], ' lines']], io, []) io.rewind expect(io.read).to eq(<<~BANNER) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Oh, this is a banner β”‚ β”‚ It has \e[34m\e[1mtwo\e[0m\e[0m lines β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ BANNER end end context 'with custom borders' do it 'process the border with the provided attributes' do display_banner('this is a banner', io, %i[bold blue]) io.rewind expect(io.read).to eq(<<~BANNER) \e[34m\e[1mβ”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”\e[0m\e[0m \e[34m\e[1mβ”‚\e[0m\e[0m this is a banner \e[34m\e[1mβ”‚\e[0m\e[0m \e[34m\e[1mβ””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\e[0m\e[0m BANNER end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/filters/retry_spec.rb
spec/cucumber/filters/retry_spec.rb
# frozen_string_literal: true require 'cucumber' require 'cucumber/filters/retry' require 'cucumber/core/gherkin/writer' require 'cucumber/configuration' require 'cucumber/core/test/case' require 'cucumber/core' require 'cucumber/events' describe Cucumber::Filters::Retry do include Cucumber::Core::Gherkin::Writer include Cucumber::Core include Cucumber::Events let(:configuration) { Cucumber::Configuration.new(retry: 2, retry_total: retry_total) } let(:retry_total) { Float::INFINITY } let(:test_case) { Cucumber::Core::Test::Case.new(double, double, [double('test steps')], double, double, [], double) } let(:receiver) { double('receiver').as_null_object } let(:filter) { described_class.new(configuration, receiver) } let(:fail) { Cucumber::Events::AfterTestCase.new(test_case, double('result', failed?: true, ok?: false)) } let(:pass) { Cucumber::Events::AfterTestCase.new(test_case, double('result', failed?: false, ok?: true)) } let(:fail_result) { Cucumber::Core::Test::Result::Failed.new(0, StandardError.new) } it { is_expected.to respond_to(:test_case) } it { is_expected.to respond_to(:with_receiver) } it { is_expected.to respond_to(:done) } context 'with a passing test case' do let(:result) { Cucumber::Core::Test::Result::Passed.new(0) } it 'describes the test case once' do expect(receiver).to receive(:test_case).with(test_case).once test_case.describe_to filter configuration.notify(:test_case_finished, test_case, result) end end context 'when performing retry' do it 'describes the same test case object each time' do allow(receiver).to receive(:test_case) do |tc| expect(tc).to equal(test_case) configuration.notify(:test_case_finished, tc.with_steps(tc.test_steps), fail_result) end filter.test_case(test_case) end end context 'with a consistently failing test case' do shared_examples 'retries the test case the specified number of times' do |expected_number_of_times| it 'describes the test case the specified number of times' do expect(receiver).to receive(:test_case) { |test_case| configuration.notify(:test_case_finished, test_case, fail_result) }.exactly(expected_number_of_times).times filter.test_case(test_case) end end context 'when retry_total is infinite' do let(:retry_total) { Float::INFINITY } include_examples 'retries the test case the specified number of times', 3 end context 'when retry_total is 1' do let(:retry_total) { 1 } include_examples 'retries the test case the specified number of times', 3 end context 'when retry_total is 0' do let(:retry_total) { 0 } include_examples 'retries the test case the specified number of times', 1 end end context 'with slighty flaky test cases' do let(:results) { [fail_result, Cucumber::Core::Test::Result::Passed.new(0)] } it 'describes the test case twice' do expect(receiver).to receive(:test_case) { |test_case| configuration.notify(:test_case_finished, test_case, results.shift) }.twice filter.test_case(test_case) end end context 'with really flaky test cases' do let(:results) { [fail_result, fail_result, Cucumber::Core::Test::Result::Passed.new(0)] } it 'describes the test case 3 times' do expect(receiver).to receive(:test_case) { |test_case| configuration.notify(:test_case_finished, test_case, results.shift) }.exactly(3).times filter.test_case(test_case) end end context 'with too many failing tests' do let(:retry_total) { 1 } let(:always_failing_test_case1) do Cucumber::Core::Test::Case.new(double, double, [double('test steps')], 'test.rb:1', nil, [], double) end let(:always_failing_test_case2) do Cucumber::Core::Test::Case.new(double, double, [double('test steps')], 'test.rb:9', nil, [], double) end it 'stops retrying tests' do expect(receiver).to receive(:test_case).with(always_failing_test_case1) { |test_case| configuration.notify(:test_case_finished, test_case, fail_result) }.ordered.exactly(3).times expect(receiver).to receive(:test_case).with(always_failing_test_case2) { |test_case| configuration.notify(:test_case_finished, test_case, fail_result) }.ordered.once filter.test_case(always_failing_test_case1) filter.test_case(always_failing_test_case2) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/filters/activate_steps_spec.rb
spec/cucumber/filters/activate_steps_spec.rb
# frozen_string_literal: true require 'cucumber/filters/activate_steps' require 'cucumber/core/gherkin/writer' require 'cucumber/core' describe Cucumber::Filters::ActivateSteps do include Cucumber::Core::Gherkin::Writer include Cucumber::Core let(:step_match) { double(activate: activated_test_step) } let(:activated_test_step) { double } let(:receiver) { double.as_null_object } let(:filter) { described_class.new(step_match_search, configuration) } let(:step_match_search) { proc { [step_match] } } let(:configuration) { double(dry_run?: false, notify: nil) } context 'with a scenario containing a single step' do let(:doc) do gherkin do feature do scenario do step 'a passing step' end end end end it 'activates each step' do allow(step_match).to receive(:activate) do |test_step| expect(test_step.text).to eq('a passing step') end compile([doc], receiver, [filter]) end it 'notifies with a StepActivated event' do allow(configuration).to receive(:notify) do |message, _test_step, _step_match| expect(message).to eq(:step_activated) end compile([doc], receiver, [filter]) end it 'notifies with the correct step' do allow(configuration).to receive(:notify) do |_message, test_step, _step_match| expect(test_step.text).to eq('a passing step') end compile([doc], receiver, [filter]) end end context 'with a scenario outline' do let(:doc) do gherkin do feature do scenario_outline do step 'a <status> step' examples do row 'status' row 'passing' end end end end end it 'activates each step' do allow(step_match).to receive(:activate) do |test_step| expect(test_step.text).to eq('a passing step') end compile([doc], receiver, [filter]) end end context 'with an undefined step' do let(:step_match_search) { proc { [] } } let(:doc) do gherkin do feature do scenario do step 'an undefined step' end end end end it 'does not activate the step' do allow(receiver).to receive(:test_case) do |test_case| expect(test_case.test_steps[0].execute).to be_undefined end compile([doc], receiver, [filter]) end it 'does not notify' do expect(configuration).not_to receive(:notify) compile([doc], receiver, [filter]) end end context 'when using dry run' do let(:configuration) { double(dry_run?: true, notify: nil) } let(:doc) do gherkin do feature do scenario do step 'a passing step' end end end end it 'activates each step with a skipping action' do allow(receiver).to receive(:test_case) do |test_case| expect(test_case.test_steps[0].execute).to be_skipped end compile([doc], receiver, [filter]) end it 'notifies with a StepActivated event' do allow(configuration).to receive(:notify) do |message, _test_step, _step_match| expect(message).to eq(:step_activated) end compile([doc], receiver, [filter]) end it 'notifies with the correct step' do allow(configuration).to receive(:notify) do |_message, test_step, _step_match| expect(test_step.text).to eq('a passing step') end compile([doc], receiver, [filter]) end end context 'with an undefined step in a dry run' do let(:step_match_search) { proc { [] } } let(:configuration) { double(dry_run?: true, notify: nil) } let(:doc) do gherkin do feature do scenario do step 'an undefined step' end end end end it 'does not activate the step' do allow(receiver).to receive(:test_case) do |test_case| expect(test_case.test_steps[0].execute).to be_undefined end compile([doc], receiver, [filter]) end it 'does not notify' do expect(configuration).not_to receive(:notify) compile([doc], receiver, [filter]) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/filters/tag_limits_spec.rb
spec/cucumber/filters/tag_limits_spec.rb
# frozen_string_literal: true require 'cucumber/filters/tag_limits' describe Cucumber::Filters::TagLimits do subject(:filter) { described_class.new(tag_limits, receiver) } let(:tag_limits) { double(:tag_limits) } let(:receiver) { double(:receiver) } let(:gated_receiver) { double(:gated_receiver) } let(:test_case_index) { double(:test_case_index) } let(:test_case) { double(:test_case) } before do allow(Cucumber::Filters::GatedReceiver).to receive(:new).with(receiver) { gated_receiver } allow(Cucumber::Filters::TagLimits::TestCaseIndex).to receive(:new) { test_case_index } end describe '#test_case' do before do allow(test_case_index).to receive(:add) allow(gated_receiver).to receive(:test_case) end it 'indexes the test case' do expect(test_case_index).to receive(:add).with(test_case) filter.test_case(test_case) end it 'adds the test case to the gated receiver' do expect(gated_receiver).to receive(:test_case).with(test_case) filter.test_case(test_case) end end describe '#done' do let(:verifier) { double(:verifier) } before do allow(Cucumber::Filters::TagLimits::Verifier).to receive(:new).with(tag_limits) { verifier } allow(gated_receiver).to receive(:done) end it 'verifies tag limits have not been exceeded' do expect(verifier).to receive(:verify!).with(test_case_index) filter.done end context 'the verifier verifies successfully' do before do allow(verifier).to receive(:verify!).with(test_case_index) end it 'calls done on the receiver gate' do expect(gated_receiver).to receive(:done) filter.done end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/spec/cucumber/filters/gated_receiver_spec.rb
spec/cucumber/filters/gated_receiver_spec.rb
# frozen_string_literal: true require 'cucumber/filters/gated_receiver' describe Cucumber::Filters::GatedReceiver do subject(:gated_receiver) { described_class.new(receiver) } let(:receiver) { double(:receiver) } let(:test_cases) { [double(:test_case), double(:test_case)] } describe '#test_case' do it 'does not immediately describe the test case to the receiver' do test_cases.each do |test_case| expect(test_case).not_to receive(:describe_to).with(receiver) gated_receiver.test_case(test_case) end end end describe '#done' do before do test_cases.each do |test_case| gated_receiver.test_case(test_case) allow(test_case).to receive(:describe_to).with(receiver) end allow(receiver).to receive(:done) end it 'describes all test cases to the receiver' do expect(test_cases).to all receive(:describe_to).with(receiver) gated_receiver.done end it 'calls done on the receiver' do expect(receiver).to receive(:done) gated_receiver.done end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false