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
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/headers_processor.rb
lib/httparty/headers_processor.rb
# frozen_string_literal: true module HTTParty class HeadersProcessor attr_reader :headers, :options def initialize(headers, options) @headers = headers @options = options end def call return unless options[:headers] options[:headers] = headers.merge(options[:headers]) if headers.any? options[:headers] = Utils.stringify_keys(process_dynamic_headers) end private def process_dynamic_headers options[:headers].each_with_object({}) do |header, processed_headers| key, value = header processed_headers[key] = if value.respond_to?(:call) value.arity == 0 ? value.call : value.call(options) else value end end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/version.rb
lib/httparty/version.rb
# frozen_string_literal: true module HTTParty VERSION = '0.24.0' end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/exceptions.rb
lib/httparty/exceptions.rb
# frozen_string_literal: true module HTTParty COMMON_NETWORK_ERRORS = [ EOFError, Errno::ECONNABORTED, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH, Errno::EINVAL, Errno::ENETUNREACH, Errno::ENOTSOCK, Errno::EPIPE, Errno::ETIMEDOUT, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Net::ReadTimeout, OpenSSL::SSL::SSLError, SocketError, Timeout::Error # Also covers subclasses like Net::OpenTimeout ].freeze # @abstract Exceptions raised by HTTParty inherit from Error class Error < StandardError; end # @abstract Exceptions raised by HTTParty inherit from this because it is funny # and if you don't like fun you should be using a different library. class Foul < Error; end # Exception raised when you attempt to set a non-existent format class UnsupportedFormat < Foul; end # Exception raised when using a URI scheme other than HTTP or HTTPS class UnsupportedURIScheme < Foul; end # @abstract Exceptions which inherit from ResponseError contain the Net::HTTP # response object accessible via the {#response} method. class ResponseError < Foul # Returns the response of the last request # @return [Net::HTTPResponse] A subclass of Net::HTTPResponse, e.g. # Net::HTTPOK attr_reader :response # Instantiate an instance of ResponseError with a Net::HTTPResponse object # @param [Net::HTTPResponse] def initialize(response) @response = response super(response) end end # Exception that is raised when request has redirected too many times. # Calling {#response} returns the Net:HTTP response object. class RedirectionTooDeep < ResponseError; end # Exception that is raised when request redirects and location header is present more than once class DuplicateLocationHeader < ResponseError; end # Exception that is raised when common network errors occur. class NetworkError < Foul; end # Exception that is raised when an absolute URI is used that doesn't match # the configured base_uri, which could indicate an SSRF attempt. class UnsafeURIError < Foul; end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/response_fragment.rb
lib/httparty/response_fragment.rb
# frozen_string_literal: true require 'delegate' module HTTParty # Allow access to http_response and code by delegation on fragment class ResponseFragment < SimpleDelegator attr_reader :http_response, :connection def code @http_response.code.to_i end def initialize(fragment, http_response, connection) @fragment = fragment @http_response = http_response @connection = connection super fragment end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/hash_conversions.rb
lib/httparty/hash_conversions.rb
# frozen_string_literal: true require 'erb' module HTTParty module HashConversions # @return <String> This hash as a query string # # @example # { name: "Bob", # address: { # street: '111 Ruby Ave.', # city: 'Ruby Central', # phones: ['111-111-1111', '222-222-2222'] # } # }.to_params # #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111 Ruby Ave." def self.to_params(hash) hash.to_hash.map { |k, v| normalize_param(k, v) }.join.chop end # @param key<Object> The key for the param. # @param value<Object> The value for the param. # # @return <String> This key value pair as a param # # @example normalize_param(:name, "Bob Jones") #=> "name=Bob%20Jones&" def self.normalize_param(key, value) normalized_keys = normalize_keys(key, value) normalized_keys.flatten.each_slice(2).inject(''.dup) do |string, (k, v)| string << "#{ERB::Util.url_encode(k)}=#{ERB::Util.url_encode(v.to_s)}&" end end def self.normalize_keys(key, value) stack = [] normalized_keys = [] if value.respond_to?(:to_ary) if value.empty? normalized_keys << ["#{key}[]", ''] else normalized_keys = value.to_ary.flat_map do |element| normalize_keys("#{key}[]", element) end end elsif value.respond_to?(:to_hash) stack << [key, value.to_hash] else normalized_keys << [key.to_s, value] end stack.each do |parent, hash| hash.each do |child_key, child_value| if child_value.respond_to?(:to_hash) stack << ["#{parent}[#{child_key}]", child_value.to_hash] elsif child_value.respond_to?(:to_ary) child_value.to_ary.each do |v| normalized_keys << normalize_keys("#{parent}[#{child_key}][]", v).flatten end else normalized_keys << normalize_keys("#{parent}[#{child_key}]", child_value).flatten end end end normalized_keys end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/decompressor.rb
lib/httparty/decompressor.rb
# frozen_string_literal: true module HTTParty # Decompresses the response body based on the Content-Encoding header. # # Net::HTTP automatically decompresses Content-Encoding values "gzip" and "deflate". # This class will handle "br" (Brotli) and "compress" (LZW) if the requisite # gems are installed. Otherwise, it returns nil if the body data cannot be # decompressed. # # @abstract Read the HTTP Compression section for more information. class Decompressor # "gzip" and "deflate" are handled by Net::HTTP # hence they do not need to be handled by HTTParty SupportedEncodings = { 'none' => :none, 'identity' => :none, 'br' => :brotli, 'compress' => :lzw, 'zstd' => :zstd }.freeze # The response body of the request # @return [String] attr_reader :body # The Content-Encoding algorithm used to encode the body # @return [Symbol] e.g. :gzip attr_reader :encoding # @param [String] body - the response body of the request # @param [Symbol] encoding - the Content-Encoding algorithm used to encode the body def initialize(body, encoding) @body = body @encoding = encoding end # Perform decompression on the response body # @return [String] the decompressed body # @return [nil] when the response body is nil or cannot decompressed def decompress return nil if body.nil? return body if encoding.nil? || encoding.strip.empty? if supports_encoding? decompress_supported_encoding else nil end end protected def supports_encoding? SupportedEncodings.keys.include?(encoding) end def decompress_supported_encoding method = SupportedEncodings[encoding] if respond_to?(method, true) send(method) else raise NotImplementedError, "#{self.class.name} has not implemented a decompression method for #{encoding.inspect} encoding." end end def none body end def brotli return nil unless defined?(::Brotli) begin ::Brotli.inflate(body) rescue StandardError nil end end def lzw begin if defined?(::LZWS::String) ::LZWS::String.decompress(body) elsif defined?(::LZW::Simple) ::LZW::Simple.new.decompress(body) end rescue StandardError nil end end def zstd return nil unless defined?(::Zstd) begin ::Zstd.decompress(body) rescue StandardError nil end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/utils.rb
lib/httparty/utils.rb
# frozen_string_literal: true module HTTParty module Utils def self.stringify_keys(hash) return hash.transform_keys(&:to_s) if hash.respond_to?(:transform_keys) hash.each_with_object({}) do |(key, value), new_hash| new_hash[key.to_s] = value end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/response.rb
lib/httparty/response.rb
# frozen_string_literal: true module HTTParty class Response < Object def self.underscore(string) string.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z])([A-Z])/, '\1_\2').downcase end def self._load(data) req, resp, parsed_resp, resp_body = Marshal.load(data) new(req, resp, -> { parsed_resp }, body: resp_body) end attr_reader :request, :response, :body, :headers def initialize(request, response, parsed_block, options = {}) @request = request @response = response @body = options[:body] || response.body @parsed_block = parsed_block @headers = Headers.new(response.to_hash) if request.options[:logger] logger = ::HTTParty::Logger.build( request.options[:logger], request.options[:log_level], request.options[:log_format] ) logger.format(request, self) end throw_exception end def parsed_response @parsed_response ||= @parsed_block.call end def code response.code.to_i end def http_version response.http_version end def tap yield self self end def inspect inspect_id = ::Kernel::format '%x', (object_id * 2) %(#<#{self.class}:0x#{inspect_id} parsed_response=#{parsed_response.inspect}, @response=#{response.inspect}, @headers=#{headers.inspect}>) end CODES_TO_OBJ = ::Net::HTTPResponse::CODE_CLASS_TO_OBJ.merge ::Net::HTTPResponse::CODE_TO_OBJ CODES_TO_OBJ.each do |response_code, klass| name = klass.name.sub('Net::HTTP', '') name = "#{underscore(name)}?".to_sym define_method(name) do klass === response end end # Support old multiple_choice? method from pre 2.0.0 era. if ::RUBY_PLATFORM != 'java' alias_method :multiple_choice?, :multiple_choices? end # Support old status codes method from pre 2.6.0 era. if ::RUBY_PLATFORM != 'java' alias_method :gateway_time_out?, :gateway_timeout? alias_method :request_entity_too_large?, :payload_too_large? alias_method :request_time_out?, :request_timeout? alias_method :request_uri_too_long?, :uri_too_long? alias_method :requested_range_not_satisfiable?, :range_not_satisfiable? end def nil? warn_about_nil_deprecation response.nil? || response.body.nil? || response.body.empty? end def to_s if !response.nil? && !response.body.nil? && response.body.respond_to?(:to_s) response.body.to_s else inspect end end def pretty_print(pp) if !parsed_response.nil? && parsed_response.respond_to?(:pretty_print) parsed_response.pretty_print(pp) else super end end def display(port=$>) if !parsed_response.nil? && parsed_response.respond_to?(:display) parsed_response.display(port) elsif !response.nil? && !response.body.nil? && response.body.respond_to?(:display) response.body.display(port) else port.write(inspect) end end def respond_to_missing?(name, *args) return true if super parsed_response.respond_to?(name) || response.respond_to?(name) end def _dump(_level) Marshal.dump([request, response, parsed_response, body]) end protected def method_missing(name, *args, &block) if parsed_response.respond_to?(name) parsed_response.send(name, *args, &block) elsif response.respond_to?(name) response.send(name, *args, &block) else super end end def throw_exception if @request.options[:raise_on].to_a.detect { |c| code.to_s.match(/#{c.to_s}/) } ::Kernel.raise ::HTTParty::ResponseError.new(@response), "Code #{code} - #{body}" end end private def warn_about_nil_deprecation trace_line = caller.reject { |line| line.include?('httparty') }.first warning = "[DEPRECATION] HTTParty will no longer override `response#nil?`. " \ "This functionality will be removed in future versions. " \ "Please, add explicit check `response.body.nil? || response.body.empty?`. " \ "For more info refer to: https://github.com/jnunemaker/httparty/issues/568\n" \ "#{trace_line}" warn(warning) end end end require 'httparty/response/headers'
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/parser.rb
lib/httparty/parser.rb
# frozen_string_literal: true module HTTParty # The default parser used by HTTParty, supports xml, json, html, csv and # plain text. # # == Custom Parsers # # If you'd like to do your own custom parsing, subclassing HTTParty::Parser # will make that process much easier. There are a few different ways you can # utilize HTTParty::Parser as a superclass. # # @example Intercept the parsing for all formats # class SimpleParser < HTTParty::Parser # def parse # perform_parsing # end # end # # @example Add the atom format and parsing method to the default parser # class AtomParsingIncluded < HTTParty::Parser # SupportedFormats.merge!( # {"application/atom+xml" => :atom} # ) # # def atom # perform_atom_parsing # end # end # # @example Only support the atom format # class ParseOnlyAtom < HTTParty::Parser # SupportedFormats = {"application/atom+xml" => :atom} # # def atom # perform_atom_parsing # end # end # # @abstract Read the Custom Parsers section for more information. class Parser SupportedFormats = { 'text/xml' => :xml, 'application/xml' => :xml, 'application/json' => :json, 'application/vnd.api+json' => :json, 'application/hal+json' => :json, 'text/json' => :json, 'application/javascript' => :plain, 'text/javascript' => :plain, 'text/html' => :html, 'text/plain' => :plain, 'text/csv' => :csv, 'application/csv' => :csv, 'text/comma-separated-values' => :csv } # The response body of the request # @return [String] attr_reader :body # The intended parsing format for the request # @return [Symbol] e.g. :json attr_reader :format # Instantiate the parser and call {#parse}. # @param [String] body the response body # @param [Symbol] format the response format # @return parsed response def self.call(body, format) new(body, format).parse end # @return [Hash] the SupportedFormats hash def self.formats const_get(:SupportedFormats) end # @param [String] mimetype response MIME type # @return [Symbol] # @return [nil] mime type not supported def self.format_from_mimetype(mimetype) formats[formats.keys.detect {|k| mimetype.include?(k)}] end # @return [Array<Symbol>] list of supported formats def self.supported_formats formats.values.uniq end # @param [Symbol] format e.g. :json, :xml # @return [Boolean] def self.supports_format?(format) supported_formats.include?(format) end def initialize(body, format) @body = body @format = format end # @return [Object] the parsed body # @return [nil] when the response body is nil, an empty string, spaces only or "null" def parse return nil if body.nil? return nil if body == 'null' return nil if body.valid_encoding? && body.strip.empty? if body.valid_encoding? && body.encoding == Encoding::UTF_8 @body = body.gsub(/\A#{UTF8_BOM}/, '') end if supports_format? parse_supported_format else body end end protected def xml require 'multi_xml' MultiXml.parse(body) end UTF8_BOM = "\xEF\xBB\xBF" def json require 'json' JSON.parse(body, :quirks_mode => true, :allow_nan => true) end def csv require 'csv' CSV.parse(body) end def html body end def plain body end def supports_format? self.class.supports_format?(format) end def parse_supported_format if respond_to?(format, true) send(format) else raise NotImplementedError, "#{self.class.name} has not implemented a parsing method for the #{format.inspect} format." end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/connection_adapter.rb
lib/httparty/connection_adapter.rb
# frozen_string_literal: true module HTTParty # Default connection adapter that returns a new Net::HTTP each time # # == Custom Connection Factories # # If you like to implement your own connection adapter, subclassing # HTTParty::ConnectionAdapter will make it easier. Just override # the #connection method. The uri and options attributes will have # all the info you need to construct your http connection. Whatever # you return from your connection method needs to adhere to the # Net::HTTP interface as this is what HTTParty expects. # # @example log the uri and options # class LoggingConnectionAdapter < HTTParty::ConnectionAdapter # def connection # puts uri # puts options # Net::HTTP.new(uri) # end # end # # @example count number of http calls # class CountingConnectionAdapter < HTTParty::ConnectionAdapter # @@count = 0 # # self.count # @@count # end # # def connection # self.count += 1 # super # end # end # # === Configuration # There is lots of configuration data available for your connection adapter # in the #options attribute. It is up to you to interpret them within your # connection adapter. Take a look at the implementation of # HTTParty::ConnectionAdapter#connection for examples of how they are used. # The keys used in options are # * :+timeout+: timeout in seconds # * :+open_timeout+: http connection open_timeout in seconds, overrides timeout if set # * :+read_timeout+: http connection read_timeout in seconds, overrides timeout if set # * :+write_timeout+: http connection write_timeout in seconds, overrides timeout if set (Ruby >= 2.6.0 required) # * :+debug_output+: see HTTParty::ClassMethods.debug_output. # * :+cert_store+: contains certificate data. see method 'attach_ssl_certificates' # * :+pem+: contains pem client certificate data. see method 'attach_ssl_certificates' # * :+p12+: contains PKCS12 client client certificate data. see method 'attach_ssl_certificates' # * :+verify+: verify the server’s certificate against the ca certificate. # * :+verify_peer+: set to false to turn off server verification but still send client certificate # * :+ssl_ca_file+: see HTTParty::ClassMethods.ssl_ca_file. # * :+ssl_ca_path+: see HTTParty::ClassMethods.ssl_ca_path. # * :+ssl_version+: SSL versions to allow. see method 'attach_ssl_certificates' # * :+ciphers+: The list of SSL ciphers to support # * :+connection_adapter_options+: contains the hash you passed to HTTParty.connection_adapter when you configured your connection adapter # * :+local_host+: The local address to bind to # * :+local_port+: The local port to bind to # * :+http_proxyaddr+: HTTP Proxy address # * :+http_proxyport+: HTTP Proxy port # * :+http_proxyuser+: HTTP Proxy user # * :+http_proxypass+: HTTP Proxy password # # === Inherited methods # * :+clean_host+: Method used to sanitize host names class ConnectionAdapter # Private: Regex used to strip brackets from IPv6 URIs. StripIpv6BracketsRegex = /\A\[(.*)\]\z/ OPTION_DEFAULTS = { verify: true, verify_peer: true } # Public def self.call(uri, options) new(uri, options).connection end def self.default_cert_store @default_cert_store ||= OpenSSL::X509::Store.new.tap do |cert_store| cert_store.set_default_paths end end attr_reader :uri, :options def initialize(uri, options = {}) uri_adapter = options[:uri_adapter] || URI raise ArgumentError, "uri must be a #{uri_adapter}, not a #{uri.class}" unless uri.is_a? uri_adapter @uri = uri @options = OPTION_DEFAULTS.merge(options) end def connection host = clean_host(uri.host) port = uri.port || (uri.scheme == 'https' ? 443 : 80) if options.key?(:http_proxyaddr) http = Net::HTTP.new( host, port, options[:http_proxyaddr], options[:http_proxyport], options[:http_proxyuser], options[:http_proxypass] ) else http = Net::HTTP.new(host, port) end http.use_ssl = ssl_implied?(uri) attach_ssl_certificates(http, options) if add_timeout?(options[:timeout]) http.open_timeout = options[:timeout] http.read_timeout = options[:timeout] http.write_timeout = options[:timeout] end if add_timeout?(options[:read_timeout]) http.read_timeout = options[:read_timeout] end if add_timeout?(options[:open_timeout]) http.open_timeout = options[:open_timeout] end if add_timeout?(options[:write_timeout]) http.write_timeout = options[:write_timeout] end if add_max_retries?(options[:max_retries]) http.max_retries = options[:max_retries] end if options[:debug_output] http.set_debug_output(options[:debug_output]) end if options[:ciphers] http.ciphers = options[:ciphers] end # Bind to a specific local address or port # # @see https://bugs.ruby-lang.org/issues/6617 if options[:local_host] http.local_host = options[:local_host] end if options[:local_port] http.local_port = options[:local_port] end http end private def add_timeout?(timeout) timeout && (timeout.is_a?(Integer) || timeout.is_a?(Float)) end def add_max_retries?(max_retries) max_retries && max_retries.is_a?(Integer) && max_retries >= 0 end def clean_host(host) strip_ipv6_brackets(host) end def strip_ipv6_brackets(host) StripIpv6BracketsRegex =~ host ? $1 : host end def ssl_implied?(uri) uri.port == 443 || uri.scheme == 'https' end def verify_ssl_certificate? !(options[:verify] == false || options[:verify_peer] == false) end def attach_ssl_certificates(http, options) if http.use_ssl? if options.fetch(:verify, true) http.verify_mode = OpenSSL::SSL::VERIFY_PEER if options[:cert_store] http.cert_store = options[:cert_store] else # Use the default cert store by default, i.e. system ca certs http.cert_store = self.class.default_cert_store end else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # Client certificate authentication # Note: options[:pem] must contain the content of a PEM file having the private key appended if options[:pem] http.cert = OpenSSL::X509::Certificate.new(options[:pem]) http.key = OpenSSL::PKey.read(options[:pem], options[:pem_password]) http.verify_mode = verify_ssl_certificate? ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE end # PKCS12 client certificate authentication if options[:p12] p12 = OpenSSL::PKCS12.new(options[:p12], options[:p12_password]) http.cert = p12.certificate http.key = p12.key http.verify_mode = verify_ssl_certificate? ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE end # SSL certificate authority file and/or directory if options[:ssl_ca_file] http.ca_file = options[:ssl_ca_file] http.verify_mode = OpenSSL::SSL::VERIFY_PEER end if options[:ssl_ca_path] http.ca_path = options[:ssl_ca_path] http.verify_mode = OpenSSL::SSL::VERIFY_PEER end # This is only Ruby 1.9+ if options[:ssl_version] && http.respond_to?(:ssl_version=) http.ssl_version = options[:ssl_version] end end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/cookie_hash.rb
lib/httparty/cookie_hash.rb
# frozen_string_literal: true class HTTParty::CookieHash < Hash #:nodoc: CLIENT_COOKIES = %w(path expires domain path secure httponly samesite) def add_cookies(data) case data when Hash merge!(data) when String data.split('; ').each do |cookie| key, value = cookie.split('=', 2) self[key.to_sym] = value if key end else raise "add_cookies only takes a Hash or a String" end end def to_cookie_string select { |k, v| !CLIENT_COOKIES.include?(k.to_s.downcase) }.collect { |k, v| "#{k}=#{v}" }.join('; ') end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/module_inheritable_attributes.rb
lib/httparty/module_inheritable_attributes.rb
# frozen_string_literal: true module HTTParty module ModuleInheritableAttributes #:nodoc: def self.included(base) base.extend(ClassMethods) end # borrowed from Rails 3.2 ActiveSupport def self.hash_deep_dup(hash) duplicate = hash.dup duplicate.each_pair do |key, value| if value.is_a?(Hash) duplicate[key] = hash_deep_dup(value) elsif value.is_a?(Proc) duplicate[key] = value.dup else duplicate[key] = value end end duplicate end module ClassMethods #:nodoc: def mattr_inheritable(*args) @mattr_inheritable_attrs ||= [:mattr_inheritable_attrs] @mattr_inheritable_attrs += args args.each do |arg| singleton_class.attr_accessor(arg) end @mattr_inheritable_attrs end def inherited(subclass) super @mattr_inheritable_attrs.each do |inheritable_attribute| ivar = :"@#{inheritable_attribute}" subclass.instance_variable_set(ivar, instance_variable_get(ivar).clone) if instance_variable_get(ivar).respond_to?(:merge) subclass.class_eval <<~RUBY, __FILE__, __LINE__ + 1 def self.#{inheritable_attribute} duplicate = ModuleInheritableAttributes.hash_deep_dup(#{ivar}) #{ivar} = superclass.#{inheritable_attribute}.merge(duplicate) end RUBY end end end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/request.rb
lib/httparty/request.rb
# frozen_string_literal: true require 'erb' module HTTParty class Request #:nodoc: SupportedHTTPMethods = [ Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Patch, Net::HTTP::Put, Net::HTTP::Delete, Net::HTTP::Head, Net::HTTP::Options, Net::HTTP::Move, Net::HTTP::Copy, Net::HTTP::Mkcol, Net::HTTP::Lock, Net::HTTP::Unlock, ] SupportedURISchemes = ['http', 'https', 'webcal', nil] NON_RAILS_QUERY_STRING_NORMALIZER = proc do |query| Array(query).sort_by { |a| a[0].to_s }.map do |key, value| if value.nil? key.to_s elsif value.respond_to?(:to_ary) value.to_ary.map {|v| "#{key}=#{ERB::Util.url_encode(v.to_s)}"} else HashConversions.to_params(key => value) end end.flatten.join('&') end JSON_API_QUERY_STRING_NORMALIZER = proc do |query| Array(query).sort_by { |a| a[0].to_s }.map do |key, value| if value.nil? key.to_s elsif value.respond_to?(:to_ary) values = value.to_ary.map{|v| ERB::Util.url_encode(v.to_s)} "#{key}=#{values.join(',')}" else HashConversions.to_params(key => value) end end.flatten.join('&') end def self._load(data) http_method, path, options, last_response, last_uri, raw_request = Marshal.load(data) instance = new(http_method, path, options) instance.last_response = last_response instance.last_uri = last_uri instance.instance_variable_set("@raw_request", raw_request) instance end attr_accessor :http_method, :options, :last_response, :redirect, :last_uri attr_reader :path def initialize(http_method, path, o = {}) @changed_hosts = false @credentials_sent = false self.http_method = http_method self.options = { limit: o.delete(:no_follow) ? 1 : 5, assume_utf16_is_big_endian: true, default_params: {}, follow_redirects: true, parser: Parser, uri_adapter: URI, connection_adapter: ConnectionAdapter }.merge(o) self.path = path set_basic_auth_from_uri end def path=(uri) uri_adapter = options[:uri_adapter] @path = if uri.is_a?(uri_adapter) uri elsif String.try_convert(uri) uri_adapter.parse(uri).normalize else raise ArgumentError, "bad argument (expected #{uri_adapter} object or URI string)" end end def request_uri(uri) if uri.respond_to? :request_uri uri.request_uri else uri.path end end def uri if redirect && path.relative? && path.path[0] != '/' last_uri_host = @last_uri.path.gsub(/[^\/]+$/, '') path.path = "/#{path.path}" if last_uri_host[-1] != '/' path.path = "#{last_uri_host}#{path.path}" end if path.relative? && path.host new_uri = options[:uri_adapter].parse("#{@last_uri.scheme}:#{path}").normalize elsif path.relative? new_uri = options[:uri_adapter].parse("#{base_uri}#{path}").normalize else new_uri = path.clone end validate_uri_safety!(new_uri) unless redirect # avoid double query string on redirects [#12] unless redirect new_uri.query = query_string(new_uri) end unless SupportedURISchemes.include? new_uri.scheme raise UnsupportedURIScheme, "'#{new_uri}' Must be HTTP, HTTPS or Generic" end @last_uri = new_uri end def base_uri if redirect base_uri = "#{@last_uri.scheme}://#{@last_uri.host}" base_uri = "#{base_uri}:#{@last_uri.port}" if @last_uri.port != 80 base_uri else options[:base_uri] && HTTParty.normalize_base_uri(options[:base_uri]) end end def format options[:format] || (format_from_mimetype(last_response['content-type']) if last_response) end def parser options[:parser] end def connection_adapter options[:connection_adapter] end def perform(&block) validate setup_raw_request chunked_body = nil current_http = http begin self.last_response = current_http.request(@raw_request) do |http_response| if block chunks = [] http_response.read_body do |fragment| encoded_fragment = encode_text(fragment, http_response['content-type']) chunks << encoded_fragment if !options[:stream_body] block.call ResponseFragment.new(encoded_fragment, http_response, current_http) end chunked_body = chunks.join end end handle_host_redirection if response_redirects? result = handle_unauthorized result ||= handle_response(chunked_body, &block) result rescue *COMMON_NETWORK_ERRORS => e raise options[:foul] ? HTTParty::NetworkError.new("#{e.class}: #{e.message}") : e end end def handle_unauthorized(&block) return unless digest_auth? && response_unauthorized? && response_has_digest_auth_challenge? return if @credentials_sent @credentials_sent = true perform(&block) end def raw_body @raw_request.body end def _dump(_level) opts = options.dup opts.delete(:logger) opts.delete(:parser) if opts[:parser] && opts[:parser].is_a?(Proc) Marshal.dump([http_method, path, opts, last_response, @last_uri, @raw_request]) end private def http connection_adapter.call(uri, options) end def credentials (options[:basic_auth] || options[:digest_auth]).to_hash end def username credentials[:username] end def password credentials[:password] end def normalize_query(query) if query_string_normalizer query_string_normalizer.call(query) else HashConversions.to_params(query) end end def query_string_normalizer options[:query_string_normalizer] end def setup_raw_request if options[:headers].respond_to?(:to_hash) headers_hash = options[:headers].to_hash else headers_hash = nil end @raw_request = http_method.new(request_uri(uri), headers_hash) @raw_request.body_stream = options[:body_stream] if options[:body_stream] if options[:body] body = Body.new( options[:body], query_string_normalizer: query_string_normalizer, force_multipart: options[:multipart] ) if body.multipart? content_type = "multipart/form-data; boundary=#{body.boundary}" @raw_request['Content-Type'] = content_type elsif options[:body].respond_to?(:to_hash) && !@raw_request['Content-Type'] @raw_request['Content-Type'] = 'application/x-www-form-urlencoded' end if body.streaming? && options[:stream_body] != false stream = body.to_stream @raw_request.body_stream = stream @raw_request['Content-Length'] = stream.size.to_s else @raw_request.body = body.call end end @raw_request.instance_variable_set(:@decode_content, decompress_content?) if options[:basic_auth] && send_authorization_header? @raw_request.basic_auth(username, password) @credentials_sent = true end setup_digest_auth if digest_auth? && response_unauthorized? && response_has_digest_auth_challenge? end def digest_auth? !!options[:digest_auth] end def decompress_content? !options[:skip_decompression] end def response_unauthorized? !!last_response && last_response.code == '401' end def response_has_digest_auth_challenge? !last_response['www-authenticate'].nil? && last_response['www-authenticate'].length > 0 end def setup_digest_auth @raw_request.digest_auth(username, password, last_response) end def query_string(uri) query_string_parts = [] query_string_parts << uri.query unless uri.query.nil? if options[:query].respond_to?(:to_hash) query_string_parts << normalize_query(options[:default_params].merge(options[:query].to_hash)) else query_string_parts << normalize_query(options[:default_params]) unless options[:default_params].empty? query_string_parts << options[:query] unless options[:query].nil? end query_string_parts.reject!(&:empty?) unless query_string_parts == [''] query_string_parts.size > 0 ? query_string_parts.join('&') : nil end def assume_utf16_is_big_endian options[:assume_utf16_is_big_endian] end def handle_response(raw_body, &block) if response_redirects? handle_redirection(&block) else raw_body ||= last_response.body body = decompress(raw_body, last_response['content-encoding']) unless raw_body.nil? unless body.nil? body = encode_text(body, last_response['content-type']) if decompress_content? last_response.delete('content-encoding') raw_body = body end end Response.new(self, last_response, lambda { parse_response(body) }, body: raw_body) end end def handle_redirection(&block) options[:limit] -= 1 if options[:logger] logger = HTTParty::Logger.build(options[:logger], options[:log_level], options[:log_format]) logger.format(self, last_response) end self.path = last_response['location'] self.redirect = true if last_response.class == Net::HTTPSeeOther unless options[:maintain_method_across_redirects] && options[:resend_on_redirect] self.http_method = Net::HTTP::Get end elsif last_response.code != '307' && last_response.code != '308' unless options[:maintain_method_across_redirects] self.http_method = Net::HTTP::Get end end if http_method == Net::HTTP::Get clear_body end capture_cookies(last_response) perform(&block) end def handle_host_redirection check_duplicate_location_header redirect_path = options[:uri_adapter].parse(last_response['location']).normalize return if redirect_path.relative? || path.host == redirect_path.host || uri.host == redirect_path.host @changed_hosts = true end def check_duplicate_location_header location = last_response.get_fields('location') if location.is_a?(Array) && location.count > 1 raise DuplicateLocationHeader.new(last_response) end end def send_authorization_header? !@changed_hosts end def response_redirects? case last_response when Net::HTTPNotModified # 304 false when Net::HTTPRedirection options[:follow_redirects] && last_response.key?('location') end end def parse_response(body) parser.call(body, format) end # Some Web Application Firewalls reject incoming GET requests that have a body # if we redirect, and the resulting verb is GET then we will clear the body that # may be left behind from the initiating request def clear_body options[:body] = nil @raw_request.body = nil end def capture_cookies(response) return unless response['Set-Cookie'] cookies_hash = HTTParty::CookieHash.new cookies_hash.add_cookies(options[:headers].to_hash['Cookie']) if options[:headers] && options[:headers].to_hash['Cookie'] response.get_fields('Set-Cookie').each { |cookie| cookies_hash.add_cookies(cookie) } options[:headers] ||= {} options[:headers]['Cookie'] = cookies_hash.to_cookie_string end # Uses the HTTP Content-Type header to determine the format of the # response It compares the MIME type returned to the types stored in the # SupportedFormats hash def format_from_mimetype(mimetype) if mimetype && parser.respond_to?(:format_from_mimetype) parser.format_from_mimetype(mimetype) end end def validate raise HTTParty::RedirectionTooDeep.new(last_response), 'HTTP redirects too deep' if options[:limit].to_i <= 0 raise ArgumentError, 'only get, post, patch, put, delete, head, and options methods are supported' unless SupportedHTTPMethods.include?(http_method) raise ArgumentError, ':headers must be a hash' if options[:headers] && !options[:headers].respond_to?(:to_hash) raise ArgumentError, 'only one authentication method, :basic_auth or :digest_auth may be used at a time' if options[:basic_auth] && options[:digest_auth] raise ArgumentError, ':basic_auth must be a hash' if options[:basic_auth] && !options[:basic_auth].respond_to?(:to_hash) raise ArgumentError, ':digest_auth must be a hash' if options[:digest_auth] && !options[:digest_auth].respond_to?(:to_hash) raise ArgumentError, ':query must be hash if using HTTP Post' if post? && !options[:query].nil? && !options[:query].respond_to?(:to_hash) end def post? Net::HTTP::Post == http_method end def set_basic_auth_from_uri if path.userinfo username, password = path.userinfo.split(':') options[:basic_auth] = {username: username, password: password} @credentials_sent = true end end def decompress(body, encoding) Decompressor.new(body, encoding).decompress end def encode_text(text, content_type) TextEncoder.new( text, content_type: content_type, assume_utf16_is_big_endian: assume_utf16_is_big_endian ).call end def validate_uri_safety!(new_uri) return if options[:skip_uri_validation] configured_base_uri = options[:base_uri] return unless configured_base_uri normalized_base = options[:uri_adapter].parse( HTTParty.normalize_base_uri(configured_base_uri) ) return if new_uri.host == normalized_base.host raise UnsafeURIError, "Requested URI '#{new_uri}' has host '#{new_uri.host}' but the " \ "configured base_uri '#{normalized_base}' has host '#{normalized_base.host}'. " \ "This request could send credentials to an unintended server." end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/net_digest_auth.rb
lib/httparty/net_digest_auth.rb
# frozen_string_literal: true require 'digest/md5' require 'net/http' module Net module HTTPHeader def digest_auth(username, password, response) authenticator = DigestAuthenticator.new( username, password, @method, @path, response ) authenticator.authorization_header.each do |v| add_field('Authorization', v) end authenticator.cookie_header.each do |v| add_field('Cookie', v) end end class DigestAuthenticator def initialize(username, password, method, path, response_header) @username = username @password = password @method = method @path = path @response = parse(response_header) @cookies = parse_cookies(response_header) end def authorization_header @cnonce = md5(random) header = [ %(Digest username="#{@username}"), %(realm="#{@response['realm']}"), %(nonce="#{@response['nonce']}"), %(uri="#{@path}"), %(response="#{request_digest}") ] header << %(algorithm="#{@response['algorithm']}") if algorithm_present? if qop_present? header << %(cnonce="#{@cnonce}") header << %(qop="#{@response['qop']}") header << 'nc=00000001' end header << %(opaque="#{@response['opaque']}") if opaque_present? header end def cookie_header @cookies end private def parse(response_header) header = response_header['www-authenticate'] header = header.gsub(/qop=(auth(?:-int)?)/, 'qop="\\1"') header =~ /Digest (.*)/ params = {} if $1 non_quoted = $1.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 } non_quoted.gsub(/(\w+)=([^,]*)/) { params[$1] = $2 } end params end def parse_cookies(response_header) return [] unless response_header['Set-Cookie'] cookies = response_header['Set-Cookie'].split('; ') cookies.reduce([]) do |ret, cookie| ret << cookie ret end cookies end def opaque_present? @response.key?('opaque') && !@response['opaque'].empty? end def qop_present? @response.key?('qop') && !@response['qop'].empty? end def random format '%x', (Time.now.to_i + rand(65535)) end def request_digest a = [md5(a1), @response['nonce'], md5(a2)] a.insert(2, '00000001', @cnonce, @response['qop']) if qop_present? md5(a.join(':')) end def md5(str) Digest::MD5.hexdigest(str) end def algorithm_present? @response.key?('algorithm') && !@response['algorithm'].empty? end def use_md5_sess? algorithm_present? && @response['algorithm'] == 'MD5-sess' end def a1 a1_user_realm_pwd = [@username, @response['realm'], @password].join(':') if use_md5_sess? [ md5(a1_user_realm_pwd), @response['nonce'], @cnonce ].join(':') else a1_user_realm_pwd end end def a2 [@method, @path].join(':') end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/text_encoder.rb
lib/httparty/text_encoder.rb
# frozen_string_literal: true module HTTParty class TextEncoder attr_reader :text, :content_type, :assume_utf16_is_big_endian def initialize(text, assume_utf16_is_big_endian: true, content_type: nil) @text = +text @content_type = content_type @assume_utf16_is_big_endian = assume_utf16_is_big_endian end def call if can_encode? encoded_text else text end end private def can_encode? ''.respond_to?(:encoding) && charset end def encoded_text if 'utf-16'.casecmp(charset) == 0 encode_utf_16 else encode_with_ruby_encoding end end def encode_utf_16 if text.bytesize >= 2 if text.getbyte(0) == 0xFF && text.getbyte(1) == 0xFE return text.force_encoding('UTF-16LE') elsif text.getbyte(0) == 0xFE && text.getbyte(1) == 0xFF return text.force_encoding('UTF-16BE') end end if assume_utf16_is_big_endian # option text.force_encoding('UTF-16BE') else text.force_encoding('UTF-16LE') end end def encode_with_ruby_encoding # NOTE: This will raise an argument error if the # charset does not exist encoding = Encoding.find(charset) text.force_encoding(encoding.to_s) rescue ArgumentError text end def charset return nil if content_type.nil? if (matchdata = content_type.match(/;\s*charset\s*=\s*([^=,;"\s]+)/i)) return matchdata.captures.first end if (matchdata = content_type.match(/;\s*charset\s*=\s*"((\\.|[^\\"])+)"/i)) return matchdata.captures.first.gsub(/\\(.)/, '\1') end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/logger/logger.rb
lib/httparty/logger/logger.rb
# frozen_string_literal: true require 'httparty/logger/apache_formatter' require 'httparty/logger/curl_formatter' require 'httparty/logger/logstash_formatter' module HTTParty module Logger def self.formatters @formatters ||= { :curl => Logger::CurlFormatter, :apache => Logger::ApacheFormatter, :logstash => Logger::LogstashFormatter, } end def self.add_formatter(name, formatter) raise HTTParty::Error.new("Log Formatter with name #{name} already exists") if formatters.include?(name) formatters.merge!(name.to_sym => formatter) end def self.build(logger, level, formatter) level ||= :info formatter ||= :apache logger_klass = formatters[formatter] || Logger::ApacheFormatter logger_klass.new(logger, level) end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/logger/curl_formatter.rb
lib/httparty/logger/curl_formatter.rb
# frozen_string_literal: true module HTTParty module Logger class CurlFormatter #:nodoc: TAG_NAME = HTTParty.name OUT = '>' IN = '<' attr_accessor :level, :logger def initialize(logger, level) @logger = logger @level = level.to_sym @messages = [] end def format(request, response) @request = request @response = response log_request log_response logger.public_send level, messages.join("\n") end private attr_reader :request, :response attr_accessor :messages def log_request log_url log_headers log_query log OUT, request.raw_body if request.raw_body log OUT end def log_response log IN, "HTTP/#{response.http_version} #{response.code}" log_response_headers log IN, "\n#{response.body}" log IN end def log_url http_method = request.http_method.name.split('::').last.upcase uri = if request.options[:base_uri] request.options[:base_uri] + request.path.path else request.path.to_s end log OUT, "#{http_method} #{uri}" end def log_headers return unless request.options[:headers] && request.options[:headers].size > 0 log OUT, 'Headers: ' log_hash request.options[:headers] end def log_query return unless request.options[:query] log OUT, 'Query: ' log_hash request.options[:query] end def log_response_headers headers = response.respond_to?(:headers) ? response.headers : response response.each_header do |response_header| log IN, "#{response_header.capitalize}: #{headers[response_header]}" end end def log_hash(hash) hash.each { |k, v| log(OUT, "#{k}: #{v}") } end def log(direction, line = '') messages << "[#{TAG_NAME}] [#{current_time}] #{direction} #{line}" end def current_time Time.now.strftime("%Y-%m-%d %H:%M:%S %z") end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/logger/logstash_formatter.rb
lib/httparty/logger/logstash_formatter.rb
# frozen_string_literal: true module HTTParty module Logger class LogstashFormatter #:nodoc: TAG_NAME = HTTParty.name attr_accessor :level, :logger def initialize(logger, level) @logger = logger @level = level.to_sym end def format(request, response) @request = request @response = response logger.public_send level, logstash_message end private attr_reader :request, :response def logstash_message require 'json' { '@timestamp' => current_time, '@version' => 1, 'content_length' => content_length || '-', 'http_method' => http_method, 'message' => message, 'path' => path, 'response_code' => response.code, 'severity' => level, 'tags' => [TAG_NAME], }.to_json end def message "[#{TAG_NAME}] #{response.code} \"#{http_method} #{path}\" #{content_length || '-'} " end def current_time Time.now.strftime('%Y-%m-%d %H:%M:%S %z') end def http_method @http_method ||= request.http_method.name.split('::').last.upcase end def path @path ||= request.path.to_s end def content_length @content_length ||= response.respond_to?(:headers) ? response.headers['Content-Length'] : response['Content-Length'] end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/logger/apache_formatter.rb
lib/httparty/logger/apache_formatter.rb
# frozen_string_literal: true module HTTParty module Logger class ApacheFormatter #:nodoc: TAG_NAME = HTTParty.name attr_accessor :level, :logger def initialize(logger, level) @logger = logger @level = level.to_sym end def format(request, response) @request = request @response = response logger.public_send level, message end private attr_reader :request, :response def message "[#{TAG_NAME}] [#{current_time}] #{response.code} \"#{http_method} #{path}\" #{content_length || '-'} " end def current_time Time.now.strftime('%Y-%m-%d %H:%M:%S %z') end def http_method request.http_method.name.split('::').last.upcase end def path request.path.to_s end def content_length response.respond_to?(:headers) ? response.headers['Content-Length'] : response['Content-Length'] end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/response/headers.rb
lib/httparty/response/headers.rb
# frozen_string_literal: true require 'delegate' module HTTParty class Response #:nodoc: class Headers < ::SimpleDelegator include ::Net::HTTPHeader def initialize(header_values = nil) @header = {} if header_values header_values.each_pair do |k,v| if v.is_a?(Array) v.each do |sub_v| add_field(k, sub_v) end else add_field(k, v) end end end super(@header) end def ==(other) if other.is_a?(::Net::HTTPHeader) @header == other.instance_variable_get(:@header) elsif other.is_a?(Hash) @header == other || @header == Headers.new(other).instance_variable_get(:@header) end end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/request/body.rb
lib/httparty/request/body.rb
# frozen_string_literal: true require_relative 'multipart_boundary' require_relative 'streaming_multipart_body' module HTTParty class Request class Body NEWLINE = "\r\n" private_constant :NEWLINE def initialize(params, query_string_normalizer: nil, force_multipart: false) @params = params @query_string_normalizer = query_string_normalizer @force_multipart = force_multipart end def call if params.respond_to?(:to_hash) multipart? ? generate_multipart : normalize_query(params) else params end end def boundary @boundary ||= MultipartBoundary.generate end def multipart? params.respond_to?(:to_hash) && (force_multipart || has_file?(params)) end def streaming? multipart? && has_file?(params) end def to_stream return nil unless streaming? StreamingMultipartBody.new(prepared_parts, boundary) end def prepared_parts normalized_params = params.flat_map { |key, value| HashConversions.normalize_keys(key, value) } normalized_params.map do |key, value| [key, value, file?(value)] end end private # https://html.spec.whatwg.org/#multipart-form-data MULTIPART_FORM_DATA_REPLACEMENT_TABLE = { '"' => '%22', "\r" => '%0D', "\n" => '%0A' }.freeze def generate_multipart normalized_params = params.flat_map { |key, value| HashConversions.normalize_keys(key, value) } multipart = normalized_params.inject(''.b) do |memo, (key, value)| memo << "--#{boundary}#{NEWLINE}".b memo << %(Content-Disposition: form-data; name="#{key}").b # value.path is used to support ActionDispatch::Http::UploadedFile # https://github.com/jnunemaker/httparty/pull/585 memo << %(; filename="#{file_name(value).gsub(/["\r\n]/, MULTIPART_FORM_DATA_REPLACEMENT_TABLE)}").b if file?(value) memo << NEWLINE.b memo << "Content-Type: #{content_type(value)}#{NEWLINE}".b if file?(value) memo << NEWLINE.b memo << content_body(value) memo << NEWLINE.b end multipart << "--#{boundary}--#{NEWLINE}".b end def has_file?(value) if value.respond_to?(:to_hash) value.to_hash.any? { |_, v| has_file?(v) } elsif value.respond_to?(:to_ary) value.to_ary.any? { |v| has_file?(v) } else file?(value) end end def file?(object) object.respond_to?(:path) && object.respond_to?(:read) end def normalize_query(query) if query_string_normalizer query_string_normalizer.call(query) else HashConversions.to_params(query) end end def content_body(object) if file?(object) object = (file = object).read object.force_encoding(Encoding::BINARY) if object.respond_to?(:force_encoding) file.rewind if file.respond_to?(:rewind) object.to_s else object.to_s.b end end def content_type(object) return object.content_type if object.respond_to?(:content_type) require 'mini_mime' mime = MiniMime.lookup_by_filename(object.path) mime ? mime.content_type : 'application/octet-stream' end def file_name(object) object.respond_to?(:original_filename) ? object.original_filename : File.basename(object.path) end attr_reader :params, :query_string_normalizer, :force_multipart end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/request/multipart_boundary.rb
lib/httparty/request/multipart_boundary.rb
# frozen_string_literal: true require 'securerandom' module HTTParty class Request class MultipartBoundary def self.generate "------------------------#{SecureRandom.urlsafe_base64(12)}" end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty/request/streaming_multipart_body.rb
lib/httparty/request/streaming_multipart_body.rb
# frozen_string_literal: true module HTTParty class Request class StreamingMultipartBody NEWLINE = "\r\n" CHUNK_SIZE = 64 * 1024 # 64 KB chunks def initialize(parts, boundary) @parts = parts @boundary = boundary @part_index = 0 @state = :header @current_file = nil @header_buffer = nil @header_offset = 0 @footer_sent = false end def size @size ||= calculate_size end def read(length = nil, outbuf = nil) outbuf = outbuf ? outbuf.replace(''.b) : ''.b return read_all(outbuf) if length.nil? while outbuf.bytesize < length chunk = read_chunk(length - outbuf.bytesize) break if chunk.nil? outbuf << chunk end outbuf.empty? ? nil : outbuf end def rewind @part_index = 0 @state = :header @current_file = nil @header_buffer = nil @header_offset = 0 @footer_sent = false @parts.each do |_key, value, _is_file| value.rewind if value.respond_to?(:rewind) end end private def read_all(outbuf) while (chunk = read_chunk(CHUNK_SIZE)) outbuf << chunk end outbuf.empty? ? nil : outbuf end def read_chunk(max_length) loop do return nil if @part_index >= @parts.size && @footer_sent if @part_index >= @parts.size @footer_sent = true return "--#{@boundary}--#{NEWLINE}".b end key, value, is_file = @parts[@part_index] case @state when :header chunk = read_header_chunk(key, value, is_file, max_length) return chunk if chunk when :body chunk = read_body_chunk(value, is_file, max_length) return chunk if chunk when :newline @state = :header @part_index += 1 return NEWLINE.b end end end def read_header_chunk(key, value, is_file, max_length) if @header_buffer.nil? @header_buffer = build_part_header(key, value, is_file) @header_offset = 0 end remaining = @header_buffer.bytesize - @header_offset if remaining > 0 chunk_size = [remaining, max_length].min chunk = @header_buffer.byteslice(@header_offset, chunk_size) @header_offset += chunk_size return chunk end @header_buffer = nil @header_offset = 0 @state = :body nil end def read_body_chunk(value, is_file, max_length) if is_file chunk = read_file_chunk(value, max_length) if chunk return chunk else @current_file = nil @state = :newline return nil end else @state = :newline return value.to_s.b end end def read_file_chunk(file, max_length) chunk_size = [max_length, CHUNK_SIZE].min chunk = file.read(chunk_size) return nil if chunk.nil? chunk.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding) chunk end def build_part_header(key, value, is_file) header = "--#{@boundary}#{NEWLINE}".b header << %(Content-Disposition: form-data; name="#{key}").b if is_file header << %(; filename="#{file_name(value).gsub(/["\r\n]/, replacement_table)}").b header << NEWLINE.b header << "Content-Type: #{content_type(value)}#{NEWLINE}".b end header << NEWLINE.b header end def calculate_size total = 0 @parts.each do |key, value, is_file| total += build_part_header(key, value, is_file).bytesize total += content_size(value, is_file) total += NEWLINE.bytesize end total += "--#{@boundary}--#{NEWLINE}".bytesize total end def content_size(value, is_file) if is_file if value.respond_to?(:size) value.size elsif value.respond_to?(:stat) value.stat.size else value.read.bytesize.tap { value.rewind } end else value.to_s.b.bytesize end end def content_type(object) return object.content_type if object.respond_to?(:content_type) require 'mini_mime' mime = MiniMime.lookup_by_filename(object.path) mime ? mime.content_type : 'application/octet-stream' end def file_name(object) object.respond_to?(:original_filename) ? object.original_filename : File.basename(object.path) end def replacement_table @replacement_table ||= { '"' => '%22', "\r" => '%0D', "\n" => '%0A' }.freeze end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/.github/workflows/actions/memprof.rb
.github/workflows/actions/memprof.rb
# frozen_string_literal: true require 'jekyll' require 'memory_profiler' MemoryProfiler.report(allow_files: ['lib/jekyll/', 'lib/jekyll.rb']) do Jekyll::PluginManager.require_from_bundler Jekyll::Commands::Build.process({ "source" => File.expand_path(ARGV[0]), "destination" => File.expand_path("#{ARGV[0]}/_site"), "disable_disk_cache" => true, }) puts '' end.pretty_print(scale_bytes: true, normalize_paths: true)
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/rubocop/jekyll.rb
rubocop/jekyll.rb
# frozen_string_literal: true Dir[File.join(File.expand_path("jekyll", __dir__), "*.rb")].each do |ruby_file| require ruby_file end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/rubocop/jekyll/no_puts_allowed.rb
rubocop/jekyll/no_puts_allowed.rb
# frozen_string_literal: true module RuboCop module Cop module Jekyll class NoPutsAllowed < Base MSG = "Avoid using `puts` to print things. Use `Jekyll.logger` instead." RESTRICT_ON_SEND = %i[puts].freeze def_node_search :puts_called?, <<-PATTERN (send nil? :puts _) PATTERN def on_send(node) if puts_called?(node) add_offense(node.loc.selector) end end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/rubocop/jekyll/no_p_allowed.rb
rubocop/jekyll/no_p_allowed.rb
# frozen_string_literal: true module RuboCop module Cop module Jekyll class NoPAllowed < Base MSG = "Avoid using `p` to print things. Use `Jekyll.logger` instead." RESTRICT_ON_SEND = %i[p].freeze def_node_search :p_called?, <<-PATTERN (send _ :p _) PATTERN def on_send(node) if p_called?(node) add_offense(node.loc.selector) end end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/rubocop/jekyll/assert_equal_literal_actual.rb
rubocop/jekyll/assert_equal_literal_actual.rb
# frozen_string_literal: true module RuboCop module Cop module Jekyll # Checks for `assert_equal(exp, act, msg = nil)` calls containing literal values as # second argument. The second argument should ideally be a method called on the tested # instance. # # @example # # bad # assert_equal @foo.bar, "foobar" # assert_equal @alpha.beta, { "foo" => "bar", "lorem" => "ipsum" } # assert_equal @alpha.omega, ["foobar", "lipsum"] # # # good # assert_equal "foobar", @foo.bar # # assert_equal( # { "foo" => "bar", "lorem" => "ipsum" }, # @alpha.beta # ) # # assert_equal( # ["foobar", "lipsum"], # @alpha.omega # ) # class AssertEqualLiteralActual < Base extend AutoCorrector MSG = "Provide the 'expected value' as the first argument to `assert_equal`." RESTRICT_ON_SEND = %i[assert_equal].freeze SIMPLE_LITERALS = %i( true false nil int float str sym complex rational regopt ).freeze COMPLEX_LITERALS = %i( array hash pair irange erange regexp ).freeze def_node_matcher :literal_actual?, <<-PATTERN (send nil? :assert_equal $(send ...) $#literal?) PATTERN def_node_matcher :literal_actual_with_msg?, <<-PATTERN (send nil? :assert_equal $(send ...) $#literal? $#opt_msg?) PATTERN def on_send(node) return unless literal_actual?(node) || literal_actual_with_msg?(node) range = node.loc.expression add_offense(range) do |corrector| corrector.replace(range, replacement(node)) end end private def opt_msg?(node) node&.source end # This is not implement using a NodePattern because it seems # to not be able to match against an explicit (nil) sexp def literal?(node) node && (simple_literal?(node) || complex_literal?(node)) end def simple_literal?(node) SIMPLE_LITERALS.include?(node.type) end def complex_literal?(node) COMPLEX_LITERALS.include?(node.type) && node.each_child_node.all?(&method(:literal?)) end def replacement(node) _, _, first_param, second_param, optional_param = *node replaced_text = \ if second_param.type == :hash replace_hash_with_variable(first_param.source, second_param.source) elsif second_param.type == :array && second_param.source != "[]" replace_array_with_variable(first_param.source, second_param.source) else replace_based_on_line_length(first_param.source, second_param.source) end return "#{replaced_text}, #{optional_param.source}" if optional_param replaced_text end def replace_based_on_line_length(first_expression, second_expression) result = "assert_equal #{second_expression}, #{first_expression}" return result if result.length < 80 # fold long lines independent of Rubocop configuration for better readability <<~TEXT assert_equal( #{second_expression}, #{first_expression} ) TEXT end def replace_hash_with_variable(first_expression, second_expression) expect_expression = if second_expression.start_with?("{") second_expression else "{#{second_expression}}" end <<~TEXT expected = #{expect_expression} assert_equal expected, #{first_expression} TEXT end def replace_array_with_variable(first_expression, second_expression) expect_expression = if second_expression.start_with?("%") second_expression else Array(second_expression) end <<~TEXT expected = #{expect_expression} assert_equal expected, #{first_expression} TEXT end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/conditional_liquid.rb
benchmark/conditional_liquid.rb
#!/usr/bin/env ruby # frozen_string_literal: true require "liquid" require "benchmark/ips" # Test if processing content string without any Liquid constructs, via Liquid, # is slower than checking whether constructs exist ( using `String#include?` ) # and return-ing the "plaintext" content string as is.. # # Ref: https://github.com/jekyll/jekyll/pull/6735 # Sample contents WITHOUT_LIQUID = <<-TEXT.freeze Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor libero at pharetra tempus. Etiam bibendum magna et metus fermentum, eu cursus lorem mattis. Curabitur vel dui et lacus rutrum suscipit et eget neque. Nullam luctus fermentum est id blandit. Phasellus consectetur ullamcorper ligula, at finibus eros laoreet id. Etiam sit amet est in libero efficitur tristique. Ut nec magna augue. Quisque ut fringilla lacus, ac dictum enim. Aliquam vel ornare mauris. Suspendisse ornare diam tempor nulla facilisis aliquet. Sed ultrices placerat ultricies. TEXT WITH_LIQUID = <<-LIQUID.freeze Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor libero at pharetra tempus. {{ author }} et metus fermentum, eu cursus lorem mattis. Curabitur vel dui et lacus rutrum suscipit et eget neque. Nullam luctus fermentum est id blandit. Phasellus consectetur ullamcorper ligula, {% if author == "Jane Doe" %} at finibus eros laoreet id. {% else %} Etiam sit amet est in libero efficitur.{% endif %} tristique. Ut nec magna augue. Quisque ut fringilla lacus, ac dictum enim. Aliquam vel ornare mauris. Suspendisse ornare diam tempor nulla facilisis aliquet. Sed ultrices placerat ultricies. LIQUID WITH_JUST_LIQUID_VAR = <<-LIQUID.freeze Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor libero at pharetra tempus. et metus fermentum, eu cursus lorem, ac dictum enim. mattis. Curabitur vel dui et lacus rutrum suscipit et {{ title }} neque. Nullam luctus fermentum est id blandit. Phasellus consectetur ullamcorper ligula, at finibus eros laoreet id. Etiam sit amet est in libero efficitur. tristique. Ut nec magna augue. {{ author }} Quisque ut fringilla lacus Aliquam vel ornare mauris. Suspendisse ornare diam tempor nulla facilisis aliquet. Sed ultrices placerat ultricies. LIQUID SUITE = { :"plain text" => WITHOUT_LIQUID, :"tags n vars" => WITH_LIQUID, :"just vars" => WITH_JUST_LIQUID_VAR, }.freeze # Mimic how Jekyll's LiquidRenderer would process a non-static file, with # some dummy payload def always_liquid(content) Liquid::Template.error_mode = :warn Liquid::Template.parse(content, :line_numbers => true).render( "author" => "John Doe", "title" => "FooBar" ) end # Mimic how the proposed change would first execute a couple of checks and # proceed to process with Liquid if necessary def conditional_liquid(content) return content if content.nil? || content.empty? return content unless content.include?("{%") || content.include?("{{") always_liquid(content) end # Test https://github.com/jekyll/jekyll/pull/6735#discussion_r165499868 # ------------------------------------------------------------------------ def check_with_regex(content) !content.to_s.match?(%r!{[{%]!) end def check_with_builtin(content) content.include?("{%") || content.include?("{{") end SUITE.each do |key, text| Benchmark.ips do |x| x.report("regex-check - #{key}") { check_with_regex(text) } x.report("builtin-check - #{key}") { check_with_builtin(text) } x.compare! end end # ------------------------------------------------------------------------ # Let's roll! SUITE.each do |key, text| Benchmark.ips do |x| x.report("always thru liquid - #{key}") { always_liquid(text) } x.report("conditional liquid - #{key}") { conditional_liquid(text) } x.compare! end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/path-manager.rb
benchmark/path-manager.rb
# frozen_string_literal: true require 'benchmark/ips' require 'jekyll' class FooPage def initialize(dir:, name:) @dir = dir @name = name end def slow_path File.join(*[@dir, @name].map(&:to_s).reject(&:empty?)).sub(%r!\A/!, "") end def fast_path Jekyll::PathManager.join(@dir, @name).sub(%r!\A/!, "") end end nil_page = FooPage.new(:dir => nil, :name => nil) empty_page = FooPage.new(:dir => "", :name => "") root_page = FooPage.new(:dir => "", :name => "ipsum.md") nested_page = FooPage.new(:dir => "lorem", :name => "ipsum.md") slashed_page = FooPage.new(:dir => "/lorem/", :name => "/ipsum.md") if nil_page.slow_path == nil_page.fast_path Benchmark.ips do |x| x.report('nil_page slow') { nil_page.slow_path } x.report('nil_page fast') { nil_page.fast_path } x.compare! end end if empty_page.slow_path == empty_page.fast_path Benchmark.ips do |x| x.report('empty_page slow') { empty_page.slow_path } x.report('empty_page fast') { empty_page.fast_path } x.compare! end end if root_page.slow_path == root_page.fast_path Benchmark.ips do |x| x.report('root_page slow') { root_page.slow_path } x.report('root_page fast') { root_page.fast_path } x.compare! end end if nested_page.slow_path == nested_page.fast_path Benchmark.ips do |x| x.report('nested_page slow') { nested_page.slow_path } x.report('nested_page fast') { nested_page.fast_path } x.compare! end end if slashed_page.slow_path == slashed_page.fast_path Benchmark.ips do |x| x.report('slashed_page slow') { slashed_page.slow_path } x.report('slashed_page fast') { slashed_page.fast_path } x.compare! end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/find-filter-vs-where-first-filters.rb
benchmark/find-filter-vs-where-first-filters.rb
#!/usr/bin/env ruby # frozen_string_literal: true require 'benchmark/ips' require_relative '../lib/jekyll' puts '' print 'Setting up... ' SITE = Jekyll::Site.new( Jekyll.configuration({ "source" => File.expand_path("../docs", __dir__), "destination" => File.expand_path("../docs/_site", __dir__), "disable_disk_cache" => true, "quiet" => true, }) ) TEMPLATE_1 = Liquid::Template.parse(<<~HTML) {%- assign doc = site.documents | where: 'url', '/docs/assets/' | first -%} {{- doc.title -}} HTML TEMPLATE_2 = Liquid::Template.parse(<<~HTML) {%- assign doc = site.documents | find: 'url', '/docs/assets/' -%} {{- doc.title -}} HTML [:reset, :read, :generate].each { |phase| SITE.send(phase) } puts 'done.' puts 'Testing... ' puts " #{'where + first'.cyan} results in #{TEMPLATE_1.render(SITE.site_payload).inspect.green}" puts " #{'find'.cyan} results in #{TEMPLATE_2.render(SITE.site_payload).inspect.green}" if TEMPLATE_1.render(SITE.site_payload) == TEMPLATE_2.render(SITE.site_payload) puts 'Success! Proceeding to run benchmarks.'.green puts '' else puts 'Something went wrong. Aborting.'.magenta puts '' return end Benchmark.ips do |x| x.report('where + first') { TEMPLATE_1.render(SITE.site_payload) } x.report('find') { TEMPLATE_2.render(SITE.site_payload) } x.compare! end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/capture-assign.rb
benchmark/capture-assign.rb
#!/usr/bin/env ruby require "liquid" require "benchmark/ips" puts "Ruby #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}" puts "Liquid #{Liquid::VERSION}" template1 = '{% capture foobar %}foo{{ bar }}{% endcapture %}{{ foo }}{{ foobar }}' template2 = '{% assign foobar = "foo" | append: bar %}{{ foobar }}' def render(template) Liquid::Template.parse(template).render("bar" => "42") end puts render(template1) puts render(template2) Benchmark.ips do |x| x.report('capture') { render(template1) } x.report('assign') { render(template2) } end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/static-drop-vs-forwarded.rb
benchmark/static-drop-vs-forwarded.rb
#!/usr/bin/env ruby # frozen_string_literal: true require "forwardable" require "colorator" require "liquid" require "benchmark/ips" require "memory_profiler" # Set up (memory) profiler class Profiler def self.run yield new(ARGV[0] || 10_000) end def initialize(count) @count = count.to_i end def report(label, color, &block) prof_report = MemoryProfiler.report { @count.to_i.times(&block) } allocated_memory = prof_report.scale_bytes(prof_report.total_allocated_memsize) allocated_objects = prof_report.total_allocated retained_memory = prof_report.scale_bytes(prof_report.total_retained_memsize) retained_objects = prof_report.total_retained puts <<~MSG.send(color) With #{label} calls Total allocated: #{allocated_memory} (#{allocated_objects} objects) Total retained: #{retained_memory} (#{retained_objects} objects) MSG end end # Set up stage class Drop < Liquid::Drop def initialize(obj) @obj = obj end end class ForwardDrop < Drop extend Forwardable def_delegators :@obj, :name end class StaticDrop < Drop def name @obj.name end end class Document def name "lipsum" end end # Set up actors document = Document.new alpha = ForwardDrop.new(document) beta = StaticDrop.new(document) count = ARGV[0] || 10_000 # Run profilers puts "\nMemory profiles for #{count} calls to invoke drop key:" Profiler.run do |x| x.report("forwarded", :cyan) { alpha["name"] } x.report("static", :green) { beta["name"] } end # Benchmark puts "\nBenchmarking the two scenarios..." Benchmark.ips do |x| x.report("forwarded".cyan) { alpha["name"] } x.report("static".green) { beta["name"] } x.compare! end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/parse-include-tag-params.rb
benchmark/parse-include-tag-params.rb
#!/usr/bin/env ruby # frozen_string_literal: true # For pull request: https://github.com/jekyll/jekyll/pull/8192 require 'benchmark/ips' require 'bundler/setup' require 'memory_profiler' require 'jekyll' CONTEXT = {"bar"=>"The quick brown fox"} MARKUP_1 = %Q(foo=bar lorem="ipsum \\"dolor\\"" alpha='beta \\'gamma\\'').freeze MARKUP_2 = %Q(foo=bar lorem="ipsum 'dolor'" alpha='beta "gamma"').freeze # def old_parse_params(markup) params = {} while (match = Jekyll::Tags::IncludeTag::VALID_SYNTAX.match(markup)) markup = markup[match.end(0)..-1] value = if match[2] match[2].gsub('\\"', '"') elsif match[3] match[3].gsub("\\'", "'") elsif match[4] CONTEXT[match[4]] end params[match[1]] = value end params end def new_parse_params(markup) params = {} markup.scan(Jekyll::Tags::IncludeTag::VALID_SYNTAX) do |key, d_quoted, s_quoted, variable| value = if d_quoted d_quoted.include?('\\"') ? d_quoted.gsub('\\"', '"') : d_quoted elsif s_quoted s_quoted.include?("\\'") ? s_quoted.gsub("\\'", "'") : s_quoted elsif variable CONTEXT[variable] end params[key] = value end params end # def report(label, markup, color) prof_report = MemoryProfiler.report { yield } allocated_memory = prof_report.scale_bytes(prof_report.total_allocated_memsize) allocated_objects = prof_report.total_allocated retained_memory = prof_report.scale_bytes(prof_report.total_retained_memsize) retained_objects = prof_report.total_retained puts <<~MSG.send(color) #{(label + " ").ljust(49, "-")} MARKUP: #{markup} RESULT: #{yield} Total allocated: #{allocated_memory} (#{allocated_objects} objects) Total retained: #{retained_memory} (#{retained_objects} objects) MSG end report('old w/ escaping', MARKUP_1, :magenta) { old_parse_params(MARKUP_1) } report('new w/ escaping', MARKUP_1, :cyan) { new_parse_params(MARKUP_1) } report('old no escaping', MARKUP_2, :green) { old_parse_params(MARKUP_2) } report('new no escaping', MARKUP_2, :yellow) { new_parse_params(MARKUP_2) } # Benchmark.ips do |x| x.report("old + esc".magenta) { old_parse_params(MARKUP_1) } x.report("new + esc".cyan) { new_parse_params(MARKUP_1) } x.compare! end Benchmark.ips do |x| x.report("old - esc".green) { old_parse_params(MARKUP_2) } x.report("new - esc".yellow) { new_parse_params(MARKUP_2) } x.compare! end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/schwartzian_transform.rb
benchmark/schwartzian_transform.rb
#!/usr/bin/env ruby # frozen_string_literal: true # # The Ruby documentation for #sort_by describes what's called a Schwartzian transform: # # > A more efficient technique is to cache the sort keys (modification times in this case) # > before the sort. Perl users often call this approach a Schwartzian transform, after # > Randal Schwartz. We construct a temporary array, where each element is an array # > containing our sort key along with the filename. We sort this array, and then extract # > the filename from the result. # > This is exactly what sort_by does internally. # # The well-documented efficiency of sort_by is a good reason to use it. However, when a property # does not exist on an item being sorted, it can cause issues (no nil's allowed!) # In Jekyll::Filters#sort_input, we extract the property in each iteration of #sort, # which is quite inefficient! How inefficient? This benchmark will tell you just how, and how much # it can be improved by using the Schwartzian transform. Thanks, Randall! require 'benchmark/ips' require 'minitest' require File.expand_path("../lib/jekyll", __dir__) def site @site ||= Jekyll::Site.new( Jekyll.configuration("source" => File.expand_path("../docs", __dir__)) ).tap(&:reset).tap(&:read) end def site_docs site.collections["docs"].docs.dup end def sort_by_property_directly(docs, meta_key) docs.sort! do |apple, orange| apple_property = apple[meta_key] orange_property = orange[meta_key] if !apple_property.nil? && !orange_property.nil? apple_property <=> orange_property elsif !apple_property.nil? && orange_property.nil? -1 elsif apple_property.nil? && !orange_property.nil? 1 else apple <=> orange end end end def schwartzian_transform(docs, meta_key) docs.collect! { |d| [d[meta_key], d] }.sort! { |apple, orange| if !apple[0].nil? && !orange[0].nil? apple.first <=> orange.first elsif !apple[0].nil? && orange[0].nil? -1 elsif apple[0].nil? && !orange[0].nil? 1 else apple[-1] <=> orange[-1] end }.collect! { |d| d[-1] } end # Before we test efficiency, do they produce the same output? class Correctness include Minitest::Assertions require "pp" define_method :mu_pp, &:pretty_inspect attr_accessor :assertions def initialize(docs, property) @assertions = 0 @docs = docs @property = property end def assert! assert sort_by_property_directly(@docs, @property).is_a?(Array), "sort_by_property_directly must return an array" assert schwartzian_transform(@docs, @property).is_a?(Array), "schwartzian_transform must return an array" assert_equal sort_by_property_directly(@docs, @property), schwartzian_transform(@docs, @property) puts "Yeah, ok, correctness all checks out for property #{@property.inspect}" end end Correctness.new(site_docs, "redirect_from".freeze).assert! Correctness.new(site_docs, "title".freeze).assert! def property(property, meta_key) Benchmark.ips do |x| x.config(time: 10, warmup: 5) x.report("sort_by_property_directly with #{property} property") do sort_by_property_directly(site_docs, meta_key) end x.report("schwartzian_transform with #{property} property") do schwartzian_transform(site_docs, meta_key) end x.compare! end end # First, test with a property only a handful of documents have. test_property('sparse', 'redirect_from') # Next, test with a property they all have. test_property('non-sparse', 'title')
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/sanitize-url.rb
benchmark/sanitize-url.rb
#!/usr/bin/env ruby require "benchmark/ips" PATH = "/../../..../...//.....//lorem/ipsum//dolor///sit.xyz" def sanitize_with_regex "/" + PATH.gsub(%r!/{2,}!, "/").gsub(%r!\.+/|\A/+!, "") end def sanitize_with_builtin "/#{PATH}".gsub("..", "/").gsub("./", "").squeeze("/") end if sanitize_with_regex == sanitize_with_builtin Benchmark.ips do |x| x.report("sanitize w/ regexes") { sanitize_with_regex } x.report("sanitize w/ builtin") { sanitize_with_builtin } x.compare! end else puts "w/ regexes: #{sanitize_with_regex}" puts "w/ builtin: #{sanitize_with_builtin}" puts "" puts "Thank you. Do try again :(" end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/benchmark/regexp-vs-include.rb
benchmark/regexp-vs-include.rb
#!/usr/bin/env ruby require 'benchmark/ips' # For this pull request, which changes Page#dir # https://github.com/jekyll/jekyll/pull/4403 CONTENT_CONTAINING = <<-HTML.freeze <!DOCTYPE HTML> <html lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"> <title>Jemoji</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="/css/screen.css"> </head> <body class="wrap"> <p><img class="emoji" title=":+1:" alt=":+1:" src="https://assets.github.com/images/icons/emoji/unicode/1f44d.png" height="20" width="20" align="absmiddle"></p> </body> </html> HTML CONTENT_NOT_CONTAINING = <<-HTML.freeze <!DOCTYPE HTML> <html lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"> <title>Jemoji</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="/css/screen.css"> </head> <body class="wrap"> <p><img class="emoji" title=":+1:" alt=":+1:" src="https://assets.github.com/images/icons/emoji/unicode/1f44d.png" height="20" width="20" align="absmiddle"></p> </body> </html> HTML Benchmark.ips do |x| x.report("no body include?") { CONTENT_NOT_CONTAINING.include?('<body') } x.report("no body regexp") { CONTENT_NOT_CONTAINING =~ /<\s*body/ } x.compare! end # No trailing slash Benchmark.ips do |x| x.report("with body include?") { CONTENT_CONTAINING.include?('<body') } x.report("with body regexp") { CONTENT_CONTAINING =~ /<\s*body/ } x.compare! end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_page.rb
test/test_page.rb
# frozen_string_literal: true require "helper" class TestPage < JekyllUnitTest def setup_page(*args) dir, file = args if file.nil? file = dir dir = "" end @page = Page.new(@site, source_dir, dir, file) end def do_render(page) layouts = { "default" => Layout.new(@site, source_dir("_layouts"), "simple.html"), } page.render(layouts, @site.site_payload) end context "A Page" do setup do clear_dest @site = Site.new(Jekyll.configuration( "source" => source_dir, "destination" => dest_dir, "skip_config_files" => true )) end context "processing pages" do should "create URL based on filename" do @page = setup_page("contacts.html") assert_equal "/contacts.html", @page.url end should "create proper URL from filename" do @page = setup_page("trailing-dots...md") assert_equal "/trailing-dots.html", @page.url end should "not published when published yaml is false" do @page = setup_page("unpublished.html") refute @page.published? end should "create URL with non-alphabetic characters" do @page = setup_page("+", "%# +.md") assert_equal "/+/%25%23%20+.html", @page.url end context "in a directory hierarchy" do should "create URL based on filename" do @page = setup_page("/contacts", "bar.html") assert_equal "/contacts/bar.html", @page.url end should "create index URL based on filename" do @page = setup_page("/contacts", "index.html") assert_equal "/contacts/", @page.url end end should "deal properly with extensions" do @page = setup_page("deal.with.dots.html") assert_equal ".html", @page.ext end should "deal properly with non-html extensions" do @page = setup_page("dynamic_page.php") @dest_file = dest_dir("dynamic_page.php") assert_equal ".php", @page.ext assert_equal "dynamic_page", @page.basename assert_equal "/dynamic_page.php", @page.url assert_equal @dest_file, @page.destination(dest_dir) end should "deal properly with dots" do @page = setup_page("deal.with.dots.html") @dest_file = dest_dir("deal.with.dots.html") assert_equal "deal.with.dots", @page.basename assert_equal @dest_file, @page.destination(dest_dir) end should "make properties accessible through #[]" do page = setup_page("properties.html") attrs = { :content => "All the properties.\n", :dir => "/properties/", :excerpt => nil, :foo => "bar", :layout => "default", :name => "properties.html", :path => "properties.html", :permalink => "/properties/", :published => nil, :title => "Properties Page", :url => "/properties/", } attrs.each do |attr, val| attr_str = attr.to_s result = page[attr_str] if val.nil? assert_nil result, "For <page[\"#{attr_str}\"]>:" else assert_equal val, result, "For <page[\"#{attr_str}\"]>:" end end end context "with pretty permalink style" do setup do @site.permalink_style = :pretty end should "return dir, URL, and destination correctly" do @page = setup_page("contacts.html") @dest_file = dest_dir("contacts/index.html") assert_equal "/contacts/", @page.dir assert_equal "/contacts/", @page.url assert_equal @dest_file, @page.destination(dest_dir) end should "return dir correctly for index page" do @page = setup_page("index.html") assert_equal "/", @page.dir end context "in a directory hierarchy" do should "create url based on filename" do @page = setup_page("/contacts", "bar.html") assert_equal "/contacts/bar/", @page.url end should "create index URL based on filename" do @page = setup_page("/contacts", "index.html") assert_equal "/contacts/", @page.url end should "return dir correctly" do @page = setup_page("/contacts", "bar.html") assert_equal "/contacts/bar/", @page.dir end should "return dir correctly for index page" do @page = setup_page("/contacts", "index.html") assert_equal "/contacts/", @page.dir end end end context "with date permalink style" do setup do @site.permalink_style = :date end should "return url and destination correctly" do @page = setup_page("contacts.html") @dest_file = dest_dir("contacts.html") assert_equal "/contacts.html", @page.url assert_equal @dest_file, @page.destination(dest_dir) end should "return dir correctly" do assert_equal "/", setup_page("contacts.html").dir assert_equal "/contacts/", setup_page("contacts/bar.html").dir assert_equal "/contacts/", setup_page("contacts/index.html").dir end end context "with custom permalink style with trailing slash" do setup do @site.permalink_style = "/:title/" end should "return URL and destination correctly" do @page = setup_page("contacts.html") @dest_file = dest_dir("contacts/index.html") assert_equal "/contacts/", @page.url assert_equal @dest_file, @page.destination(dest_dir) end end context "with custom permalink style with file extension" do setup do @site.permalink_style = "/:title:output_ext" end should "return URL and destination correctly" do @page = setup_page("contacts.html") @dest_file = dest_dir("contacts.html") assert_equal "/contacts.html", @page.url assert_equal @dest_file, @page.destination(dest_dir) end end context "with custom permalink style with no extension" do setup do @site.permalink_style = "/:title" end should "return URL and destination correctly" do @page = setup_page("contacts.html") @dest_file = dest_dir("contacts.html") assert_equal "/contacts", @page.url assert_equal @dest_file, @page.destination(dest_dir) end end context "with any other permalink style" do should "return dir correctly" do @site.permalink_style = nil assert_equal "/", setup_page("contacts.html").dir assert_equal "/contacts/", setup_page("contacts/index.html").dir assert_equal "/contacts/", setup_page("contacts/bar.html").dir end end should "respect permalink in YAML front matter" do file = "about.html" @page = setup_page(file) assert_equal "/about/", @page.permalink assert_equal @page.permalink, @page.url assert_equal "/about/", @page.dir end should "return nil permalink if no permalink exists" do @page = setup_page("") assert_nil @page.permalink end should "not be writable outside of destination" do unexpected = File.expand_path("../../../baddie.html", dest_dir) File.delete unexpected if File.exist?(unexpected) page = setup_page("exploit.md") do_render(page) page.write(dest_dir) refute_exist unexpected end end context "with specified layout of nil" do setup do @page = setup_page("sitemap.xml") end should "layout of nil is respected" do assert_equal "nil", @page.data["layout"] end end context "rendering" do setup do clear_dest end should "write properly" do page = setup_page("contacts.html") do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts.html") end should "write even when the folder name is plus and permalink has +" do page = setup_page("+", "foo.md") do_render(page) page.write(dest_dir) assert File.directory?(dest_dir), "#{dest_dir} should be a directory" assert_exist dest_dir("+", "plus+in+url.html") end should "write even when permalink has '%# +'" do page = setup_page("+", "%# +.md") do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("+", "%# +.html") end should "write properly without html extension" do page = setup_page("contacts.html") page.site.permalink_style = :pretty do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts", "index.html") end should "support .htm extension and respects that" do page = setup_page("contacts.htm") page.site.permalink_style = :pretty do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts", "index.htm") end should "support .xhtml extension and respects that" do page = setup_page("contacts.xhtml") page.site.permalink_style = :pretty do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts", "index.xhtml") end should "write properly with extension different from html" do page = setup_page("sitemap.xml") page.site.permalink_style = :pretty do_render(page) page.write(dest_dir) assert_equal "/sitemap.xml", page.url assert_nil page.url[%r!\.html$!] assert File.directory?(dest_dir) assert_exist dest_dir("sitemap.xml") end should "write dotfiles properly" do page = setup_page(".htaccess") do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir(".htaccess") end context "in a directory hierarchy" do should "write properly the index" do page = setup_page("/contacts", "index.html") do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts", "index.html") end should "write properly" do page = setup_page("/contacts", "bar.html") do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts", "bar.html") end should "write properly without html extension" do page = setup_page("/contacts", "bar.html") page.site.permalink_style = :pretty do_render(page) page.write(dest_dir) assert File.directory?(dest_dir) assert_exist dest_dir("contacts", "bar", "index.html") end end context "read-in by default" do should "not initialize excerpts by default" do page = setup_page("contacts", "foo.md") assert_nil page.excerpt end should "not expose an excerpt to Liquid templates by default" do page = setup_page("/contacts", "bar.html") assert_nil page.to_liquid["excerpt"] end context "in a site configured to generate page excerpts" do setup { @configured_site = fixture_site("page_excerpts" => true) } should "initialize excerpt eagerly but render only when needed" do test_page = Jekyll::Page.new(@configured_site, source_dir, "contacts", "foo.md") assert_instance_of Jekyll::PageExcerpt, test_page.data["excerpt"] assert_instance_of String, test_page.excerpt assert_equal( "<h2 id=\"contact-information\">Contact Information</h2>\n", test_page.excerpt ) end should "expose an excerpt to Liquid templates" do test_page = Jekyll::Page.new(@configured_site, source_dir, "/contacts", "bar.html") assert_equal "Contact Information\n", test_page.to_liquid["excerpt"] end should "not expose an excerpt for non-html pages" do test_page = Jekyll::Page.new(@configured_site, source_dir, "assets", "test-styles.scss") refute_equal ".half { width: 50%; }\n", test_page.to_liquid["excerpt"] assert_nil test_page.to_liquid["excerpt"] end end end context "generated via plugin" do setup do PageSubclass = Class.new(Jekyll::Page) @test_page = PageSubclass.new(@site, source_dir, "/contacts", "bar.html") @test_page.data.clear end should "not expose an excerpt to Liquid templates by default" do assert_equal "Contact Information\n", @test_page.content assert_nil @test_page.to_liquid["excerpt"] end should "expose an excerpt to Liquid templates if hardcoded" do @test_page.data["excerpt"] = "Test excerpt." assert_equal "Contact Information\n", @test_page.content assert_equal "Test excerpt.", @test_page.to_liquid["excerpt"] end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_entry_filter.rb
test/test_entry_filter.rb
# frozen_string_literal: true require "helper" class TestEntryFilter < JekyllUnitTest context "Filtering entries" do setup do @site = fixture_site end should "filter entries" do ent1 = %w(foo.markdown bar.markdown baz.markdown #baz.markdown# .baz.markdown foo.markdown~ .htaccess _posts _pages ~$benbalter.docx) entries = EntryFilter.new(@site).filter(ent1) assert_equal %w(foo.markdown bar.markdown baz.markdown .htaccess), entries end should "allow regexp filtering" do files = %w(README.md) @site.exclude = [ %r!README!, ] assert_empty @site.reader.filter_entries( files ) end should "filter entries with exclude" do excludes = %w(README TODO vendor/bundle) files = %w(index.html site.css .htaccess vendor) @site.exclude = excludes + ["exclude*"] assert_equal files, @site.reader.filter_entries(excludes + files + ["excludeA"]) end should "filter entries with exclude relative to site source" do excludes = %w(README TODO css) files = %w(index.html vendor/css .htaccess) @site.exclude = excludes assert_equal files, @site.reader.filter_entries(excludes + files + ["css"]) end should "filter excluded directory and contained files" do excludes = %w(README TODO css) files = %w(index.html .htaccess) @site.exclude = excludes assert_equal( files, @site.reader.filter_entries( excludes + files + ["css", "css/main.css", "css/vendor.css"] ) ) end should "not filter entries within include" do includes = %w(_index.html .htaccess include*) files = %w(index.html _index.html .htaccess includeA) @site.include = includes assert_equal files, @site.reader.filter_entries(files) end should "not exclude explicitly included entry" do entries = %w(README TODO css .htaccess _movies/.) excludes = %w(README TODO css) includes = %w(README .htaccess) @site.exclude = excludes @site.include = includes filtered_entries = EntryFilter.new(@site).filter(entries) assert_equal %w(README .htaccess), filtered_entries end should "keep safe symlink entries when safe mode enabled" do allow(File).to receive(:symlink?).with("symlink.js").and_return(true) files = %w(symlink.js) assert_equal files, @site.reader.filter_entries(files) end should "not filter symlink entries when safe mode disabled" do allow(File).to receive(:symlink?).with("symlink.js").and_return(true) files = %w(symlink.js) assert_equal files, @site.reader.filter_entries(files) end should "filter symlink pointing outside site source" do ent1 = %w(_includes/tmp) entries = EntryFilter.new(@site).filter(ent1) assert_equal %w(), entries end should "include only safe symlinks in safe mode" do # no support for symlinks on Windows skip_if_windows "Jekyll does not currently support symlinks on Windows." site = fixture_site("safe" => true) site.reader.read_directories("symlink-test") assert_equal %w(main.scss symlinked-file).length, site.pages.length refute_equal [], site.static_files end should "include symlinks in unsafe mode" do # no support for symlinks on Windows skip_if_windows "Jekyll does not currently support symlinks on Windows." @site.reader.read_directories("symlink-test") refute_equal [], @site.pages refute_equal [], @site.static_files end should "include only safe symlinks in safe mode even when included" do # no support for symlinks on Windows skip_if_windows "Jekyll does not currently support symlinks on Windows." site = fixture_site("safe" => true, "include" => ["symlinked-file-outside-source"]) site.reader.read_directories("symlink-test") assert_equal %w(main.scss symlinked-file).length, site.pages.length refute_includes site.static_files.map(&:name), "symlinked-file-outside-source" end end context "#glob_include?" do setup do @site = Site.new(site_configuration) @filter = EntryFilter.new(@site) end should "return false with no glob patterns" do refute @filter.glob_include?([], "a.txt") end should "return false with all not match path" do data = ["a*", "b?"] refute @filter.glob_include?(data, "ca.txt") refute @filter.glob_include?(data, "ba.txt") end should "return true with match path" do data = ["a*", "b?", "**/a*"] assert @filter.glob_include?(data, "a.txt") assert @filter.glob_include?(data, "ba") assert @filter.glob_include?(data, "c/a/a.txt") assert @filter.glob_include?(data, "c/a/b/a.txt") end should "match even if there is no leading slash" do data = ["vendor/bundle"] assert @filter.glob_include?(data, "/vendor/bundle") assert @filter.glob_include?(data, "vendor/bundle") end should "match even if there is no trailing slash" do data = ["/vendor/bundle/", "vendor/ruby"] assert @filter.glob_include?(data, "vendor/bundle/jekyll/lib/page.rb") assert @filter.glob_include?(data, "/vendor/ruby/lib/set.rb") end should "match directory only if there is trailing slash" do data = ["_glob_include_test/_is_dir/", "_glob_include_test/_not_dir/"] assert @filter.glob_include?(data, "_glob_include_test/_is_dir") assert @filter.glob_include?(data, "_glob_include_test/_is_dir/include_me.txt") refute @filter.glob_include?(data, "_glob_include_test/_not_dir") end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_kramdown.rb
test/test_kramdown.rb
# frozen_string_literal: true require "helper" require "rouge" class TestKramdown < JekyllUnitTest def fixture_converter(config) site = fixture_site( Utils.deep_merge_hashes( { "markdown" => "kramdown", }, config ) ) Jekyll::Cache.clear site.find_converter_instance( Jekyll::Converters::Markdown ) end context "kramdown" do setup do @config = { "kramdown" => { "smart_quotes" => "lsquo,rsquo,ldquo,rdquo", "entity_output" => "as_char", "toc_levels" => "1..6", "auto_ids" => false, "footnote_nr" => 1, "show_warnings" => true, "syntax_highlighter" => "rouge", "syntax_highlighter_opts" => { "bold_every" => 8, "css" => :class, "css_class" => "highlight", "formatter" => ::Rouge::Formatters::HTMLLegacy, "foobar" => "lipsum", }, }, } @kramdown_config_keys = @config["kramdown"].keys @syntax_highlighter_opts_config_keys = \ @config["kramdown"]["syntax_highlighter_opts"].keys @config = Jekyll.configuration(@config) @converter = fixture_converter(@config) end should "not break kramdown" do kramdown_doc = Kramdown::Document.new("# Some Header #", @config["kramdown"]) assert_equal :class, kramdown_doc.options[:syntax_highlighter_opts][:css] assert_equal "lipsum", kramdown_doc.options[:syntax_highlighter_opts][:foobar] end should "run Kramdown" do assert_equal "<h1>Some Header</h1>", @converter.convert("# Some Header #").strip end should "should log kramdown warnings" do allow_any_instance_of(Kramdown::Document).to receive(:warnings).and_return(["foo"]) expect(Jekyll.logger).to receive(:warn).with("Kramdown warning:", "foo") @converter.convert("Something") end should "render fenced code blocks with syntax highlighting" do result = nokogiri_fragment(@converter.convert(<<~MARKDOWN)) ~~~ruby puts "Hello World" ~~~ MARKDOWN div_highlight = ">div.highlight" selector = "div.highlighter-rouge#{div_highlight}>pre.highlight>code" refute_empty(result.css(selector), result.to_html) end context "when configured" do setup do @source = <<~TEXT ## Code Sample def ruby_fu "Hello" end TEXT end should "have 'plaintext' as the default syntax_highlighter language" do converter = fixture_converter(@config) parser = converter.setup && converter.instance_variable_get(:@parser) parser_config = parser.instance_variable_get(:@config) assert_equal "plaintext", parser_config.dig("syntax_highlighter_opts", "default_lang") end should "accept the specified default syntax_highlighter language" do override = { "kramdown" => { "syntax_highlighter_opts" => { "default_lang" => "yaml", }, }, } converter = fixture_converter(Utils.deep_merge_hashes(@config, override)) parser = converter.setup && converter.instance_variable_get(:@parser) parser_config = parser.instance_variable_get(:@config) assert_equal "yaml", parser_config.dig("syntax_highlighter_opts", "default_lang") refute_match %r!<div class="language-plaintext!, converter.convert(@source) refute_match %r!<div class="language-html!, converter.convert(@source) assert_match %r!<div class="language-yaml!, converter.convert(@source) end end context "when asked to convert smart quotes" do should "convert" do converter = fixture_converter(@config) assert_match( %r!<p>(&#8220;|“)Pit(&#8217;|’)hy(&#8221;|”)</p>!, converter.convert(%("Pit'hy")).strip ) end should "support custom types" do override = { "highlighter" => nil, "kramdown" => { "smart_quotes" => "lsaquo,rsaquo,laquo,raquo", }, } converter = fixture_converter(Utils.deep_merge_hashes(@config, override)) assert_match %r!<p>(&#171;|«)Pit(&#8250;|›)hy(&#187;|»)</p>!, \ converter.convert(%("Pit'hy")).strip end end context "when a custom highlighter is chosen" do should "use the chosen highlighter if it's available" do override = { "highlighter" => nil, "kramdown" => { "syntax_highlighter" => "coderay", }, } converter = fixture_converter(Utils.deep_merge_hashes(@config, override)) result = nokogiri_fragment(converter.convert(<<~MARKDOWN)) ~~~ruby puts "Hello World" ~~~ MARKDOWN selector = "div.highlighter-coderay>div.CodeRay>div.code>pre" refute_empty result.css(selector) end should "support legacy enable_coderay... for now" do override = { "kramdown" => { "enable_coderay" => true, }, } @config.delete("highlighter") @config["kramdown"].delete("syntax_highlighter") converter = fixture_converter(Utils.deep_merge_hashes(@config, override)) result = nokogiri_fragment(converter.convert(<<~MARKDOWN)) ~~~ruby puts "Hello World" ~~~ MARKDOWN selector = "div.highlighter-coderay>div.CodeRay>div.code>pre" refute_empty result.css(selector), "pre tag should exist" end end should "move coderay to syntax_highlighter_opts" do override = { "highlighter" => nil, "kramdown" => { "syntax_highlighter" => "coderay", "coderay" => { "hello" => "world", }, }, } original = Kramdown::Document.method(:new) converter = fixture_converter( Utils.deep_merge_hashes(@config, override) ) expect(Kramdown::Document).to receive(:new) do |arg1, hash| assert_equal "world", hash["syntax_highlighter_opts"]["hello"] original.call(arg1, hash) end converter.convert("hello world") end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_theme.rb
test/test_theme.rb
# frozen_string_literal: true require "helper" class TestTheme < JekyllUnitTest def setup @theme = Theme.new("test-theme") end context "initializing" do should "normalize the theme name" do theme = Theme.new(" Test-Theme ") assert_equal "test-theme", theme.name end should "know the theme root" do assert_equal theme_dir, @theme.root end should "know the theme version" do assert_equal Gem::Version.new("0.1.0"), @theme.version end should "raise an error for invalid themes" do assert_raises Jekyll::Errors::MissingDependencyException do Theme.new("foo").version end end end context "path generation" do [:assets, :_data, :_layouts, :_includes, :_sass].each do |folder| should "know the #{folder} path" do expected = theme_dir(folder.to_s) assert_equal expected, @theme.public_send("#{folder.to_s.tr("_", "")}_path") end end should "generate folder paths" do expected = theme_dir("_sass") assert_equal expected, @theme.send(:path_for, :_sass) end should "not allow paths outside of the theme root" do assert_nil @theme.send(:path_for, "../../source") end should "return nil for paths that don't exist" do assert_nil @theme.send(:path_for, "foo") end should "return the resolved path when a symlink & resolved path exists" do # no support for symlinks on Windows skip_if_windows "Jekyll does not currently support symlinks on Windows." expected = theme_dir("_layouts") assert_equal expected, @theme.send(:path_for, :_symlink) end end context "invalid theme" do context "initializing" do setup do stub_gemspec = Object.new # the directory for this theme should not exist allow(stub_gemspec).to receive(:full_gem_path) .and_return(File.expand_path("test/fixtures/test-non-existent-theme", __dir__)) allow(Gem::Specification).to receive(:find_by_name) .with("test-non-existent-theme") .and_return(stub_gemspec) end should "raise when getting theme root" do error = assert_raises(RuntimeError) { Theme.new("test-non-existent-theme") } assert_match(%r!fixtures/test-non-existent-theme does not exist!, error.message) end end end should "retrieve the gemspec" do assert_equal "test-theme-0.1.0", @theme.send(:gemspec).full_name end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_log_adapter.rb
test/test_log_adapter.rb
# frozen_string_literal: true require "helper" class TestLogAdapter < JekyllUnitTest class LoggerDouble attr_accessor :level def debug(*); end def info(*); end def warn(*); end def error(*); end end context "#log_level=" do should "set the writers logging level" do subject = Jekyll::LogAdapter.new(LoggerDouble.new) subject.log_level = :error assert_equal Jekyll::LogAdapter::LOG_LEVELS[:error], subject.writer.level end end context "#adjust_verbosity" do should "set the writers logging level to error when quiet" do subject = Jekyll::LogAdapter.new(LoggerDouble.new) subject.adjust_verbosity(:quiet => true) assert_equal Jekyll::LogAdapter::LOG_LEVELS[:error], subject.writer.level end should "set the writers logging level to debug when verbose" do subject = Jekyll::LogAdapter.new(LoggerDouble.new) subject.adjust_verbosity(:verbose => true) assert_equal Jekyll::LogAdapter::LOG_LEVELS[:debug], subject.writer.level end should "set the writers logging level to error when quiet and verbose are both set" do subject = Jekyll::LogAdapter.new(LoggerDouble.new) subject.adjust_verbosity(:quiet => true, :verbose => true) assert_equal Jekyll::LogAdapter::LOG_LEVELS[:error], subject.writer.level end should "not change the writer's logging level when neither verbose or quiet" do subject = Jekyll::LogAdapter.new(LoggerDouble.new) original_level = subject.writer.level refute_equal Jekyll::LogAdapter::LOG_LEVELS[:error], subject.writer.level refute_equal Jekyll::LogAdapter::LOG_LEVELS[:debug], subject.writer.level subject.adjust_verbosity(:quiet => false, :verbose => false) assert_equal original_level, subject.writer.level end should "call #debug on writer return true" do writer = LoggerDouble.new logger = Jekyll::LogAdapter.new(writer, :debug) allow(writer).to receive(:debug).and_return(true) assert logger.adjust_verbosity end end context "#debug" do should "call #debug on writer return true" do writer = LoggerDouble.new logger = Jekyll::LogAdapter.new(writer, :debug) allow(writer).to receive(:debug) .with("topic ".rjust(20) + "log message").and_return(true) assert logger.debug("topic", "log message") end end context "#info" do should "call #info on writer return true" do writer = LoggerDouble.new logger = Jekyll::LogAdapter.new(writer, :info) allow(writer).to receive(:info) .with("topic ".rjust(20) + "log message").and_return(true) assert logger.info("topic", "log message") end end context "#warn" do should "call #warn on writer return true" do writer = LoggerDouble.new logger = Jekyll::LogAdapter.new(writer, :warn) allow(writer).to receive(:warn) .with("topic ".rjust(20) + "log message").and_return(true) assert logger.warn("topic", "log message") end end context "#error" do should "call #error on writer return true" do writer = LoggerDouble.new logger = Jekyll::LogAdapter.new(writer, :error) allow(writer).to receive(:error) .with("topic ".rjust(20) + "log message").and_return(true) assert logger.error("topic", "log message") end end context "#abort_with" do should "call #error and abort" do logger = Jekyll::LogAdapter.new(LoggerDouble.new, :error) allow(logger).to receive(:error).with("topic", "log message").and_return(true) assert_raises(SystemExit) { logger.abort_with("topic", "log message") } end end context "#messages" do should "return an array" do assert_equal [], Jekyll::LogAdapter.new(LoggerDouble.new).messages end should "store each log value in the array" do logger = Jekyll::LogAdapter.new(LoggerDouble.new, :debug) values = %w(one two three four) logger.debug(values[0]) logger.info(values[1]) logger.warn(values[2]) logger.error(values[3]) assert_equal values.map { |value| "#{value} ".rjust(20) }, logger.messages end end context "#write_message?" do should "return false up to the desired logging level" do subject = Jekyll::LogAdapter.new(LoggerDouble.new, :warn) refute subject.write_message?(:debug), "Should not print debug messages" refute subject.write_message?(:info), "Should not print info messages" assert subject.write_message?(:warn), "Should print warn messages" assert subject.write_message?(:error), "Should print error messages" end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_collections.rb
test/test_collections.rb
# frozen_string_literal: true require "helper" class TestCollections < JekyllUnitTest context "an evil collection" do setup do @collection = Jekyll::Collection.new(fixture_site, "../../etc/password") end should "sanitize the label name" do assert_equal "....etcpassword", @collection.label end should "have a sanitized relative path name" do assert_equal "_....etcpassword", @collection.relative_directory end should "have a sanitized full path" do assert_equal @collection.directory, source_dir("_....etcpassword") end end context "a simple collection" do setup do @collection = Jekyll::Collection.new(fixture_site, "methods") end should "sanitize the label name" do assert_equal "methods", @collection.label end should "have default URL template" do assert_equal "/:collection/:path:output_ext", @collection.url_template end should "contain no docs when initialized" do assert_empty @collection.docs end should "know its relative directory" do assert_equal "_methods", @collection.relative_directory end should "know the full path to itself on the filesystem" do assert_equal @collection.directory, source_dir("_methods") end context "when turned into Liquid" do should "have a label attribute" do assert_equal "methods", @collection.to_liquid["label"] end should "have a docs attribute" do assert_equal [], @collection.to_liquid["docs"] end should "have a files attribute" do assert_equal [], @collection.to_liquid["files"] end should "have a directory attribute" do assert_equal @collection.to_liquid["directory"], source_dir("_methods") end should "have a relative_directory attribute" do assert_equal "_methods", @collection.to_liquid["relative_directory"] end should "have a output attribute" do refute @collection.to_liquid["output"] end end should "know whether it should be written or not" do refute @collection.write? @collection.metadata["output"] = true assert @collection.write? @collection.metadata.delete "output" end end context "with no collections specified" do setup do @site = fixture_site @site.process end should "contain only the default collections" do expected = {} refute_equal expected, @site.collections refute_nil @site.collections end end context "a collection with permalink" do setup do @site = fixture_site( "collections" => { "methods" => { "permalink" => "/awesome/:path/", }, } ) @site.process @collection = @site.collections["methods"] end should "have custom URL template" do assert_equal "/awesome/:path/", @collection.url_template end end context "with a collection" do setup do @site = fixture_site( "collections" => ["methods"] ) @site.process @collection = @site.collections["methods"] end should "create a Hash mapping label to Collection instance" do assert_kind_of Hash, @site.collections refute_nil @site.collections["methods"] assert_kind_of Jekyll::Collection, @site.collections["methods"] end should "collects docs in an array on the Collection object" do assert_kind_of Array, @site.collections["methods"].docs @site.collections["methods"].docs.each do |doc| assert_kind_of Jekyll::Document, doc # rubocop:disable Style/WordArray assert_includes %w( _methods/configuration.md _methods/sanitized_path.md _methods/collection/entries _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md _methods/escape-+\ #%20[].md _methods/yaml_with_dots.md _methods/3940394-21-9393050-fifif1323-test.md _methods/trailing-dots...md ), doc.relative_path # rubocop:enable Style/WordArray end end should "not include files from base dir which start with an underscore" do refute_includes @collection.filtered_entries, "_do_not_read_me.md" end should "not include files which start with an underscore in a subdirectory" do refute_includes @collection.filtered_entries, "site/_dont_include_me_either.md" end should "not include the underscored files in the list of docs" do refute_includes @collection.docs.map(&:relative_path), "_methods/_do_not_read_me.md" refute_includes @collection.docs.map(&:relative_path), "_methods/site/_dont_include_me_either.md" end end context "with a collection with metadata" do setup do @site = fixture_site( "collections" => { "methods" => { "foo" => "bar", "baz" => "whoo", }, } ) @site.process @collection = @site.collections["methods"] end should "extract the configuration collection information as metadata" do expected = { "foo" => "bar", "baz" => "whoo" } assert_equal expected, @collection.metadata end end context "with a collection with metadata to sort items by attribute" do setup do @site = fixture_site( "collections" => { "methods" => { "output" => true, }, "tutorials" => { "output" => true, "sort_by" => "lesson", }, } ) @site.process @tutorials_collection = @site.collections["tutorials"] @actual_array = @tutorials_collection.docs.map(&:relative_path) end should "sort documents in a collection with 'sort_by' metadata set to a " \ "FrontMatter key 'lesson'" do default_tutorials_array = %w( _tutorials/dive-in-and-publish-already.md _tutorials/extending-with-plugins.md _tutorials/getting-started.md _tutorials/graduation-day.md _tutorials/lets-roll.md _tutorials/tip-of-the-iceberg.md ) tutorials_sorted_by_lesson_array = %w( _tutorials/getting-started.md _tutorials/lets-roll.md _tutorials/dive-in-and-publish-already.md _tutorials/tip-of-the-iceberg.md _tutorials/extending-with-plugins.md _tutorials/graduation-day.md ) refute_equal default_tutorials_array, @actual_array assert_equal tutorials_sorted_by_lesson_array, @actual_array end end context "with a collection with metadata to rearrange items" do setup do @site = fixture_site( "collections" => { "methods" => { "output" => true, }, "tutorials" => { "output" => true, "order" => [ "getting-started.md", "lets-roll.md", "dive-in-and-publish-already.md", "tip-of-the-iceberg.md", "graduation-day.md", "extending-with-plugins.md", ], }, } ) @site.process @tutorials_collection = @site.collections["tutorials"] @actual_array = @tutorials_collection.docs.map(&:relative_path) end should "sort documents in a collection in the order outlined in the config file" do default_tutorials_array = %w( _tutorials/dive-in-and-publish-already.md _tutorials/extending-with-plugins.md _tutorials/getting-started.md _tutorials/graduation-day.md _tutorials/lets-roll.md _tutorials/tip-of-the-iceberg.md ) tutorials_rearranged_in_config_array = %w( _tutorials/getting-started.md _tutorials/lets-roll.md _tutorials/dive-in-and-publish-already.md _tutorials/tip-of-the-iceberg.md _tutorials/graduation-day.md _tutorials/extending-with-plugins.md ) refute_equal default_tutorials_array, @actual_array assert_equal tutorials_rearranged_in_config_array, @actual_array end end context "in safe mode" do setup do @site = fixture_site( "collections" => ["methods"], "safe" => true ) @site.process @collection = @site.collections["methods"] end should "include the symlinked file as it resolves to inside site.source" do assert_includes @collection.filtered_entries, "um_hi.md" refute_includes @collection.filtered_entries, "/um_hi.md" end should "include the symlinked file from site.source in the list of docs" do # no support for including symlinked file on Windows skip_if_windows "Jekyll does not currently support symlinks on Windows." assert_includes @collection.docs.map(&:relative_path), "_methods/um_hi.md" end end context "with dots in the filenames" do setup do @site = fixture_site( "collections" => ["with.dots"], "safe" => true ) @site.process @collection = @site.collections["with.dots"] end should "exist" do refute_nil @collection end should "contain one document" do assert_equal 4, @collection.docs.size end should "allow dots in the filename" do assert_equal "_with.dots", @collection.relative_directory end should "read document in subfolders with dots" do assert( @collection.docs.any? { |d| d.path.include?("all.dots") } ) end end context "a collection with included dotfiles" do setup do @site = fixture_site( "collections" => { "methods" => { "permalink" => "/awesome/:path/", }, }, "include" => %w(.htaccess .gitignore) ) @site.process @collection = @site.collections["methods"] end should "contain .htaccess file" do assert(@collection.files.any? { |d| d.name == ".htaccess" }) end should "contain .gitignore file" do assert(@collection.files.any? { |d| d.name == ".gitignore" }) end should "have custom URL in static file" do assert( @collection.files.any? { |d| d.url.include?("/awesome/with.dots/") } ) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_doctor_command.rb
test/test_doctor_command.rb
# frozen_string_literal: true require "helper" require "jekyll/commands/doctor" class TestDoctorCommand < JekyllUnitTest context "URLs only differ by case" do setup do clear_dest end should "return success on a valid site/page" do @site = Site.new(Jekyll.configuration( "source" => File.join(source_dir, "/_urls_differ_by_case_valid"), "destination" => dest_dir )) @site.process output = capture_stderr do ret = Jekyll::Commands::Doctor.urls_only_differ_by_case(@site) refute ret end assert_equal "", output end # rubocop:disable Layout/LineLength should "return warning for pages only differing by case" do @site = Site.new(Jekyll.configuration( "source" => File.join(source_dir, "/_urls_differ_by_case_invalid"), "destination" => dest_dir )) @site.process output = capture_stderr do ret = Jekyll::Commands::Doctor.urls_only_differ_by_case(@site) assert ret end assert_includes output, "Warning: The following URLs only differ by case. On a case-" \ "insensitive file system one of the URLs will be overwritten by the " \ "other: #{dest_dir}/about/index.html, #{dest_dir}/About/index.html" end # rubocop:enable Layout/LineLength end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_liquid_renderer.rb
test/test_liquid_renderer.rb
# frozen_string_literal: true require "helper" class TestLiquidRenderer < JekyllUnitTest context "profiler" do setup do @site = Site.new(site_configuration) @renderer = @site.liquid_renderer end should "return a table with profiling results" do @site.process output = @renderer.stats_table # rubocop:disable Layout/LineLength expected = [ %r!^\| Filename\s+|\s+Count\s+|\s+Bytes\s+|\s+Time$!, %r!^\+(?:-+\+){4}$!, %r!^\|_posts/2010-01-09-date-override\.markdown\s+|\s+\d+\s+|\s+\d+\.\d{2}K\s+|\s+\d+\.\d{3}$!, ] # rubocop:enable Layout/LineLength expected.each do |regexp| assert_match regexp, output end end should "normalize paths of rendered items" do site = fixture_site("theme" => "test-theme") MockRenderer = Class.new(Jekyll::LiquidRenderer) { public :normalize_path } renderer = MockRenderer.new(site) assert_equal "feed.xml", renderer.normalize_path("/feed.xml") assert_equal( "_layouts/post.html", renderer.normalize_path(site.in_source_dir("_layouts", "post.html")) ) assert_equal( "test-theme/_layouts/page.html", renderer.normalize_path(site.in_theme_dir("_layouts", "page.html")) ) assert_equal( "my_plugin-0.1.0/lib/my_plugin/layout.html", renderer.normalize_path( "/users/jo/blog/vendor/bundle/ruby/2.4.0/gems/my_plugin-0.1.0/lib/my_plugin/layout.html" ) ) assert_equal( "test_plugin-0.1.0/lib/test_plugin/layout.html", renderer.normalize_path( "C:/Ruby2.4/lib/ruby/gems/2.4.0/gems/test_plugin-0.1.0/lib/test_plugin/layout.html" ) ) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_site.rb
test/test_site.rb
# frozen_string_literal: true require "helper" class TestSite < JekyllUnitTest def with_image_as_post tmp_image_path = File.join(source_dir, "_posts", "2017-09-01-jekyll-sticker.jpg") FileUtils.cp File.join(Dir.pwd, "docs", "img", "jekyll-sticker.jpg"), tmp_image_path yield ensure FileUtils.rm tmp_image_path end def read_posts @site.posts.docs.concat(PostReader.new(@site).read_posts("")) posts = Dir[source_dir("_posts", "**", "*")] posts.delete_if do |post| File.directory?(post) && post !~ Document::DATE_FILENAME_MATCHER end end context "configuring sites" do should "have an array for plugins by default" do site = Site.new default_configuration assert_equal [File.join(Dir.pwd, "_plugins")], site.plugins end should "look for plugins under the site directory by default" do site = Site.new(site_configuration) assert_equal [source_dir("_plugins")], site.plugins end should "have an array for plugins if passed as a string" do site = Site.new(site_configuration("plugins_dir" => "/tmp/plugins")) array = [temp_dir("plugins")] assert_equal array, site.plugins end should "have an array for plugins if passed as an array" do site = Site.new(site_configuration( "plugins_dir" => ["/tmp/plugins", "/tmp/otherplugins"] )) array = [temp_dir("plugins"), temp_dir("otherplugins")] assert_equal array, site.plugins end should "have an empty array for plugins if nothing is passed" do site = Site.new(site_configuration("plugins_dir" => [])) assert_equal [], site.plugins end should "have the default for plugins if nil is passed" do site = Site.new(site_configuration("plugins_dir" => nil)) assert_equal [source_dir("_plugins")], site.plugins end should "default baseurl to `nil`" do site = Site.new(default_configuration) assert_nil site.baseurl end should "expose baseurl passed in from config" do site = Site.new(site_configuration("baseurl" => "/blog")) assert_equal "/blog", site.baseurl end should "only include theme includes_path if the path exists" do site = fixture_site("theme" => "test-theme") assert_equal [source_dir("_includes"), theme_dir("_includes")], site.includes_load_paths allow(File).to receive(:directory?).with(theme_dir("_sass")).and_return(true) allow(File).to receive(:directory?).with(theme_dir("_layouts")).and_return(true) allow(File).to receive(:directory?).with(theme_dir("_includes")).and_return(false) site = fixture_site("theme" => "test-theme") assert_equal [source_dir("_includes")], site.includes_load_paths end should "configure cache_dir" do fixture_site.process assert File.directory?(source_dir(".jekyll-cache", "Jekyll", "Cache")) assert File.directory?(source_dir(".jekyll-cache", "Jekyll", "Cache", "Jekyll--Cache")) end should "use .jekyll-cache directory at source as cache_dir by default" do site = Site.new(default_configuration) assert_equal File.join(site.source, ".jekyll-cache"), site.cache_dir end should "have the cache_dir hidden from Git" do site = fixture_site assert_equal site.source, source_dir assert_exist source_dir(".jekyll-cache", ".gitignore") assert_equal( "# ignore everything in this directory\n*\n", File.binread(source_dir(".jekyll-cache", ".gitignore")) ) end should "load config file from theme-gem as Jekyll::Configuration instance" do site = fixture_site("theme" => "test-theme") assert_instance_of Jekyll::Configuration, site.config assert_equal "Hello World", site.config["title"] end context "with a custom cache_dir configuration" do should "have the custom cache_dir hidden from Git" do site = fixture_site("cache_dir" => "../../custom-cache-dir") refute_exist File.expand_path("../../custom-cache-dir/.gitignore", site.source) assert_exist source_dir("custom-cache-dir", ".gitignore") assert_equal( "# ignore everything in this directory\n*\n", File.binread(source_dir("custom-cache-dir", ".gitignore")) ) end end end context "creating sites" do setup do @site = Site.new(site_configuration) @num_invalid_posts = 6 end teardown do self.class.send(:remove_const, :MyGenerator) if defined?(MyGenerator) end should "have an empty tag hash by default" do assert_equal({}, @site.tags) end should "give site with parsed pages and posts to generators" do class MyGenerator < Generator def generate(site) site.pages.dup.each do |page| raise "#{page} isn't a page" unless page.is_a?(Page) raise "#{page} doesn't respond to :name" unless page.respond_to?(:name) end site.file_read_opts[:secret_message] = "hi" end end @site = Site.new(site_configuration) @site.read @site.generate refute_equal 0, @site.pages.size assert_equal "hi", @site.file_read_opts[:secret_message] end should "reset data before processing" do clear_dest @site.process before_posts = @site.posts.length before_layouts = @site.layouts.length before_categories = @site.categories.length before_tags = @site.tags.length before_pages = @site.pages.length before_static_files = @site.static_files.length before_time = @site.time @site.process assert_equal before_posts, @site.posts.length assert_equal before_layouts, @site.layouts.length assert_equal before_categories, @site.categories.length assert_equal before_tags, @site.tags.length assert_equal before_pages, @site.pages.length assert_equal before_static_files, @site.static_files.length assert before_time <= @site.time end should "write only modified static files" do clear_dest StaticFile.reset_cache @site.regenerator.clear @site.process some_static_file = @site.static_files[0].path dest = File.expand_path(@site.static_files[0].destination(@site.dest)) mtime1 = File.stat(dest).mtime.to_i # first run must generate dest file # need to sleep because filesystem timestamps have best resolution in seconds sleep 1 @site.process mtime2 = File.stat(dest).mtime.to_i assert_equal mtime1, mtime2 # simulate file modification by user FileUtils.touch some_static_file sleep 1 @site.process mtime3 = File.stat(dest).mtime.to_i refute_equal mtime2, mtime3 # must be regenerated! sleep 1 @site.process mtime4 = File.stat(dest).mtime.to_i assert_equal mtime3, mtime4 # no modifications, so must be the same end should "write static files if not modified but missing in destination" do clear_dest StaticFile.reset_cache @site.regenerator.clear @site.process dest = File.expand_path(@site.static_files[0].destination(@site.dest)) mtime1 = File.stat(dest).mtime.to_i # first run must generate dest file # need to sleep because filesystem timestamps have best resolution in seconds sleep 1 @site.process mtime2 = File.stat(dest).mtime.to_i assert_equal mtime1, mtime2 # simulate destination file deletion File.unlink dest refute_path_exists(dest) sleep 1 @site.process mtime3 = File.stat(dest).mtime.to_i assert_equal mtime2, mtime3 # must be regenerated and with original mtime! sleep 1 @site.process mtime4 = File.stat(dest).mtime.to_i assert_equal mtime3, mtime4 # no modifications, so remain the same end should "setup plugins in priority order" do assert_equal( @site.converters.sort_by(&:class).map { |c| c.class.priority }, @site.converters.map { |c| c.class.priority } ) assert_equal( @site.generators.sort_by(&:class).map { |g| g.class.priority }, @site.generators.map { |g| g.class.priority } ) end should "sort pages alphabetically" do method = Dir.method(:entries) allow(Dir).to receive(:entries) do |*args, &block| method.call(*args, &block).reverse end @site.process # exclude files in symlinked directories here and insert them in the # following step when not on Windows. # rubocop:disable Style/WordArray sorted_pages = %w( %#\ +.md .htaccess about.html application.coffee bar.html coffeescript.coffee contacts.html deal.with.dots.html dynamic_file.php environment.html exploit.md foo.md foo.md humans.txt index.html index.html info.md main.css.map main.scss properties.html sitemap.xml static_files.html test-styles.css.map test-styles.scss trailing-dots...md ) # rubocop:enable Style/WordArray unless Utils::Platforms.really_windows? # files in symlinked directories may appear twice sorted_pages.push("main.css.map", "main.scss", "symlinked-file").sort! end assert_equal sorted_pages, @site.pages.map(&:name).sort! end should "read posts" do posts = read_posts assert_equal posts.size - @num_invalid_posts, @site.posts.size end should "skip posts with invalid encoding" do with_image_as_post do posts = read_posts num_invalid_posts = @num_invalid_posts + 1 assert_equal posts.size - num_invalid_posts, @site.posts.size end end should "read pages with YAML front matter" do abs_path = File.expand_path("about.html", @site.source) assert Utils.has_yaml_header?(abs_path) end should "enforce a strict 3-dash limit on the start of the YAML front matter" do abs_path = File.expand_path("pgp.key", @site.source) refute Utils.has_yaml_header?(abs_path) end should "expose jekyll version to site payload" do assert_equal Jekyll::VERSION, @site.site_payload["jekyll"]["version"] end should "expose list of static files to site payload" do assert_equal @site.static_files, @site.site_payload["site"]["static_files"] end should "deploy payload" do clear_dest @site.process posts = Dir[source_dir("**", "_posts", "**", "*")] posts.delete_if do |post| File.directory?(post) && post !~ Document::DATE_FILENAME_MATCHER end categories = %w( 2013 bar baz category foo z_category MixedCase Mixedcase publish_test win ).sort assert_equal posts.size - @num_invalid_posts, @site.posts.size assert_equal categories, @site.categories.keys.sort assert_equal 5, @site.categories["foo"].size end context "error handling" do should "raise if destination is included in source" do assert_raises Jekyll::Errors::FatalException do Site.new(site_configuration("destination" => source_dir)) end end should "raise if destination is source" do assert_raises Jekyll::Errors::FatalException do Site.new(site_configuration("destination" => File.join(source_dir, ".."))) end end should "raise for bad frontmatter if strict_front_matter is set" do site = Site.new(site_configuration( "collections" => ["broken"], "strict_front_matter" => true )) assert_raises(Psych::SyntaxError) do site.process end end should "not raise for bad frontmatter if strict_front_matter is not set" do site = Site.new(site_configuration( "collections" => ["broken"], "strict_front_matter" => false )) site.process end end context "with orphaned files in destination" do setup do clear_dest @site.regenerator.clear @site.process # generate some orphaned files: # single file FileUtils.touch(dest_dir("obsolete.html")) # single file in sub directory FileUtils.mkdir(dest_dir("qux")) FileUtils.touch(dest_dir("qux/obsolete.html")) # empty directory FileUtils.mkdir(dest_dir("quux")) FileUtils.mkdir(dest_dir(".git")) FileUtils.mkdir(dest_dir(".svn")) FileUtils.mkdir(dest_dir(".hg")) # single file in repository FileUtils.touch(dest_dir(".git/HEAD")) FileUtils.touch(dest_dir(".svn/HEAD")) FileUtils.touch(dest_dir(".hg/HEAD")) end teardown do FileUtils.rm_f(dest_dir("obsolete.html")) FileUtils.rm_rf(dest_dir("qux")) FileUtils.rm_f(dest_dir("quux")) FileUtils.rm_rf(dest_dir(".git")) FileUtils.rm_rf(dest_dir(".svn")) FileUtils.rm_rf(dest_dir(".hg")) end should "remove orphaned files in destination" do @site.process refute_exist dest_dir("obsolete.html") refute_exist dest_dir("qux") refute_exist dest_dir("quux") assert_exist dest_dir(".git") assert_exist dest_dir(".git", "HEAD") end should "remove orphaned files in destination - keep_files .svn" do config = site_configuration("keep_files" => %w(.svn)) @site = Site.new(config) @site.process refute_exist dest_dir(".htpasswd") refute_exist dest_dir("obsolete.html") refute_exist dest_dir("qux") refute_exist dest_dir("quux") refute_exist dest_dir(".git") refute_exist dest_dir(".git", "HEAD") assert_exist dest_dir(".svn") assert_exist dest_dir(".svn", "HEAD") end end context "using a non-default markdown processor in the configuration" do should "use the non-default markdown processor" do class Jekyll::Converters::Markdown::CustomMarkdown def initialize(*args) @args = args end def convert(*_args) "" end end custom_processor = "CustomMarkdown" s = Site.new(site_configuration("markdown" => custom_processor)) s.process # Do some cleanup, we don't like straggling stuff. Jekyll::Converters::Markdown.send(:remove_const, :CustomMarkdown) end should "ignore, if there are any bad characters in the class name" do module Jekyll::Converters::Markdown::Custom class Markdown def initialize(*args) @args = args end def convert(*_args) "" end end end bad_processor = "Custom::Markdown" s = Site.new(site_configuration( "markdown" => bad_processor, "incremental" => false )) assert_raises Jekyll::Errors::FatalException do s.process end # Do some cleanup, we don't like straggling stuff. Jekyll::Converters::Markdown.send(:remove_const, :Custom) end end context "with an invalid markdown processor in the configuration" do should "not throw an error at initialization time" do bad_processor = "not a processor name" assert Site.new(site_configuration("markdown" => bad_processor)) end should "throw FatalException at process time" do bad_processor = "not a processor name" s = Site.new(site_configuration( "markdown" => bad_processor, "incremental" => false )) assert_raises Jekyll::Errors::FatalException do s.process end end end context "data directory" do should "auto load yaml files" do site = Site.new(site_configuration) site.process file_content = SafeYAML.load_file(File.join(source_dir, "_data", "members.yaml")) assert_equal site.data["members"], file_content assert_equal site.site_payload["site"]["data"]["members"], file_content end should "load yaml files from extracted method" do site = Site.new(site_configuration) site.process file_content = DataReader.new(site) .read_data_file(source_dir("_data", "members.yaml")) assert_equal site.data["members"], file_content assert_equal site.site_payload["site"]["data"]["members"], file_content end should "auto load yml files" do site = Site.new(site_configuration) site.process file_content = SafeYAML.load_file(File.join(source_dir, "_data", "languages.yml")) assert_equal site.data["languages"], file_content assert_equal site.site_payload["site"]["data"]["languages"], file_content end should "auto load json files" do site = Site.new(site_configuration) site.process file_content = SafeYAML.load_file(File.join(source_dir, "_data", "members.json")) assert_equal site.data["members"], file_content assert_equal site.site_payload["site"]["data"]["members"], file_content end should "auto load yaml files in subdirectory" do site = Site.new(site_configuration) site.process file_content = SafeYAML.load_file(File.join( source_dir, "_data", "categories", "dairy.yaml" )) assert_equal site.data["categories"]["dairy"], file_content assert_equal( site.site_payload["site"]["data"]["categories"]["dairy"], file_content ) end should "auto load yaml files in subdirectory with a period in the name" do site = Site.new(site_configuration) site.process file_content = SafeYAML.load_file(File.join( source_dir, "_data", "categories.01", "dairy.yaml" )) assert_equal site.data["categories01"]["dairy"], file_content assert_equal( site.site_payload["site"]["data"]["categories01"]["dairy"], file_content ) end should "load symlink files in unsafe mode" do site = Site.new(site_configuration("safe" => false)) site.process file_content = SafeYAML.load_file(File.join(source_dir, "_data", "products.yml")) assert_equal site.data["products"], file_content assert_equal site.site_payload["site"]["data"]["products"], file_content end should "load the symlink files in safe mode, " \ "as they resolve to inside site.source" do site = Site.new(site_configuration("safe" => true)) site.process file_content = SafeYAML.load_file(File.join(source_dir, "_data", "products.yml")) assert_equal site.data["products"], file_content assert_equal site.site_payload["site"]["data"]["products"], file_content end end context "manipulating the Jekyll environment" do setup do @site = Site.new(site_configuration( "incremental" => false )) @site.process @page = @site.pages.find { |p| p.name == "environment.html" } end should "default to 'development'" do assert_equal "development", @page.content.strip end context "in production" do setup do ENV["JEKYLL_ENV"] = "production" @site = Site.new(site_configuration( "incremental" => false )) @site.process @page = @site.pages.find { |p| p.name == "environment.html" } end teardown do ENV.delete("JEKYLL_ENV") end should "be overridden by JEKYLL_ENV" do assert_equal "production", @page.content.strip end end end context "when setting theme" do should "set no theme if config is not set" do expect($stderr).not_to receive(:puts) expect($stdout).not_to receive(:puts) site = fixture_site("theme" => nil) assert_nil site.theme end should "set no theme if config is a hash" do output = capture_output do site = fixture_site("theme" => {}) assert_nil site.theme end expected_msg = "Theme: value of 'theme' in config should be String to use " \ "gem-based themes, but got Hash\n" assert_includes output, expected_msg end should "set a theme if the config is a string" do [:debug, :info, :warn, :error].each do |level| if level == :info expect(Jekyll.logger.writer).to receive(level) else expect(Jekyll.logger.writer).not_to receive(level) end end site = fixture_site("theme" => "test-theme") assert_instance_of Jekyll::Theme, site.theme assert_equal "test-theme", site.theme.name end end context "with liquid profiling" do setup do @site = Site.new(site_configuration("profile" => true)) end # Suppress output while testing setup do $stdout = StringIO.new end teardown do $stdout = STDOUT end should "print profile table" do expect(@site.liquid_renderer).to receive(:stats_table) @site.process end end context "incremental build" do setup do @site = Site.new(site_configuration( "incremental" => true )) @site.read end should "build incrementally" do contacts_html = @site.pages.find { |p| p.name == "contacts.html" } @site.process source = @site.in_source_dir(contacts_html.path) dest = File.expand_path(contacts_html.destination(@site.dest)) mtime1 = File.stat(dest).mtime.to_i # first run must generate dest file # need to sleep because filesystem timestamps have best resolution in seconds sleep 1 @site.process mtime2 = File.stat(dest).mtime.to_i assert_equal mtime1, mtime2 # no modifications, so remain the same # simulate file modification by user FileUtils.touch source sleep 1 @site.process mtime3 = File.stat(dest).mtime.to_i refute_equal mtime2, mtime3 # must be regenerated sleep 1 @site.process mtime4 = File.stat(dest).mtime.to_i assert_equal mtime3, mtime4 # no modifications, so remain the same end should "regenerate files that have had their destination deleted" do contacts_html = @site.pages.find { |p| p.name == "contacts.html" } @site.process dest = File.expand_path(contacts_html.destination(@site.dest)) mtime1 = File.stat(dest).mtime.to_i # first run must generate dest file # simulate file modification by user File.unlink dest refute File.file?(dest) sleep 1 # sleep for 1 second, since mtimes have 1s resolution @site.process assert File.file?(dest) mtime2 = File.stat(dest).mtime.to_i refute_equal mtime1, mtime2 # must be regenerated end end context "#in_cache_dir method" do setup do @site = Site.new( site_configuration( "cache_dir" => "../../custom-cache-dir" ) ) end should "create sanitized paths within the cache directory" do assert_equal File.join(@site.source, "custom-cache-dir"), @site.cache_dir assert_equal( File.join(@site.source, "custom-cache-dir", "foo.md.metadata"), @site.in_cache_dir("../../foo.md.metadata") ) end end end context "site process phases" do should "return nil as documented" do site = fixture_site [:reset, :read, :generate, :render, :cleanup, :write].each do |phase| assert_nil site.send(phase) end end end context "static files in a collection" do should "be exposed via site instance" do site = fixture_site("collections" => ["methods"]) site.read assert_includes site.static_files.map(&:relative_path), "_methods/extensionless_static_file" end should "not be revisited in `Site#each_site_file`" do site = fixture_site("collections" => { "methods" => { "output" => true } }) site.read visited_files = [] site.each_site_file { |file| visited_files << file } assert_equal visited_files.count, visited_files.uniq.count end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_sass.rb
test/test_sass.rb
# frozen_string_literal: true require "helper" class TestSass < JekyllUnitTest context "importing partials" do setup do @site = Jekyll::Site.new(Jekyll.configuration( "source" => source_dir, "destination" => dest_dir )) @site.process @test_css_file = dest_dir("css/main.css") end should "import SCSS partial" do result = <<~CSS .half { width: 50%; } /*# sourceMappingURL=main.css.map */ CSS assert_equal result.rstrip, File.read(@test_css_file) end should "register the SCSS converter" do message = "SCSS converter implementation should exist." refute !@site.find_converter_instance(Jekyll::Converters::Scss), message end should "register the Sass converter" do message = "Sass converter implementation should exist." refute !@site.find_converter_instance(Jekyll::Converters::Sass), message end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_tag_link.rb
test/test_tag_link.rb
# frozen_string_literal: true require "helper" class TestTagLink < TagUnitTest def render_content_with_collection(content, collection_label) render_content( content, "collections" => { collection_label => { "output" => true } }, "read_collections" => true ) end context "post content has raw tag" do setup do content = <<~CONTENT --- title: This is a test --- ```liquid {% raw %} {% link _collection/name-of-document.md %} {% endraw %} ``` CONTENT render_content(content) end should "render markdown with rouge" do assert_match( %(<div class="language-liquid highlighter-rouge">) + %(<div class="highlight"><pre class="highlight"><code>), @result ) end end context "simple page with linking to a page" do setup do content = <<~CONTENT --- title: linking --- {% link contacts.html %} {% link info.md %} {% link /css/screen.css %} CONTENT render_content(content, "read_all" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'contacts' item" do assert_match(%r!/contacts\.html!, @result) end should "have the URL to the 'info' item" do assert_match(%r!/info\.html!, @result) end should "have the URL to the 'screen.css' item" do assert_match(%r!/css/screen\.css!, @result) end end context "simple page with dynamic linking to a page" do setup do content = <<~CONTENT --- title: linking --- {% assign contacts_filename = 'contacts' %} {% assign contacts_ext = 'html' %} {% link {{contacts_filename}}.{{contacts_ext}} %} {% assign info_path = 'info.md' %} {% link {{ info_path }} %} {% assign screen_css_path = '/css' %} {% link {{ screen_css_path }}/screen.css %} CONTENT render_content(content, "read_all" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'contacts' item" do assert_match(%r!/contacts\.html!, @result) end should "have the URL to the 'info' item" do assert_match(%r!/info\.html!, @result) end should "have the URL to the 'screen.css' item" do assert_match(%r!/css/screen\.css!, @result) end end context "simple page with linking" do setup do content = <<~CONTENT --- title: linking --- {% link _methods/yaml_with_dots.md %} CONTENT render_content_with_collection(content, "methods") end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'yaml_with_dots' item" do assert_match(%r!/methods/yaml_with_dots\.html!, @result) end end context "simple page with dynamic linking" do setup do content = <<~CONTENT --- title: linking --- {% assign yaml_with_dots_path = '_methods/yaml_with_dots.md' %} {% link {{yaml_with_dots_path}} %} CONTENT render_content_with_collection(content, "methods") end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'yaml_with_dots' item" do assert_match(%r!/methods/yaml_with_dots\.html!, @result) end end context "simple page with nested linking" do setup do content = <<~CONTENT --- title: linking --- - 1 {% link _methods/sanitized_path.md %} - 2 {% link _methods/site/generate.md %} CONTENT render_content_with_collection(content, "methods") end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'sanitized_path' item" do assert_match %r!1\s/methods/sanitized_path\.html!, @result end should "have the URL to the 'site/generate' item" do assert_match %r!2\s/methods/site/generate\.html!, @result end end context "simple page with invalid linking" do should "cause an error" do content = <<~CONTENT --- title: Invalid linking --- {% link non-existent-collection-item %} CONTENT assert_raises ArgumentError do render_content_with_collection(content, "methods") end end end context "simple page with invalid dynamic linking" do should "cause an error" do content = <<~CONTENT --- title: Invalid linking --- {% assign non_existent_path = 'non-existent-collection-item' %} {% link {{ non_existent_path }} %} CONTENT assert_raises ArgumentError do render_content_with_collection(content, "methods") end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_cleaner.rb
test/test_cleaner.rb
# frozen_string_literal: true require "helper" class TestCleaner < JekyllUnitTest context "directory in keep_files" do setup do clear_dest FileUtils.mkdir_p(dest_dir("to_keep/child_dir")) FileUtils.touch(File.join(dest_dir("to_keep"), "index.html")) FileUtils.touch(File.join(dest_dir("to_keep/child_dir"), "index.html")) @site = fixture_site @site.keep_files = ["to_keep/child_dir"] @cleaner = Cleaner.new(@site) @cleaner.cleanup! end teardown do FileUtils.rm_rf(dest_dir("to_keep")) end should "keep the parent directory" do assert_exist dest_dir("to_keep") end should "keep the child directory" do assert_exist dest_dir("to_keep", "child_dir") end should "keep the file in the directory in keep_files" do assert_exist dest_dir("to_keep", "child_dir", "index.html") end should "delete the file in the directory not in keep_files" do refute_exist dest_dir("to_keep", "index.html") end end context "non-nested directory & similarly-named directory *not* in keep_files" do setup do clear_dest FileUtils.mkdir_p(dest_dir(".git/child_dir")) FileUtils.mkdir_p(dest_dir("username.github.io")) FileUtils.touch(File.join(dest_dir(".git"), "index.html")) FileUtils.touch(File.join(dest_dir("username.github.io"), "index.html")) @site = fixture_site @site.keep_files = [".git"] @cleaner = Cleaner.new(@site) @cleaner.cleanup! end teardown do FileUtils.rm_rf(dest_dir(".git")) FileUtils.rm_rf(dest_dir("username.github.io")) end should "keep the file in the directory in keep_files" do assert_path_exists(File.join(dest_dir(".git"), "index.html")) end should "delete the file in the directory not in keep_files" do refute_path_exists(File.join(dest_dir("username.github.io"), "index.html")) end should "delete the directory not in keep_files" do refute_path_exists(dest_dir("username.github.io")) end end context "directory containing no files and non-empty directories" do setup do clear_dest FileUtils.mkdir_p(source_dir("no_files_inside", "child_dir")) FileUtils.touch(source_dir("no_files_inside", "child_dir", "index.html")) @site = fixture_site @site.process @cleaner = Cleaner.new(@site) @cleaner.cleanup! end teardown do FileUtils.rm_rf(source_dir("no_files_inside")) FileUtils.rm_rf(dest_dir("no_files_inside")) end should "keep the parent directory" do assert_exist dest_dir("no_files_inside") end should "keep the child directory" do assert_exist dest_dir("no_files_inside", "child_dir") end should "keep the file" do assert_exist source_dir("no_files_inside", "child_dir", "index.html") end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_excerpt_drop.rb
test/test_excerpt_drop.rb
# frozen_string_literal: true require "helper" class TestExcerptDrop < JekyllUnitTest context "an excerpt drop" do setup do @site = fixture_site @site.read @doc = @site.docs_to_write.find { |d| !d.data["layout"].nil? } @doc_drop = @doc.to_liquid @excerpt = @doc.data["excerpt"] @excerpt_drop = @excerpt.to_liquid end should "have the right thing" do assert_kind_of Jekyll::Document, @doc assert_kind_of Jekyll::Drops::DocumentDrop, @doc_drop assert_kind_of Jekyll::Excerpt, @excerpt assert_kind_of Jekyll::Drops::ExcerptDrop, @excerpt_drop end should "not have an excerpt" do assert_nil @excerpt.data["excerpt"] assert @excerpt_drop.class.invokable? "excerpt" assert_nil @excerpt_drop["excerpt"] end should "inherit the layout for the drop but not the excerpt" do assert_nil @excerpt.data["layout"] assert_equal @doc_drop["layout"], @excerpt_drop["layout"] end should "be inspectable" do refute_empty @excerpt_drop.inspect end should "inherit values from the document" do assert_equal @doc_drop.keys.sort, @excerpt_drop.keys.sort end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_tag_post_url.rb
test/test_tag_post_url.rb
# frozen_string_literal: true require "helper" class TestTagPostUrl < TagUnitTest context "simple page with post linking" do setup do content = <<~CONTENT --- title: Post linking --- {% post_url 2008-11-21-complex %} CONTENT render_content(content, "permalink" => "pretty", "read_posts" => true) end should "not cause an error" do refute_match %r!markdown-html-error!, @result end should "have the URL to the 'complex' post from 2008-11-21" do assert_match %r!/2008/11/21/complex/!, @result end end context "simple page with post linking containing special characters" do setup do content = <<~CONTENT --- title: Post linking --- {% post_url 2016-11-26-special-chars-(+) %} CONTENT render_content(content, "permalink" => "pretty", "read_posts" => true) end should "not cause an error" do refute_match %r!markdown-html-error!, @result end should "have the URL to the 'special-chars' post from 2016-11-26" do assert_match %r!/2016/11/26/special-chars-\(\+\)/!, @result end end context "simple page with nested post linking" do setup do content = <<~CONTENT --- title: Post linking --- - 1 {% post_url 2008-11-21-complex %} - 2 {% post_url /2008-11-21-complex %} - 3 {% post_url es/2008-11-21-nested %} - 4 {% post_url /es/2008-11-21-nested %} CONTENT render_content(content, "permalink" => "pretty", "read_posts" => true) end should "not cause an error" do refute_match %r!markdown-html-error!, @result end should "have the URL to the 'complex' post from 2008-11-21" do assert_match %r!1\s/2008/11/21/complex/!, @result assert_match %r!2\s/2008/11/21/complex/!, @result end should "have the URL to the 'nested' post from 2008-11-21" do assert_match %r!3\s/2008/11/21/nested/!, @result assert_match %r!4\s/2008/11/21/nested/!, @result end end context "simple page with nested post linking and path not used in `post_url`" do setup do content = <<~CONTENT --- title: Deprecated Post linking --- - 1 {% post_url 2008-11-21-nested %} CONTENT render_content(content, "permalink" => "pretty", "read_posts" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the url to the 'nested' post from 2008-11-21" do assert_match %r!1\s/2008/11/21/nested/!, @result end should "throw a deprecation warning" do deprecation_warning = " Deprecation: A call to '{% post_url 2008-11-21-nested %}' " \ "did not match a post using the new matching method of checking " \ "name (path-date-slug) equality. Please make sure that you change " \ "this tag to match the post's name exactly." assert_includes Jekyll.logger.messages, deprecation_warning end end context "simple page with invalid post name linking" do should "cause an error" do assert_raises Jekyll::Errors::PostURLError do render_content(<<~CONTENT, "read_posts" => true) --- title: Invalid post name linking --- {% post_url abc2008-11-21-complex %} CONTENT end end should "cause an error with a bad date" do assert_raises Jekyll::Errors::InvalidDateError do render_content(<<~CONTENT, "read_posts" => true) --- title: Invalid post name linking --- {% post_url 2008-42-21-complex %} CONTENT end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_plugin_manager.rb
test/test_plugin_manager.rb
# frozen_string_literal: true require "helper" class TestPluginManager < JekyllUnitTest def with_no_gemfile FileUtils.mv "Gemfile", "Gemfile.old" yield ensure FileUtils.mv "Gemfile.old", "Gemfile" end def with_bundle_gemfile FileUtils.mv "Gemfile", "AlternateGemfile" yield ensure FileUtils.mv "AlternateGemfile", "Gemfile" end context "JEKYLL_NO_BUNDLER_REQUIRE set to `nil`" do should "require from bundler" do with_env("JEKYLL_NO_BUNDLER_REQUIRE", nil) do assert Jekyll::PluginManager.require_from_bundler, "require_from_bundler should return true." assert ENV["JEKYLL_NO_BUNDLER_REQUIRE"], "Gemfile plugins were not required." end end end context "BUNDLE_GEMFILE set to `AlternateGemfile`" do should "require from bundler" do with_env("BUNDLE_GEMFILE", "AlternateGemfile") do with_bundle_gemfile do assert Jekyll::PluginManager.require_from_bundler, "require_from_bundler should return true" assert ENV["JEKYLL_NO_BUNDLER_REQUIRE"], "Gemfile plugins were not required." end end end end context "JEKYLL_NO_BUNDLER_REQUIRE set to `true`" do should "not require from bundler" do with_env("JEKYLL_NO_BUNDLER_REQUIRE", "true") do refute Jekyll::PluginManager.require_from_bundler, "Gemfile plugins were required but shouldn't have been" assert ENV["JEKYLL_NO_BUNDLER_REQUIRE"] end end end context "JEKYLL_NO_BUNDLER_REQUIRE set to `nil` and no Gemfile present" do should "not require from bundler" do with_env("JEKYLL_NO_BUNDLER_REQUIRE", nil) do with_no_gemfile do refute Jekyll::PluginManager.require_from_bundler, "Gemfile plugins were required but shouldn't have been" assert_nil ENV["JEKYLL_NO_BUNDLER_REQUIRE"] end end end end context "require gems" do should "invoke `require_with_graceful_fail`" do gems = %w(jemojii foobar) expect(Jekyll::External).to( receive(:require_with_graceful_fail).with(gems).and_return(nil) ) site = double(:gems => gems) plugin_manager = PluginManager.new(site) allow(plugin_manager).to receive(:plugin_allowed?).with("foobar").and_return(true) allow(plugin_manager).to receive(:plugin_allowed?).with("jemojii").and_return(true) plugin_manager.require_gems end end context "site is not marked as safe" do should "allow all plugins" do site = double(:safe => false) plugin_manager = PluginManager.new(site) assert plugin_manager.plugin_allowed?("foobar") end should "require plugin files" do site = double(:safe => false, :config => { "plugins_dir" => "_plugins" }, :in_source_dir => "/tmp/") plugin_manager = PluginManager.new(site) expect(Jekyll::External).to receive(:require_with_graceful_fail) plugin_manager.require_plugin_files end end context "site is marked as safe" do should "allow plugins if they are whitelisted" do site = double(:safe => true, :config => { "whitelist" => ["jemoji"] }) plugin_manager = PluginManager.new(site) assert plugin_manager.plugin_allowed?("jemoji") refute plugin_manager.plugin_allowed?("not_allowed_plugin") end should "not require plugin files" do site = double(:safe => true) plugin_manager = PluginManager.new(site) expect(Jekyll::External).to_not receive(:require_with_graceful_fail) plugin_manager.require_plugin_files end end context "plugins_dir is set to the default" do should "call site's in_source_dir" do site = double( :config => { "plugins_dir" => Jekyll::Configuration::DEFAULTS["plugins_dir"], }, :in_source_dir => "/tmp/" ) plugin_manager = PluginManager.new(site) expect(site).to receive(:in_source_dir).with("_plugins") plugin_manager.plugins_path end end context "plugins_dir is set to a different dir" do should "expand plugin path" do site = double(:config => { "plugins_dir" => "some_other_plugins_path" }) plugin_manager = PluginManager.new(site) expect(File).to receive(:expand_path).with("some_other_plugins_path") plugin_manager.plugins_path end end context "`paginate` config is activated" do should "print deprecation warning if jekyll-paginate is not present" do site = double(:config => { "paginate" => true }) plugin_manager = PluginManager.new(site) expect(Jekyll::Deprecator).to( receive(:deprecation_message).with(%r!jekyll-paginate!) ) plugin_manager.deprecation_checks end should "print no deprecation warning if jekyll-paginate is present" do site = double( :config => { "paginate" => true, "plugins" => ["jekyll-paginate"] } ) plugin_manager = PluginManager.new(site) expect(Jekyll::Deprecator).to_not receive(:deprecation_message) plugin_manager.deprecation_checks end end should "conscientious require" do site = double( :config => { "theme" => "test-dependency-theme" }, :in_dest_dir => "/tmp/_site/" ) plugin_manager = PluginManager.new(site) expect(site).to receive(:theme).and_return(true) expect(site).to receive(:process).and_return(true) expect(plugin_manager).to( receive_messages([ :require_theme_deps, :require_plugin_files, :require_gems, :deprecation_checks, ]) ) plugin_manager.conscientious_require site.process assert site.in_dest_dir("test.txt") end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_convertible.rb
test/test_convertible.rb
# frozen_string_literal: true require "helper" require "ostruct" class TestConvertible < JekyllUnitTest context "YAML front matter" do setup do @convertible = OpenStruct.new( "site" => Site.new(Jekyll.configuration( "source" => File.expand_path("fixtures", __dir__) )) ) @convertible.extend Jekyll::Convertible @base = File.expand_path("fixtures", __dir__) end should "parse the front matter correctly" do ret = @convertible.read_yaml(@base, "front_matter.erb") assert_equal({ "test" => "good" }, ret) end should "not parse if the front matter is not at the start of the file" do ret = @convertible.read_yaml(@base, "broken_front_matter1.erb") assert_equal({}, ret) end should "not parse if there is syntax error in front matter" do name = "broken_front_matter2.erb" out = capture_stderr do ret = @convertible.read_yaml(@base, name) assert_equal({}, ret) end assert_match(%r!YAML Exception!, out) assert_match(%r!#{Regexp.escape(File.join(@base, name))}!, out) end should "raise for broken front matter with `strict_front_matter` set" do name = "broken_front_matter2.erb" @convertible.site.config["strict_front_matter"] = true assert_raises(Psych::SyntaxError) do @convertible.read_yaml(@base, name) end end should "not allow ruby objects in YAML" do out = capture_stderr do @convertible.read_yaml(@base, "exploit_front_matter.erb") end refute_match(%r!undefined class/module DoesNotExist!, out) end should "not parse if there is encoding error in file" do name = "broken_front_matter3.erb" out = capture_stderr do ret = @convertible.read_yaml(@base, name, :encoding => "utf-8") assert_equal({}, ret) end assert_match(%r!invalid byte sequence in UTF-8!, out) assert_match(%r!#{Regexp.escape(File.join(@base, name))}!, out) end should "parse the front matter but show an error if permalink is empty" do name = "empty_permalink.erb" assert_raises(Errors::InvalidPermalinkError) do @convertible.read_yaml(@base, name) end end should "parse the front matter correctly without permalink" do out = capture_stderr do @convertible.read_yaml(@base, "front_matter.erb") end refute_match(%r!Invalid permalink!, out) end should "not parse Liquid if disabled in front matter" do name = "no_liquid.erb" @convertible.read_yaml(@base, name) ret = @convertible.content.strip assert_equal("{% raw %}{% endraw %}", ret) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_path_manager.rb
test/test_path_manager.rb
# frozen_string_literal: true require "helper" class TestPathManager < JekyllUnitTest context "PathManager" do setup do @source = Dir.pwd end should "return frozen copy of base if questionable path is nil" do assert_equal @source, Jekyll::PathManager.sanitized_path(@source, nil) assert Jekyll::PathManager.sanitized_path(@source, nil).frozen? end should "return a frozen copy of base if questionable path expands into the base" do assert_equal @source, Jekyll::PathManager.sanitized_path(@source, File.join(@source, "/")) assert Jekyll::PathManager.sanitized_path(@source, File.join(@source, "/")).frozen? end should "return a frozen string result" do if Jekyll::Utils::Platforms.really_windows? assert_equal( "#{@source}/_config.yml", Jekyll::PathManager.sanitized_path(@source, "E:\\_config.yml") ) end assert_equal( "#{@source}/_config.yml", Jekyll::PathManager.sanitized_path(@source, "//_config.yml") ) assert Jekyll::PathManager.sanitized_path(@source, "//_config.yml").frozen? end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_ansi.rb
test/test_ansi.rb
# frozen_string_literal: true require "helper" class TestAnsi < JekyllUnitTest context nil do setup do @subject = Jekyll::Utils::Ansi end Jekyll::Utils::Ansi::COLORS.each_key do |color| should "respond_to? #{color}" do assert_respond_to(@subject, color) end end should "be able to strip colors" do assert_equal "hello", @subject.strip(@subject.yellow(@subject.red("hello"))) end should "be able to detect colors" do assert @subject.has?(@subject.yellow("hello")) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_related_posts.rb
test/test_related_posts.rb
# frozen_string_literal: true require "helper" class TestRelatedPosts < JekyllUnitTest context "building related posts without lsi" do setup do @site = fixture_site end should "use the most recent posts for related posts" do @site.reset @site.read last_post = @site.posts.last related_posts = Jekyll::RelatedPosts.new(last_post).build last_ten_recent_posts = (@site.posts.docs.reverse - [last_post]).first(10) assert_equal last_ten_recent_posts, related_posts end end context "building related posts with LSI" do setup do if jruby? skip( "JRuby does not perform well with CExt, test disabled." ) end allow_any_instance_of(Jekyll::RelatedPosts).to receive(:display) @site = fixture_site( "lsi" => true ) @site.reset @site.read require "classifier-reborn" Jekyll::RelatedPosts.lsi = nil end should "index Jekyll::Post objects" do @site.posts.docs = @site.posts.docs.first(1) expect_any_instance_of(::ClassifierReborn::LSI).to \ receive(:add_item).with(kind_of(Jekyll::Document)) Jekyll::RelatedPosts.new(@site.posts.last).build_index end should "find related Jekyll::Post objects, given a Jekyll::Post object" do post = @site.posts.last allow_any_instance_of(::ClassifierReborn::LSI).to receive(:build_index) expect_any_instance_of(::ClassifierReborn::LSI).to \ receive(:find_related).with(post, 11).and_return(@site.posts[-1..-9]) Jekyll::RelatedPosts.new(post).build end should "use LSI for the related posts" do allow_any_instance_of(::ClassifierReborn::LSI).to \ receive(:find_related).and_return(@site.posts[-1..-9]) allow_any_instance_of(::ClassifierReborn::LSI).to receive(:build_index) assert_equal @site.posts[-1..-9], Jekyll::RelatedPosts.new(@site.posts.last).build end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_generated_site.rb
test/test_generated_site.rb
# frozen_string_literal: true require "helper" class TestGeneratedSite < JekyllUnitTest context "generated sites" do setup do clear_dest @site = fixture_site @site.process @index = File.read( dest_dir("index.html"), **Utils.merged_file_read_opts(@site, {}) ) end should "ensure post count is as expected" do assert_equal 59, @site.posts.size end should "insert site.posts into the index" do assert_includes @index, "#{@site.posts.size} Posts" end should "insert variable from layout into the index" do assert_includes @index, "variable from layout" end should "render latest post's content" do assert_includes @index, @site.posts.last.content end should "hide unpublished posts" do published = Dir[dest_dir("publish_test/2008/02/02/*.html")].map \ { |f| File.basename(f) } assert_equal 1, published.size assert_equal "published.html", published.first end should "hide unpublished page" do refute_exist dest_dir("/unpublished.html") end should "not copy _posts directory" do refute_exist dest_dir("_posts") end should "process a page with a folder permalink properly" do about = @site.pages.find { |page| page.name == "about.html" } assert_equal dest_dir("about", "index.html"), about.destination(dest_dir) assert_exist dest_dir("about", "index.html") end should "process other static files and generate correct permalinks" do assert_exist dest_dir("contacts.html") assert_exist dest_dir("dynamic_file.php") end should "include a post with a abbreviated dates" do refute_nil( @site.posts.index do |post| post.relative_path == "_posts/2017-2-5-i-dont-like-zeroes.md" end ) assert_exist dest_dir("2017", "02", "05", "i-dont-like-zeroes.html") end should "print a nice list of static files" do time_regexp = "\\d+:\\d+" # # adding a pipe character at the beginning preserves formatting with newlines expected_output = Regexp.new <<~OUTPUT | - /css/screen.css last edited at #{time_regexp} with extname .css - /pgp.key last edited at #{time_regexp} with extname .key - /products.yml last edited at #{time_regexp} with extname .yml - /symlink-test/symlinked-dir/screen.css last edited at #{time_regexp} with extname .css OUTPUT assert_match expected_output, File.read(dest_dir("static_files.html")) end end context "generating limited posts" do setup do clear_dest @site = fixture_site("limit_posts" => 5) @site.process @index = File.read(dest_dir("index.html")) end should "generate only the specified number of posts" do assert_equal 5, @site.posts.size end should "ensure limit posts is 0 or more" do assert_raises ArgumentError do clear_dest @site = fixture_site("limit_posts" => -1) end end should "acceptable limit post is 0" do clear_dest assert( fixture_site("limit_posts" => 0), "Couldn't create a site with limit_posts=0." ) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_theme_data_reader.rb
test/test_theme_data_reader.rb
# frozen_string_literal: true require "helper" class TestThemeDataReader < JekyllUnitTest context "site without a theme" do setup do @site = fixture_site("theme" => nil) @site.reader.read_data assert @site.data["greetings"] assert @site.data["categories"]["dairy"] end should "should read data from source" do assert_equal "Hello! I’m foo. And who are you?", @site.data["greetings"]["foo"] assert_equal "Dairy", @site.data["categories"]["dairy"]["name"] end end context "site with a theme without _data" do setup do @site = fixture_site("theme" => "test-theme-skinny") @site.reader.read_data assert @site.data["greetings"] assert @site.data["categories"]["dairy"] end should "should read data from source" do assert_equal "Hello! I’m foo. And who are you?", @site.data["greetings"]["foo"] assert_equal "Dairy", @site.data["categories"]["dairy"]["name"] end end context "site with a theme with empty _data directory" do setup do @site = fixture_site("theme" => "test-theme-w-empty-data") @site.reader.read_data assert @site.data["greetings"] assert @site.data["categories"]["dairy"] end should "should read data from source" do assert_equal "Hello! I’m foo. And who are you?", @site.data["greetings"]["foo"] assert_equal "Dairy", @site.data["categories"]["dairy"]["name"] end end context "site with a theme with data at root of _data" do setup do @site = fixture_site("theme" => "test-theme") @site.reader.read_data assert @site.data["greetings"] assert @site.data["categories"]["dairy"] assert @site.data["cars"] end should "should merge nested keys" do refute_equal "Hello! I’m bar. What’s up so far?", @site.data["greetings"]["foo"] assert_equal "Hello! I’m foo. And who are you?", @site.data["greetings"]["foo"] assert_equal "Mercedes", @site.data["cars"]["manufacturer"] end end context "site with a theme with data at root of _data and in a subdirectory" do setup do @site = fixture_site("theme" => "test-theme") @site.reader.read_data assert @site.data["greetings"] assert @site.data["categories"]["dairy"] assert @site.data["cars"] end should "should merge nested keys" do refute_equal "Cheese Dairy", @site.data["categories"]["dairy"]["name"] expected_names = %w(cheese milk) product_names = @site.data["categories"]["dairy"]["products"].map do |product| product["name"] end expected_names.each do |expected_name| assert_includes product_names, expected_name end assert_equal "Dairy", @site.data["categories"]["dairy"]["name"] end should "should illustrate the documented sample" do assert_equal "Kundenstimmen", @site.data["i18n"]["testimonials"]["header"] assert_equal "Design by FTC", @site.data["i18n"]["testimonials"]["footer"] end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_path_sanitization.rb
test/test_path_sanitization.rb
# frozen_string_literal: true require "helper" class TestPathSanitization < JekyllUnitTest context "on Windows with absolute source" do setup do @source = "C:/Users/xmr/Desktop/mpc-hc.org" @dest = "./_site/" allow(Dir).to receive(:pwd).and_return("C:/Users/xmr/Desktop/mpc-hc.org") end should "strip drive name from path" do assert_equal "C:/Users/xmr/Desktop/mpc-hc.org/_site", Jekyll.sanitized_path(@source, @dest) end should "strip just the initial drive name" do assert_equal "/tmp/foobar/jail/..c:/..c:/..c:/etc/passwd", Jekyll.sanitized_path("/tmp/foobar/jail", "..c:/..c:/..c:/etc/passwd") end end should "escape tilde" do assert_equal source_dir("~hi.txt"), Jekyll.sanitized_path(source_dir, "~hi.txt") assert_equal source_dir("files", "~hi.txt"), Jekyll.sanitized_path(source_dir, "files/../files/~hi.txt") end should "remove path traversals" do assert_equal source_dir("files", "hi.txt"), Jekyll.sanitized_path(source_dir, "f./../../../../../../files/hi.txt") end should "strip extra slashes in questionable path" do subdir = "/files/" file_path = "/hi.txt" assert_equal source_dir("files", "hi.txt"), Jekyll.sanitized_path(source_dir, "/#{subdir}/#{file_path}") end should "handle nil questionable_path" do assert_equal source_dir, Jekyll.sanitized_path(source_dir, nil) end if Jekyll::Utils::Platforms.really_windows? context "on Windows with absolute path" do setup do @base_path = "D:/demo" @file_path = "D:/demo/_site" allow(Dir).to receive(:pwd).and_return("D:/") end should "strip just the clean path drive name" do assert_equal "D:/demo/_site", Jekyll.sanitized_path(@base_path, @file_path) end end context "on Windows with file path has matching prefix" do setup do @base_path = "D:/site" @file_path = "D:/sitemap.xml" allow(Dir).to receive(:pwd).and_return("D:/") end should "not strip base path" do assert_equal "D:/site/sitemap.xml", Jekyll.sanitized_path(@base_path, @file_path) end end end should "not strip base path if file path has matching prefix" do assert_equal "/site/sitemap.xml", Jekyll.sanitized_path("/site", "sitemap.xml") end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_static_file.rb
test/test_static_file.rb
# frozen_string_literal: true require "helper" class TestStaticFile < JekyllUnitTest def make_dummy_file(filename) File.write(source_dir(filename), "some content") end def modify_dummy_file(filename) string = "some content" offset = string.size File.write(source_dir(filename), "more content", offset) end def remove_dummy_file(filename) File.delete(source_dir(filename)) end def setup_static_file(base, dir, name) Dir.chdir(@site.source) { StaticFile.new(@site, base, dir, name) } end def setup_static_file_with_collection(base, dir, name, metadata) site = fixture_site("collections" => { "foo" => metadata }) Dir.chdir(site.source) do StaticFile.new(site, base, dir, name, site.collections["foo"]) end end def setup_static_file_with_defaults(base, dir, name, defaults) site = fixture_site("defaults" => defaults) Dir.chdir(site.source) do StaticFile.new(site, base, dir, name) end end context "A StaticFile" do setup do clear_dest @site = fixture_site @filename = "static_file.txt" make_dummy_file(@filename) @static_file = setup_static_file(@site.source, "", @filename) end teardown do remove_dummy_file(@filename) if File.exist?(source_dir(@filename)) end should "return a simple string on inspection" do static_file = setup_static_file("root", "dir", @filename) assert_equal "#<Jekyll::StaticFile @relative_path=\"dir/#{@filename}\">", static_file.inspect end should "have a source file path" do static_file = setup_static_file("root", "dir", @filename) assert_equal "root/dir/#{@filename}", static_file.path end should "ignore a nil base or dir" do assert_equal "dir/#{@filename}", setup_static_file(nil, "dir", @filename).path assert_equal "base/#{@filename}", setup_static_file("base", nil, @filename).path end should "have a destination relative directory without a collection" do static_file = setup_static_file("root", "dir/subdir", "file.html") assert_nil static_file.type assert_equal "dir/subdir/file.html", static_file.url assert_equal "dir/subdir", static_file.destination_rel_dir end should "have a destination relative directory with a collection" do static_file = setup_static_file_with_collection( "root", "_foo/dir/subdir", "file.html", "output" => true ) assert_equal :foo, static_file.type assert_equal "/foo/dir/subdir/file.html", static_file.url assert_equal "/foo/dir/subdir", static_file.destination_rel_dir end should "use its collection's permalink template for destination relative directory" do static_file = setup_static_file_with_collection( "root", "_foo/dir/subdir", "file.html", "output" => true, "permalink" => "/:path/" ) assert_equal :foo, static_file.type assert_equal "/dir/subdir/file.html", static_file.url assert_equal "/dir/subdir", static_file.destination_rel_dir end should "be writable by default" do static_file = setup_static_file("root", "dir/subdir", "file.html") assert(static_file.write?, "static_file.write? should return true by default") end should "use the _config.yml defaults to determine writability" do defaults = [{ "scope" => { "path" => "private" }, "values" => { "published" => false }, }] static_file = setup_static_file_with_defaults( "root", "private/dir/subdir", "file.html", defaults ) refute(static_file.write?, "static_file.write? should return false when _config.yml sets " \ "`published: false`") end should "respect front matter defaults" do defaults = [{ "scope" => { "path" => "" }, "values" => { "front-matter" => "default" }, }] static_file = setup_static_file_with_defaults "", "", "file.pdf", defaults assert_equal "default", static_file.data["front-matter"] end should "include front matter defaults in to_liquid" do defaults = [{ "scope" => { "path" => "" }, "values" => { "front-matter" => "default" }, }] static_file = setup_static_file_with_defaults "", "", "file.pdf", defaults hash = static_file.to_liquid assert hash.key? "front-matter" assert_equal "default", hash["front-matter"] end should "know its last modification time" do assert_equal File.stat(@static_file.path).mtime.to_i, @static_file.mtime end should "only set modified time if not a symlink" do expect(File).to receive(:symlink?).and_return(true) expect(File).not_to receive(:utime) @static_file.write(dest_dir) allow(File).to receive(:symlink?).and_call_original end should "known if the source path is modified, when it is" do sleep 1 modify_dummy_file(@filename) assert @static_file.modified? end should "known if the source path is modified, when it's not" do @static_file.write(dest_dir) sleep 1 # wait, else the times are still the same refute @static_file.modified? end should "known whether to write the file to the filesystem" do assert @static_file.write?, "always true, with current implementation" end should "be able to write itself to the destination directory" do assert @static_file.write(dest_dir) end should "be able to convert to liquid" do expected = { "basename" => "static_file", "name" => "static_file.txt", "extname" => ".txt", "modified_time" => @static_file.modified_time, "path" => "/static_file.txt", "collection" => nil, } assert_equal expected, @static_file.to_liquid.to_h end should "jsonify its liquid drop instead of itself" do assert_equal @static_file.to_liquid.to_json, @static_file.to_json end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_tag_include_relative.rb
test/test_tag_include_relative.rb
# frozen_string_literal: true require "helper" class TestTagIncludeRelative < TagUnitTest context "include_relative tag with variable and liquid filters" do setup do site = fixture_site.tap do |s| s.read s.render end post = site.posts.docs.find do |p| p.basename.eql? "2014-09-02-relative-includes.markdown" end @content = post.output end should "include file as variable with liquid filters" do assert_match(%r!1 relative_include!, @content) assert_match(%r!2 relative_include!, @content) assert_match(%r!3 relative_include!, @content) end should "include file as variable and liquid filters with arbitrary whitespace" do assert_match(%r!4 relative_include!, @content) assert_match(%r!5 relative_include!, @content) assert_match(%r!6 relative_include!, @content) end should "include file as variable and filters with additional parameters" do assert_match("<li>var1 = foo</li>", @content) assert_match("<li>var2 = bar</li>", @content) end should "include file as partial variable" do assert_match(%r!8 relative_include!, @content) end should "include files relative to self" do assert_match(%r!9 —\ntitle: Test Post Where YAML!, @content) end context "trying to do bad stuff" do context "include missing file" do setup do @content = <<~CONTENT --- title: missing file --- {% include_relative missing.html %} CONTENT end should "raise error relative to source directory" do exception = assert_raises(IOError) { render_content(@content) } assert_match "Could not locate the included file 'missing.html' in any of " \ "[\"#{source_dir}\"].", exception.message end end context "include existing file above you" do setup do @content = <<~CONTENT --- title: higher file --- {% include_relative ../README.markdown %} CONTENT end should "raise error relative to source directory" do exception = assert_raises(ArgumentError) { render_content(@content) } assert_equal( "Invalid syntax for include tag. File contains invalid characters or " \ "sequences:\n\n ../README.markdown\n\nValid syntax:\n\n " \ "{% include_relative file.ext param='value' param2='value' %}\n\n", exception.message ) end end end context "with symlink'd include" do should "not allow symlink includes" do FileUtils.mkdir_p("tmp") File.write("tmp/pages-test", "SYMLINK TEST") assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include_relative tmp/pages-test %} CONTENT render_content(content, "safe" => true) end @result ||= "" refute_match(%r!SYMLINK TEST!, @result) end should "not expose the existence of symlinked files" do exception = assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include_relative tmp/pages-test-does-not-exist %} CONTENT render_content(content, "safe" => true) end assert_match( "Ensure it exists in one of those directories and is not a symlink " \ "as those are not allowed in safe mode.", exception.message ) end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_tag_highlight.rb
test/test_tag_highlight.rb
# frozen_string_literal: true require "helper" class TestTagHighlight < TagUnitTest def render_content_with_text_to_highlight(code) content = <<~CONTENT --- title: This is a test --- This document has some highlighted code in it. {% highlight text %} #{code} {% endhighlight %} {% highlight text linenos %} #{code} {% endhighlight %} CONTENT render_content(content) end # Syntax sugar for low-level version of: # ``` # {% highlight markup%}test{% endhighlight %} # ``` def highlight_block_with_markup(markup) Jekyll::Tags::HighlightBlock.parse( "highlight", markup, Liquid::Tokenizer.new("test{% endhighlight %}\n"), Liquid::ParseContext.new ) end context "language name" do should "match only the required set of chars" do r = Jekyll::Tags::HighlightBlock::SYNTAX [ "ruby", "c#", "xml+cheetah", "x.y", "coffee-script", "shell_session", "ruby key=val", "ruby a=b c=d", ].each { |sample| assert_match(r, sample) } refute_match r, "blah^" end end context "highlight tag in unsafe mode" do should "set the no options with just a language name" do tag = highlight_block_with_markup("ruby ") assert_equal({}, tag.instance_variable_get(:@highlight_options)) end should "set the linenos option as 'inline' if no linenos value" do tag = highlight_block_with_markup("ruby linenos ") assert_equal( { :linenos => "inline" }, tag.instance_variable_get(:@highlight_options) ) end should "set the linenos option to 'table' " \ "if the linenos key is given the table value" do tag = highlight_block_with_markup("ruby linenos=table ") assert_equal( { :linenos => "table" }, tag.instance_variable_get(:@highlight_options) ) end should "recognize nowrap option with linenos set" do tag = highlight_block_with_markup("ruby linenos=table nowrap ") assert_equal( { :linenos => "table", :nowrap => true }, tag.instance_variable_get(:@highlight_options) ) end should "recognize the cssclass option" do tag = highlight_block_with_markup("ruby linenos=table cssclass=hl ") assert_equal( { :cssclass => "hl", :linenos => "table" }, tag.instance_variable_get(:@highlight_options) ) end should "recognize the hl_linenos option and its value" do tag = highlight_block_with_markup("ruby linenos=table cssclass=hl hl_linenos=3 ") assert_equal( { :cssclass => "hl", :linenos => "table", :hl_linenos => "3" }, tag.instance_variable_get(:@highlight_options) ) end should "recognize multiple values of hl_linenos" do tag = highlight_block_with_markup 'ruby linenos=table cssclass=hl hl_linenos="3 5 6" ' assert_equal( { :cssclass => "hl", :linenos => "table", :hl_linenos => %w(3 5 6) }, tag.instance_variable_get(:@highlight_options) ) end should "treat language name as case insensitive" do tag = highlight_block_with_markup("Ruby ") assert_equal "ruby", tag.instance_variable_get(:@lang), "lexers should be case insensitive" end end context "with the rouge highlighter" do context "post content has highlight tag" do setup do render_content_with_text_to_highlight "test" end should "render markdown with rouge" do assert_match( %(<pre><code class="language-text" data-lang="text">test</code></pre>), @result ) end should "render markdown with rouge with line numbers" do assert_match( %(<table class="rouge-table"><tbody>) + %(<tr><td class="gutter gl">) + %(<pre class="lineno">1\n</pre></td>) + %(<td class="code"><pre>test\n</pre></td></tr>) + %(</tbody></table>), @result ) end end context "post content has highlight with file reference" do setup do render_content_with_text_to_highlight "./jekyll.gemspec" end should "not embed the file" do assert_match( '<pre><code class="language-text" data-lang="text">' \ "./jekyll.gemspec</code></pre>", @result ) end end context "post content has highlight tag with UTF character" do setup do render_content_with_text_to_highlight "Æ" end should "render markdown with pygments line handling" do assert_match( '<pre><code class="language-text" data-lang="text">Æ</code></pre>', @result ) end end context "post content has highlight tag with preceding spaces & lines" do setup do render_content_with_text_to_highlight <<~EOS [,1] [,2] [1,] FALSE TRUE [2,] FALSE TRUE EOS end should "only strip the preceding newlines" do assert_match( '<pre><code class="language-text" data-lang="text"> [,1] [,2]', @result ) end end context "post content has highlight tag with preceding spaces & lines in several places" do setup do render_content_with_text_to_highlight <<~EOS [,1] [,2] [1,] FALSE TRUE [2,] FALSE TRUE EOS end should "only strip the newlines which precede and succeed the entire block" do assert_match( "<pre><code class=\"language-text\" data-lang=\"text\"> [,1] [,2]\n\n\n" \ "[1,] FALSE TRUE\n[2,] FALSE TRUE</code></pre>", @result ) end end context "post content has highlight tag with linenumbers" do setup do render_content <<~EOS --- title: This is a test --- This is not yet highlighted {% highlight php linenos %} test {% endhighlight %} This should not be highlighted, right? EOS end should "should stop highlighting at boundary with rouge" do expected = <<~EOS <p>This is not yet highlighted</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1 </pre></td><td class="code"><pre><span class="n">test</span> </pre></td></tr></tbody></table></code></pre></figure> <p>This should not be highlighted, right?</p> EOS assert_match(expected, @result) end end context "post content has highlight tag with " \ "preceding spaces & Windows-style newlines" do setup do render_content_with_text_to_highlight "\r\n\r\n\r\n [,1] [,2]" end should "only strip the preceding newlines" do assert_match( '<pre><code class="language-text" data-lang="text"> [,1] [,2]', @result ) end end context "post content has highlight tag with only preceding spaces" do setup do render_content_with_text_to_highlight <<~EOS [,1] [,2] [1,] FALSE TRUE [2,] FALSE TRUE EOS end should "only strip the preceding newlines" do assert_match( '<pre><code class="language-text" data-lang="text"> [,1] [,2]', @result ) end end end context "simple post with markdown and pre tags" do setup do @content = <<~CONTENT --- title: Kramdown post with pre --- _FIGHT!_ {% highlight ruby %} puts "3..2..1.." {% endhighlight %} *FINISH HIM* CONTENT end context "using Kramdown" do setup do render_content(@content, "markdown" => "kramdown") end should "parse correctly" do assert_match %r{<em>FIGHT!</em>}, @result assert_match %r!<em>FINISH HIM</em>!, @result end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_coffeescript.rb
test/test_coffeescript.rb
# frozen_string_literal: true require "helper" class TestCoffeeScript < JekyllUnitTest context "converting CoffeeScript" do setup do External.require_with_graceful_fail("jekyll-coffeescript") @site = fixture_site @site.process @test_coffeescript_file = dest_dir("js/coffeescript.js") @js_output = <<~JS (function() { $(function() { var cube, cubes, list, num, square; list = [1, 2, 3, 4, 5]; square = function(x) { return x * x; }; cube = function(x) { return square(x) * x; }; cubes = (function() { var i, len, results; results = []; for (i = 0, len = list.length; i < len; i++) { num = list[i]; results.push(math.cube(num)); } return results; })(); if (typeof elvis !== "undefined" && elvis !== null) { return alert("I knew it!"); } }); }).call(this); JS end should "write a JS file in place" do assert_exist @test_coffeescript_file end should "produce JS" do assert_equal @js_output, File.read(@test_coffeescript_file) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_theme_drop.rb
test/test_theme_drop.rb
# frozen_string_literal: true require "helper" class TestThemeDrop < JekyllUnitTest should "be initialized only for gem-based themes" do assert_nil fixture_site.to_liquid.theme end context "a theme drop" do setup do @drop = fixture_site("theme" => "test-theme").to_liquid.theme end should "respond to `key?`" do assert_respond_to @drop, :key? end should "export relevant data to Liquid templates" do expected = { "authors" => "Jekyll", "dependencies" => [], "description" => "This is a theme used to test Jekyll", "metadata" => {}, "root" => "", "version" => "0.1.0", } expected.each_key do |key| assert @drop.key?(key) assert_equal expected[key], @drop[key] end end should "render gem root only in development mode" do with_env("JEKYLL_ENV", nil) do drop = fixture_site("theme" => "test-theme").to_liquid.theme assert_equal "", drop["root"] end with_env("JEKYLL_ENV", "development") do drop = fixture_site("theme" => "test-theme").to_liquid.theme assert_equal theme_dir, drop["root"] end with_env("JEKYLL_ENV", "production") do drop = fixture_site("theme" => "test-theme").to_liquid.theme assert_equal "", drop["root"] end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_document.rb
test/test_document.rb
# frozen_string_literal: true require "helper" class TestDocument < JekyllUnitTest def assert_equal_value(key, one, other) assert_equal(one[key], other[key]) end def setup_encoded_document(filename) site = fixture_site("collections" => ["encodings"]) site.process Document.new(site.in_source_dir(File.join("_encodings", filename)), :site => site, :collection => site.collections["encodings"]).tap(&:read) end def setup_document_with_dates(filename) site = fixture_site("collections" => ["dates"]) site.process docs = nil with_env("TZ", "UTC") do docs = Document.new(site.in_source_dir(File.join("_dates", filename)), :site => site, :collection => site.collections["dates"]).tap(&:read) end docs end context "a document in a collection" do setup do @site = fixture_site( "collections" => ["methods"] ) @site.process @document = @site.collections["methods"].docs.detect do |d| d.relative_path == "_methods/configuration.md" end end should "exist" do refute_nil @document end should "know its relative path" do assert_equal "_methods/configuration.md", @document.relative_path end should "knows its extname" do assert_equal ".md", @document.extname end should "know its basename" do assert_equal "configuration.md", @document.basename end should "know its basename without extname" do assert_equal "configuration", @document.basename_without_ext end should "know its type" do assert_equal :methods, @document.type end should "know whether it's a YAML file" do refute @document.yaml_file? end should "know its data" do assert_equal "Jekyll.configuration", @document.data["title"] assert_equal "foo.bar", @document.data["whatever"] end should "know its date" do assert_nil @document.data["date"] assert_equal Time.now.strftime("%Y/%m/%d"), @document.date.strftime("%Y/%m/%d") assert_equal Time.now.strftime("%Y/%m/%d"), @document.to_liquid["date"].strftime("%Y/%m/%d") end should "be jsonify-able" do page_json = @document.to_liquid.to_json parsed = JSON.parse(page_json) assert_equal "Jekyll.configuration", parsed["title"] assert_equal "foo.bar", parsed["whatever"] assert_equal "_methods/collection/entries", parsed["previous"]["path"] assert_equal "Collection#entries", parsed["previous"]["title"] next_doc = parsed["next"] assert_equal "_methods/escape-+ #%20[].md", next_doc["path"] assert_equal "Jekyll.escape", next_doc["title"] next_prev_doc = next_doc["previous"] assert_equal "Jekyll.configuration", next_prev_doc["title"] assert_equal "_methods/configuration.md", next_prev_doc["path"] assert_equal "_methods/escape-+ #%20[].md", next_prev_doc["next"]["path"] assert_equal "_methods/collection/entries", next_prev_doc["previous"]["path"] assert_nil next_prev_doc["next"]["next"] assert_nil next_prev_doc["next"]["previous"] assert_nil next_prev_doc["next"]["content"] assert_nil next_prev_doc["next"]["excerpt"] assert_nil next_prev_doc["next"]["output"] next_next_doc = next_doc["next"] assert_equal "Jekyll.sanitized_path", next_next_doc["title"] assert_equal "_methods/sanitized_path.md", next_next_doc["path"] assert_equal "_methods/escape-+ #%20[].md", next_next_doc["previous"]["path"] assert_equal "_methods/site/generate.md", next_next_doc["next"]["path"] assert_nil next_next_doc["next"]["next"] assert_nil next_next_doc["next"]["previous"] assert_nil next_next_doc["next"]["content"] assert_nil next_next_doc["next"]["excerpt"] assert_nil next_next_doc["next"]["output"] assert_nil next_next_doc["previous"]["next"] assert_nil next_next_doc["previous"]["previous"] assert_nil next_next_doc["previous"]["content"] assert_nil next_next_doc["previous"]["excerpt"] assert_nil next_next_doc["previous"]["output"] end context "with the basename (without extension) ending with dot(s)" do setup do @site = fixture_site("collections" => ["methods"]) @site.process @document = @site.collections["methods"].docs.detect do |d| d.relative_path == "_methods/trailing-dots...md" end end should "render into the proper url" do assert_equal "/methods/trailing-dots.html", @document.url trailing_dots_doc = @site.posts.docs.detect do |d| d.relative_path == "_posts/2018-10-12-trailing-dots...markdown" end assert_equal "/2018/10/12/trailing-dots.html", trailing_dots_doc.url end end context "with YAML ending in three dots" do setup do @site = fixture_site("collections" => ["methods"]) @site.process @document = @site.collections["methods"].docs.detect do |d| d.relative_path == "_methods/yaml_with_dots.md" end end should "know its data" do assert_equal "YAML with Dots", @document.data["title"] assert_equal "foo.bar", @document.data["whatever"] end end should "output the collection name in the #to_liquid method" do assert_equal "methods", @document.to_liquid["collection"] end should "output its relative path as path in Liquid" do assert_equal "_methods/configuration.md", @document.to_liquid["path"] end context "when rendered with Liquid" do should "respect the front matter definition" do site = fixture_site("collections" => ["roles"]).tap(&:process) docs = site.collections["roles"].docs # Ruby context: doc.basename is aliased as doc.to_liquid["name"] by default. document = docs.detect { |d| d.relative_path == "_roles/unnamed.md" } assert_equal "unnamed.md", document.basename assert_equal "unnamed.md", document.to_liquid["name"] document = docs.detect { |d| d.relative_path == "_roles/named.md" } assert_equal "named.md", document.basename assert_equal "launcher", document.to_liquid["name"] end end end context "a document as part of a collection with front matter defaults" do setup do @site = fixture_site( "collections" => ["slides"], "defaults" => [{ "scope" => { "path" => "", "type" => "slides" }, "values" => { "nested" => { "key" => "myval", }, }, }] ) @site.process @document = @site.collections["slides"].docs.find { |d| d.is_a?(Document) } end should "know the front matter defaults" do assert_equal "Example slide", @document.data["title"] assert_equal "slide", @document.data["layout"] assert_equal({ "key"=>"myval" }, @document.data["nested"]) end should "return front matter defaults via to_liquid" do hash = @document.to_liquid assert hash.key? "nested" assert_equal({ "key"=>"myval" }, hash["nested"]) end end context "a document as part of a collection with overridden default values" do setup do @site = fixture_site( "collections" => ["slides"], "defaults" => [{ "scope" => { "path" => "", "type" => "slides" }, "values" => { "nested" => { "test1" => "default1", "test2" => "default1", }, }, }] ) @site.process @document = @site.collections["slides"].docs[1] end should "override default values in the document front matter" do assert_equal "Override title", @document.data["title"] assert_equal "slide", @document.data["layout"] assert_equal( { "test1" => "override1", "test2" => "override2" }, @document.data["nested"] ) end end context "a document as part of a collection with valid path" do setup do @site = fixture_site( "collections" => ["slides"], "defaults" => [{ "scope" => { "path" => "_slides", "type" => "slides" }, "values" => { "nested" => { "key" => "value123", }, }, }] ) @site.process @document = @site.collections["slides"].docs.first end should "know the front matter defaults" do assert_equal "Example slide", @document.data["title"] assert_equal "slide", @document.data["layout"] assert_equal({ "key"=>"value123" }, @document.data["nested"]) end end context "a document as part of a collection with invalid path" do setup do @site = fixture_site( "collections" => ["slides"], "defaults" => [{ "scope" => { "path" => "somepath", "type" => "slides" }, "values" => { "nested" => { "key" => "myval", }, }, }] ) @site.process @document = @site.collections["slides"].docs.first end should "not know the specified front matter defaults" do assert_equal "Example slide", @document.data["title"] assert_equal "slide", @document.data["layout"] assert_nil @document.data["nested"] end end context "a document in a collection with a custom permalink" do setup do @site = fixture_site( "collections" => ["slides"] ) @site.process @document = @site.collections["slides"].docs[2] @dest_file = dest_dir("slide/3/index.html") end should "know its permalink" do assert_equal "/slide/3/", @document.permalink end should "produce the right URL" do assert_equal "/slide/3/", @document.url end end context "a document in a collection with custom filename permalinks" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, "permalink" => "/slides/test/:name", }, }, "permalink" => "pretty" ) @site.process @document = @site.collections["slides"].docs[0] @dest_file = dest_dir("slides/test/example-slide-1.html") end should "produce the right URL" do assert_equal "/slides/test/example-slide-1", @document.url end should "produce the right destination file" do assert_equal @dest_file, @document.destination(dest_dir) end should "honor the output extension of its permalink" do assert_equal ".html", @document.output_ext end end context "a document in a collection with pretty permalink style" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, }, } ) @site.permalink_style = :pretty @site.process @document = @site.collections["slides"].docs[0] @dest_file = dest_dir("slides/example-slide-1/index.html") end should "produce the right URL" do assert_equal "/slides/example-slide-1/", @document.url end should "produce the right destination file" do assert_equal @dest_file, @document.destination(dest_dir) end end context "a document in a collection with cased file name" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, }, } ) @site.permalink_style = :pretty @site.process @document = @site.collections["slides"].docs[7] @dest_file = dest_dir("slides/example-slide-Upper-Cased/index.html") end should "produce the right cased URL" do assert_equal "/slides/example-slide-Upper-Cased/", @document.url end end context "a document in a collection with cased file name" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, }, } ) @site.process @document = @site.collections["slides"].docs[6] @dest_file = dest_dir("slides/example-slide-7.php") end should "be written out properly" do assert_exist @dest_file end should "produce the permalink as the url" do assert_equal "/slides/example-slide-7.php", @document.url end should "be written to the proper directory" do assert_equal @dest_file, @document.destination(dest_dir) end should "honor the output extension of its permalink" do assert_equal ".php", @document.output_ext end end context "documents in a collection with custom title permalinks" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, "permalink" => "/slides/:title", }, } ) @site.process @document = @site.collections["slides"].docs[3] @document_without_slug = @site.collections["slides"].docs[4] @document_with_strange_slug = @site.collections["slides"].docs[5] end should "produce the right URL if they have a slug" do assert_equal "/slides/so-what-is-jekyll-exactly", @document.url end should "produce the right destination file if they have a slug" do dest_file = dest_dir("slides/so-what-is-jekyll-exactly.html") assert_equal dest_file, @document.destination(dest_dir) end should "produce the right URL if they don't have a slug" do assert_equal "/slides/example-slide-5", @document_without_slug.url end should "produce the right destination file if they don't have a slug" do dest_file = dest_dir("slides/example-slide-5.html") assert_equal dest_file, @document_without_slug.destination(dest_dir) end should "produce the right URL if they have a wild slug" do assert_equal( "/slides/Well,-so-what-is-Jekyll,-then", @document_with_strange_slug.url ) end should "produce the right destination file if they have a wild slug" do dest_file = dest_dir("/slides/Well,-so-what-is-Jekyll,-then.html") assert_equal dest_file, @document_with_strange_slug.destination(dest_dir) end end context "document with a permalink with dots & a trailing slash" do setup do @site = fixture_site("collections" => { "with.dots" => { "output" => true }, }) @site.process @document = @site.collections["with.dots"].docs.last @dest_file = dest_dir("with.dots", "permalink.with.slash.tho", "index.html") end should "yield an HTML document" do assert_equal @dest_file, @document.destination(dest_dir) end should "be written properly" do assert_exist @dest_file end should "get the right output_ext" do assert_equal ".html", @document.output_ext end end context "documents in a collection" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, }, } ) @site.process @files = @site.collections["slides"].docs end context "without output overrides" do should "be output according to collection defaults" do refute_nil @files.find do |doc| doc.relative_path == "_slides/example-slide-4.html" end assert_exist dest_dir("slides/example-slide-4.html") end end context "with output overrides" do should "be output according its front matter" do assert @files.find do |doc| doc.relative_path == "_slides/non-outputted-slide.html" end refute_exist dest_dir("slides/non-outputted-slide.html") end end end context "a static file in a collection" do setup do @site = fixture_site( "collections" => { "slides" => { "output" => true, }, } ) @site.process @document = @site.collections["slides"].files.find do |doc| doc.relative_path == "_slides/octojekyll.png" end @dest_file = dest_dir("slides/octojekyll.png") end should "be a static file" do assert_kind_of StaticFile, @document end should "be set to write" do assert @document.write? end should "be in the list of docs_to_write" do assert_includes @site.docs_to_write, @document end should "be output in the correct place" do assert File.file?(@dest_file) end end context "a document in a collection with non-alphabetic file name" do setup do @site = fixture_site( "collections" => { "methods" => { "output" => true, }, } ) @site.process @document = @site.collections["methods"].docs.find do |doc| doc.relative_path == "_methods/escape-+ #%20[].md" end @dest_file = dest_dir("methods/escape-+ #%20[].html") end should "produce the right URL" do assert_equal "/methods/escape-+%20%23%2520%5B%5D.html", @document.url end should "produce the right destination" do assert_equal @dest_file, @document.destination(dest_dir) end should "be output in the correct place" do assert File.file?(@dest_file) end end context "a document in a collection with dash-separated numeric file name" do setup do @site = fixture_site( "collections" => { "methods" => { "output" => true, }, } ) @site.process @document = @site.collections["methods"].docs.find do |doc| doc.relative_path == "_methods/3940394-21-9393050-fifif1323-test.md" end @dest_file = dest_dir("methods/3940394-21-9393050-fifif1323-test.html") end should "produce the right URL" do assert_equal "/methods/3940394-21-9393050-fifif1323-test.html", @document.url end should "produce the right destination" do assert_equal @dest_file, @document.destination(dest_dir) end should "be output in the correct place" do assert File.file?(@dest_file) end end context "a document with UTF-8 CLRF" do setup do @document = setup_encoded_document "UTF8CRLFandBOM.md" end should "not throw an error" do Jekyll::Renderer.new(@document.site, @document).render_document end end context "a document with UTF-16LE CLRF" do setup do @document = setup_encoded_document "Unicode16LECRLFandBOM.md" end should "not throw an error" do Jekyll::Renderer.new(@document.site, @document).render_document end end context "a document with a date with timezone" do setup do @document = setup_document_with_dates "time_with_timezone.md" end should "have the expected date" do assert_equal "2015/09/30", @document.data["date"].strftime("%Y/%m/%d") end should "return the expected date via Liquid" do assert_equal "2015/09/30", @document.to_liquid["date"].strftime("%Y/%m/%d") end end context "a document with a date with time but without timezone" do setup do @document = setup_document_with_dates "time_without_timezone.md" end should "have the expected date" do assert_equal "2015/10/01", @document.data["date"].strftime("%Y/%m/%d") end should "return the expected date via Liquid" do assert_equal "2015/10/01", @document.to_liquid["date"].strftime("%Y/%m/%d") end end context "a document with a date without time" do setup do @document = setup_document_with_dates "date_without_time.md" end should "have the expected date" do assert_equal "2015/10/01", @document.data["date"].strftime("%Y/%m/%d") end should "return the expected date via Liquid" do assert_equal "2015/10/01", @document.to_liquid["date"].strftime("%Y/%m/%d") end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_page_without_a_file.rb
test/test_page_without_a_file.rb
# frozen_string_literal: true require "helper" class TestPageWithoutAFile < JekyllUnitTest def setup_page(*args, base: source_dir, klass: PageWithoutAFile) dir, file = args if file.nil? file = dir dir = "" end klass.new(@site, base, dir, file) end def render_and_write @site.render @site.cleanup @site.write end context "A PageWithoutAFile" do setup do clear_dest @site = Site.new(Jekyll.configuration( "source" => source_dir, "destination" => dest_dir, "skip_config_files" => true )) end should "have non-frozen path and relative_path attributes" do { ["foo", "bar.md"] => "foo/bar.md", [nil, nil] => "", ["", ""] => "", ["/lorem/", "/ipsum"] => "lorem/ipsum", %w(lorem ipsum) => "lorem/ipsum", }.each do |(dir, name), result| page = PageWithoutAFile.new(@site, @site.source, dir, name) assert_equal result, page.path assert_equal result, page.relative_path refute page.relative_path.frozen? end end context "with default site configuration" do setup do @page = setup_page("properties.html") end should "identify itself properly" do assert_equal '#<Jekyll::PageWithoutAFile @relative_path="properties.html">', @page.inspect end should "not have page-content and page-data defined within it" do assert_equal "pages", @page.type.to_s assert_nil @page.content assert_empty @page.data end should "have basic attributes defined in it" do regular_page = setup_page("properties.html", :klass => Page) # assert a couple of attributes accessible in a regular Jekyll::Page instance assert_equal "All the properties.\n", regular_page["content"] assert_equal "properties.html", regular_page["name"] basic_attrs = %w(dir name path url excerpt) attrs = { "content" => nil, "dir" => "/", "excerpt" => nil, "foo" => "bar", "layout" => "default", "name" => "properties.html", "path" => "properties.html", "permalink" => "/properties/", "published" => nil, "title" => "Properties Page", "url" => "/properties.html", } attrs.each do |prop, value| # assert that all attributes (of a Jekyll::PageWithoutAFile instance) other than # "dir", "name", "path", "url" are `nil`. # For example, @page[dir] should be "/" but @page[content] or @page[layout], should # simply be nil. # if basic_attrs.include?(prop) assert_equal value, @page[prop], "For Jekyll::PageWithoutAFile attribute '#{prop}':" else assert_nil @page[prop] end end end end context "with site-wide permalink configuration" do setup do @site.permalink_style = :title end should "generate page url accordingly" do page = setup_page("properties.html") assert_equal "/properties", page.url end end context "with default front matter configuration" do setup do @site.config["defaults"] = [ { "scope" => { "path" => "", "type" => "pages", }, "values" => { "layout" => "default", "author" => "John Doe", }, }, ] @page = setup_page("info.md") end should "respect front matter defaults" do assert_nil @page.data["title"] assert_equal "John Doe", @page.data["author"] assert_equal "default", @page.data["layout"] end end context "with a path outside site.source" do should "not access its contents" do base = "../../../" page = setup_page("pwd", :base => base) assert_equal "pwd", page.path assert_nil page.content end end context "while processing" do setup do clear_dest @site.config["title"] = "Test Site" @page = setup_page("physical.html", :base => test_dir("fixtures")) end should "receive content provided to it" do assert_nil @page.content @page.content = "{{ site.title }}" assert_equal "{{ site.title }}", @page.content end should "not be processed and written to disk at destination" do @page.content = "Lorem ipsum dolor sit amet" @page.data["permalink"] = "/virtual-about/" render_and_write refute_exist dest_dir("physical") refute_exist dest_dir("virtual-about") refute_path_exists(dest_dir("virtual-about", "index.html")) end should "be processed and written to destination when passed as an entry in " \ "'site.pages' array" do @page.content = "{{ site.title }}" @page.data["permalink"] = "/virtual-about/" @site.pages << @page render_and_write refute_exist dest_dir("physical") assert_exist dest_dir("virtual-about") assert_path_exists(dest_dir("virtual-about", "index.html")) assert_equal "Test Site", File.read(dest_dir("virtual-about", "index.html")) end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_liquid_extensions.rb
test/test_liquid_extensions.rb
# frozen_string_literal: true require "helper" class TestLiquidExtensions < JekyllUnitTest context "looking up a variable in a Liquid context" do class SayHi < Liquid::Tag include Jekyll::LiquidExtensions def initialize(_tag_name, markup, _tokens) @markup = markup.strip end def render(context) "hi #{lookup_variable(context, @markup)}" end end Liquid::Template.register_tag("say_hi", SayHi) setup do # Parses and compiles the template @template = Liquid::Template.parse("{% say_hi page.name %}") end should "extract the var properly" do assert_equal "hi tobi", @template.render("page" => { "name" => "tobi" }) end should "return the variable name if the value isn't there" do assert_equal "hi page.name", @template.render("page" => { "title" => "tobi" }) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_post_reader.rb
test/test_post_reader.rb
# frozen_string_literal: true require "helper" class TestPostReader < JekyllUnitTest context "#read_publishable" do setup do @site = Site.new(site_configuration) @post_reader = PostReader.new(@site) @dir = "" @magic_dir = "_posts" @matcher = Document::DATE_FILENAME_MATCHER end should "skip unprocessable documents" do all_file_names = all_documents.collect(&:basename) processed_file_names = processed_documents.collect(&:basename) actual_skipped_file_names = all_file_names - processed_file_names expected_skipped_file_names = [ "2008-02-02-not-published.markdown", "2008-02-03-wrong-extension.yml", ] skipped_file_names_difference = expected_skipped_file_names - actual_skipped_file_names assert expected_skipped_file_names.count.positive?, "There should be at least one document expected to be skipped" assert_empty skipped_file_names_difference, "The skipped documents (expected/actual) should be congruent (= empty array)" end end def all_documents @post_reader.read_content(@dir, @magic_dir, @matcher) end def processed_documents @post_reader.read_publishable(@dir, @magic_dir, @matcher) end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_filters.rb
test/test_filters.rb
# frozen_string_literal: true require "helper" class TestFilters < JekyllUnitTest class JekyllFilter include Jekyll::Filters attr_accessor :site, :context def initialize(opts = {}) @site = Jekyll::Site.new(opts.merge("skip_config_files" => true)) @context = Liquid::Context.new(@site.site_payload, {}, :site => @site) end end class Value def initialize(value) @value = value end def to_s @value.respond_to?(:call) ? @value.call : @value.to_s end end def make_filter_mock(opts = {}) JekyllFilter.new(site_configuration(opts)).tap do |f| tz = f.site.config["timezone"] Jekyll.set_timezone(tz) if tz end end class SelectDummy def select; end end class KeyValue def initialize(key:, value:) @key = key @val = value end def inspect "{#{@key.inspect}=>#{@val.inspect}}" end end context "filters" do setup do @sample_time = Time.utc(2013, 3, 27, 11, 22, 33) @timezone_before_test = ENV["TZ"] @filter = make_filter_mock( "timezone" => "UTC", "url" => "http://example.com", "baseurl" => "/base", "dont_show_posts_before" => @sample_time ) @sample_date = Date.parse("2013-03-02") @time_as_string = "September 11, 2001 12:46:30 -0000" @time_as_numeric = 1_399_680_607 @integer_as_string = "142857" @array_of_objects = [ { "color" => "teal", "size" => "large" }, { "color" => "red", "size" => "large" }, { "color" => "red", "size" => "medium" }, { "color" => "blue", "size" => "medium" }, ] end teardown do ENV["TZ"] = @timezone_before_test end should "markdownify with simple string" do assert_equal( "<p>something <strong>really</strong> simple</p>\n", @filter.markdownify("something **really** simple") ) end should "markdownify with a number" do assert_equal( "<p>404</p>\n", @filter.markdownify(404) ) end context "smartify filter" do should "convert quotes and typographic characters" do assert_equal( "SmartyPants is *not* Markdown", @filter.smartify("SmartyPants is *not* Markdown") ) assert_equal( "“This filter’s test…”", @filter.smartify(%q{"This filter's test..."}) ) end should "convert not convert markdown to block HTML elements" do assert_equal( "#hashtag", # NOT "<h1>hashtag</h1>" @filter.smartify("#hashtag") ) end should "escapes special characters when configured to do so" do kramdown = make_filter_mock(:kramdown => { :entity_output => :symbolic }) assert_equal( "&ldquo;This filter&rsquo;s test&hellip;&rdquo;", kramdown.smartify(%q{"This filter's test..."}) ) end should "convert HTML entities to unicode characters" do assert_equal "’", @filter.smartify("&rsquo;") assert_equal "“", @filter.smartify("&ldquo;") end should "convert multiple lines" do assert_equal "…\n…", @filter.smartify("...\n...") end should "allow raw HTML passthrough" do assert_equal( "Span HTML is <em>not</em> escaped", @filter.smartify("Span HTML is <em>not</em> escaped") ) assert_equal( "<div>Block HTML is not escaped</div>", @filter.smartify("<div>Block HTML is not escaped</div>") ) end should "escape special characters" do assert_equal "3 &lt; 4", @filter.smartify("3 < 4") assert_equal "5 &gt; 4", @filter.smartify("5 > 4") assert_equal "This &amp; that", @filter.smartify("This & that") end should "convert a number to a string" do assert_equal( "404", @filter.smartify(404) ) end should "not output any warnings" do assert_empty( capture_output { @filter.smartify("Test") } ) end end should "sassify with simple string" do assert_equal( "p {\n color: #123456;\n}", @filter.sassify(<<~SASS) $blue: #123456 p color: $blue SASS ) end should "scssify with simple string" do assert_equal( "p {\n color: #123456;\n}", @filter.scssify("$blue:#123456; p{color: $blue}") ) end should "convert array to sentence string with no args" do assert_equal "", @filter.array_to_sentence_string([]) end should "convert array to sentence string with one arg" do assert_equal "1", @filter.array_to_sentence_string([1]) assert_equal "chunky", @filter.array_to_sentence_string(["chunky"]) end should "convert array to sentence string with two args" do assert_equal "1 and 2", @filter.array_to_sentence_string([1, 2]) assert_equal "chunky and bacon", @filter.array_to_sentence_string(%w(chunky bacon)) end should "convert array to sentence string with multiple args" do assert_equal "1, 2, 3, and 4", @filter.array_to_sentence_string([1, 2, 3, 4]) assert_equal( "chunky, bacon, bits, and pieces", @filter.array_to_sentence_string(%w(chunky bacon bits pieces)) ) end should "convert array to sentence string with different connector" do assert_equal "1 or 2", @filter.array_to_sentence_string([1, 2], "or") assert_equal "1, 2, 3, or 4", @filter.array_to_sentence_string([1, 2, 3, 4], "or") end context "normalize_whitespace filter" do should "replace newlines with a space" do assert_equal "a b", @filter.normalize_whitespace("a\nb") assert_equal "a b", @filter.normalize_whitespace("a\n\nb") end should "replace tabs with a space" do assert_equal "a b", @filter.normalize_whitespace("a\tb") assert_equal "a b", @filter.normalize_whitespace("a\t\tb") end should "replace multiple spaces with a single space" do assert_equal "a b", @filter.normalize_whitespace("a b") assert_equal "a b", @filter.normalize_whitespace("a\t\nb") assert_equal "a b", @filter.normalize_whitespace("a \t \n\nb") end should "strip whitespace from beginning and end of string" do assert_equal "a", @filter.normalize_whitespace("a ") assert_equal "a", @filter.normalize_whitespace(" a") assert_equal "a", @filter.normalize_whitespace(" a ") end end context "date filters" do context "with Time object" do should "format a date with short format" do assert_equal "27 Mar 2013", @filter.date_to_string(@sample_time) end should "format a date with long format" do assert_equal "27 March 2013", @filter.date_to_long_string(@sample_time) end should "format a date with ordinal, US format" do assert_equal "Mar 27th, 2013", @filter.date_to_string(@sample_time, "ordinal", "US") end should "format a date with long, ordinal format" do assert_equal "27th March 2013", @filter.date_to_long_string(@sample_time, "ordinal") end should "format a time with xmlschema" do assert_equal( "2013-03-27T11:22:33+00:00", @filter.date_to_xmlschema(@sample_time) ) end should "format a time according to RFC-822" do assert_equal( "Wed, 27 Mar 2013 11:22:33 +0000", @filter.date_to_rfc822(@sample_time) ) end should "not modify a time in-place when using filters" do t = Time.new(2004, 9, 15, 0, 2, 37, "+01:00") assert_equal 3600, t.utc_offset @filter.date_to_string(t) assert_equal 3600, t.utc_offset end end context "with Date object" do should "format a date with short format" do assert_equal "02 Mar 2013", @filter.date_to_string(@sample_date) end should "format a date with long format" do assert_equal "02 March 2013", @filter.date_to_long_string(@sample_date) end should "format a date with ordinal format" do assert_equal "2nd Mar 2013", @filter.date_to_string(@sample_date, "ordinal") end should "format a date with ordinal, US, long format" do assert_equal "March 2nd, 2013", @filter.date_to_long_string(@sample_date, "ordinal", "US") end should "format a time with xmlschema" do assert_equal( "2013-03-02T00:00:00+00:00", @filter.date_to_xmlschema(@sample_date) ) end should "format a time according to RFC-822" do assert_equal( "Sat, 02 Mar 2013 00:00:00 +0000", @filter.date_to_rfc822(@sample_date) ) end end context "with String object" do should "format a date with short format" do assert_equal "11 Sep 2001", @filter.date_to_string(@time_as_string) end should "format a date with long format" do assert_equal "11 September 2001", @filter.date_to_long_string(@time_as_string) end should "format a date with ordinal, US format" do assert_equal "Sep 11th, 2001", @filter.date_to_string(@time_as_string, "ordinal", "US") end should "format a date with ordinal long format" do assert_equal "11th September 2001", @filter.date_to_long_string(@time_as_string, "ordinal", "UK") end should "format a time with xmlschema" do assert_equal( "2001-09-11T12:46:30+00:00", @filter.date_to_xmlschema(@time_as_string) ) end should "format a time according to RFC-822" do assert_equal( "Tue, 11 Sep 2001 12:46:30 +0000", @filter.date_to_rfc822(@time_as_string) ) end should "convert a String to Integer" do assert_equal( 142_857, @filter.to_integer(@integer_as_string) ) end end context "with a Numeric object" do should "format a date with short format" do assert_equal "10 May 2014", @filter.date_to_string(@time_as_numeric) end should "format a date with long format" do assert_equal "10 May 2014", @filter.date_to_long_string(@time_as_numeric) end should "format a date with ordinal, US format" do assert_equal "May 10th, 2014", @filter.date_to_string(@time_as_numeric, "ordinal", "US") end should "format a date with ordinal, long format" do assert_equal "10th May 2014", @filter.date_to_long_string(@time_as_numeric, "ordinal") end should "format a time with xmlschema" do assert_match( "2014-05-10T00:10:07", @filter.date_to_xmlschema(@time_as_numeric) ) end should "format a time according to RFC-822" do assert_equal( "Sat, 10 May 2014 00:10:07 +0000", @filter.date_to_rfc822(@time_as_numeric) ) end end context "without input" do should "return input" do assert_nil(@filter.date_to_xmlschema(nil)) assert_equal("", @filter.date_to_xmlschema("")) end end end should "escape xml with ampersands" do assert_equal "AT&amp;T", @filter.xml_escape("AT&T") assert_equal( "&lt;code&gt;command &amp;lt;filename&amp;gt;&lt;/code&gt;", @filter.xml_escape("<code>command &lt;filename&gt;</code>") ) end should "not error when xml escaping nil" do assert_equal "", @filter.xml_escape(nil) end should "escape space as plus" do assert_equal "my+things", @filter.cgi_escape("my things") end should "escape special characters" do assert_equal "hey%21", @filter.cgi_escape("hey!") end should "escape space as %20" do assert_equal "my%20things", @filter.uri_escape("my things") end should "allow reserver characters in URI" do assert_equal( "foo!*'();:@&=+$,/?#[]bar", @filter.uri_escape("foo!*'();:@&=+$,/?#[]bar") ) assert_equal( "foo%20bar!*'();:@&=+$,/?#[]baz", @filter.uri_escape("foo bar!*'();:@&=+$,/?#[]baz") ) end context "absolute_url filter" do should "produce an absolute URL from a page URL" do page_url = "/about/my_favorite_page/" assert_equal "http://example.com/base#{page_url}", @filter.absolute_url(page_url) end should "ensure the leading slash" do page_url = "about/my_favorite_page/" assert_equal "http://example.com/base/#{page_url}", @filter.absolute_url(page_url) end should "ensure the leading slash for the baseurl" do page_url = "about/my_favorite_page/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "base" ) assert_equal "http://example.com/base/#{page_url}", filter.absolute_url(page_url) end should "be ok with a blank but present 'url'" do page_url = "about/my_favorite_page/" filter = make_filter_mock( "url" => "", "baseurl" => "base" ) assert_equal "/base/#{page_url}", filter.absolute_url(page_url) end should "be ok with a nil 'url'" do page_url = "about/my_favorite_page/" filter = make_filter_mock( "url" => nil, "baseurl" => "base" ) assert_equal "/base/#{page_url}", filter.absolute_url(page_url) end should "be ok with a nil 'baseurl'" do page_url = "about/my_favorite_page/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => nil ) assert_equal "http://example.com/#{page_url}", filter.absolute_url(page_url) end should "not prepend a forward slash if input is empty" do page_url = "" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/base" ) assert_equal "http://example.com/base", filter.absolute_url(page_url) end should "not append a forward slash if input is '/'" do page_url = "/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/base" ) assert_equal "http://example.com/base/", filter.absolute_url(page_url) end should "not append a forward slash if input is '/' and nil 'baseurl'" do page_url = "/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => nil ) assert_equal "http://example.com/", filter.absolute_url(page_url) end should "not append a forward slash if both input and baseurl are simply '/'" do page_url = "/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/" ) assert_equal "http://example.com/", filter.absolute_url(page_url) end should "normalize international URLs" do page_url = "" filter = make_filter_mock( "url" => "http://ümlaut.example.org/", "baseurl" => nil ) assert_equal "http://xn--mlaut-jva.example.org/", filter.absolute_url(page_url) end should "not modify an absolute URL" do page_url = "http://example.com/" assert_equal "http://example.com/", @filter.absolute_url(page_url) end should "transform the input URL to a string" do page_url = "/my-page.html" filter = make_filter_mock("url" => Value.new(proc { "http://example.org" })) assert_equal "http://example.org#{page_url}", filter.absolute_url(page_url) end should "not raise a TypeError when passed a hash" do assert @filter.absolute_url("foo" => "bar") end context "with a document" do setup do @site = fixture_site( "collections" => ["methods"] ) @site.process @document = @site.collections["methods"].docs.detect do |d| d.relative_path == "_methods/configuration.md" end end should "make a url" do expected = "http://example.com/base/methods/configuration.html" assert_equal expected, @filter.absolute_url(@document) end end end context "relative_url filter" do should "produce a relative URL from a page URL" do page_url = "/about/my_favorite_page/" assert_equal "/base#{page_url}", @filter.relative_url(page_url) end should "ensure the leading slash between baseurl and input" do page_url = "about/my_favorite_page/" assert_equal "/base/#{page_url}", @filter.relative_url(page_url) end should "ensure the leading slash for the baseurl" do page_url = "about/my_favorite_page/" filter = make_filter_mock("baseurl" => "base") assert_equal "/base/#{page_url}", filter.relative_url(page_url) end should "normalize international URLs" do page_url = "错误.html" assert_equal "/base/%E9%94%99%E8%AF%AF.html", @filter.relative_url(page_url) end should "be ok with a nil 'baseurl'" do page_url = "about/my_favorite_page/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => nil ) assert_equal "/#{page_url}", filter.relative_url(page_url) end should "not prepend a forward slash if input is empty" do page_url = "" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/base" ) assert_equal "/base", filter.relative_url(page_url) end should "not prepend a forward slash if baseurl ends with a single '/'" do page_url = "/css/main.css" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/base/" ) assert_equal "/base/css/main.css", filter.relative_url(page_url) end should "not return valid URI if baseurl ends with multiple '/'" do page_url = "/css/main.css" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/base//" ) refute_equal "/base/css/main.css", filter.relative_url(page_url) end should "not prepend a forward slash if both input and baseurl are simply '/'" do page_url = "/" filter = make_filter_mock( "url" => "http://example.com", "baseurl" => "/" ) assert_equal "/", filter.relative_url(page_url) end should "not return the url by reference" do filter = make_filter_mock(:baseurl => nil) page = Page.new(filter.site, test_dir("fixtures"), "", "front_matter.erb") assert_equal "/front_matter.erb", page.url url = filter.relative_url(page.url) url << "foo" assert_equal "/front_matter.erb", filter.relative_url(page.url) assert_equal "/front_matter.erb", page.url end should "transform the input baseurl to a string" do page_url = "/my-page.html" filter = make_filter_mock("baseurl" => Value.new(proc { "/baseurl/" })) assert_equal "/baseurl#{page_url}", filter.relative_url(page_url) end should "transform protocol-relative url" do url = "//example.com/" assert_equal "/base//example.com/", @filter.relative_url(url) end should "not modify an absolute url with scheme" do url = "file:///file.html" assert_equal url, @filter.relative_url(url) end should "not normalize absolute international URLs" do url = "https://example.com/错误" assert_equal "https://example.com/错误", @filter.relative_url(url) end end context "strip_index filter" do should "strip trailing /index.html" do assert_equal "/foo/", @filter.strip_index("/foo/index.html") end should "strip trailing /index.htm" do assert_equal "/foo/", @filter.strip_index("/foo/index.htm") end should "not strip HTML in the middle of URLs" do assert_equal "/index.html/foo", @filter.strip_index("/index.html/foo") end should "not raise an error on nil strings" do assert_nil @filter.strip_index(nil) end should "not mangle other URLs" do assert_equal "/foo/", @filter.strip_index("/foo/") end end context "jsonify filter" do should "convert hash to json" do assert_equal "{\"age\":18}", @filter.jsonify(:age => 18) end should "convert array to json" do assert_equal "[1,2]", @filter.jsonify([1, 2]) assert_equal( "[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]", @filter.jsonify([{ :name => "Jack" }, { :name => "Smith" }]) ) end should "convert drop to json" do @filter.site.read expected = { "name" => "2008-02-02-published.markdown", "path" => "_posts/2008-02-02-published.markdown", "previous" => nil, "output" => nil, "content" => "This should be published.\n", "id" => "/publish_test/2008/02/02/published", "url" => "/publish_test/2008/02/02/published.html", "relative_path" => "_posts/2008-02-02-published.markdown", "collection" => "posts", "excerpt" => "<p>This should be published.</p>\n", "draft" => false, "categories" => [ "publish_test", ], "layout" => "default", "title" => "Publish", "category" => "publish_test", "date" => "2008-02-02 00:00:00 +0000", "slug" => "published", "ext" => ".markdown", "tags" => [], } actual = JSON.parse(@filter.jsonify(@filter.site.docs_to_write.first.to_liquid)) next_doc = actual.delete("next") refute_nil next_doc assert_kind_of Hash, next_doc, "doc.next should be an object" assert_equal expected, actual end should "convert drop with drops to json" do @filter.site.read actual = @filter.jsonify(@filter.site.to_liquid) expected = { "environment" => "development", "version" => Jekyll::VERSION, } assert_equal expected, JSON.parse(actual)["jekyll"] end # rubocop:disable Style/StructInheritance class M < Struct.new(:message) def to_liquid [message] end end class T < Struct.new(:name) def to_liquid { "name" => name, :v => 1, :thing => M.new({:kay => "jewelers"}), :stuff => true, } end end should "call #to_liquid " do expected = [ { "name" => "Jeremiah", "v" => 1, "thing" => [ { "kay" => "jewelers", }, ], "stuff" => true, }, { "name" => "Smathers", "v" => 1, "thing" => [ { "kay" => "jewelers", }, ], "stuff" => true, }, ] result = @filter.jsonify([T.new("Jeremiah"), T.new("Smathers")]) assert_equal expected, JSON.parse(result) end # rubocop:enable Style/StructInheritance should "handle hashes with all sorts of weird keys and values" do my_hash = { "posts" => Array.new(3) { |i| T.new(i) } } expected = { "posts" => [ { "name" => 0, "v" => 1, "thing" => [ { "kay" => "jewelers", }, ], "stuff" => true, }, { "name" => 1, "v" => 1, "thing" => [ { "kay" => "jewelers", }, ], "stuff" => true, }, { "name" => 2, "v" => 1, "thing" => [ { "kay" => "jewelers", }, ], "stuff" => true, }, ], } result = @filter.jsonify(my_hash) assert_equal expected, JSON.parse(result) end end context "group_by filter" do should "successfully group array of Jekyll::Page's" do @filter.site.process grouping = @filter.group_by(@filter.site.pages, "layout") names = ["default", "nil", ""] grouping.each do |g| assert_includes names, g["name"], "#{g["name"]} isn't a valid grouping." case g["name"] when "default" assert_kind_of( Array, g["items"], "The list of grouped items for 'default' is not an Array." ) # adjust array.size to ignore symlinked page in Windows qty = Utils::Platforms.really_windows? ? 4 : 5 assert_equal qty, g["items"].size when "nil" assert_kind_of( Array, g["items"], "The list of grouped items for 'nil' is not an Array." ) assert_equal 2, g["items"].size when "" assert_kind_of( Array, g["items"], "The list of grouped items for '' is not an Array." ) # adjust array.size to ignore symlinked page in Windows qty = Utils::Platforms.really_windows? ? 19 : 21 assert_equal qty, g["items"].size end end end should "include the size of each grouping" do grouping = @filter.group_by(@filter.site.pages, "layout") grouping.each do |g| assert_equal( g["items"].size, g["size"], "The size property for '#{g["name"]}' doesn't match the size of the Array." ) end end should "should pass integers as is" do grouping = @filter.group_by([ { "name" => "Allison", "year" => 2016 }, { "name" => "Amy", "year" => 2016 }, { "name" => "George", "year" => 2019 }, ], "year") assert_equal "2016", grouping[0]["name"] assert_equal "2019", grouping[1]["name"] end end context "where filter" do should "return any input that is not an array" do assert_equal "some string", @filter.where("some string", "la", "le") end should "filter objects in a hash appropriately" do hash = { "a" => { "color"=>"red" }, "b" => { "color"=>"blue" } } assert_equal 1, @filter.where(hash, "color", "red").length assert_equal [{ "color"=>"red" }], @filter.where(hash, "color", "red") end should "filter objects appropriately" do assert_equal 2, @filter.where(@array_of_objects, "color", "red").length end should "filter objects with null properties appropriately" do array = [{}, { "color" => nil }, { "color" => "" }, { "color" => "text" }] assert_equal 2, @filter.where(array, "color", nil).length end should "filter objects with numerical properties appropriately" do array = [ { "value" => "555" }, { "value" => 555 }, { "value" => 24.625 }, { "value" => "24.625" }, ] assert_equal 2, @filter.where(array, "value", 24.625).length assert_equal 2, @filter.where(array, "value", 555).length end should "filter array properties appropriately" do hash = { "a" => { "tags"=>%w(x y) }, "b" => { "tags"=>["x"] }, "c" => { "tags"=>%w(y z) }, } assert_equal 2, @filter.where(hash, "tags", "x").length end should "filter array properties alongside string properties" do hash = { "a" => { "tags"=>%w(x y) }, "b" => { "tags"=>"x" }, "c" => { "tags"=>%w(y z) }, } assert_equal 2, @filter.where(hash, "tags", "x").length end should "filter hash properties with null and empty values" do hash = { "a" => { "tags" => {} }, "b" => { "tags" => "" }, "c" => { "tags" => nil }, "d" => { "tags" => ["x", nil] }, "e" => { "tags" => [] }, "f" => { "tags" => "xtra" }, } assert_equal [{ "tags" => nil }], @filter.where(hash, "tags", nil) assert_equal( [{ "tags" => "" }, { "tags" => ["x", nil] }], @filter.where(hash, "tags", "") ) # `{{ hash | where: 'tags', empty }}` assert_equal( [{ "tags" => {} }, { "tags" => "" }, { "tags" => nil }, { "tags" => [] }], @filter.where(hash, "tags", Liquid::Expression::LITERALS["empty"]) ) # `{{ `hash | where: 'tags', blank }}` assert_equal( [{ "tags" => {} }, { "tags" => "" }, { "tags" => nil }, { "tags" => [] }], @filter.where(hash, "tags", Liquid::Expression::LITERALS["blank"]) ) end should "not match substrings" do hash = { "a" => { "category"=>"bear" }, "b" => { "category"=>"wolf" }, "c" => { "category"=>%w(bear lion) }, } assert_equal 0, @filter.where(hash, "category", "ear").length end should "stringify during comparison for compatibility with liquid parsing" do hash = { "The Words" => { "rating" => 1.2, "featured" => false }, "Limitless" => { "rating" => 9.2, "featured" => true }, "Hustle" => { "rating" => 4.7, "featured" => true }, } results = @filter.where(hash, "featured", "true") assert_equal 2, results.length assert_in_delta(9.2, results[0]["rating"]) assert_in_delta(4.7, results[1]["rating"]) results = @filter.where(hash, "rating", 4.7) assert_equal 1, results.length assert_in_delta(4.7, results[0]["rating"]) end should "always return an array if the object responds to 'select'" do results = @filter.where(SelectDummy.new, "obj", "1 == 1") assert_equal [], results end should "gracefully handle invalid property type" do hash = { "members" => { "name" => %w(John Jane Jimmy) }, "roles" => %w(Admin Recruiter Manager), } err = assert_raises(TypeError) { @filter.where(hash, "name", "Jimmy") } truncatd_arr_str = hash["roles"].to_liquid.to_s[0...20] msg = "Error accessing object (#{truncatd_arr_str}) with given key. Expected an integer " \ 'but got "name" instead.' assert_equal msg, err.message end end context "where_exp filter" do should "return any input that is not an array" do assert_equal "some string", @filter.where_exp("some string", "la", "le") end should "filter objects in a hash appropriately" do hash = { "a" => { "color"=>"red" }, "b" => { "color"=>"blue" } } assert_equal 1, @filter.where_exp(hash, "item", "item.color == 'red'").length assert_equal( [{ "color"=>"red" }], @filter.where_exp(hash, "item", "item.color == 'red'") ) end should "filter objects appropriately" do assert_equal( 2, @filter.where_exp(@array_of_objects, "item", "item.color == 'red'").length ) end should "filter objects appropriately with 'or', 'and' operators" do assert_equal( [ { "color" => "teal", "size" => "large" }, { "color" => "red", "size" => "large" },
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
true
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_layout_reader.rb
test/test_layout_reader.rb
# frozen_string_literal: true require "helper" class TestLayoutReader < JekyllUnitTest context "reading layouts" do setup do config = Jekyll::Configuration::DEFAULTS.merge("source" => source_dir, "destination" => dest_dir) @site = fixture_site(config) end should "read layouts" do layouts = LayoutReader.new(@site).read assert_equal ["default", "simple", "post/simple"].sort, layouts.keys.sort end context "when no _layouts directory exists in CWD" do should "know to use the layout directory relative to the site source" do assert_equal LayoutReader.new(@site).layout_directory, source_dir("_layouts") end end context "when a _layouts directory exists in CWD" do setup do allow(File).to receive(:directory?).and_return(true) allow(Dir).to receive(:pwd).and_return(source_dir("blah")) end should "ignore the layout directory in CWD and use the directory relative to site source" do refute_equal source_dir("blah/_layouts"), LayoutReader.new(@site).layout_directory assert_equal source_dir("_layouts"), LayoutReader.new(@site).layout_directory end end context "when a layout is a symlink" do setup do symlink_if_allowed("/etc/passwd", source_dir("_layouts", "symlink.html")) @site = fixture_site( "safe" => true, "include" => ["symlink.html"] ) end teardown do FileUtils.rm_f(source_dir("_layouts", "symlink.html")) end should "only read the layouts which are in the site" do skip_if_windows "Jekyll does not currently support symlinks on Windows." layouts = LayoutReader.new(@site).read refute layouts.key?("symlink"), "Should not read the symlinked layout" end end context "with a theme" do setup do symlink_if_allowed("/etc/passwd", theme_dir("_layouts", "theme-symlink.html")) @site = fixture_site( "include" => ["theme-symlink.html"], "theme" => "test-theme", "safe" => true ) end teardown do FileUtils.rm_f(theme_dir("_layouts", "theme-symlink.html")) end should "not read a symlink'd theme" do skip_if_windows "Jekyll does not currently support symlinks on Windows." layouts = LayoutReader.new(@site).read refute layouts.key?("theme-symlink"), \ "Should not read symlinked layout from theme" end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_utils.rb
test/test_utils.rb
# frozen_string_literal: true require "helper" class TestUtils < JekyllUnitTest context "The `Utils.deep_merge_hashes` method" do setup do clear_dest @site = fixture_site @site.process end should "merge a drop into a hash" do data = { "page" => {} } merged = Utils.deep_merge_hashes(data, @site.site_payload) assert_kind_of Hash, merged assert_kind_of Drops::SiteDrop, merged["site"] assert_equal data["page"], merged["page"] end should "merge a hash into a drop" do data = { "page" => {} } assert_nil @site.site_payload["page"] merged = Utils.deep_merge_hashes(@site.site_payload, data) assert_kind_of Drops::UnifiedPayloadDrop, merged assert_kind_of Drops::SiteDrop, merged["site"] assert_equal data["page"], merged["page"] end end context "hash" do context "pluralized_array" do should "return empty array with no values" do data = {} assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return empty array with no matching values" do data = { "foo" => "bar" } assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return plural array with nil singular" do data = { "foo" => "bar", "tag" => nil, "tags" => %w(dog cat) } assert_equal %w(dog cat), Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching singular" do data = { "foo" => "bar", "tag" => "dog", "tags" => %w(dog cat) } assert_equal ["dog"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching singular with spaces" do data = { "foo" => "bar", "tag" => "dog cat", "tags" => %w(dog cat) } assert_equal ["dog cat"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return empty array with matching nil plural" do data = { "foo" => "bar", "tags" => nil } assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return empty array with matching empty array" do data = { "foo" => "bar", "tags" => [] } assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching plural with single string value" do data = { "foo" => "bar", "tags" => "dog" } assert_equal ["dog"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return multiple value array with matching plural with " \ "single string value with spaces" do data = { "foo" => "bar", "tags" => "dog cat" } assert_equal %w(dog cat), Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching plural with single value array" do data = { "foo" => "bar", "tags" => ["dog"] } assert_equal ["dog"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return multiple value array with matching plural with " \ "multiple value array" do data = { "foo" => "bar", "tags" => %w(dog cat) } assert_equal %w(dog cat), Utils.pluralized_array_from_hash(data, "tag", "tags") end end end context "The `Utils.parse_date` method" do should "parse a properly formatted date" do assert_kind_of Time, Utils.parse_date("2014-08-02 14:43:06 PDT") end should "throw an error if the input contains no date data" do assert_raises Jekyll::Errors::InvalidDateError do Utils.parse_date("Blah") end end should "throw an error if the input is out of range" do assert_raises Jekyll::Errors::InvalidDateError do Utils.parse_date("9999-99-99") end end should "throw an error with the default message if no message is passed in" do date = "Blah this is invalid" assert_raises( Jekyll::Errors::InvalidDateError, "Invalid date '#{date}': Input could not be parsed." ) do Utils.parse_date(date) end end should "throw an error with the provided message if a message is passed in" do date = "Blah this is invalid" message = "Aaaah, the world has exploded!" assert_raises( Jekyll::Errors::InvalidDateError, "Invalid date '#{date}': #{message}" ) do Utils.parse_date(date, message) end end end context "The `Utils.slugify` method" do should "return nil if passed nil" do assert_nil Utils.slugify(nil) rescue NoMethodError assert false, "Threw NoMethodError" end should "replace whitespace with hyphens" do assert_equal "working-with-drafts", Utils.slugify("Working with drafts") end should "replace consecutive whitespace with a single hyphen" do assert_equal "basic-usage", Utils.slugify("Basic Usage") end should "trim leading and trailing whitespace" do assert_equal "working-with-drafts", Utils.slugify(" Working with drafts ") end should "drop trailing punctuation" do assert_equal( "so-what-is-jekyll-exactly", Utils.slugify("So what is Jekyll, exactly?") ) assert_equal "كيف-حالك", Utils.slugify("كيف حالك؟") end should "ignore hyphens" do assert_equal "pre-releases", Utils.slugify("Pre-releases") end should "replace underscores with hyphens" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file") end should "combine adjacent hyphens and spaces" do assert_equal( "customizing-git-git-hooks", Utils.slugify("Customizing Git - Git Hooks") ) end should "replace punctuation in any scripts by hyphens" do assert_equal "5時-6時-三-一四", Utils.slugify("5時〜6時 三・一四") end should "not replace Unicode 'Mark', 'Letter', or 'Number: Decimal Digit' category characters" do assert_equal "மல்லிப்பூ-வகைகள்", Utils.slugify("மல்லிப்பூ வகைகள்") assert_equal "மல்லிப்பூ-வகைகள்", Utils.slugify("மல்லிப்பூ வகைகள்", :mode => "pretty") end should "not modify the original string" do title = "Quick-start guide" Utils.slugify(title) assert_equal "Quick-start guide", title end should "not change behaviour if mode is default" do assert_equal( "the-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "default") ) end should "not change behaviour if mode is nil" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file?") end should "not replace period and underscore if mode is pretty" do assert_equal( "the-_config.yml-file", Utils.slugify("The _config.yml file?", :mode => "pretty") ) end should "replace everything else but ASCII characters" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "ascii") assert_equal "f-rtive-glance", Utils.slugify("fürtive glance!!!!", :mode => "ascii") end should "map accented latin characters to ASCII characters" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "latin") assert_equal "furtive-glance", Utils.slugify("fürtive glance!!!!", :mode => "latin") assert_equal "aaceeiioouu", Utils.slugify("àáçèéíïòóúü", :mode => "latin") assert_equal "a-z", Utils.slugify("Aあわれ鬱господинZ", :mode => "latin") end should "only replace whitespace if mode is raw" do assert_equal( "the-_config.yml-file?", Utils.slugify("The _config.yml file?", :mode => "raw") ) end should "return the given string if mode is none" do assert_equal( "the _config.yml file?", Utils.slugify("The _config.yml file?", :mode => "none") ) end should "Keep all uppercase letters if cased is true" do assert_equal( "Working-with-drafts", Utils.slugify("Working with drafts", :cased => true) ) assert_equal( "Basic-Usage", Utils.slugify("Basic Usage", :cased => true) ) assert_equal( "Working-with-drafts", Utils.slugify(" Working with drafts ", :cased => true) ) assert_equal( "So-what-is-Jekyll-exactly", Utils.slugify("So what is Jekyll, exactly?", :cased => true) ) assert_equal( "Pre-releases", Utils.slugify("Pre-releases", :cased => true) ) assert_equal( "The-config-yml-file", Utils.slugify("The _config.yml file", :cased => true) ) assert_equal( "Customizing-Git-Git-Hooks", Utils.slugify("Customizing Git - Git Hooks", :cased => true) ) assert_equal( "The-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "default", :cased => true) ) assert_equal( "The-config-yml-file", Utils.slugify("The _config.yml file?", :cased => true) ) assert_equal( "The-_config.yml-file", Utils.slugify("The _config.yml file?", :mode => "pretty", :cased => true) ) assert_equal( "The-_config.yml-file?", Utils.slugify("The _config.yml file?", :mode => "raw", :cased => true) ) assert_equal( "The _config.yml file?", Utils.slugify("The _config.yml file?", :mode => "none", :cased => true) ) end should "records a warning in the log if the returned slug is empty" do expect(Jekyll.logger).to receive(:warn) assert_equal "", Utils.slugify("💎") end end context "The `Utils.titleize_slug` method" do should "capitalize all words and not drop any words" do assert_equal( "This Is A Long Title With Mixed Capitalization", Utils.titleize_slug("This-is-a-Long-title-with-Mixed-capitalization") ) assert_equal( "This Is A Title With Just The Initial Word Capitalized", Utils.titleize_slug("This-is-a-title-with-just-the-initial-word-capitalized") ) assert_equal( "This Is A Title With No Capitalization", Utils.titleize_slug("this-is-a-title-with-no-capitalization") ) end end context "The `Utils.add_permalink_suffix` method" do should "handle built-in permalink styles" do assert_equal( "/:basename/", Utils.add_permalink_suffix("/:basename", :pretty) ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", :date) ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", :ordinal) ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", :none) ) end should "handle custom permalink styles" do assert_equal( "/:basename/", Utils.add_permalink_suffix("/:basename", "/:title/") ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", "/:title:output_ext") ) assert_equal( "/:basename", Utils.add_permalink_suffix("/:basename", "/:title") ) end end context "The `Utils.safe_glob` method" do should "not apply pattern to the dir" do dir = "test/safe_glob_test[" assert_equal [], Dir.glob(dir + "/*") unless jruby? assert_equal ["test/safe_glob_test[/find_me.txt"], Utils.safe_glob(dir, "*") end should "return the same data to #glob" do dir = "test" assert_equal Dir.glob(dir + "/*"), Utils.safe_glob(dir, "*") assert_equal Dir.glob(dir + "/**/*"), Utils.safe_glob(dir, "**/*") end should "return the same data to #glob if dir is not found" do dir = "dir_not_exist" assert_equal [], Utils.safe_glob(dir, "*") assert_equal Dir.glob(dir + "/*"), Utils.safe_glob(dir, "*") end should "return the same data to #glob if pattern is blank" do dir = "test" assert_equal [dir], Utils.safe_glob(dir, "") assert_equal Dir.glob(dir), Utils.safe_glob(dir, "") assert_equal Dir.glob(dir), Utils.safe_glob(dir, nil) end should "return the same data to #glob if flag is given" do dir = "test" assert_equal Dir.glob(dir + "/*", File::FNM_DOTMATCH), Utils.safe_glob(dir, "*", File::FNM_DOTMATCH) end should "support pattern as an array to support windows" do dir = "test" assert_equal Dir.glob(dir + "/**/*"), Utils.safe_glob(dir, ["**", "*"]) end end context "The `Utils.has_yaml_header?` method" do should "accept files with YAML front matter" do file = source_dir("_posts", "2008-10-18-foo-bar.markdown") assert_equal "---\n", File.open(file, "rb") { |f| f.read(4) } assert Utils.has_yaml_header?(file) end should "accept files with extraneous spaces after YAML front matter" do file = source_dir("_posts", "2015-12-27-extra-spaces.markdown") assert_equal "--- \n", File.open(file, "rb") { |f| f.read(6) } assert Utils.has_yaml_header?(file) end should "reject pgp files and the like which resemble front matter" do file = source_dir("pgp.key") assert_equal "-----B", File.open(file, "rb") { |f| f.read(6) } refute Utils.has_yaml_header?(file) end end context "The `Utils.merged_file_read_opts` method" do should "ignore encoding if it's not there" do opts = Utils.merged_file_read_opts(nil, {}) assert_nil opts["encoding"] assert_nil opts[:encoding] end should "add bom to utf-encoding" do opts = { "encoding" => "utf-8", :encoding => "utf-8" } merged = Utils.merged_file_read_opts(nil, opts) assert_equal "bom|utf-8", merged["encoding"] assert_equal "bom|utf-8", merged[:encoding] end should "not add bom to non-utf encoding" do opts = { "encoding" => "ISO-8859-1", :encoding => "ISO-8859-1" } merged = Utils.merged_file_read_opts(nil, opts) assert_equal "ISO-8859-1", merged["encoding"] assert_equal "ISO-8859-1", merged[:encoding] end should "preserve bom in encoding" do opts = { "encoding" => "bom|another", :encoding => "bom|another" } merged = Utils.merged_file_read_opts(nil, opts) assert_equal "bom|another", merged["encoding"] assert_equal "bom|another", merged[:encoding] end end context "Utils::Internet.connected?" do should "return true if there's internet" do assert Utils::Internet.connected? end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_url.rb
test/test_url.rb
# frozen_string_literal: true require "helper" class TestURL < JekyllUnitTest context "The URL class" do should "throw an exception if neither permalink or template is specified" do assert_raises ArgumentError do URL.new(:placeholders => {}) end end should "replace placeholders in templates" do assert_equal "/foo/bar", URL.new( :template => "/:x/:y", :placeholders => { :x => "foo", :y => "bar" } ).to_s end should "handle multiple of the same key in the template" do assert_equal "/foo/bar/foo/", URL.new( :template => "/:x/:y/:x/", :placeholders => { :x => "foo", :y => "bar" } ).to_s end should "use permalink if given" do assert_equal "/le/perma/link", URL.new( :template => "/:x/:y", :placeholders => { :x => "foo", :y => "bar" }, :permalink => "/le/perma/link" ).to_s end should "replace placeholders in permalinks" do assert_equal "/foo/bar", URL.new( :template => "/baz", :permalink => "/:x/:y", :placeholders => { :x => "foo", :y => "bar" } ).to_s end should "handle multiple of the same key in the permalink" do assert_equal "/foo/bar/foo/", URL.new( :template => "/baz", :permalink => "/:x/:y/:x/", :placeholders => { :x => "foo", :y => "bar" } ).to_s end should "handle nil values for keys in the template" do assert_equal "/foo/bar/", URL.new( :template => "/:x/:y/:z/", :placeholders => { :x => "foo", :y => "bar", :z => nil } ).to_s end should "handle UrlDrop as a placeholder in addition to a hash" do _, matching_doc = fixture_document("_methods/escape-+ #%20[].md") assert_equal "/methods/escape-+-20/escape-20.html", URL.new( :template => "/methods/:title/:name:output_ext", :placeholders => matching_doc.url_placeholders ).to_s end should "check for key without trailing underscore" do _, matching_doc = fixture_document("_methods/configuration.md") assert_equal "/methods/configuration-configuration_methods_configuration", URL.new( :template => "/methods/:name-:slug_:collection_:title", :placeholders => matching_doc.url_placeholders ).to_s end should "raise custom error when URL placeholder doesn't have key" do _, matching_doc = fixture_document("_methods/escape-+ #%20[].md") assert_raises NoMethodError do URL.new( :template => "/methods/:headline", :placeholders => matching_doc.url_placeholders ).to_s end end should "not treat colons in placeholders as uri delimiters" do assert_equal "/foo/foo%20bar:foobar/", URL.new( :template => "/:x/:y/", :placeholders => { :x => "foo", :y => "foo bar:foobar" } ).to_s end should "unescape urls with colons" do assert_equal "/foo/foo bar:foobar/", Jekyll::URL.unescape_path("/foo/foo%20bar:foobar/") end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/helper.rb
test/helper.rb
# frozen_string_literal: true $stdout.puts "# -------------------------------------------------------------" $stdout.puts "# SPECS AND TESTS ARE RUNNING WITH WARNINGS OFF." $stdout.puts "# SEE: https://github.com/Shopify/liquid/issues/730" $stdout.puts "# SEE: https://github.com/jekyll/jekyll/issues/4719" $stdout.puts "# -------------------------------------------------------------" $VERBOSE = nil def jruby? defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby" end if ENV["CI"] require "simplecov" SimpleCov.start else require File.expand_path("simplecov_custom_profile", __dir__) SimpleCov.start "gem" do add_filter "/vendor/gem" add_filter "/vendor/bundle" add_filter ".bundle" end end require "nokogiri" require "rubygems" require "ostruct" require "minitest/autorun" require "minitest/reporters" require "minitest/profile" require "rspec/mocks" require_relative "../lib/jekyll" Jekyll.logger = Logger.new(StringIO.new, :error) require "kramdown" require "shoulda-context" include Jekyll require "jekyll/commands/serve/servlet" # Report with color. Minitest::Reporters.use! [ Minitest::Reporters::DefaultReporter.new( :color => true ), ] module Minitest::Assertions def assert_exist(filename, msg = nil) msg = message(msg) { "Expected '#{filename}' to exist" } assert_path_exists(filename, msg) end def refute_exist(filename, msg = nil) msg = message(msg) { "Expected '#{filename}' not to exist" } refute_path_exists(filename, msg) end end module DirectoryHelpers def root_dir(*subdirs) File.expand_path(File.join("..", *subdirs), __dir__) end def dest_dir(*subdirs) test_dir("dest", *subdirs) end def source_dir(*subdirs) test_dir("source", *subdirs) end def theme_dir(*subdirs) test_dir("fixtures", "test-theme", *subdirs) end def test_dir(*subdirs) root_dir("test", *subdirs) end def temp_dir(*subdirs) if Utils::Platforms.vanilla_windows? drive = Dir.pwd.sub(%r!^([^/]+).*!, '\1') temp_root = File.join(drive, "tmp") else temp_root = "/tmp" end File.join(temp_root, *subdirs) end end module Jekyll # # --- NOTE: --- # # This monkey-patch was introduced because GitHub Actions on Windows acknowledges symlinked test # file `test/source/symlink-test/symlinked-file-outside-source` but errors out since the linked # location `/etc/passwd` does not exist on Windows. # # --- TODO: --- # # Consider having the `symlinked-file-outside-source` point to a file that is outside the # `source_dir` (defaults to `test/source`) yet is certain to exist on tested platforms. # For example, `jekyll.gemspec` is a good candidate. # # This monkey-patch will then no longer be necessary. # class ModifiedReader < Reader def read_directories(dir = "") if dir.start_with?("/symlink") && Utils::Platforms.really_windows? Jekyll.logger.debug "Skipping:", "Jekyll does not support symlinks on Windows" else super end end end Hooks.register :site, :after_init do |site| site.instance_variable_set(:@reader, ModifiedReader.new(site)) end end class JekyllUnitTest < Minitest::Test include ::RSpec::Mocks::ExampleMethods include DirectoryHelpers extend DirectoryHelpers def mu_pp(obj) s = obj.is_a?(Hash) ? JSON.pretty_generate(obj) : obj.inspect s = s.encode Encoding.default_external if defined? Encoding s end def mocks_expect(*args) RSpec::Mocks::ExampleMethods::ExpectHost.instance_method(:expect).bind(self).call(*args) end def before_setup RSpec::Mocks.setup super end def after_teardown super RSpec::Mocks.verify ensure RSpec::Mocks.teardown end def fixture_document(relative_path) site = fixture_site( "collections" => { "methods" => { "output" => true, }, } ) site.read matching_doc = site.collections["methods"].docs.find do |doc| doc.relative_path == relative_path end [site, matching_doc] end def fixture_site(overrides = {}) Jekyll::Site.new(site_configuration(overrides)) end def default_configuration Marshal.load(Marshal.dump(Jekyll::Configuration::DEFAULTS)) end def build_configs(overrides, base_hash = default_configuration) Utils.deep_merge_hashes(base_hash, overrides) end def site_configuration(overrides = {}) full_overrides = build_configs(overrides, build_configs( "destination" => dest_dir, "incremental" => false )) Configuration.from(full_overrides.merge( "source" => source_dir )) end def clear_dest FileUtils.rm_rf(dest_dir) FileUtils.rm_rf(source_dir(".jekyll-metadata")) end def directory_with_contents(path) FileUtils.rm_rf(path) FileUtils.mkdir(path) File.write("#{path}/index.html", "I was previously generated.") end def with_env(key, value) old_value = ENV[key] ENV[key] = value yield ENV[key] = old_value end def capture_output(level = :debug) buffer = StringIO.new Jekyll.logger = Logger.new(buffer) Jekyll.logger.log_level = level yield buffer.rewind buffer.string.to_s ensure Jekyll.logger = Logger.new(StringIO.new, :error) end alias_method :capture_stdout, :capture_output alias_method :capture_stderr, :capture_output def nokogiri_fragment(str) Nokogiri::HTML.fragment( str ) end def skip_if_windows(msg = nil) if Utils::Platforms.really_windows? msg ||= "Jekyll does not currently support this feature on Windows." skip msg.to_s.magenta end end def symlink_if_allowed(target, sym_file) FileUtils.ln_sf(target, sym_file) rescue Errno::EACCES skip "Permission denied for creating a symlink to #{target.inspect} " \ "on this machine".magenta rescue NotImplementedError => e skip e.to_s.magenta end end class FakeLogger def <<(str); end end module TestWEBrick module_function def mount_server(&block) server = WEBrick::HTTPServer.new(config) begin server.mount("/", Jekyll::Commands::Serve::Servlet, document_root, document_root_options) server.start addr = server.listeners[0].addr block.yield([server, addr[3], addr[1]]) rescue StandardError => e raise e ensure server.shutdown sleep 0.1 until server.status == :Stop end end def config logger = FakeLogger.new { :BindAddress => "127.0.0.1", :Port => 0, :ShutdownSocketWithoutClose => true, :ServerType => Thread, :Logger => WEBrick::Log.new(logger), :AccessLog => [[logger, ""]], :MimeTypesCharset => Jekyll::Commands::Serve.send(:mime_types_charset), :JekyllOptions => {}, } end def document_root "#{File.dirname(__FILE__)}/fixtures/webrick" end def document_root_options WEBrick::Config::FileHandler.merge( :FancyIndexing => true, :NondisclosureName => [ ".ht*", "~*", ] ) end end class TagUnitTest < JekyllUnitTest def render_content(content, override = {}) base_config = { "source" => source_dir, "destination" => dest_dir, } site = fixture_site(base_config.merge(override)) if override["read_posts"] site.posts.docs.concat(PostReader.new(site).read_posts("")) elsif override["read_collections"] CollectionReader.new(site).read elsif override["read_all"] site.read end @result = render_with(site, content) end private def render_with(site, content) converter = site.converters.find { |c| c.instance_of?(Jekyll::Converters::Markdown) } payload = { "highlighter_prefix" => converter.highlighter_prefix, "highlighter_suffix" => converter.highlighter_suffix, } info = { :registers => { :site => site } } converter.convert( Liquid::Template.parse(content).render!(payload, info) ) end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_excerpt.rb
test/test_excerpt.rb
# frozen_string_literal: true require "helper" class TestExcerpt < JekyllUnitTest def setup_post(file) Document.new(@site.in_source_dir(File.join("_posts", file)), :site => @site, :collection => @site.posts).tap(&:read) end def do_render(document) @site.layouts = { "default" => Layout.new(@site, source_dir("_layouts"), "simple.html"), } document.output = Jekyll::Renderer.new(@site, document, @site.site_payload).run end context "With extraction disabled" do setup do clear_dest @site = fixture_site("excerpt_separator" => "") @post = setup_post("2013-07-22-post-excerpt-with-layout.markdown") end should "not be generated" do refute @post.generate_excerpt? end end context "An extracted excerpt" do setup do clear_dest @site = fixture_site @post = setup_post("2013-07-22-post-excerpt-with-layout.markdown") @excerpt = @post.data["excerpt"] end context "#include(string)" do setup do @excerpt.output = "Here is a fake output stub" end should "return true only if an excerpt output contains a specified string" do assert_includes @excerpt, "fake output" refute_includes @excerpt, "real output" end end context "#id" do should "contain the UID for the post" do assert_equal @excerpt.id, "#{@post.id}#excerpt" end should "return a string" do assert_same @post.id.class, String end end context "#type" do should "return the post's type" do assert_equal @excerpt.type, @post.type end should "return a symbol" do assert_same @excerpt.type.class, Symbol end end context "#to_s" do should "return rendered output" do assert_equal @excerpt.output, @excerpt.to_s end should "return its output if output present" do @excerpt.output = "Fake Output" assert_equal @excerpt.output, @excerpt.to_s end end context "#inspect" do should "contain the excerpt id as a shorthand string identifier" do assert_equal @excerpt.inspect, "<#{@excerpt.class} id=#{@excerpt.id}>" end should "return a string" do assert_same @post.id.class, String end end context "#relative_path" do should "return its document's relative path with '/#excerpt' appended" do assert_equal "#{@excerpt.doc.relative_path}/#excerpt", @excerpt.relative_path assert_equal "_posts/2013-07-22-post-excerpt-with-layout.markdown/#excerpt", @excerpt.relative_path end end context "#to_liquid" do should "contain the proper page data to mimic the post liquid" do assert_equal "Post Excerpt with Layout", @excerpt.to_liquid["title"] url = "/bar/baz/z_category/mixedcase/2013/07/22/post-excerpt-with-layout.html" assert_equal url, @excerpt.to_liquid["url"] assert_equal Time.parse("2013-07-22"), @excerpt.to_liquid["date"] assert_equal %w(bar baz z_category MixedCase), @excerpt.to_liquid["categories"] assert_equal %w(first second third jekyllrb.com), @excerpt.to_liquid["tags"] assert_equal "_posts/2013-07-22-post-excerpt-with-layout.markdown/#excerpt", @excerpt.to_liquid["path"] end end context "#content" do context "before render" do should "be the first paragraph of the page" do expected = "First paragraph with [link ref][link].\n\n[link]: https://jekyllrb.com/" assert_equal expected, @excerpt.content end should "contain any refs at the bottom of the page" do assert_includes @excerpt.content, "[link]: https://jekyllrb.com/" end end context "after render" do setup do @rendered_post = @post.dup do_render(@rendered_post) @extracted_excerpt = @rendered_post.data["excerpt"] end should "be the first paragraph of the page" do expected = "<p>First paragraph with <a href=\"https://jekyllrb.com/\">link " \ "ref</a>.</p>\n\n" assert_equal expected, @extracted_excerpt.output end should "link properly" do assert_includes @extracted_excerpt.content, "https://jekyllrb.com/" end end context "with indented link references" do setup do @post = setup_post("2016-08-16-indented-link-references.markdown") @excerpt = @post.excerpt end should "contain all refs at the bottom of the page" do 4.times do |i| assert_match "[link_#{i}]: www.example.com/#{i}", @excerpt.content end end should "ignore indented code" do refute_match "[fakelink]:", @excerpt.content end should "render links properly" do @rendered_post = @post.dup do_render(@rendered_post) output = @rendered_post.data["excerpt"].output 4.times do |i| assert_includes output, "<a href=\"www.example.com/#{i}\">" end end end end end context "A whole-post excerpt" do setup do clear_dest @site = fixture_site @post = setup_post("2008-02-02-published.markdown") @excerpt = @post.data["excerpt"] end should "be generated" do assert_kind_of Jekyll::Excerpt, @excerpt end context "#content" do should "match the post content" do assert_equal @post.content, @excerpt.content end end end context "An excerpt with non-closed but valid Liquid block tag" do setup do clear_dest @site = fixture_site @post = setup_post("2018-01-28-open-liquid-block-excerpt.markdown") @excerpt = @post.data["excerpt"] head = @post.content.split("\n\n")[0] assert_includes @post.content, "{%\n highlight\n" assert_includes @post.content, "{% raw" refute_includes head, "{% endraw %}" refute_includes head, "{% endhighlight %}" end should "be appended to as necessary and generated" do assert_includes @excerpt.content, "{% endraw %}" assert_includes @excerpt.content, "{% endhighlight %}" assert_kind_of Jekyll::Excerpt, @excerpt end end context "An excerpt with valid closed Liquid block tag" do setup do clear_dest @site = fixture_site @post = setup_post("2018-01-28-closed-liquid-block-excerpt.markdown") @excerpt = @post.data["excerpt"] head = @post.content.split("\n\n")[0] assert_includes @post.content, "{%\n highlight\n" assert_includes @post.content, "{% raw" assert_includes head, "{%\n endraw\n%}" assert_includes head, "{%\n endhighlight\n%}" end should "not be appended to but generated as is" do assert_includes @excerpt.content, "{%\n endraw\n%}" assert_includes @excerpt.content, "{%\n endhighlight\n%}" refute_includes @excerpt.content, "{%\n endraw\n%}\n\n{% endraw %}" refute_includes @excerpt.content, "{%\n endhighlight\n%}\n\n{% endhighlight %}" assert_kind_of Jekyll::Excerpt, @excerpt end end context "An excerpt with non-closed but valid Liquid block tag with whitespace control" do setup do clear_dest @site = fixture_site @post = setup_post("2018-05-15-open-liquid-block-excerpt-whitespace-control.md") @excerpt = @post.data["excerpt"] assert_includes @post.content, "{%- for" refute_includes @post.content.split("\n\n")[0], "{%- endfor -%}" end should "be appended to as necessary and generated" do assert_includes @excerpt.content, "{% endfor %}" refute_includes @excerpt.content, "{% endfor %}\n\n{% endfor %}" assert_kind_of Jekyll::Excerpt, @excerpt end end context "An excerpt with valid closed Liquid block tag with whitespace control" do setup do clear_dest @site = fixture_site @post = setup_post("2018-05-15-closed-liquid-block-excerpt-whitespace-control.md") @excerpt = @post.data["excerpt"] assert_includes @post.content, "{%- for" assert_includes @post.content.split("\n\n")[0], "{%- endfor -%}" end should "not be appended to but generated as is" do assert_includes @excerpt.content, "{%- endfor -%}" refute_includes @excerpt.content, "{% endfor %}\n\n{% endfor %}" assert_kind_of Jekyll::Excerpt, @excerpt end end context "An excerpt with valid Liquid variable with whitespace control" do setup do clear_dest @site = fixture_site @post = setup_post("2018-05-15-excerpt-whitespace-control-variable.md") @excerpt = @post.data["excerpt"] assert_includes @post.content, "{%- assign" end should "not be appended to but generated as is" do assert_includes @excerpt.content, "{{- xyzzy -}}" assert_kind_of Jekyll::Excerpt, @excerpt end end context "An excerpt with Liquid tags" do setup do clear_dest @site = fixture_site @post = setup_post("2018-11-15-excerpt-liquid-block.md") @excerpt = @post.data["excerpt"] assert_includes @post.content.split("\n\n")[0].strip, "{% continue %}" assert_includes Jekyll::DoNothingBlock.ancestors, Liquid::Block refute_includes Jekyll::DoNothingOther.ancestors, Liquid::Block assert_match "Jekyll::DoNothingBlock", Liquid::Template.tags["do_nothing"].name assert_match "Jekyll::DoNothingOther", Liquid::Template.tags["do_nothing_other"].name end should "close open block tags, including custom tags, and ignore others" do assert_includes @excerpt.content, "{% endcase %}" assert_includes @excerpt.content, "{% endif %}" assert_includes @excerpt.content, "{% endfor %}" assert_includes @excerpt.content, "{% endunless %}" assert_includes @excerpt.content, "{% enddo_nothing %}" refute_includes @excerpt.content, "{% enddo_nothing_other %}" assert_kind_of Jekyll::Excerpt, @excerpt end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_command.rb
test/test_command.rb
# frozen_string_literal: true require "helper" class TestCommand < JekyllUnitTest context "when calling .add_build_options" do should "add common options" do cmd = Object.new mocks_expect(cmd).to receive(:option).at_least(:once) Command.add_build_options(cmd) end end context "when calling .process_site" do context "when fatal error occurs" do should "exit with non-zero error code" do site = Object.new def site.process raise Jekyll::Errors::FatalException end error = assert_raises(SystemExit) { Command.process_site(site) } refute_equal 0, error.status end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_site_drop.rb
test/test_site_drop.rb
# frozen_string_literal: true require "helper" class TestSiteDrop < JekyllUnitTest context "a site drop" do setup do @site = fixture_site( "collections" => ["thanksgiving"] ) @site.process @drop = @site.to_liquid.site end should "respond to `key?`" do assert_respond_to @drop, :key? end should "find a key if it's in the collection of the drop" do assert @drop.key?("thanksgiving") end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/simplecov_custom_profile.rb
test/simplecov_custom_profile.rb
# frozen_string_literal: true require "simplecov" SimpleCov.profiles.define "gem" do add_filter "/test/" add_filter "/features/" add_filter "/autotest/" add_group "Binaries", "/bin/" add_group "Libraries", "/lib/" end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_tag_include.rb
test/test_tag_include.rb
# frozen_string_literal: true require "helper" class TestTagInclude < TagUnitTest context "include tag with parameters" do context "with symlink'd include" do should "not allow symlink includes" do FileUtils.mkdir_p("tmp") File.write("tmp/pages-test", "SYMLINK TEST") assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include tmp/pages-test %} CONTENT render_content(content, "safe" => true) end @result ||= "" refute_match(%r!SYMLINK TEST!, @result) end should "not expose the existence of symlinked files" do ex = assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include tmp/pages-test-does-not-exist %} CONTENT render_content(content, "safe" => true) end assert_match( "Could not locate the included file 'tmp/pages-test-does-not-exist' in any of " \ "[\"#{source_dir}/_includes\"]. Ensure it exists in one of those directories and is " \ "not a symlink as those are not allowed in safe mode.", ex.message ) end end context "with one parameter" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% include params.html param="value" %} CONTENT render_content(content) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with simple syntax but multiline markup" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% include params.html param="value" %} CONTENT render_content(content) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with variable syntax but multiline markup" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% assign path = "params" | append: ".html" %} {% include {{ path }} param="value" %} CONTENT render_content(content) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with invalid parameter syntax" do should "throw a ArgumentError" do content = <<~CONTENT --- title: Invalid parameter syntax --- {% include params.html param s="value" %} CONTENT assert_raises ArgumentError, %(Did not raise exception on invalid "include" syntax) do render_content(content) end content = <<~CONTENT --- title: Invalid parameter syntax --- {% include params.html params="value %} CONTENT assert_raises ArgumentError, %(Did not raise exception on invalid "include" syntax) do render_content(content) end end end context "with several parameters" do setup do content = <<~CONTENT --- title: multiple include parameters --- {% include params.html param1="new_value" param2="another" %} CONTENT render_content(content) end should "list all parameters" do assert_match "<li>param1 = new_value</li>", @result assert_match "<li>param2 = another</li>", @result end should "not include previously used parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "without parameters" do setup do content = <<~CONTENT --- title: without parameters --- {% include params.html %} CONTENT render_content(content) end should "include file with empty parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "with include file with special characters without params" do setup do content = <<~CONTENT --- title: special characters --- {% include params@2.0.html %} CONTENT render_content(content) end should "include file with empty parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "with include file with special characters with params" do setup do content = <<~CONTENT --- title: special characters --- {% include params@2.0.html param1="foobar" param2="bazbar" %} CONTENT render_content(content) end should "include file with empty parameters" do assert_match "<li>param1 = foobar</li>", @result assert_match "<li>param2 = bazbar</li>", @result end end context "with custom includes directory" do setup do content = <<~CONTENT --- title: custom includes directory --- {% include custom.html %} CONTENT render_content(content, "includes_dir" => "_includes_custom") end should "include file from custom directory" do assert_match "custom_included", @result end end context "without parameters within if statement" do setup do content = <<~CONTENT --- title: without parameters within if statement --- {% if true %}{% include params.html %}{% endif %} CONTENT render_content(content) end should "include file with empty parameters within if statement" do assert_match "<span id=\"include-param\"></span>", @result end end context "include missing file" do setup do @content = <<~CONTENT --- title: missing file --- {% include missing.html %} CONTENT end should "raise error relative to source directory" do exception = assert_raises IOError do render_content(@content) end assert_match( "Could not locate the included file 'missing.html' in any of " \ "[\"#{source_dir}/_includes\"].", exception.message ) end end context "include tag with variable and liquid filters" do setup do site = fixture_site.tap do |s| s.read s.render end post = site.posts.docs.find do |p| p.basename.eql? "2013-12-17-include-variable-filters.markdown" end @content = post.output end should "include file as variable with liquid filters" do assert_match(%r!1 included!, @content) assert_match(%r!2 included!, @content) assert_match(%r!3 included!, @content) end should "include file as variable and liquid filters with arbitrary whitespace" do assert_match(%r!4 included!, @content) assert_match(%r!5 included!, @content) assert_match(%r!6 included!, @content) end should "include file as variable and filters with additional parameters" do assert_match("<li>var1 = foo</li>", @content) assert_match("<li>var2 = bar</li>", @content) end should "include file as partial variable" do assert_match(%r!8 included!, @content) end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_regenerator.rb
test/test_regenerator.rb
# frozen_string_literal: true require "helper" class TestRegenerator < JekyllUnitTest context "The site regenerator" do setup do FileUtils.rm_rf(source_dir(".jekyll-metadata")) @site = fixture_site( "collections" => { "methods" => { "output" => true, }, }, "incremental" => true ) @site.read @page = @site.pages.first @post = @site.posts.first @document = @site.docs_to_write.first @asset_file = @site.pages.find(&:asset_file?) @regenerator = @site.regenerator end should "regenerate documents and assets if changed or not in metadata" do assert @regenerator.regenerate?(@page) assert @regenerator.regenerate?(@post) assert @regenerator.regenerate?(@document) assert @regenerator.regenerate?(@asset_file) end should "not regenerate if not changed" do # Process files @regenerator.regenerate?(@page) @regenerator.regenerate?(@post) @regenerator.regenerate?(@document) @regenerator.regenerate?(@asset_file) # we need to create the destinations for these files, # because regenerate? checks if the destination exists [@page, @post, @document, @asset_file].each do |item| next unless item.respond_to?(:destination) dest = item.destination(@site.dest) FileUtils.mkdir_p(File.dirname(dest)) FileUtils.touch(dest) end @regenerator.write_metadata @regenerator = Regenerator.new(@site) # these should pass, since nothing has changed, and the # loop above made sure the designations exist refute @regenerator.regenerate?(@page) refute @regenerator.regenerate?(@post) refute @regenerator.regenerate?(@document) end should "regenerate if destination missing" do # Process files @regenerator.regenerate?(@page) @regenerator.regenerate?(@post) @regenerator.regenerate?(@document) @regenerator.regenerate?(@asset_file) @regenerator.write_metadata @regenerator = Regenerator.new(@site) # make sure the files don't actually exist [@page, @post, @document, @asset_file].each do |item| if item.respond_to?(:destination) dest = item.destination(@site.dest) File.unlink(dest) if File.exist?(dest) end end # while nothing has changed, the output files were not # generated, so they still need to be regenerated assert @regenerator.regenerate?(@page) assert @regenerator.regenerate?(@post) assert @regenerator.regenerate?(@document) end should "always regenerate asset files" do assert @regenerator.regenerate?(@asset_file) end should "always regenerate objects that don't respond to :path" do assert @regenerator.regenerate?(Object.new) end end context "The site regenerator" do setup do FileUtils.rm_rf(source_dir(".jekyll-metadata")) @site = fixture_site( "incremental" => true ) @site.read @post = @site.posts.first @regenerator = @site.regenerator @regenerator.regenerate?(@post) @layout_path = source_dir("_layouts/default.html") end teardown do File.rename(@layout_path + ".tmp", @layout_path) end should "handle deleted/nonexistent dependencies" do assert_equal 1, @regenerator.metadata.size path = @regenerator.metadata.keys[0] assert_exist @layout_path @regenerator.add_dependency(path, @layout_path) File.rename(@layout_path, @layout_path + ".tmp") refute_path_exists(@layout_path) @regenerator.clear_cache assert @regenerator.regenerate?(@post) end end context "The site metadata" do setup do FileUtils.rm_rf(source_dir(".jekyll-metadata")) @site = Site.new(Jekyll.configuration( "source" => source_dir, "destination" => dest_dir, "incremental" => true )) @site.process @path = @site.in_source_dir(@site.pages.first.path) @regenerator = @site.regenerator end should "store modification times" do assert_equal File.mtime(@path), @regenerator.metadata[@path]["mtime"] end should "cache processed entries" do assert @regenerator.cache[@path] end should "clear the cache on clear_cache" do # @path will be in the cache because the # site will have processed it assert @regenerator.cache[@path] @regenerator.clear_cache expected = {} assert_equal expected, @regenerator.cache end should "write to the metadata file" do @regenerator.clear @regenerator.add(@path) @regenerator.write_metadata assert File.file?(source_dir(".jekyll-metadata")) end should "read from the metadata file" do @regenerator = Regenerator.new(@site) assert_equal File.mtime(@path), @regenerator.metadata[@path]["mtime"] end should "read legacy YAML metadata" do metadata_file = source_dir(".jekyll-metadata") @regenerator = Regenerator.new(@site) File.write(metadata_file, @regenerator.metadata.to_yaml) @regenerator = Regenerator.new(@site) assert_equal File.mtime(@path), @regenerator.metadata[@path]["mtime"] end should "not crash when reading corrupted marshal file" do metadata_file = source_dir(".jekyll-metadata") File.open(metadata_file, "w") do |file| file.puts Marshal.dump(:foo => "bar")[0, 5] end @regenerator = Regenerator.new(@site) assert_equal({}, @regenerator.metadata) end # Methods should "be able to add a path to the metadata" do @regenerator.clear @regenerator.add(@path) assert_equal File.mtime(@path), @regenerator.metadata[@path]["mtime"] assert_equal [], @regenerator.metadata[@path]["deps"] assert @regenerator.cache[@path] end should "return true on nonexistent path" do @regenerator.clear assert @regenerator.add("/bogus/path.md") assert @regenerator.modified?("/bogus/path.md") end should "be able to force a path to regenerate" do @regenerator.clear @regenerator.force(@path) assert @regenerator.cache[@path] assert @regenerator.modified?(@path) end should "be able to clear metadata and cache" do @regenerator.clear @regenerator.add(@path) assert_equal 1, @regenerator.metadata.length assert_equal 1, @regenerator.cache.length @regenerator.clear assert_equal 0, @regenerator.metadata.length assert_equal 0, @regenerator.cache.length end should "not regenerate a path if it is not modified" do @regenerator.clear @regenerator.add(@path) @regenerator.write_metadata @regenerator = Regenerator.new(@site) refute @regenerator.modified?(@path) end should "not regenerate if path in cache is false" do @regenerator.clear @regenerator.add(@path) @regenerator.write_metadata @regenerator = Regenerator.new(@site) refute @regenerator.modified?(@path) refute @regenerator.cache[@path] refute @regenerator.modified?(@path) end should "regenerate if path in not in metadata" do @regenerator.clear @regenerator.add(@path) assert @regenerator.modified?(@path) end should "regenerate if path in cache is true" do @regenerator.clear @regenerator.add(@path) assert @regenerator.modified?(@path) assert @regenerator.cache[@path] assert @regenerator.modified?(@path) end should "regenerate if file is modified" do @regenerator.clear @regenerator.add(@path) @regenerator.metadata[@path]["mtime"] = Time.at(0) @regenerator.write_metadata @regenerator = Regenerator.new(@site) refute_same File.mtime(@path), @regenerator.metadata[@path]["mtime"] assert @regenerator.modified?(@path) end should "regenerate if dependency is modified" do @regenerator.clear @regenerator.add(@path) @regenerator.write_metadata @regenerator = Regenerator.new(@site) @regenerator.add_dependency(@path, "new.dependency") assert_equal ["new.dependency"], @regenerator.metadata[@path]["deps"] assert @regenerator.modified?("new.dependency") assert @regenerator.modified?(@path) end should "not regenerate again if multiple dependencies" do multi_deps = @regenerator.metadata.select { |_k, v| v["deps"].length > 2 } multi_dep_path = multi_deps.keys.first assert @regenerator.metadata[multi_dep_path]["deps"].length > 2 assert @regenerator.modified?(multi_dep_path) @site.process @regenerator.clear_cache refute @regenerator.modified?(multi_dep_path) end should "regenerate everything if metadata is disabled" do @site.config["incremental"] = false @regenerator.clear @regenerator.add(@path) @regenerator.write_metadata @regenerator = Regenerator.new(@site) assert @regenerator.modified?(@path) end end context "when incremental regeneration is disabled" do setup do FileUtils.rm_rf(source_dir(".jekyll-metadata")) @site = Site.new(Jekyll.configuration( "source" => source_dir, "destination" => dest_dir, "incremental" => false )) @site.process @path = @site.in_source_dir(@site.pages.first.path) @regenerator = @site.regenerator end should "not create .jekyll-metadata" do refute File.file?(source_dir(".jekyll-metadata")) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_data_reader.rb
test/test_data_reader.rb
# frozen_string_literal: true require "helper" class TestDataReader < JekyllUnitTest context "#sanitize_filename" do setup do @reader = DataReader.new(fixture_site) end should "remove evil characters" do assert_equal "helpwhathaveIdone", @reader.sanitize_filename( "help/what^&$^#*(!^%*!#haveId&&&&&&&&&one" ) end end context "with no csv options set" do setup do @reader = DataReader.new(fixture_site) @parsed = [{ "id" => "1", "field_a" => "foo" }, { "id" => "2", "field_a" => "bar" }] end should "parse CSV normally" do assert_equal @parsed, @reader.read_data_file(File.expand_path("fixtures/sample.csv", __dir__)) end should "parse TSV normally" do assert_equal @parsed, @reader.read_data_file(File.expand_path("fixtures/sample.tsv", __dir__)) end end context "with csv options set" do setup do reader_config = { "csv_converters" => [:numeric], "headers" => false, } @reader = DataReader.new( fixture_site( { "csv_reader" => reader_config, "tsv_reader" => reader_config, } ) ) @parsed = [%w(id field_a), [1, "foo"], [2, "bar"]] end should "parse CSV with options" do assert_equal @parsed, @reader.read_data_file(File.expand_path("fixtures/sample.csv", __dir__)) end should "parse TSV with options" do assert_equal @parsed, @reader.read_data_file(File.expand_path("fixtures/sample.tsv", __dir__)) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_theme_assets_reader.rb
test/test_theme_assets_reader.rb
# frozen_string_literal: true require "helper" class TestThemeAssetsReader < JekyllUnitTest def setup @site = fixture_site( "theme" => "test-theme", "theme-color" => "black" ) assert @site.theme end def assert_file_with_relative_path(haystack, relative_path) assert haystack.any? { |f| f.relative_path == relative_path }, "Site should read in the #{relative_path} file, but it was not found in #{haystack.inspect}" end def refute_file_with_relative_path(haystack, relative_path) refute haystack.any? { |f| f.relative_path == relative_path }, "Site should not have read in the #{relative_path} file, but it was found in " \ "#{haystack.inspect}" end context "with a valid theme" do should "read all assets" do @site.reset ThemeAssetsReader.new(@site).read assert_file_with_relative_path @site.static_files, "/assets/img/logo.png" assert_file_with_relative_path @site.pages, "assets/style.scss" end should "convert pages" do @site.process file = @site.pages.find { |f| f.relative_path == "assets/style.scss" } refute_nil file assert_equal @site.in_dest_dir("assets/style.css"), file.destination(@site.dest) assert_includes file.output, ".sample {\n color: black;\n}" end should "not overwrite site content with the same relative path" do @site.reset @site.read file = @site.pages.find { |f| f.relative_path == "assets/application.coffee" } static_script = File.read( @site.static_files.find { |f| f.relative_path == "/assets/base.js" }.path ) refute_nil file refute_nil static_script assert_includes file.content, "alert \"From your site.\"" assert_includes static_script, "alert(\"From your site.\");" end end context "with a valid theme without an assets dir" do should "not read any assets" do site = fixture_site("theme" => "test-theme") allow(site.theme).to receive(:assets_path).and_return(nil) ThemeAssetsReader.new(site).read refute_file_with_relative_path site.static_files, "/assets/img/logo.png" refute_file_with_relative_path site.pages, "assets/style.scss" end end context "with no theme" do should "not read any assets" do site = fixture_site("theme" => nil) ThemeAssetsReader.new(site).read refute_file_with_relative_path site.static_files, "/assets/img/logo.png" refute_file_with_relative_path site.pages, "assets/style.scss" end end context "symlinked theme" do should "not read assets from symlinked theme" do skip_if_windows "Jekyll does not currently support symlinks on Windows." begin tmp_dir = Dir.mktmpdir("jekyll-theme-test") File.binwrite(File.join(tmp_dir, "test.txt"), "content") theme_dir = File.join(__dir__, "fixtures", "test-theme-symlink") File.symlink(tmp_dir, File.join(theme_dir, "assets")) site = fixture_site( "theme" => "test-theme-symlink", "theme-color" => "black" ) ThemeAssetsReader.new(site).read assert_empty site.static_files, "static file should not have been picked up" ensure FileUtils.rm_rf(tmp_dir) FileUtils.rm_rf(File.join(theme_dir, "assets")) end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_front_matter_defaults.rb
test/test_front_matter_defaults.rb
# frozen_string_literal: true require "helper" class TestFrontMatterDefaults < JekyllUnitTest context "A site with full front matter defaults" do setup do @site = fixture_site( "defaults" => [{ "scope" => { "path" => "contacts", "type" => "page", }, "values" => { "key" => "val", }, }] ) @output = capture_output { @site.process } @affected = @site.pages.find { |page| page.relative_path == "contacts/bar.html" } @not_affected = @site.pages.find { |page| page.relative_path == "about.html" } end should "affect only the specified path and type" do assert_equal "val", @affected.data["key"] assert_nil @not_affected.data["key"] end should "not call Dir.glob block" do refute_includes @output, "Globbed Scope Path:" end end context "A site with full front matter defaults (glob)" do setup do @site = fixture_site( "defaults" => [{ "scope" => { "path" => "contacts/*.html", "type" => "page", }, "values" => { "key" => "val", }, }] ) @output = capture_output { @site.process } @affected = @site.pages.find { |page| page.relative_path == "contacts/bar.html" } @not_affected = @site.pages.find { |page| page.relative_path == "about.html" } end should "affect only the specified path and type" do assert_equal "val", @affected.data["key"] assert_nil @not_affected.data["key"] end should "call Dir.glob block" do assert_includes @output, "Globbed Scope Path:" end end context "A site with front matter type pages and an extension" do setup do @site = fixture_site( "defaults" => [{ "scope" => { "path" => "index.html", }, "values" => { "key" => "val", }, }] ) @site.process @affected = @site.pages.find { |page| page.relative_path == "index.html" } @not_affected = @site.pages.find { |page| page.relative_path == "about.html" } end should "affect only the specified path" do assert_equal "val", @affected.data["key"] assert_nil @not_affected.data["key"] end end context "A site with front matter defaults with no type" do setup do @site = fixture_site( "defaults" => [{ "scope" => { "path" => "win", }, "values" => { "key" => "val", }, }] ) @site.process @affected = @site.posts.docs.find { |page| page.relative_path.include?("win") } @not_affected = @site.pages.find { |page| page.relative_path == "about.html" } end should "affect only the specified path and all types" do assert_equal "val", @affected.data["key"] assert_nil @not_affected.data["key"] end end context "A site with front matter defaults with no path and a deprecated type" do setup do @site = fixture_site( "defaults" => [{ "scope" => { "type" => "page", }, "values" => { "key" => "val", }, }] ) @site.process @affected = @site.pages @not_affected = @site.posts.docs end should "affect only the specified type and all paths" do assert_equal([], @affected.reject { |page| page.data["key"] == "val" }) assert_equal @not_affected.reject { |page| page.data["key"] == "val" }, @not_affected end end context "A site with front matter defaults with no path" do setup do @site = fixture_site( "defaults" => [{ "scope" => { "type" => "pages", }, "values" => { "key" => "val", }, }] ) @site.process @affected = @site.pages @not_affected = @site.posts.docs end should "affect only the specified type and all paths" do assert_equal([], @affected.reject { |page| page.data["key"] == "val" }) assert_equal @not_affected.reject { |page| page.data["key"] == "val" }, @not_affected end end context "A site with front matter defaults with no path or type" do setup do @site = fixture_site( "defaults" => [{ "scope" => { }, "values" => { "key" => "val", }, }] ) @site.process @affected = @site.pages @not_affected = @site.posts end should "affect all types and paths" do assert_equal([], @affected.reject { |page| page.data["key"] == "val" }) assert_equal([], @not_affected.reject { |page| page.data["key"] == "val" }) end end context "A site with front matter defaults with no scope" do setup do @site = fixture_site( "defaults" => [{ "values" => { "key" => "val", }, }] ) @site.process @affected = @site.pages @not_affected = @site.posts end should "affect all types and paths" do assert_equal([], @affected.reject { |page| page.data["key"] == "val" }) assert_equal([], @not_affected.reject { |page| page.data["key"] == "val" }) end end context "A site with front matter defaults with quoted date" do setup do @site = Site.new(Jekyll.configuration( "source" => source_dir, "destination" => dest_dir, "defaults" => [{ "values" => { "date" => "2015-01-01 00:00:01", }, }] )) end should "not raise error" do @site.process end should "parse date" do @site.process date = Time.parse("2015-01-01 00:00:01") assert(@site.pages.find { |page| page.data["date"] == date }) assert(@site.posts.find { |page| page.data["date"] == date }) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_win_tz.rb
test/test_win_tz.rb
# frozen_string_literal: true require "helper" class TestWinTz < JekyllUnitTest [["America/New_York", "WTZ+05:00"], ["Europe/Paris", "WTZ-01:00"]].each do |tz, expected| should "use base offset in winter for #{tz}" do result = Jekyll::Utils::WinTZ.calculate(tz, Time.utc(2021, 1, 1)) assert_equal expected, result end end [["America/New_York", "WTZ+04:00"], ["Europe/Paris", "WTZ-02:00"]].each do |tz, expected| should "apply DST in summer for #{tz}" do result = Jekyll::Utils::WinTZ.calculate(tz, Time.utc(2021, 7, 1)) assert_equal expected, result end end [["Australia/Eucla", "WTZ-08:45"], ["Pacific/Marquesas", "WTZ+09:30"]].each do |tz, expected| should "handle non zero minutes for #{tz}" do result = Jekyll::Utils::WinTZ.calculate(tz, Time.utc(2021, 1, 1)) assert_equal expected, result end end should "return zero for UTC" do result = Jekyll::Utils::WinTZ.calculate("UTC") assert_equal "WTZ+00:00", result end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_configuration.rb
test/test_configuration.rb
# frozen_string_literal: true require "helper" require "colorator" class TestConfiguration < JekyllUnitTest test_config = { "source" => new(nil).source_dir, "destination" => dest_dir, } context ".from" do should "create a Configuration object" do assert_instance_of Configuration, Configuration.from({}) end should "merge input over defaults" do result = Configuration.from("source" => "blah") refute_equal result["source"], Configuration::DEFAULTS["source"] assert_equal "blah", result["source"] end should "return a valid Configuration instance" do assert_instance_of Configuration, Configuration.from({}) end should "add default collections" do result = Configuration.from({}) expected = { "posts" => { "output" => true, "permalink" => "/:categories/:year/:month/:day/:title:output_ext", } } assert_equal expected, result["collections"] end should "NOT backwards-compatibilize" do assert( Configuration.from("watch" => true)["watch"], "Expected the 'watch' key to not be removed." ) end end context "the effective site configuration" do setup do @config = Configuration.from( "exclude" => %w( README.md Licence ) ) end should "always exclude node_modules" do assert_includes @config["exclude"], "node_modules" end should "always exclude Gemfile and related paths" do exclude = @config["exclude"] assert_includes exclude, "Gemfile" assert_includes exclude, "Gemfile.lock" assert_includes exclude, "gemfiles" end should "always exclude ruby vendor directories" do exclude = @config["exclude"] assert_includes exclude, "vendor/bundle/" assert_includes exclude, "vendor/cache/" assert_includes exclude, "vendor/gems/" assert_includes exclude, "vendor/ruby/" end should "always exclude default cache directories" do exclude = @config["exclude"] assert_includes exclude, ".sass-cache" assert_includes exclude, ".jekyll-cache" end end context "#add_default_collections" do should "no-op if collections is nil" do result = Configuration[{ "collections" => nil }].add_default_collections assert_nil result["collections"] end should "turn an array into a hash" do result = Configuration[{ "collections" => %w(methods) }].add_default_collections assert_instance_of Hash, result["collections"] expected = { "posts" => { "output" => true }, "methods" => {} } assert_equal expected, result["collections"] end should "only assign collections.posts.permalink if a permalink is specified" do result = Configuration[{ "permalink" => "pretty", "collections" => {} }] .add_default_collections expected = { "posts" => { "output" => true, "permalink" => "/:categories/:year/:month/:day/:title/", }, } assert_equal expected, result["collections"] result = Configuration[{ "permalink" => nil, "collections" => {} }].add_default_collections expected = { "posts" => { "output" => true } } assert_equal expected, result["collections"] end should "forces posts to output" do result = Configuration[{ "collections" => { "posts" => { "output" => false } } }] .add_default_collections assert result["collections"]["posts"]["output"] end end context "#stringify_keys" do setup do @mixed_keys = Configuration[{ "markdown" => "kramdown", :permalink => "date", "baseurl" => "/", :include => [".htaccess"], :source => "./", }] @string_keys = Configuration[{ "markdown" => "kramdown", "permalink" => "date", "baseurl" => "/", "include" => [".htaccess"], "source" => "./", }] end should "stringify symbol keys" do assert_equal @string_keys, @mixed_keys.stringify_keys end should "not mess with keys already strings" do assert_equal @string_keys, @string_keys.stringify_keys end end context "#config_files" do setup do @config = Configuration[{ "source" => source_dir }] @no_override = {} @one_config_file = { "config" => "config.yml" } @multiple_files = { "config" => %w(config/site.yml config/deploy.toml configuration.yml), } end should "always return an array" do assert_kind_of Array, @config.config_files(@no_override) assert_kind_of Array, @config.config_files(@one_config_file) assert_kind_of Array, @config.config_files(@multiple_files) end should "return the default config path if no config files are specified" do assert_equal [source_dir("_config.yml")], @config.config_files(@no_override) end should "return .yaml if it exists but .yml does not" do allow(File).to receive(:exist?).with(source_dir("_config.yml")).and_return(false) allow(File).to receive(:exist?).with(source_dir("_config.yaml")).and_return(true) assert_equal [source_dir("_config.yaml")], @config.config_files(@no_override) end should "return .yml if both .yml and .yaml exist" do allow(File).to receive(:exist?).with(source_dir("_config.yml")).and_return(true) assert_equal [source_dir("_config.yml")], @config.config_files(@no_override) end should "return .toml if that exists" do allow(File).to receive(:exist?).with(source_dir("_config.yml")).and_return(false) allow(File).to receive(:exist?).with(source_dir("_config.yaml")).and_return(false) allow(File).to receive(:exist?).with(source_dir("_config.toml")).and_return(true) assert_equal [source_dir("_config.toml")], @config.config_files(@no_override) end should "return .yml if both .yml and .toml exist" do allow(File).to receive(:exist?).with(source_dir("_config.yml")).and_return(true) allow(File).to receive(:exist?).with(source_dir("_config.toml")).and_return(true) assert_equal [source_dir("_config.yml")], @config.config_files(@no_override) end should "return the config if given one config file" do assert_equal %w(config.yml), @config.config_files(@one_config_file) end should "return an array of the config files if given many config files" do assert_equal( %w(config/site.yml config/deploy.toml configuration.yml), @config.config_files(@multiple_files) ) end end context "#read_config_file" do setup do @config = Configuration[{ "source" => source_dir("empty.yml") }] end should "not raise an error on empty files" do allow(SafeYAML).to receive(:load_file).with(File.expand_path("empty.yml")).and_return(false) Jekyll.logger.log_level = :warn @config.read_config_file("empty.yml") Jekyll.logger.log_level = :info end end context "#read_config_files" do setup do @config = Configuration[{ "source" => source_dir }] end should "continue to read config files if one is empty" do allow(SafeYAML).to receive(:load_file).with(File.expand_path("empty.yml")).and_return(false) allow(SafeYAML).to receive(:load_file).with(File.expand_path("not_empty.yml")).and_return( "foo" => "bar" ) Jekyll.logger.log_level = :warn read_config = @config.read_config_files(%w(empty.yml not_empty.yml)) Jekyll.logger.log_level = :info assert_equal "bar", read_config["foo"] end end context "#validate" do setup do @config = Configuration[{ "auto" => true, "watch" => true, "server" => true, "pygments" => true, "layouts" => true, "data_source" => true, "gems" => [], }] end should "raise an error if `exclude` key is a string" do config = Configuration[{ "exclude" => "READ-ME.md, Gemfile,CONTRIBUTING.hello.markdown" }] assert_raises(Jekyll::Errors::InvalidConfigurationError) { config.validate } end should "raise an error if `include` key is a string" do config = Configuration[{ "include" => "STOP_THE_PRESSES.txt,.heloses, .git" }] assert_raises(Jekyll::Errors::InvalidConfigurationError) { config.validate } end should "raise an error if `plugins` key is a string" do config = Configuration[{ "plugins" => "_plugin" }] assert_raises(Jekyll::Errors::InvalidConfigurationError) { config.validate } end should "not rename configuration keys" do assert @config.key?("layouts") assert @config.validate.key?("layouts") refute @config.validate.key?("layouts_dir") assert @config.key?("data_source") assert @config.validate.key?("data_source") refute @config.validate.key?("data_dir") assert @config.key?("gems") assert @config.validate.key?("gems") refute @config.validate.key?("plugins") end end context "loading configuration" do setup do @path = source_dir("_config.yml") @user_config = File.join(Dir.pwd, "my_config_file.yml") end should "fire warning with no _config.yml" do allow(SafeYAML).to receive(:load_file).with(@path) do raise SystemCallError, "No such file or directory - #{@path}" end allow($stderr).to receive(:puts).with( Colorator.yellow("Configuration file: none") ) assert_equal site_configuration, Jekyll.configuration(test_config) end should "load configuration as hash" do allow(SafeYAML).to receive(:load_file).with(@path).and_return({}) allow($stdout).to receive(:puts).with("Configuration file: #{@path}") assert_equal site_configuration, Jekyll.configuration(test_config) end should "fire warning with bad config" do allow(SafeYAML).to receive(:load_file).with(@path).and_return([]) allow($stderr) .to receive(:puts) .and_return( "WARNING: ".rjust(20) + Colorator.yellow("Error reading configuration. Using defaults (and options).") ) allow($stderr) .to receive(:puts) .and_return(Colorator.yellow("Configuration file: (INVALID) #{@path}")) assert_equal site_configuration, Jekyll.configuration(test_config) end should "fire warning when user-specified config file isn't there" do allow(SafeYAML).to receive(:load_file).with(@user_config) do raise SystemCallError, "No such file or directory - #{@user_config}" end allow($stderr) .to receive(:puts) .with(Colorator.red( "Fatal: ".rjust(20) + \ "The configuration file '#{@user_config}' could not be found." )) assert_raises LoadError do Jekyll.configuration("config" => [@user_config]) end end should "not clobber YAML.load to the dismay of other libraries" do assert_equal :foo, YAML.load(":foo") # as opposed to: assert_equal ':foo', SafeYAML.load(':foo') end end context "loading config from external file" do setup do @paths = { :default => source_dir("_config.yml"), :other => source_dir("_config.live.yml"), :toml => source_dir("_config.dev.toml"), :empty => "", } end should "load default plus posts config if no config_file is set" do allow(SafeYAML).to receive(:load_file).with(@paths[:default]).and_return({}) allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:default]}") assert_equal site_configuration, Jekyll.configuration(test_config) end should "load different config if specified" do allow(SafeYAML) .to receive(:load_file) .with(@paths[:other]) .and_return("baseurl" => "http://example.com") allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:other]}") assert_equal \ site_configuration( "baseurl" => "http://example.com", "config" => @paths[:other] ), Jekyll.configuration(test_config.merge("config" => @paths[:other])) end should "load different config if specified with symbol key" do allow(SafeYAML).to receive(:load_file).with(@paths[:default]).and_return({}) allow(SafeYAML) .to receive(:load_file) .with(@paths[:other]) .and_return("baseurl" => "http://example.com") allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:other]}") assert_equal \ site_configuration( "baseurl" => "http://example.com", "config" => @paths[:other] ), Jekyll.configuration(test_config.merge(:config => @paths[:other])) end should "load default config if path passed is empty" do allow(SafeYAML).to receive(:load_file).with(@paths[:default]).and_return({}) allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:default]}") assert_equal \ site_configuration("config" => [@paths[:empty]]), Jekyll.configuration(test_config.merge("config" => [@paths[:empty]])) end should "successfully load a TOML file" do Jekyll.logger.log_level = :warn assert_equal \ site_configuration( "baseurl" => "/you-beautiful-blog-you", "title" => "My magnificent site, wut", "config" => [@paths[:toml]] ), Jekyll.configuration(test_config.merge("config" => [@paths[:toml]])) Jekyll.logger.log_level = :info end should "load multiple config files" do External.require_with_graceful_fail("tomlrb") allow(SafeYAML).to receive(:load_file).with(@paths[:default]).and_return({}) allow(SafeYAML).to receive(:load_file).with(@paths[:other]).and_return({}) allow(Tomlrb).to receive(:load_file).with(@paths[:toml]).and_return({}) allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:default]}") allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:other]}") allow($stdout).to receive(:puts).with("Configuration file: #{@paths[:toml]}") assert_equal( site_configuration( "config" => [@paths[:default], @paths[:other], @paths[:toml]] ), Jekyll.configuration( test_config.merge( "config" => [@paths[:default], @paths[:other], @paths[:toml]] ) ) ) end should "load multiple config files and last config should win" do allow(SafeYAML) .to receive(:load_file) .with(@paths[:default]) .and_return("baseurl" => "http://example.dev") allow(SafeYAML) .to receive(:load_file) .with(@paths[:other]) .and_return("baseurl" => "http://example.com") allow($stdout) .to receive(:puts) .with("Configuration file: #{@paths[:default]}") allow($stdout) .to receive(:puts) .with("Configuration file: #{@paths[:other]}") assert_equal \ site_configuration( "baseurl" => "http://example.com", "config" => [@paths[:default], @paths[:other]] ), Jekyll.configuration( test_config.merge("config" => [@paths[:default], @paths[:other]]) ) end end context "#add_default_collections" do should "not do anything if collections is nil" do conf = Configuration[default_configuration].tap { |c| c["collections"] = nil } assert_equal conf.add_default_collections, conf assert_nil conf.add_default_collections["collections"] end should "converts collections to a hash if an array" do conf = Configuration[default_configuration].tap do |c| c["collections"] = ["docs"] end assert_equal conf.add_default_collections, conf.merge( "collections" => { "docs" => {}, "posts" => { "output" => true, "permalink" => "/:categories/:year/:month/:day/:title:output_ext", }, } ) end should "force collections.posts.output = true" do conf = Configuration[default_configuration].tap do |c| c["collections"] = { "posts" => { "output" => false } } end assert_equal conf.add_default_collections, conf.merge( "collections" => { "posts" => { "output" => true, "permalink" => "/:categories/:year/:month/:day/:title:output_ext", }, } ) end should "set collections.posts.permalink if it's not set" do conf = Configuration[default_configuration] assert_equal conf.add_default_collections, conf.merge( "collections" => { "posts" => { "output" => true, "permalink" => "/:categories/:year/:month/:day/:title:output_ext", }, } ) end should "leave collections.posts.permalink alone if it is set" do posts_permalink = "/:year/:title/" conf = Configuration[default_configuration].tap do |c| c["collections"] = { "posts" => { "permalink" => posts_permalink }, } end assert_equal conf.add_default_collections, conf.merge( "collections" => { "posts" => { "output" => true, "permalink" => posts_permalink, }, } ) end end context "folded YAML string" do setup do @tester = Configuration.new end should "ignore newlines in that string entirely from a sample file" do config = Jekyll.configuration( @tester.read_config_file( source_dir("_config_folded.yml") ) ) assert_equal( "This string of text will ignore newlines till the next key.\n", config["folded_string"] ) assert_equal( "This string of text will ignore newlines till the next key.", config["clean_folded_string"] ) end should "ignore newlines in that string entirely from the template file" do config = Jekyll.configuration( @tester.read_config_file( File.expand_path("../lib/site_template/_config.yml", File.dirname(__FILE__)) ) ) assert_includes config["description"], "an awesome description" refute_includes config["description"], "\n" end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_new_command.rb
test/test_new_command.rb
# frozen_string_literal: true require "helper" require "jekyll/commands/new" class TestNewCommand < JekyllUnitTest def dir_contents(path) Dir["#{path}/**/*"].each do |file| file.gsub! path, "" end end def site_template File.expand_path("../lib/site_template", __dir__) end def blank_template File.expand_path("../lib/blank_template", __dir__) end context "when args contains a path" do setup do @path = "new-site" @args = [@path] @full_path = File.expand_path(@path, Dir.pwd) end teardown do FileUtils.rm_r @full_path if File.directory?(@full_path) end should "create a new directory" do refute_exist @full_path capture_output { Jekyll::Commands::New.process(@args) } assert_exist @full_path end should "create a Gemfile" do gemfile = File.join(@full_path, "Gemfile") refute_exist @full_path capture_output { Jekyll::Commands::New.process(@args) } assert_exist gemfile assert_match(%r!gem "jekyll", "~> #{Jekyll::VERSION}"!o, File.read(gemfile)) assert_match(%r!gem "github-pages"!, File.read(gemfile)) end should "display a success message" do output = capture_output { Jekyll::Commands::New.process(@args) } success_message = "New jekyll site installed in #{@full_path.cyan}. " bundle_message = "Running bundle install in #{@full_path.cyan}... " assert_includes output, success_message assert_includes output, bundle_message end should "copy the static files in site template to the new directory" do static_template_files = dir_contents(site_template).reject do |f| File.extname(f) == ".erb" end static_template_files << "/Gemfile" capture_output { Jekyll::Commands::New.process(@args) } new_site_files = dir_contents(@full_path).reject do |f| f.end_with?("welcome-to-jekyll.markdown") end assert_same_elements static_template_files, new_site_files end should "process any ERB files" do erb_template_files = dir_contents(site_template).select do |f| File.extname(f) == ".erb" end stubbed_date = "2013-01-01" allow_any_instance_of(Time).to receive(:strftime) { stubbed_date } erb_template_files.each do |f| f.chomp! ".erb" f.gsub! "0000-00-00", stubbed_date end capture_output { Jekyll::Commands::New.process(@args) } new_site_files = dir_contents(@full_path).select do |f| erb_template_files.include? f end assert_same_elements erb_template_files, new_site_files end should "create blank project" do blank_contents = dir_contents(blank_template) blank_contents += %w(/_data /_drafts /_includes /_posts) output = capture_output { Jekyll::Commands::New.process(@args, "--blank") } bundle_message = "Running bundle install in #{@full_path.cyan}..." assert_same_elements blank_contents, dir_contents(@full_path) refute_includes output, bundle_message end should "force created folder" do capture_output { Jekyll::Commands::New.process(@args) } output = capture_output { Jekyll::Commands::New.process(@args, "--force") } assert_match %r!New jekyll site installed in!, output end should "skip bundle install when opted to" do output = capture_output { Jekyll::Commands::New.process(@args, "--skip-bundle") } bundle_message = "Bundle install skipped." assert_includes output, bundle_message end end context "when multiple args are given" do setup do @site_name_with_spaces = "new site name" @multiple_args = @site_name_with_spaces.split end teardown do FileUtils.rm_r File.expand_path(@site_name_with_spaces, Dir.pwd) end should "create a new directory" do refute_exist @site_name_with_spaces capture_output { Jekyll::Commands::New.process(@multiple_args) } assert_exist @site_name_with_spaces end end context "when no args are given" do setup do @empty_args = [] end should "raise an ArgumentError" do exception = assert_raises ArgumentError do Jekyll::Commands::New.process(@empty_args) end assert_equal "You must specify a path.", exception.message end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_commands_serve_servlet.rb
test/test_commands_serve_servlet.rb
# frozen_string_literal: true require "webrick" require "helper" require "net/http" class TestCommandsServeServlet < JekyllUnitTest def get(path) TestWEBrick.mount_server do |_server, addr, port| http = Net::HTTP.new(addr, port) req = Net::HTTP::Get.new(path) http.request(req) { |response| yield(response) } end end context "with a directory and file with the same name" do should "find that file" do get("/bar/") do |response| assert_equal("200", response.code) assert_equal("Content of bar.html", response.body.strip) end end should "find file in directory" do get("/bar/baz") do |response| assert_equal("200", response.code) assert_equal("Content of baz.html", response.body.strip) end end should "return 404 for non-existing files" do get("/bar/missing") do |response| assert_equal("404", response.code) end end should "find xhtml file" do get("/bar/foo") do |response| assert_equal("200", response.code) assert_equal( '<html xmlns="http://www.w3.org/1999/xhtml">Content of foo.xhtml</html>', response.body.strip ) end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_drop.rb
test/test_drop.rb
# frozen_string_literal: true require "helper" class DropFixture < Jekyll::Drops::Drop mutable true attr_accessor :lipsum def foo "bar" end def fallback_data @fallback_data ||= { "baz" => "buzz" } end end class TestDrop < JekyllUnitTest context "Drops" do setup do @site = fixture_site( "collections" => ["methods"] ) @site.process @document = @site.collections["methods"].docs.detect do |d| d.relative_path == "_methods/configuration.md" end @document_drop = @document.to_liquid @drop = DropFixture.new({}) end should "reject 'nil' key" do refute @drop.key?(nil) end should "return values for #[]" do assert_equal "bar", @drop["foo"] end should "return values for #invoke_drop" do assert_equal "bar", @drop.invoke_drop("foo") end should "return array of strings for .getter_methods" do assert(@drop.class.getter_method_names.all? { |entry| entry.is_a?(String) }) end should "return array of only getter method name strings for .getter_methods" do [:lipsum, :lipsum=].each { |id| assert_includes(@drop.class.instance_methods, id) } assert_includes @drop.class.getter_method_names, "lipsum" refute_includes @drop.class.getter_method_names, "lipsum=" end should "not munge results for another Jekyll::Drops::Drop subclass" do fixture_ids = [:lipsum, :lipsum=, :foo] fixture_getter_names = %w(lipsum foo) fixture_ids.each { |id| assert_includes(@drop.class.instance_methods, id) } fixture_getter_names.each do |name| assert_includes @drop.class.getter_method_names, name refute_includes @document_drop.class.getter_method_names, name end end should "return only getter method names for #content_methods" do drop_base_class_method_names = Jekyll::Drops::Drop.instance_methods.map(&:to_s) sample_method_names = ["lipsum=", "fallback_data", "collapse_document"] (sample_method_names + drop_base_class_method_names).each do |entry| refute_includes @drop.content_methods, entry end assert_equal %w(foo lipsum), @drop.content_methods.sort end context "mutations" do should "return mutations for #[]" do @drop["foo"] = "baz" assert_equal "baz", @drop["foo"] end should "return mutations for #invoke_drop" do @drop["foo"] = "baz" assert_equal "baz", @drop.invoke_drop("foo") end end context "a document drop" do context "fetch" do should "raise KeyError if key is not found and no default provided" do assert_raises KeyError do @document_drop.fetch("not_existing_key") end end should "fetch value without default" do assert_equal "Jekyll.configuration", @document_drop.fetch("title") end should "fetch default if key is not found" do assert_equal "default", @document_drop.fetch("not_existing_key", "default") end should "fetch default boolean value correctly" do refute @document_drop.fetch("bar", false) end should "fetch default value from block if key is not found" do assert_equal "default bar", @document_drop.fetch("bar") { |el| "default #{el}" } end should "fetch default value from block first if both argument and block given" do assert_equal "baz", @document_drop.fetch("bar", "default") { "baz" } end should "not change mutability when fetching" do assert @drop.class.mutable? @drop["foo"] = "baz" assert_equal "baz", @drop.fetch("foo") assert @drop.class.mutable? end end end context "key?" do context "a mutable drop" do should "respond true for native methods" do assert @drop.key? "foo" end should "respond true for mutable keys" do @drop["bar"] = "baz" assert @drop.key? "bar" end should "return true for fallback data" do assert @drop.key? "baz" end end context "a document drop" do should "respond true for native methods" do assert @document_drop.key? "collection" end should "return true for fallback data" do assert @document_drop.key? "title" end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/test_commands_serve.rb
test/test_commands_serve.rb
# frozen_string_literal: true require "webrick" require "mercenary" require "helper" require "httpclient" require "openssl" require "tmpdir" class TestCommandsServe < JekyllUnitTest def custom_opts(what) @cmd.send( :webrick_opts, what ) end def start_server(opts) @thread = Thread.new do merc = nil cmd = Jekyll::Commands::Serve Mercenary.program(:jekyll) do |p| merc = cmd.init_with_program(p) end merc.execute(:serve, opts) end @thread.abort_on_exception = true Jekyll::Commands::Serve.mutex.synchronize do unless Jekyll::Commands::Serve.running? Jekyll::Commands::Serve.run_cond.wait(Jekyll::Commands::Serve.mutex) end end end def serve(opts) allow(Jekyll).to receive(:configuration).and_return(opts) allow(Jekyll::Commands::Build).to receive(:process) start_server(opts) opts end context "using LiveReload" do setup do skip_if_windows "EventMachine support on Windows is limited" skip("Refinements are not fully supported in JRuby") if jruby? @temp_dir = Dir.mktmpdir("jekyll_livereload_test") @destination = File.join(@temp_dir, "_site") Dir.mkdir(@destination) || flunk("Could not make directory #{@destination}") @client = HTTPClient.new @client.connect_timeout = 5 @standard_options = { "port" => 4000, "host" => "localhost", "baseurl" => "", "detach" => false, "livereload" => true, "source" => @temp_dir, "destination" => @destination, } site = instance_double(Jekyll::Site) simple_page = <<-HTML.gsub(%r!^\s*!, "") <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Hello World</title> </head> <body> <p>Hello! I am a simple web page.</p> </body> </html> HTML File.write(File.join(@destination, "hello.html"), simple_page) allow(Jekyll::Site).to receive(:new).and_return(site) end teardown do capture_io do Jekyll::Commands::Serve.shutdown end Jekyll::Commands::Serve.mutex.synchronize do if Jekyll::Commands::Serve.running? Jekyll::Commands::Serve.run_cond.wait(Jekyll::Commands::Serve.mutex) end end FileUtils.remove_entry_secure(@temp_dir, true) end should "serve livereload.js over HTTP on the default LiveReload port" do opts = serve(@standard_options) content = @client.get_content( "http://#{opts["host"]}:#{opts["livereload_port"]}/livereload.js" ) assert_match(%r!LiveReload.on!, content) end should "serve nothing else over HTTP on the default LiveReload port" do opts = serve(@standard_options) res = @client.get("http://#{opts["host"]}:#{opts["livereload_port"]}/") assert_equal(400, res.status_code) assert_match(%r!only serves livereload.js!, res.content) end should "insert the LiveReload script tags" do opts = serve(@standard_options) content = @client.get_content( "http://#{opts["host"]}:#{opts["port"]}/#{opts["baseurl"]}/hello.html" ) assert_match( %r!livereload.js\?snipver=1&amp;port=#{opts["livereload_port"]}!, content ) assert_match(%r!I am a simple web page!, content) end should "apply the max and min delay options" do opts = serve(@standard_options.merge( "livereload_max_delay" => "1066", "livereload_min_delay" => "3" )) content = @client.get_content( "http://#{opts["host"]}:#{opts["port"]}/#{opts["baseurl"]}/hello.html" ) assert_match(%r!&amp;mindelay=3!, content) assert_match(%r!&amp;maxdelay=1066!, content) end end context "with a program" do setup do @merc = nil @cmd = Jekyll::Commands::Serve Mercenary.program(:jekyll) do |p| @merc = @cmd.init_with_program( p ) end Jekyll.sites.clear allow(SafeYAML).to receive(:load_file).and_return({}) allow(Jekyll::Commands::Build).to receive(:build).and_return("") end teardown do Jekyll.sites.clear end should "label itself" do assert_equal :serve, @merc.name end should "have aliases" do assert_includes @merc.aliases, :s assert_includes @merc.aliases, :server end should "have a description" do refute_nil( @merc.description ) end should "have an action" do refute_empty( @merc.actions ) end should "not have an empty options set" do refute_empty( @merc.options ) end context "with custom options" do should "create a default set of mimetypes" do refute_nil custom_opts({})[ :MimeTypes ] end should "use user destinations" do assert_equal "foo", custom_opts("destination" => "foo")[ :DocumentRoot ] end should "use user port" do # WHAT?!?!1 Over 9000? That's impossible. assert_equal 9001, custom_opts("port" => 9001)[ :Port ] end should "use empty directory index list when show_dir_listing is true" do opts = { "show_dir_listing" => true } assert_empty custom_opts(opts)[:DirectoryIndex] end should "keep config between build and serve" do options = { "config" => %w(_config.yml _development.yml), "serving" => true, "watch" => false, # for not having guard output when running the tests "url" => "http://localhost:4000", } config = Jekyll::Configuration.from(options) allow(Jekyll::Command).to( receive(:configuration_from_options).with(options).and_return(config) ) allow(Jekyll::Command).to( receive(:configuration_from_options).with(config).and_return(config) ) expect(Jekyll::Commands::Build).to( receive(:process).with(config).and_call_original ) expect(Jekyll::Commands::Serve).to receive(:process).with(config) @merc.execute(:serve, options) end context "in development environment" do setup do expect(Jekyll).to receive(:env).and_return("development") expect(Jekyll::Commands::Serve).to receive(:start_up_webrick) end should "set the site url by default to `http://localhost:4000`" do @merc.execute(:serve, "watch" => false, "url" => "https://jekyllrb.com/") assert_equal 1, Jekyll.sites.count assert_equal "http://localhost:4000", Jekyll.sites.first.config["url"] end should "take `host`, `port` and `ssl` into consideration if set" do @merc.execute(:serve, "watch" => false, "host" => "example.com", "port" => "9999", "url" => "https://jekyllrb.com/", "ssl_cert" => "foo", "ssl_key" => "bar") assert_equal 1, Jekyll.sites.count assert_equal "https://example.com:9999", Jekyll.sites.first.config["url"] end end context "not in development environment" do should "not update the site url" do expect(Jekyll).to receive(:env).and_return("production") expect(Jekyll::Commands::Serve).to receive(:start_up_webrick) @merc.execute(:serve, "watch" => false, "url" => "https://jekyllrb.com/") assert_equal 1, Jekyll.sites.count assert_equal "https://jekyllrb.com/", Jekyll.sites.first.config["url"] end end context "verbose" do should "debug when verbose" do assert_equal 5, custom_opts("verbose" => true)[:Logger].level end should "warn when not verbose" do assert_equal 3, custom_opts({})[:Logger].level end end context "enabling SSL" do should "raise if enabling without key or cert" do assert_raises RuntimeError do custom_opts( "ssl_key" => "foo" ) end assert_raises RuntimeError do custom_opts( "ssl_key" => "foo" ) end end should "allow SSL with a key and cert" do expect(OpenSSL::PKey::RSA).to receive(:new).and_return("c2") expect(OpenSSL::X509::Certificate).to receive(:new).and_return("c1") allow(File).to receive(:read).and_return("foo") result = custom_opts( "ssl_cert" => "foo", "source" => "bar", "enable_ssl" => true, "ssl_key" => "bar" ) assert result[:SSLEnable] assert_equal "c2", result[:SSLPrivateKey] assert_equal "c1", result[:SSLCertificate] end end end should "read `configuration` only once" do allow(Jekyll::Commands::Serve).to receive(:start_up_webrick) expect(Jekyll).to receive(:configuration).once.and_call_original @merc.execute(:serve, "watch" => false) end end context "using --detach" do setup do skip_if_windows "fork is not supported on Windows" skip("fork is not supported by JRuby") if jruby? @temp_dir = Dir.mktmpdir("jekyll_serve_detach_test") @destination = File.join(@temp_dir, "_site") Dir.mkdir(@destination) || flunk("Could not make directory #{@destination}") end teardown do FileUtils.remove_entry_secure(@temp_dir, true) end should "fork into daemon process" do process, output = Jekyll::Utils::Exec.run("jekyll", "serve", "--source", @temp_dir, "--dest", @destination, "--detach") re = %r!Server detached with pid '(?<pid>\d+)'! assert_match re, output assert_equal 0, process.exitstatus pid = re.match(output)["pid"].to_i assert pid > 1 Process.kill 9, pid end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/source/_plugins/dummy.rb
test/source/_plugins/dummy.rb
# frozen_string_literal: true module Jekyll class Dummy < Generator priority :high def generate(site) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/test/source/_plugins/custom_block.rb
test/source/_plugins/custom_block.rb
# frozen_string_literal: true # For testing excerpt handling of custom tags module Jekyll class DoNothingBlock < Liquid::Block end class DoNothingOther < Liquid::Tag end end Liquid::Template.register_tag("do_nothing", Jekyll::DoNothingBlock) Liquid::Template.register_tag("do_nothing_other", Jekyll::DoNothingOther)
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/features/step_definitions.rb
features/step_definitions.rb
# frozen_string_literal: true Before do FileUtils.rm_rf(Paths.test_dir) if Paths.test_dir.exist? FileUtils.mkdir_p(Paths.test_dir) unless Paths.test_dir.directory? Dir.chdir(Paths.test_dir) @timezone_before_scenario = ENV["TZ"] end # After do FileUtils.rm_rf(Paths.test_dir) if Paths.test_dir.exist? Paths.output_file.delete if Paths.output_file.exist? Paths.status_file.delete if Paths.status_file.exist? Dir.chdir(Paths.test_dir.parent) ENV["TZ"] = @timezone_before_scenario end # Given(%r!^I have a blank site in "(.*)"$!) do |path| unless File.exist?(path) then FileUtils.mkdir_p(path) end end # Given(%r!^I do not have a "(.*)" directory$!) do |path| Paths.test_dir.join(path).directory? end # Given(%r!^I have an? "(.*)" page(?: with (.*) "(.*)")? that contains "(.*)"$!) do |file, key, value, text| File.write(file, <<~DATA) --- #{key || "layout"}: #{value || "none"} --- #{text} DATA end # Given(%r!^I have an? "(.*)" file that contains "(.*)"$!) do |file, text| File.write(file, text) end # Given(%r!^I have an? (.*) (layout|theme) that contains "(.*)"$!) do |name, type, text| folder = type == "layout" ? "_layouts" : "_theme" destination_file = Pathname.new(File.join(folder, "#{name}.html")) FileUtils.mkdir_p(destination_file.parent) unless destination_file.parent.directory? File.write(destination_file, text) end # Given(%r!^I have an? "(.*)" file with content:$!) do |file, text| File.write(file, text) end # Given(%r!^I have an? "(.*)" page with content:$!) do |file, text| File.write(file, <<~DATA) --- --- #{text} DATA end # Given(%r!^I have an? (.*) directory$!) do |dir| unless File.directory?(dir) then FileUtils.mkdir_p(dir) end end # Given(%r!^I have the following (draft|page|post)s?(?: (in|under) "([^"]+)")?:$!) do |status, direction, folder, table| table.hashes.each do |input_hash| title = slug(input_hash["title"]) ext = input_hash["type"] || "markdown" filename = "#{title}.#{ext}" if %w(draft page).include?(status) before, after = location(folder, direction) dest_folder = "_drafts" if status == "draft" dest_folder = "_posts" if status == "post" dest_folder = "" if status == "page" if status == "post" parsed_date = Time.xmlschema(input_hash["date"]) rescue Time.parse(input_hash["date"]) input_hash["date"] = parsed_date filename = "#{parsed_date.strftime("%Y-%m-%d")}-#{title}.#{ext}" end path = File.join(before, dest_folder, after, filename) File.write(path, file_content_from_hash(input_hash)) end end # Given(%r!^I have the following (draft|post)s? within the "(.*)" directory:$!) do |type, folder, table| table.hashes.each do |input_hash| title = slug(input_hash["title"]) parsed_date = Time.xmlschema(input_hash["date"]) rescue Time.parse(input_hash["date"]) filename = type == "draft" ? "#{title}.markdown" : "#{parsed_date.strftime("%Y-%m-%d")}-#{title}.markdown" path = File.join(folder, "_#{type}s", filename) File.write(path, file_content_from_hash(input_hash)) end end # Given(%r!^I have the following documents? under the (.*) collection:$!) do |folder, table| table.hashes.each do |input_hash| title = slug(input_hash["title"]) filename = "#{title}.md" dest_folder = "_#{folder}" path = File.join(dest_folder, filename) File.write(path, file_content_from_hash(input_hash)) end end # Given(%r!^I have the following documents? under the "(.*)" collection within the "(.*)" directory:$!) do |label, dir, table| table.hashes.each do |input_hash| title = slug(input_hash["title"]) path = File.join(dir, "_#{label}", "#{title}.md") File.write(path, file_content_from_hash(input_hash)) end end # Given(%r!^I have the following documents? nested inside "(.*)" directory under the "(.*)" collection within the "(.*)" directory:$!) do |subdir, label, dir, table| table.hashes.each do |input_hash| title = slug(input_hash["title"]) path = File.join(dir, "_#{label}", subdir, "#{title}.md") File.write(path, file_content_from_hash(input_hash)) end end # Given(%r!^I have a configuration file with "(.*)" set to "(.*)"$!) do |key, value| config = \ if source_dir.join("_config.yml").exist? SafeYAML.load_file(source_dir.join("_config.yml")) else {} end config[key] = SafeYAML.load(value) Jekyll.set_timezone(value) if key == "timezone" File.write("_config.yml", YAML.dump(config)) end # Given(%r!^I have a configuration file with:$!) do |table| table.hashes.each do |row| step %(I have a configuration file with "#{row["key"]}" set to "#{row["value"]}") end end # Given(%r!^I have a configuration file with "([^\"]*)" set to:$!) do |key, table| File.open("_config.yml", "w") do |f| f.write("#{key}:\n") table.hashes.each do |row| f.write("- #{row["value"]}\n") end end end # Given(%r!^I have fixture collections(?: in "(.*)" directory)?$!) do |directory| collections_dir = File.join(source_dir, directory.to_s) FileUtils.cp_r Paths.source_dir.join("test", "source", "_methods"), collections_dir FileUtils.cp_r Paths.source_dir.join("test", "source", "_thanksgiving"), collections_dir FileUtils.cp_r Paths.source_dir.join("test", "source", "_tutorials"), collections_dir end # Given(%r!^I wait (\d+) second(s?)$!) do |time, _| sleep(time.to_f) end # When(%r!^I run jekyll(.*)$!) do |args| run_jekyll(args) if args.include?("--verbose") || ENV["DEBUG"] warn "\n#{jekyll_run_output}\n" end end # When(%r!^I run bundle(.*)$!) do |args| run_bundle(args) if args.include?("--verbose") || ENV["DEBUG"] warn "\n#{jekyll_run_output}\n" end end # When(%r!^I run gem(.*)$!) do |args| run_rubygem(args) if args.include?("--verbose") || ENV["DEBUG"] warn "\n#{jekyll_run_output}\n" end end # When(%r!^I run git add .$!) do run_in_shell("git", "add", ".", "--verbose") end # When(%r!^I decide to build the theme gem$!) do Dir.chdir(Paths.theme_gem_dir) [ "_includes/blank.html", "_sass/blank.scss", "assets/blank.scss", "_config.yml" ].each do |filename| File.new(filename, "w") end end # When(%r!^I change "(.*)" to contain "(.*)"$!) do |file, text| File.open(file, "a") do |f| f.write(text) end end # When(%r!^I delete the file "(.*)"$!) do |file| File.delete(file) end # Then(%r!^the (.*) directory should +(not )?exist$!) do |dir, negative| if negative.nil? expect(Pathname.new(dir)).to exist else expect(Pathname.new(dir)).to_not exist end end # Then(%r!^I should (not )?see "(.*)" in "(.*)"$!) do |negative, text, file| step %(the "#{file}" file should exist) regexp = Regexp.new(text, Regexp::MULTILINE) if negative.nil? || negative.empty? expect(file_contents(file)).to match regexp else expect(file_contents(file)).not_to match regexp end end # Then(%r!^I should (not )?see "(.*)" in "(.*)" if platform does not support symlinks$!) do |negative, text, file| step %(the "#{file}" file should exist) regexp = Regexp.new(text, Regexp::MULTILINE) if negative.nil? || negative.empty? if Platform.supports_symlink? expect(file_contents(file)).not_to match regexp else expect(file_contents(file)).to match regexp end end end # Then(%r!^I should (not )?see "(.*)" in "(.*)" if platform supports symlinks$!) do |negative, text, file| step %(the "#{file}" file should exist) regexp = Regexp.new(text, Regexp::MULTILINE) if negative.nil? || negative.empty? if Platform.supports_symlink? expect(file_contents(file)).to match regexp else expect(file_contents(file)).not_to match regexp end end end # Then(%r!^I should see date "(.*)" in "(.*)" unless Windows$!) do |text, file| step %(the "#{file}" file should exist) regexp = Regexp.new(text) if Jekyll::Utils::Platforms.really_windows? && !dst_active? expect(file_contents(file)).not_to match regexp else expect(file_contents(file)).to match regexp end end # Then(%r!^I should see date "(.*)" in "(.*)" if on Windows$!) do |text, file| step %(the "#{file}" file should exist) regexp = Regexp.new(text) if Jekyll::Utils::Platforms.really_windows? && !dst_active? expect(file_contents(file)).to match regexp else expect(file_contents(file)).not_to match regexp end end # Then(%r!^I should see exactly "(.*)" in "(.*)"$!) do |text, file| step %(the "#{file}" file should exist) expect(file_contents(file).strip).to eq text end # Then(%r!^I should see escaped "(.*)" in "(.*)"$!) do |text, file| step %(I should see "#{Regexp.escape(text)}" in "#{file}") end # Then(%r!^the "(.*)" file should +(not )?exist$!) do |file, negative| if negative.nil? expect(Pathname.new(file)).to exist else expect(Pathname.new(file)).to_not exist end end # Then(%r!^I should see today's time in "(.*)"$!) do |file| seconds = 3 build_time = Time.now content = file_contents(file) date_time_pattern = /(\d{4}-\d{2}-\d{2}\s\d+:\d{2}:\d{2})/ match_data = content.match(date_time_pattern) expect(match_data).not_to be_nil, "No date-time pattern found in #{file}" date_time_str = match_data.captures file_time = Time.parse("#{date_time_str}") time_difference = (build_time - file_time).abs expect(time_difference).to be <= seconds, <<~MSG Expected time in #{file} to be within #{seconds} seconds of build time. Build time: #{build_time} File time: #{file_time} Difference: #{time_difference} seconds MSG end # Then(%r!^I should see today's date in "(.*)"$!) do |file| step %(I should see "#{Date.today}" in "#{file}") end # Then(%r!^I should (not )?see "(.*)" in the build output$!) do |negative, text| if negative.nil? || negative.empty? expect(jekyll_run_output).to match Regexp.new(text) else expect(jekyll_run_output).not_to match Regexp.new(text) end end # Then(%r!^I should get an updated git index$!) do index = %w( .gitignore Gemfile LICENSE.txt README.md _config.yml _includes/blank.html _layouts/default.html _layouts/page.html _layouts/post.html _sass/blank.scss assets/blank.scss my-cool-theme.gemspec ) index.each do |file| expect(jekyll_run_output).to match file end end # Then(%r!^I should get a zero exit(?:\-| )status$!) do step %(I should see "EXIT STATUS: 0" in the build output) end # Then(%r!^I should get a non-zero exit(?:\-| )status$!) do step %(I should not see "EXIT STATUS: 0" in the build output) end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/features/support/helpers.rb
features/support/helpers.rb
# frozen_string_literal: true require "jekyll" class Paths SOURCE_DIR = Pathname.new(File.expand_path("../..", __dir__)) def self.test_dir; source_dir.join("tmp", "jekyll"); end def self.theme_gem_dir; source_dir.join("tmp", "jekyll", "my-cool-theme"); end def self.output_file; test_dir.join("jekyll_output.txt"); end def self.status_file; test_dir.join("jekyll_status.txt"); end def self.jekyll_bin; source_dir.join("exe", "jekyll"); end def self.source_dir; SOURCE_DIR; end end class Platform REF_FILE = File.expand_path("../../test/source/symlink-test/symlinked-file", __dir__) def self.supports_symlink?; File.symlink?(REF_FILE); end end # def file_content_from_hash(input_hash) matter_hash = input_hash.reject { |k, _v| k == "content" } matter = matter_hash.map { |k, v| "#{k}: #{v}\n" }.join matter.chomp! content = if input_hash["input"] && input_hash["filter"] "{{ #{input_hash["input"]} | #{input_hash["filter"]} }}" else input_hash["content"] end <<~EOF --- #{matter} --- #{content} EOF end # def source_dir(*files) Paths.test_dir(*files) end # def all_steps_to_path(path) source = source_dir dest = Pathname.new(path).expand_path paths = [] dest.ascend do |f| break if f == source paths.unshift f.to_s end paths end # def jekyll_run_output Paths.output_file.read if Paths.output_file.file? end # def jekyll_run_status Paths.status_file.read if Paths.status_file.file? end # def run_bundle(args) run_in_shell("bundle", *args.strip.split(" ")) end # def run_rubygem(args) run_in_shell("gem", *args.strip.split(" ")) end # def run_jekyll(args) args = args.strip.split(" ") # Shellwords? process = run_in_shell("ruby", Paths.jekyll_bin.to_s, *args, "--trace") process.exitstatus.zero? end # def run_in_shell(*args) p, output = Jekyll::Utils::Exec.run(*args) File.write(Paths.status_file, p.exitstatus) File.open(Paths.output_file, "wb") do |f| f.print "$ " f.puts args.join(" ") f.puts output f.puts "EXIT STATUS: #{p.exitstatus}" end p end # def slug(title = nil) if title title.downcase.gsub(%r![^\w]!, " ").strip.gsub(%r!\s+!, "-") else Time.now.strftime("%s%9N") # nanoseconds since the Epoch end end # def location(folder, direction) if folder before = folder if direction == "in" after = folder if direction == "under" end [before || ".", after || "",] end # def file_contents(path) Pathname.new(path).read end # # Helper method for Windows def dst_active? config = Jekyll.configuration("quiet" => true) ENV["TZ"] = config["timezone"] dst = Time.now.isdst # reset variable to default state on Windows ENV["TZ"] = nil dst end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/features/support/formatter.rb
features/support/formatter.rb
# frozen_string_literal: true require "cucumber/formatter/io" module Jekyll module Cucumber class Formatter include ::Cucumber::Formatter::Io def initialize(path_or_io, error_stream) @io = ensure_io(path_or_io, error_stream) @timings = {} end def before_test_case(test_case) @timings[timing_key(test_case)] = Time.now end def after_test_case(test_case) @timings[timing_key(test_case)] = Time.now - @timings[timing_key(test_case)] end def print_test_case_info(test_case) @io.print "\n#{test_case.location} #{truncate(test_case.name).inspect} " @io.flush end def print_test_case_duration(test_case) @io.print format(" (%.3fs)", @timings[timing_key(test_case)]) end def print_worst_offenders @io.puts "\n\nWorst offenders:" rows = @timings.sort_by { |_f, t| -t }.take(10).map! { |r| r[0].split(" \t ", 2).push(r[1]) } padding = rows.max_by { |r| r[0].length }.first.length + 2 rows.each { |row| @io.puts format_row_data(row, padding) } end private def format_row_data(row, padding) [ row[0].ljust(padding).rjust(padding + 2), row[1].ljust(45), format("(%.3fs)", row[2]), ].join end def timing_key(test_case) "#{test_case.location} \t #{truncate(test_case.name).inspect}" end def truncate(input, max_len: 40) str = input.to_s str.length > max_len ? "#{str[0..(max_len - 2)]}..." : str end end end end InstallPlugin do |config| progress_fmt = config.to_hash[:formats][0][0] == "progress" f = Jekyll::Cucumber::Formatter.new($stdout, $stderr) config.on_event :test_case_started do |event| test_case = event.test_case f.print_test_case_info(test_case) if progress_fmt f.before_test_case(test_case) end config.on_event :test_case_finished do |event| test_case = event.test_case f.after_test_case(test_case) f.print_test_case_duration(test_case) if progress_fmt end config.on_event :test_run_finished do f.print_worst_offenders end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/rake/task_utils/rubocop_config_formatter.rb
rake/task_utils/rubocop_config_formatter.rb
# frozen_string_literal: true require "yaml" module Jekyll module TaskUtils class RuboCopConfigFormatter def initialize(config_file) @registry = Hash.new { |hsh, k| hsh[k] = [] } @buffer = +"" @config = sort_hash_by_key(YAML.safe_load_file(config_file)) @config_file = config_file end def format! inject_banner consume :key => "inherit_from" consume :key => "require" consume :key => "AllCops", :comment => "Directive for all cops" do |key, conf| format_all_cops_config(key, conf) end consume :key => "Jekyll/NoPutsAllowed", :comment => "Configure custom cop" stream_builtin_cops File.write(@config_file, @buffer.chomp) end private def inject_banner @buffer << <<~MSG # ----------------------------------------------------------------------------- # This file has been formatted via a Rake Task configuring cops from # RuboCop v#{rubocop_version}. # # To add more cops, paste configurations at the end of the file and run # the rake task via `bundle exec rake rubocop:format_config`. # ----------------------------------------------------------------------------- MSG end def rubocop_version `bundle exec rubocop --version`.chomp end def consume(key:, comment: nil) conf = @config.delete(key) @buffer << "# #{comment}\n" if comment entry = block_given? ? yield(key, conf) : normalize_entry(key => conf) @buffer << entry @buffer << "\n" end def stream_cops_banner @buffer << <<~MSG # Configure built-in cops # ======================= MSG end def group_cops_by_department @config.each_with_object(@registry) do |(key, conf), registry| department = key.split("/", 2)[0] registry[department] << { key => conf } end end def stream_builtin_cops stream_cops_banner group_cops_by_department @registry.each do |(dept, cops)| @buffer << <<~MSG # #{dept} cops # #{"-" * 40} MSG while (entry = cops.shift) @buffer << normalize_entry(entry) end @buffer << "\n" end end def normalize_entry(entry) YAML.dump(entry).delete_prefix("---\n") end def format_all_cops_config(key, conf) all_cops_config = %w(TargetRubyVersion Include Exclude).each_with_object({}) do |k, res| res[k] = conf.delete(k) end normalize_entry(key => all_cops_config) end def sort_hash_by_key(hsh) sorted = hsh.sort_by { |key, _v| key }.to_h sorted.each_pair.with_object({}) do |(key, value), result| new_val = case value when Array value.sort when Hash sort_hash_by_key(value) else value end result[key] = new_val end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/lib/jekyll.rb
lib/jekyll.rb
# frozen_string_literal: true $LOAD_PATH.unshift __dir__ # For use/testing when no gem is installed # Require all of the Ruby files in the given directory. # # path - The String relative path from here to the directory. # # Returns nothing. def require_all(path) glob = File.join(__dir__, path, "*.rb") Dir[glob].sort.each do |f| require f end end # rubygems require "rubygems" # stdlib require "forwardable" require "fileutils" require "time" require "English" require "pathname" require "logger" require "set" require "csv" require "json" # 3rd party require "pathutil" require "addressable/uri" require "safe_yaml/load" require "liquid" require "kramdown" require "colorator" require "i18n" SafeYAML::OPTIONS[:suppress_warnings] = true module Jekyll # internal requires autoload :Cleaner, "jekyll/cleaner" autoload :Collection, "jekyll/collection" autoload :Configuration, "jekyll/configuration" autoload :Convertible, "jekyll/convertible" autoload :Deprecator, "jekyll/deprecator" autoload :Document, "jekyll/document" autoload :EntryFilter, "jekyll/entry_filter" autoload :Errors, "jekyll/errors" autoload :Excerpt, "jekyll/excerpt" autoload :PageExcerpt, "jekyll/page_excerpt" autoload :External, "jekyll/external" autoload :FrontmatterDefaults, "jekyll/frontmatter_defaults" autoload :Hooks, "jekyll/hooks" autoload :Layout, "jekyll/layout" autoload :Inclusion, "jekyll/inclusion" autoload :Cache, "jekyll/cache" autoload :CollectionReader, "jekyll/readers/collection_reader" autoload :DataReader, "jekyll/readers/data_reader" autoload :LayoutReader, "jekyll/readers/layout_reader" autoload :PostReader, "jekyll/readers/post_reader" autoload :PageReader, "jekyll/readers/page_reader" autoload :StaticFileReader, "jekyll/readers/static_file_reader" autoload :ThemeAssetsReader, "jekyll/readers/theme_assets_reader" autoload :LogAdapter, "jekyll/log_adapter" autoload :Page, "jekyll/page" autoload :PageWithoutAFile, "jekyll/page_without_a_file" autoload :PathManager, "jekyll/path_manager" autoload :PluginManager, "jekyll/plugin_manager" autoload :Publisher, "jekyll/publisher" autoload :Profiler, "jekyll/profiler" autoload :Reader, "jekyll/reader" autoload :Regenerator, "jekyll/regenerator" autoload :RelatedPosts, "jekyll/related_posts" autoload :Renderer, "jekyll/renderer" autoload :LiquidRenderer, "jekyll/liquid_renderer" autoload :Site, "jekyll/site" autoload :StaticFile, "jekyll/static_file" autoload :Stevenson, "jekyll/stevenson" autoload :Theme, "jekyll/theme" autoload :ThemeBuilder, "jekyll/theme_builder" autoload :URL, "jekyll/url" autoload :Utils, "jekyll/utils" autoload :VERSION, "jekyll/version" # extensions require "jekyll/plugin" require "jekyll/converter" require "jekyll/generator" require "jekyll/command" require "jekyll/liquid_extensions" require "jekyll/filters" class << self # Public: Tells you which Jekyll environment you are building in so you can skip tasks # if you need to. This is useful when doing expensive compression tasks on css and # images and allows you to skip that when working in development. def env ENV["JEKYLL_ENV"] || "development" end # Public: Generate a Jekyll configuration Hash by merging the default # options with anything in _config.yml, and adding the given options on top. # # override - A Hash of config directives that override any options in both # the defaults and the config file. # See Jekyll::Configuration::DEFAULTS for a # list of option names and their defaults. # # Returns the final configuration Hash. def configuration(override = {}) config = Configuration.new override = Configuration[override].stringify_keys unless override.delete("skip_config_files") config = config.read_config_files(config.config_files(override)) end # Merge DEFAULTS < _config.yml < override Configuration.from(Utils.deep_merge_hashes(config, override)).tap do |obj| set_timezone(obj["timezone"]) if obj["timezone"] end end # Public: Set the TZ environment variable to use the timezone specified # # timezone - the IANA Time Zone # # Returns nothing # rubocop:disable Naming/AccessorMethodName def set_timezone(timezone) ENV["TZ"] = if Utils::Platforms.really_windows? Utils::WinTZ.calculate(timezone) else timezone end end # rubocop:enable Naming/AccessorMethodName # Public: Fetch the logger instance for this Jekyll process. # # Returns the LogAdapter instance. def logger @logger ||= LogAdapter.new(Stevenson.new, (ENV["JEKYLL_LOG_LEVEL"] || :info).to_sym) end # Public: Set the log writer. # New log writer must respond to the same methods # as Ruby's internal Logger. # # writer - the new Logger-compatible log transport # # Returns the new logger. def logger=(writer) @logger = LogAdapter.new(writer, (ENV["JEKYLL_LOG_LEVEL"] || :info).to_sym) end # Public: An array of sites # # Returns the Jekyll sites created. def sites @sites ||= [] end # Public: Ensures the questionable path is prefixed with the base directory # and prepends the questionable path with the base directory if false. # # base_directory - the directory with which to prefix the questionable path # questionable_path - the path we're unsure about, and want prefixed # # Returns the sanitized path. def sanitized_path(base_directory, questionable_path) return base_directory if base_directory.eql?(questionable_path) return base_directory if questionable_path.nil? +Jekyll::PathManager.sanitized_path(base_directory, questionable_path) end # Conditional optimizations Jekyll::External.require_if_present("liquid/c") end end require "jekyll/drops/drop" require "jekyll/drops/document_drop" require_all "jekyll/commands" require_all "jekyll/converters" require_all "jekyll/converters/markdown" require_all "jekyll/drops" require_all "jekyll/generators" require_all "jekyll/tags" require "jekyll-sass-converter"
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/lib/jekyll/command.rb
lib/jekyll/command.rb
# frozen_string_literal: true module Jekyll class Command class << self # A list of subclasses of Jekyll::Command def subclasses @subclasses ||= [] end # Keep a list of subclasses of Jekyll::Command every time it's inherited # Called automatically. # # base - the subclass # # Returns nothing def inherited(base) subclasses << base super(base) end # Run Site#process and catch errors # # site - the Jekyll::Site object # # Returns nothing def process_site(site) site.process rescue Jekyll::Errors::FatalException => e Jekyll.logger.error "ERROR:", "YOUR SITE COULD NOT BE BUILT:" Jekyll.logger.error "", "------------------------------------" Jekyll.logger.error "", e.message exit(1) end # Create a full Jekyll configuration with the options passed in as overrides # # options - the configuration overrides # # Returns a full Jekyll configuration def configuration_from_options(options) return options if options.is_a?(Jekyll::Configuration) Jekyll.configuration(options) end # Add common options to a command for building configuration # # cmd - the Jekyll::Command to add these options to # # Returns nothing # rubocop:disable Metrics/MethodLength def add_build_options(cmd) cmd.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]", Array, "Custom configuration file" cmd.option "destination", "-d", "--destination DESTINATION", "The current folder will be generated into DESTINATION" cmd.option "source", "-s", "--source SOURCE", "Custom source directory" cmd.option "future", "--future", "Publishes posts with a future date" cmd.option "limit_posts", "--limit_posts MAX_POSTS", Integer, "Limits the number of posts to parse and publish" cmd.option "watch", "-w", "--[no-]watch", "Watch for changes and rebuild" cmd.option "baseurl", "-b", "--baseurl URL", "Serve the website from the given base URL" cmd.option "force_polling", "--force_polling", "Force watch to use polling" cmd.option "lsi", "--lsi", "Use LSI for improved related posts" cmd.option "show_drafts", "-D", "--drafts", "Render posts in the _drafts folder" cmd.option "unpublished", "--unpublished", "Render posts that were marked as unpublished" cmd.option "disable_disk_cache", "--disable-disk-cache", "Disable caching to disk in non-safe mode" cmd.option "quiet", "-q", "--quiet", "Silence output." cmd.option "verbose", "-V", "--verbose", "Print verbose output." cmd.option "incremental", "-I", "--incremental", "Enable incremental rebuild." cmd.option "strict_front_matter", "--strict_front_matter", "Fail if errors are present in front matter" end # rubocop:enable Metrics/MethodLength # Run ::process method in a given set of Jekyll::Command subclasses and suggest # re-running the associated command with --trace switch to obtain any additional # information or backtrace regarding the encountered Exception. # # cmd - the Jekyll::Command to be handled # options - configuration overrides # klass - an array of Jekyll::Command subclasses associated with the command # # Note that all exceptions are rescued.. # rubocop: disable Lint/RescueException def process_with_graceful_fail(cmd, options, *klass) klass.each { |k| k.process(options) if k.respond_to?(:process) } rescue Exception => e raise e if cmd.trace msg = " Please append `--trace` to the `#{cmd.name}` command " dashes = "-" * msg.length Jekyll.logger.error "", dashes Jekyll.logger.error "Jekyll #{Jekyll::VERSION} ", msg Jekyll.logger.error "", " for any additional information or backtrace. " Jekyll.logger.abort_with "", dashes end # rubocop: enable Lint/RescueException end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/lib/jekyll/convertible.rb
lib/jekyll/convertible.rb
# frozen_string_literal: true # Convertible provides methods for converting a pagelike item # from a certain type of markup into actual content # # Requires # self.site -> Jekyll::Site # self.content # self.content= # self.data= # self.ext= # self.output= # self.name # self.path # self.type -> :page, :post or :draft module Jekyll module Convertible # Returns the contents as a String. def to_s content || "" end # Whether the file is published or not, as indicated in YAML front-matter def published? !(data.key?("published") && data["published"] == false) end # Read the YAML frontmatter. # # base - The String path to the dir containing the file. # name - The String filename of the file. # opts - optional parameter to File.read, default at site configs # # Returns nothing. # rubocop:disable Metrics/AbcSize def read_yaml(base, name, opts = {}) filename = @path || site.in_source_dir(base, name) Jekyll.logger.debug "Reading:", relative_path begin self.content = File.read(filename, **Utils.merged_file_read_opts(site, opts)) if content =~ Document::YAML_FRONT_MATTER_REGEXP self.content = Regexp.last_match.post_match self.data = SafeYAML.load(Regexp.last_match(1)) end rescue Psych::SyntaxError => e Jekyll.logger.warn "YAML Exception reading #{filename}: #{e.message}" raise e if site.config["strict_front_matter"] rescue StandardError => e Jekyll.logger.warn "Error reading file #{filename}: #{e.message}" raise e if site.config["strict_front_matter"] end self.data ||= {} validate_data! filename validate_permalink! filename self.data end # rubocop:enable Metrics/AbcSize def validate_data!(filename) unless self.data.is_a?(Hash) raise Errors::InvalidYAMLFrontMatterError, "Invalid YAML front matter in #{filename}" end end def validate_permalink!(filename) if self.data["permalink"] == "" raise Errors::InvalidPermalinkError, "Invalid permalink in #{filename}" end end # Transform the contents based on the content type. # # Returns the transformed contents. def transform renderer.convert(content) end # Determine the extension depending on content_type. # # Returns the String extension for the output file. # e.g. ".html" for an HTML output file. def output_ext renderer.output_ext end # Determine which converter to use based on this convertible's # extension. # # Returns the Converter instance. def converters renderer.converters end # Render Liquid in the content # # content - the raw Liquid content to render # payload - the payload for Liquid # info - the info for Liquid # # Returns the converted content def render_liquid(content, payload, info, path) renderer.render_liquid(content, payload, info, path) end # Convert this Convertible's data to a Hash suitable for use by Liquid. # # Returns the Hash representation of this Convertible. def to_liquid(attrs = nil) further_data = \ (attrs || self.class::ATTRIBUTES_FOR_LIQUID).each_with_object({}) do |attribute, hsh| hsh[attribute] = send(attribute) end Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data) end # The type of a document, # i.e., its classname downcase'd and to_sym'd. # # Returns the type of self. def type :pages if is_a?(Page) end # returns the owner symbol for hook triggering def hook_owner :pages if is_a?(Page) end # Determine whether the document is an asset file. # Asset files include CoffeeScript files and Sass/SCSS files. # # Returns true if the extname belongs to the set of extensions # that asset files use. def asset_file? sass_file? || coffeescript_file? end # Determine whether the document is a Sass file. # # Returns true if extname == .sass or .scss, false otherwise. def sass_file? Jekyll::Document::SASS_FILE_EXTS.include?(ext) end # Determine whether the document is a CoffeeScript file. # # Returns true if extname == .coffee, false otherwise. def coffeescript_file? ext == ".coffee" end # Determine whether the file should be rendered with Liquid. # # Returns true if the file has Liquid Tags or Variables, false otherwise. def render_with_liquid? return false if data["render_with_liquid"] == false Jekyll::Utils.has_liquid_construct?(content) end # Determine whether the file should be placed into layouts. # # Returns false if the document is an asset file or if the front matter # specifies `layout: none` def place_in_layout? !(asset_file? || no_layout?) end # Checks if the layout specified in the document actually exists # # layout - the layout to check # # Returns true if the layout is invalid, false if otherwise def invalid_layout?(layout) !data["layout"].nil? && layout.nil? && !(is_a? Jekyll::Excerpt) end # Recursively render layouts # # layouts - a list of the layouts # payload - the payload for Liquid # info - the info for Liquid # # Returns nothing def render_all_layouts(layouts, payload, info) renderer.layouts = layouts self.output = renderer.place_in_layouts(output, payload, info) ensure @renderer = nil # this will allow the modifications above to disappear end # Add any necessary layouts to this convertible document. # # payload - The site payload Drop or Hash. # layouts - A Hash of {"name" => "layout"}. # # Returns nothing. def do_layout(payload, layouts) self.output = renderer.tap do |doc_renderer| doc_renderer.layouts = layouts doc_renderer.payload = payload end.run Jekyll.logger.debug "Post-Render Hooks:", relative_path Jekyll::Hooks.trigger hook_owner, :post_render, self ensure @renderer = nil # this will allow the modifications above to disappear end # Write the generated page file to the destination directory. # # dest - The String path to the destination dir. # # Returns nothing. def write(dest) path = destination(dest) FileUtils.mkdir_p(File.dirname(path)) Jekyll.logger.debug "Writing:", path File.write(path, output, :mode => "wb") Jekyll::Hooks.trigger hook_owner, :post_write, self end # Accessor for data properties by Liquid. # # property - The String name of the property to retrieve. # # Returns the String value or nil if the property isn't included. def [](property) if self.class::ATTRIBUTES_FOR_LIQUID.include?(property) send(property) else data[property] end end def renderer @renderer ||= Jekyll::Renderer.new(site, self) end private def defaults @defaults ||= site.frontmatter_defaults.all(relative_path, type) end def no_layout? data["layout"] == "none" end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/lib/jekyll/collection.rb
lib/jekyll/collection.rb
# frozen_string_literal: true module Jekyll class Collection attr_reader :site, :label, :metadata attr_writer :docs # Create a new Collection. # # site - the site to which this collection belongs. # label - the name of the collection # # Returns nothing. def initialize(site, label) @site = site @label = sanitize_label(label) @metadata = extract_metadata end # Fetch the Documents in this collection. # Defaults to an empty array if no documents have been read in. # # Returns an array of Jekyll::Document objects. def docs @docs ||= [] end # Override of normal respond_to? to match method_missing's logic for # looking in @data. def respond_to_missing?(method, include_private = false) docs.respond_to?(method.to_sym, include_private) || super end # Override of method_missing to check in @data for the key. def method_missing(method, *args, &blck) if docs.respond_to?(method.to_sym) Jekyll.logger.warn "Deprecation:", "#{label}.#{method} should be changed to #{label}.docs.#{method}." Jekyll.logger.warn "", "Called by #{caller(0..0)}." docs.public_send(method.to_sym, *args, &blck) else super end end # Fetch the static files in this collection. # Defaults to an empty array if no static files have been read in. # # Returns an array of Jekyll::StaticFile objects. def files @files ||= [] end # Read the allowed documents into the collection's array of docs. # # Returns the sorted array of docs. def read filtered_entries.each do |file_path| full_path = collection_dir(file_path) next if File.directory?(full_path) if Utils.has_yaml_header? full_path read_document(full_path) else read_static_file(file_path, full_path) end end site.static_files.concat(files) unless files.empty? sort_docs! end # All the entries in this collection. # # Returns an Array of file paths to the documents in this collection # relative to the collection's directory def entries return [] unless exists? @entries ||= begin collection_dir_slash = "#{collection_dir}/" Utils.safe_glob(collection_dir, ["**", "*"], File::FNM_DOTMATCH).map do |entry| entry[collection_dir_slash] = "" entry end end end # Filtered version of the entries in this collection. # See `Jekyll::EntryFilter#filter` for more information. # # Returns a list of filtered entry paths. def filtered_entries return [] unless exists? @filtered_entries ||= Dir.chdir(directory) do entry_filter.filter(entries).reject do |f| path = collection_dir(f) File.directory?(path) || entry_filter.symlink?(f) end end end # The directory for this Collection, relative to the site source or the directory # containing the collection. # # Returns a String containing the directory name where the collection # is stored on the filesystem. def relative_directory @relative_directory ||= "_#{label}" end # The full path to the directory containing the collection. # # Returns a String containing th directory name where the collection # is stored on the filesystem. def directory @directory ||= site.in_source_dir( File.join(container, relative_directory) ) end # The full path to the directory containing the collection, with # optional subpaths. # # *files - (optional) any other path pieces relative to the # directory to append to the path # # Returns a String containing th directory name where the collection # is stored on the filesystem. def collection_dir(*files) return directory if files.empty? site.in_source_dir(container, relative_directory, *files) end # Checks whether the directory "exists" for this collection. # The directory must exist on the filesystem and must not be a symlink # if in safe mode. # # Returns false if the directory doesn't exist or if it's a symlink # and we're in safe mode. def exists? File.directory?(directory) && !entry_filter.symlink?(directory) end # The entry filter for this collection. # Creates an instance of Jekyll::EntryFilter. # # Returns the instance of Jekyll::EntryFilter for this collection. def entry_filter @entry_filter ||= Jekyll::EntryFilter.new(site, relative_directory) end # An inspect string. # # Returns the inspect string def inspect "#<#{self.class} @label=#{label} docs=#{docs}>" end # Produce a sanitized label name # Label names may not contain anything but alphanumeric characters, # underscores, and hyphens. # # label - the possibly-unsafe label # # Returns a sanitized version of the label. def sanitize_label(label) label.gsub(%r![^a-z0-9_\-.]!i, "") end # Produce a representation of this Collection for use in Liquid. # Exposes two attributes: # - label # - docs # # Returns a representation of this collection for use in Liquid. def to_liquid Drops::CollectionDrop.new self end # Whether the collection's documents ought to be written as individual # files in the output. # # Returns true if the 'write' metadata is true, false otherwise. def write? !!metadata.fetch("output", false) end # The URL template to render collection's documents at. # # Returns the URL template to render collection's documents at. def url_template @url_template ||= metadata.fetch("permalink") do Utils.add_permalink_suffix("/:collection/:path", site.permalink_style) end end # Extract options for this collection from the site configuration. # # Returns the metadata for this collection def extract_metadata if site.config["collections"].is_a?(Hash) site.config["collections"][label] || {} else {} end end private def container @container ||= site.config["collections_dir"] end def read_document(full_path) doc = Document.new(full_path, :site => site, :collection => self) doc.read docs << doc if site.unpublished || doc.published? end def sort_docs! if metadata["order"].is_a?(Array) rearrange_docs! elsif metadata["sort_by"].is_a?(String) sort_docs_by_key! else docs.sort! end end # A custom sort function based on Schwartzian transform # Refer https://byparker.com/blog/2017/schwartzian-transform-faster-sorting/ for details def sort_docs_by_key! meta_key = metadata["sort_by"] # Modify `docs` array to cache document's property along with the Document instance docs.map! { |doc| [doc.data[meta_key], doc] }.sort! do |apples, olives| order = determine_sort_order(meta_key, apples, olives) # Fall back to `Document#<=>` if the properties were equal or were non-sortable # Otherwise continue with current sort-order if order.nil? || order.zero? apples[-1] <=> olives[-1] else order end # Finally restore the `docs` array with just the Document objects themselves end.map!(&:last) end def determine_sort_order(sort_key, apples, olives) apple_property, apple_document = apples olive_property, olive_document = olives if apple_property.nil? && !olive_property.nil? order_with_warning(sort_key, apple_document, 1) elsif !apple_property.nil? && olive_property.nil? order_with_warning(sort_key, olive_document, -1) else apple_property <=> olive_property end end def order_with_warning(sort_key, document, order) Jekyll.logger.warn "Sort warning:", "'#{sort_key}' not defined in #{document.relative_path}" order end # Rearrange documents within the `docs` array as listed in the `metadata["order"]` array. # # Involves converting the two arrays into hashes based on relative_paths as keys first, then # merging them to remove duplicates and finally retrieving the Document instances from the # merged array. def rearrange_docs! docs_table = {} custom_order = {} # pre-sort to normalize default array across platforms and then proceed to create a Hash # from that sorted array. docs.sort.each do |doc| docs_table[doc.relative_path] = doc end metadata["order"].each do |entry| custom_order[File.join(relative_directory, entry)] = nil end result = Jekyll::Utils.deep_merge_hashes(custom_order, docs_table).values result.compact! self.docs = result end def read_static_file(file_path, full_path) relative_dir = Jekyll.sanitized_path( relative_directory, File.dirname(file_path) ).chomp("/.") files << StaticFile.new( site, site.source, relative_dir, File.basename(full_path), self ) end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/lib/jekyll/external.rb
lib/jekyll/external.rb
# frozen_string_literal: true module Jekyll module External class << self # # Gems that, if installed, should be loaded. # Usually contain subcommands. # def blessed_gems %w( jekyll-compose jekyll-docs jekyll-import ) end # # Require a gem or file if it's present, otherwise silently fail. # # names - a string gem name or array of gem names # def require_if_present(names) Array(names).each do |name| require name rescue LoadError Jekyll.logger.debug "Couldn't load #{name}. Skipping." yield(name, version_constraint(name)) if block_given? false end end # # The version constraint required to activate a given gem. # Usually the gem version requirement is "> 0," because any version # will do. In the case of jekyll-docs, however, we require the exact # same version as Jekyll. # # Returns a String version constraint in a parseable form for # RubyGems. def version_constraint(gem_name) return "= #{Jekyll::VERSION}" if gem_name.to_s.eql?("jekyll-docs") "> 0" end # # Require a gem or gems. If it's not present, show a very nice error # message that explains everything and is much more helpful than the # normal LoadError. # # names - a string gem name or array of gem names # def require_with_graceful_fail(names) Array(names).each do |name| Jekyll.logger.debug "Requiring:", name.to_s require name rescue LoadError => e Jekyll.logger.error "Dependency Error:", <<~MSG Yikes! It looks like you don't have #{name} or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. If you've run Jekyll with `bundle exec`, ensure that you have included the #{name} gem in your Gemfile as well. The full error message from Ruby is: '#{e.message}' If you run into trouble, you can find helpful resources at https://jekyllrb.com/help/! MSG raise Jekyll::Errors::MissingDependencyException, name end end end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false
jekyll/jekyll
https://github.com/jekyll/jekyll/blob/4d3db3a83d8eaa2a844bef3f6222fd30b987af05/lib/jekyll/liquid_renderer.rb
lib/jekyll/liquid_renderer.rb
# frozen_string_literal: true require_relative "liquid_renderer/file" require_relative "liquid_renderer/table" module Jekyll class LiquidRenderer def initialize(site) @site = site Liquid::Template.error_mode = @site.config["liquid"]["error_mode"].to_sym reset end def reset @stats = {} @cache = {} end def file(filename) filename = normalize_path(filename) LiquidRenderer::File.new(self, filename).tap do @stats[filename] ||= new_profile_hash end end def increment_bytes(filename, bytes) @stats[filename][:bytes] += bytes end def increment_time(filename, time) @stats[filename][:time] += time end def increment_count(filename) @stats[filename][:count] += 1 end def stats_table(num_of_rows = 50) LiquidRenderer::Table.new(@stats).to_s(num_of_rows) end def self.format_error(error, path) "#{error.message} in #{path}" end # A persistent cache to store and retrieve parsed templates based on the filename # via `LiquidRenderer::File#parse` # # It is emptied when `self.reset` is called. def cache @cache ||= {} end private def normalize_path(filename) @normalize_path ||= {} @normalize_path[filename] ||= begin theme_dir = @site.theme&.root case filename when %r!\A(#{Regexp.escape(@site.source)}/)(?<rest>.*)!io Regexp.last_match(:rest) when %r!(/gems/.*)*/gems/(?<dirname>[^/]+)(?<rest>.*)!, %r!(?<dirname>[^/]+/lib)(?<rest>.*)! "#{Regexp.last_match(:dirname)}#{Regexp.last_match(:rest)}" when theme_dir && %r!\A#{Regexp.escape(theme_dir)}/(?<rest>.*)!io PathManager.join(@site.theme.basename, Regexp.last_match(:rest)) when %r!\A/(.*)! Regexp.last_match(1) else filename end end end def new_profile_hash Hash.new { |hash, key| hash[key] = 0 } end end end
ruby
MIT
4d3db3a83d8eaa2a844bef3f6222fd30b987af05
2026-01-04T15:37:27.237281Z
false