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 |
|---|---|---|---|---|---|---|---|---|
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/forgetable.rb | lib/devise/hooks/forgetable.rb | # frozen_string_literal: true
# Before logout hook to forget the user in the given scope, if it responds
# to forget_me! Also clear remember token to ensure the user won't be
# remembered again. Notice that we forget the user unless the record is not persisted.
# This avoids forgetting deleted users.
Warden::Manager.before_logout do |record, warden, options|
if record.respond_to?(:forget_me!)
Devise::Hooks::Proxy.new(warden).forget_me(record)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/trackable.rb | lib/devise/hooks/trackable.rb | # frozen_string_literal: true
# After each sign in, update sign in time, sign in count and sign in IP.
# This is only triggered when the user is explicitly set (with set_user)
# and on authentication. Retrieving the user from session (:fetch) does
# not trigger it.
Warden::Manager.after_set_user except: :fetch do |record, warden, options|
if record.respond_to?(:update_tracked_fields!) && warden.authenticated?(options[:scope]) && !warden.request.env['devise.skip_trackable']
record.update_tracked_fields!(warden.request)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/test/controller_helpers.rb | lib/devise/test/controller_helpers.rb | # frozen_string_literal: true
module Devise
module Test
# `Devise::Test::ControllerHelpers` provides a facility to test controllers
# in isolation when using `ActionController::TestCase` allowing you to
# quickly sign_in or sign_out a user. Do not use
# `Devise::Test::ControllerHelpers` in integration tests.
#
# Examples
#
# class PostsTest < ActionController::TestCase
# include Devise::Test::ControllerHelpers
#
# test 'authenticated users can GET index' do
# sign_in users(:bob)
#
# get :index
# assert_response :success
# end
# end
#
# Important: you should not test Warden specific behavior (like callbacks)
# using `Devise::Test::ControllerHelpers` since it is a stub of the actual
# behavior. Such callbacks should be tested in your integration suite instead.
module ControllerHelpers
extend ActiveSupport::Concern
included do
setup :setup_controller_for_warden, :warden
end
# Override process to consider warden.
def process(*)
_catch_warden { super }
@response
end
ruby2_keywords(:process) if respond_to?(:ruby2_keywords, true)
# We need to set up the environment variables and the response in the controller.
def setup_controller_for_warden #:nodoc:
@request.env['action_controller.instance'] = @controller
end
# Quick access to Warden::Proxy.
def warden #:nodoc:
@request.env['warden'] ||= begin
manager = Warden::Manager.new(nil) do |config|
config.merge! Devise.warden_config
end
Warden::Proxy.new(@request.env, manager)
end
end
# sign_in a given resource by storing its keys in the session.
# This method bypass any warden authentication callback.
#
# * +resource+ - The resource that should be authenticated
# * +scope+ - An optional +Symbol+ with the scope where the resource
# should be signed in with.
# Examples:
#
# sign_in users(:alice)
# sign_in users(:alice), scope: :admin
def sign_in(resource, scope: nil)
scope ||= Devise::Mapping.find_scope!(resource)
warden.instance_variable_get(:@users).delete(scope)
warden.session_serializer.store(resource, scope)
end
# Sign out a given resource or scope by calling logout on Warden.
# This method bypass any warden logout callback.
#
# Examples:
#
# sign_out :user # sign_out(scope)
# sign_out @user # sign_out(resource)
#
def sign_out(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
@controller.instance_variable_set(:"@current_#{scope}", nil)
user = warden.instance_variable_get(:@users).delete(scope)
warden.session_serializer.delete(scope, user)
end
protected
# Catch warden continuations and handle like the middleware would.
# Returns nil when interrupted, otherwise the normal result of the block.
def _catch_warden(&block)
result = catch(:warden, &block)
env = @controller.request.env
result ||= {}
# Set the response. In production, the rack result is returned
# from Warden::Manager#call, which the following is modelled on.
case result
when Array
if result.first == 401 && intercept_401?(env) # does this happen during testing?
_process_unauthenticated(env)
else
result
end
when Hash
_process_unauthenticated(env, result)
else
result
end
end
def _process_unauthenticated(env, options = {})
options[:action] ||= :unauthenticated
proxy = request.env['warden']
result = options[:result] || proxy.result
ret = case result
when :redirect
body = proxy.message || "You are being redirected to #{proxy.headers['Location']}"
[proxy.status, proxy.headers, [body]]
when :custom
proxy.custom_response
else
request.env["PATH_INFO"] = "/#{options[:action]}"
request.env["warden.options"] = options
Warden::Manager._run_callbacks(:before_failure, env, options)
status, headers, response = Devise.warden_config[:failure_app].call(env).to_a
@controller.response.headers.merge!(headers)
@controller.status = status
@controller.response_body = response.body
nil # causes process return @response
end
# ensure that the controller response is set up. In production, this is
# not necessary since warden returns the results to rack. However, at
# testing time, we want the response to be available to the testing
# framework to verify what would be returned to rack.
if ret.is_a?(Array)
status, headers, body = *ret
# ensure the controller response is set to our response.
@controller.response ||= @response
@response.status = status
@response.headers.merge!(headers)
@response.body = body
end
ret
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/test/integration_helpers.rb | lib/devise/test/integration_helpers.rb | # frozen_string_literal: true
module Devise
# Devise::Test::IntegrationHelpers is a helper module for facilitating
# authentication on Rails integration tests to bypass the required steps for
# signin in or signin out a record.
#
# Examples
#
# class PostsTest < ActionDispatch::IntegrationTest
# include Devise::Test::IntegrationHelpers
#
# test 'authenticated users can see posts' do
# sign_in users(:bob)
#
# get '/posts'
# assert_response :success
# end
# end
module Test
module IntegrationHelpers
def self.included(base)
base.class_eval do
include Warden::Test::Helpers
setup :setup_integration_for_devise
teardown :teardown_integration_for_devise
end
end
# Signs in a specific resource, mimicking a successful sign in
# operation through +Devise::SessionsController#create+.
#
# * +resource+ - The resource that should be authenticated
# * +scope+ - An optional +Symbol+ with the scope where the resource
# should be signed in with.
def sign_in(resource, scope: nil)
scope ||= Devise::Mapping.find_scope!(resource)
login_as(resource, scope: scope)
end
# Signs out a specific scope from the session.
#
# * +resource_or_scope+ - The resource or scope that should be signed out.
def sign_out(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
logout scope
end
protected
def setup_integration_for_devise
Warden.test_mode!
end
def teardown_integration_for_devise
Warden.test_reset!
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/lockable.rb | lib/devise/models/lockable.rb | # frozen_string_literal: true
require "devise/hooks/lockable"
module Devise
module Models
# Handles blocking a user access after a certain number of attempts.
# Lockable accepts two different strategies to unlock a user after it's
# blocked: email and time. The former will send an email to the user when
# the lock happens, containing a link to unlock its account. The second
# will unlock the user automatically after some configured time (ie 2.hours).
# It's also possible to set up lockable to use both email and time strategies.
#
# == Options
#
# Lockable adds the following options to +devise+:
#
# * +maximum_attempts+: how many attempts should be accepted before blocking the user.
# * +lock_strategy+: lock the user account by :failed_attempts or :none.
# * +unlock_strategy+: unlock the user account by :time, :email, :both or :none.
# * +unlock_in+: the time you want to unlock the user after lock happens. Only available when unlock_strategy is :time or :both.
# * +unlock_keys+: the keys you want to use when locking and unlocking an account
#
module Lockable
extend ActiveSupport::Concern
delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, to: "self.class"
def self.required_fields(klass)
attributes = []
attributes << :failed_attempts if klass.lock_strategy_enabled?(:failed_attempts)
attributes << :locked_at if klass.unlock_strategy_enabled?(:time)
attributes << :unlock_token if klass.unlock_strategy_enabled?(:email)
attributes
end
# Lock a user setting its locked_at to actual time.
# * +opts+: Hash options if you don't want to send email
# when you lock access, you could pass the next hash
# `{ send_instructions: false } as option`.
def lock_access!(opts = { })
self.locked_at = Time.now.utc
if unlock_strategy_enabled?(:email) && opts.fetch(:send_instructions, true)
send_unlock_instructions
else
save(validate: false)
end
end
# Unlock a user by cleaning locked_at and failed_attempts.
def unlock_access!
self.locked_at = nil
self.failed_attempts = 0 if respond_to?(:failed_attempts=)
self.unlock_token = nil if respond_to?(:unlock_token=)
save(validate: false)
end
# Resets failed attempts counter to 0.
def reset_failed_attempts!
if respond_to?(:failed_attempts) && !failed_attempts.to_i.zero?
self.failed_attempts = 0
save(validate: false)
end
end
# Verifies whether a user is locked or not.
def access_locked?
!!locked_at && !lock_expired?
end
# Send unlock instructions by email
def send_unlock_instructions
raw, enc = Devise.token_generator.generate(self.class, :unlock_token)
self.unlock_token = enc
save(validate: false)
send_devise_notification(:unlock_instructions, raw, {})
raw
end
# Resend the unlock instructions if the user is locked.
def resend_unlock_instructions
if_access_locked { send_unlock_instructions }
end
# Overwrites active_for_authentication? from Devise::Models::Authenticatable for locking purposes
# by verifying whether a user is active to sign in or not based on locked?
def active_for_authentication?
super && !access_locked?
end
# Overwrites invalid_message from Devise::Models::Authenticatable to define
# the correct reason for blocking the sign in.
def inactive_message
access_locked? ? :locked : super
end
# Overwrites valid_for_authentication? from Devise::Models::Authenticatable
# for verifying whether a user is allowed to sign in or not. If the user
# is locked, it should never be allowed.
def valid_for_authentication?
return super unless persisted? && lock_strategy_enabled?(:failed_attempts)
# Unlock the user if the lock is expired, no matter
# if the user can login or not (wrong password, etc)
unlock_access! if lock_expired?
if super && !access_locked?
true
else
increment_failed_attempts
if attempts_exceeded?
lock_access! unless access_locked?
else
save(validate: false)
end
false
end
end
def increment_failed_attempts
self.class.increment_counter(:failed_attempts, id)
reload
end
def unauthenticated_message
# If set to paranoid mode, do not show the locked message because it
# leaks the existence of an account.
if Devise.paranoid
super
elsif access_locked? || (lock_strategy_enabled?(:failed_attempts) && attempts_exceeded?)
:locked
elsif lock_strategy_enabled?(:failed_attempts) && last_attempt? && self.class.last_attempt_warning
:last_attempt
else
super
end
end
protected
def attempts_exceeded?
self.failed_attempts >= self.class.maximum_attempts
end
def last_attempt?
self.failed_attempts == self.class.maximum_attempts - 1
end
# Tells if the lock is expired if :time unlock strategy is active
def lock_expired?
if unlock_strategy_enabled?(:time)
locked_at && locked_at < self.class.unlock_in.ago
else
false
end
end
# Checks whether the record is locked or not, yielding to the block
# if it's locked, otherwise adds an error to email.
def if_access_locked
if access_locked?
yield
else
self.errors.add(Devise.unlock_keys.first, :not_locked)
false
end
end
module ClassMethods
# List of strategies that are enabled/supported if :both is used.
BOTH_STRATEGIES = [:time, :email]
# Attempt to find a user by its unlock keys. If a record is found, send new
# unlock instructions to it. If not user is found, returns a new user
# with an email not found error.
# Options must contain the user's unlock keys
def send_unlock_instructions(attributes = {})
lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found)
lockable.resend_unlock_instructions if lockable.persisted?
lockable
end
# Find a user by its unlock token and try to unlock it.
# If no user is found, returns a new user with an error.
# If the user is not locked, creates an error for the user
# Options must have the unlock_token
def unlock_access_by_token(unlock_token)
original_token = unlock_token
unlock_token = Devise.token_generator.digest(self, :unlock_token, unlock_token)
lockable = find_or_initialize_with_error_by(:unlock_token, unlock_token)
lockable.unlock_access! if lockable.persisted?
lockable.unlock_token = original_token
lockable
end
# Is the unlock enabled for the given unlock strategy?
def unlock_strategy_enabled?(strategy)
self.unlock_strategy == strategy ||
(self.unlock_strategy == :both && BOTH_STRATEGIES.include?(strategy))
end
# Is the lock enabled for the given lock strategy?
def lock_strategy_enabled?(strategy)
self.lock_strategy == strategy
end
Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys, :last_attempt_warning)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/validatable.rb | lib/devise/models/validatable.rb | # frozen_string_literal: true
module Devise
module Models
# Validatable creates all needed validations for a user email and password.
# It's optional, given you may want to create the validations by yourself.
# Automatically validate if the email is present, unique and its format is
# valid. Also tests presence of password, confirmation and length.
#
# == Options
#
# Validatable adds the following options to +devise+:
#
# * +email_regexp+: the regular expression used to validate e-mails;
# * +password_length+: a range expressing password length. Defaults to 6..128.
#
# Since +password_length+ is applied in a proc within `validates_length_of` it can be overridden
# at runtime.
module Validatable
# All validations used by this module.
VALIDATIONS = [:validates_presence_of, :validates_uniqueness_of, :validates_format_of,
:validates_confirmation_of, :validates_length_of].freeze
def self.required_fields(klass)
[]
end
def self.included(base)
base.extend ClassMethods
assert_validations_api!(base)
base.class_eval do
validates_presence_of :email, if: :email_required?
validates_uniqueness_of :email, allow_blank: true, case_sensitive: true, if: :devise_will_save_change_to_email?
validates_format_of :email, with: email_regexp, allow_blank: true, if: :devise_will_save_change_to_email?
validates_presence_of :password, if: :password_required?
validates_confirmation_of :password, if: :password_required?
validates_length_of :password, minimum: proc { password_length.min }, maximum: proc { password_length.max }, allow_blank: true
end
end
def self.assert_validations_api!(base) #:nodoc:
unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) }
unless unavailable_validations.empty?
raise "Could not use :validatable module since #{base} does not respond " \
"to the following methods: #{unavailable_validations.to_sentence}."
end
end
protected
# Checks whether a password is needed or not. For validations only.
# Passwords are always required if it's a new record, or if the password
# or confirmation are being set somewhere.
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
def email_required?
true
end
module ClassMethods
Devise::Models.config(self, :email_regexp, :password_length)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/rememberable.rb | lib/devise/models/rememberable.rb | # frozen_string_literal: true
require 'devise/strategies/rememberable'
require 'devise/hooks/rememberable'
require 'devise/hooks/forgetable'
module Devise
module Models
# Rememberable manages generating and clearing token for remembering the user
# from a saved cookie. Rememberable also has utility methods for dealing
# with serializing the user into the cookie and back from the cookie, trying
# to lookup the record based on the saved information.
# You probably wouldn't use rememberable methods directly, they are used
# mostly internally for handling the remember token.
#
# == Options
#
# Rememberable adds the following options to +devise+:
#
# * +remember_for+: the time you want the user will be remembered without
# asking for credentials. After this time the user will be blocked and
# will have to enter their credentials again. This configuration is also
# used to calculate the expires time for the cookie created to remember
# the user. By default remember_for is 2.weeks.
#
# * +extend_remember_period+: if true, extends the user's remember period
# when remembered via cookie. False by default.
#
# * +rememberable_options+: configuration options passed to the created cookie.
#
# == Examples
#
# User.find(1).remember_me! # regenerating the token
# User.find(1).forget_me! # clearing the token
#
# # generating info to put into cookies
# User.serialize_into_cookie(user)
#
# # lookup the user based on the incoming cookie information
# User.serialize_from_cookie(cookie_string)
module Rememberable
extend ActiveSupport::Concern
attr_accessor :remember_me
def self.required_fields(klass)
[:remember_created_at]
end
def remember_me!
self.remember_token ||= self.class.remember_token if respond_to?(:remember_token)
self.remember_created_at ||= Time.now.utc
save(validate: false) if self.changed?
end
# If the record is persisted, remove the remember token (but only if
# it exists), and save the record without validations.
def forget_me!
return unless persisted?
self.remember_token = nil if respond_to?(:remember_token)
self.remember_created_at = nil if self.class.expire_all_remember_me_on_sign_out
save(validate: false)
end
def remember_expires_at
self.class.remember_for.from_now
end
def extend_remember_period
self.class.extend_remember_period
end
def rememberable_value
if respond_to?(:remember_token)
remember_token
elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt.presence)
salt
else
raise "authenticatable_salt returned nil for the #{self.class.name} model. " \
"In order to use rememberable, you must ensure a password is always set " \
"or have a remember_token column in your model or implement your own " \
"rememberable_value in the model with custom logic."
end
end
def rememberable_options
self.class.rememberable_options
end
# A callback initiated after successfully being remembered. This can be
# used to insert your own logic that is only run after the user is
# remembered.
#
# Example:
#
# def after_remembered
# self.update_attribute(:invite_code, nil)
# end
#
def after_remembered
end
def remember_me?(token, generated_at)
# TODO: Normalize the JSON type coercion along with the Timeoutable hook
# in a single place https://github.com/heartcombo/devise/blob/ffe9d6d406e79108cf32a2c6a1d0b3828849c40b/lib/devise/hooks/timeoutable.rb#L14-L18
if generated_at.is_a?(String)
generated_at = time_from_json(generated_at)
end
# The token is only valid if:
# 1. we have a date
# 2. the current time does not pass the expiry period
# 3. the record has a remember_created_at date
# 4. the token date is bigger than the remember_created_at
# 5. the token matches
generated_at.is_a?(Time) &&
(self.class.remember_for.ago < generated_at) &&
(generated_at > (remember_created_at || Time.now).utc) &&
Devise.secure_compare(rememberable_value, token)
end
private
def time_from_json(value)
if value =~ /\A\d+\.\d+\Z/
Time.at(value.to_f)
else
Time.parse(value) rescue nil
end
end
module ClassMethods
# Create the cookie key using the record id and remember_token
def serialize_into_cookie(record)
[record.to_key, record.rememberable_value, Time.now.utc.to_f.to_s]
end
# Recreate the user based on the stored cookie
def serialize_from_cookie(*args)
id, token, generated_at = *args
record = to_adapter.get(id)
record if record && record.remember_me?(token, generated_at)
end
# Generate a token checking if one does not already exist in the database.
def remember_token #:nodoc:
loop do
token = Devise.friendly_token
break token unless to_adapter.find_first({ remember_token: token })
end
end
Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options, :expire_all_remember_me_on_sign_out)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/timeoutable.rb | lib/devise/models/timeoutable.rb | # frozen_string_literal: true
require 'devise/hooks/timeoutable'
module Devise
module Models
# Timeoutable takes care of verifying whether a user session has already
# expired or not. When a session expires after the configured time, the user
# will be asked for credentials again, it means, they will be redirected
# to the sign in page.
#
# == Options
#
# Timeoutable adds the following options to +devise+:
#
# * +timeout_in+: the interval to timeout the user session without activity.
#
# == Examples
#
# user.timedout?(30.minutes.ago)
#
module Timeoutable
extend ActiveSupport::Concern
def self.required_fields(klass)
[]
end
# Checks whether the user session has expired based on configured time.
def timedout?(last_access)
!timeout_in.nil? && last_access && last_access <= timeout_in.ago
end
def timeout_in
self.class.timeout_in
end
private
module ClassMethods
Devise::Models.config(self, :timeout_in)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/authenticatable.rb | lib/devise/models/authenticatable.rb | # frozen_string_literal: true
require 'devise/hooks/activatable'
require 'devise/hooks/csrf_cleaner'
module Devise
module Models
# Authenticatable module. Holds common settings for authentication.
#
# == Options
#
# Authenticatable adds the following options to +devise+:
#
# * +authentication_keys+: parameters used for authentication. By default [:email].
#
# * +http_authentication_key+: map the username passed via HTTP Auth to this parameter. Defaults to
# the first element in +authentication_keys+.
#
# * +request_keys+: parameters from the request object used for authentication.
# By specifying a symbol (which should be a request method), it will automatically be
# passed to find_for_authentication method and considered in your model lookup.
#
# For instance, if you set :request_keys to [:subdomain], :subdomain will be considered
# as key on authentication. This can also be a hash where the value is a boolean specifying
# if the value is required or not.
#
# * +http_authenticatable+: if this model allows http authentication. By default false.
# It also accepts an array specifying the strategies that should allow http.
#
# * +params_authenticatable+: if this model allows authentication through request params. By default true.
# It also accepts an array specifying the strategies that should allow params authentication.
#
# * +skip_session_storage+: By default Devise will store the user in session.
# By default is set to skip_session_storage: [:http_auth].
#
# == active_for_authentication?
#
# After authenticating a user and in each request, Devise checks if your model is active by
# calling model.active_for_authentication?. This method is overwritten by other devise modules. For instance,
# :confirmable overwrites .active_for_authentication? to only return true if your model was confirmed.
#
# You can overwrite this method yourself, but if you do, don't forget to call super:
#
# def active_for_authentication?
# super && special_condition_is_valid?
# end
#
# Whenever active_for_authentication? returns false, Devise asks the reason why your model is inactive using
# the inactive_message method. You can overwrite it as well:
#
# def inactive_message
# special_condition_is_valid? ? super : :special_condition_is_not_valid
# end
#
module Authenticatable
extend ActiveSupport::Concern
UNSAFE_ATTRIBUTES_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at,
:remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip,
:last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at,
:remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at]
included do
class_attribute :devise_modules, instance_writer: false
self.devise_modules ||= []
before_validation :downcase_keys
before_validation :strip_whitespace
end
def self.required_fields(klass)
[]
end
# Check if the current object is valid for authentication. This method and
# find_for_authentication are the methods used in a Warden::Strategy to check
# if a model should be signed in or not.
#
# However, you should not overwrite this method, you should overwrite active_for_authentication?
# and inactive_message instead.
def valid_for_authentication?
block_given? ? yield : true
end
def unauthenticated_message
:invalid
end
def active_for_authentication?
true
end
def inactive_message
:inactive
end
def authenticatable_salt
end
# Redefine serializable_hash in models for more secure defaults.
# By default, it removes from the serializable model all attributes that
# are *not* accessible. You can remove this default by using :force_except
# and passing a new list of attributes you want to exempt. All attributes
# given to :except will simply add names to exempt to Devise internal list.
def serializable_hash(options = nil)
options = options.try(:dup) || {}
options[:except] = Array(options[:except]).dup
if options[:force_except]
options[:except].concat Array(options[:force_except])
else
options[:except].concat UNSAFE_ATTRIBUTES_FOR_SERIALIZATION
end
super(options)
end
# Redefine inspect using serializable_hash, to ensure we don't accidentally
# leak passwords into exceptions.
def inspect
inspection = serializable_hash.collect do |k,v|
"#{k}: #{respond_to?(:attribute_for_inspect) ? attribute_for_inspect(k) : v.inspect}"
end
"#<#{self.class} #{inspection.join(", ")}>"
end
protected
def devise_mailer
Devise.mailer
end
# This is an internal method called every time Devise needs
# to send a notification/mail. This can be overridden if you
# need to customize the e-mail delivery logic. For instance,
# if you are using a queue to deliver e-mails (active job, delayed
# job, sidekiq, resque, etc), you must add the delivery to the queue
# just after the transaction was committed. To achieve this,
# you can override send_devise_notification to store the
# deliveries until the after_commit callback is triggered.
#
# The following example uses Active Job's `deliver_later` :
#
# class User
# devise :database_authenticatable, :confirmable
#
# after_commit :send_pending_devise_notifications
#
# protected
#
# def send_devise_notification(notification, *args)
# # If the record is new or changed then delay the
# # delivery until the after_commit callback otherwise
# # send now because after_commit will not be called.
# # For Rails < 6 use `changed?` instead of `saved_changes?`.
# if new_record? || saved_changes?
# pending_devise_notifications << [notification, args]
# else
# render_and_send_devise_message(notification, *args)
# end
# end
#
# private
#
# def send_pending_devise_notifications
# pending_devise_notifications.each do |notification, args|
# render_and_send_devise_message(notification, *args)
# end
#
# # Empty the pending notifications array because the
# # after_commit hook can be called multiple times which
# # could cause multiple emails to be sent.
# pending_devise_notifications.clear
# end
#
# def pending_devise_notifications
# @pending_devise_notifications ||= []
# end
#
# def render_and_send_devise_message(notification, *args)
# message = devise_mailer.send(notification, self, *args)
#
# # Deliver later with Active Job's `deliver_later`
# if message.respond_to?(:deliver_later)
# message.deliver_later
# else
# message.deliver_now
# end
# end
#
# end
#
def send_devise_notification(notification, *args)
message = devise_mailer.send(notification, self, *args)
message.deliver_now
end
def downcase_keys
self.class.case_insensitive_keys.each { |k| apply_to_attribute_or_variable(k, :downcase) }
end
def strip_whitespace
self.class.strip_whitespace_keys.each { |k| apply_to_attribute_or_variable(k, :strip) }
end
def apply_to_attribute_or_variable(attr, method)
if self[attr]
self[attr] = self[attr].try(method)
# Use respond_to? here to avoid a regression where globally
# configured strip_whitespace_keys or case_insensitive_keys were
# attempting to strip or downcase when a model didn't have the
# globally configured key.
elsif respond_to?(attr) && respond_to?("#{attr}=")
new_value = send(attr).try(method)
send("#{attr}=", new_value)
end
end
module ClassMethods
Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys,
:case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage,
:http_authentication_key)
def serialize_into_session(record)
[record.to_key, record.authenticatable_salt]
end
def serialize_from_session(key, salt)
record = to_adapter.get(key)
record if record && record.authenticatable_salt == salt
end
def params_authenticatable?(strategy)
params_authenticatable.is_a?(Array) ?
params_authenticatable.include?(strategy) : params_authenticatable
end
def http_authenticatable?(strategy)
http_authenticatable.is_a?(Array) ?
http_authenticatable.include?(strategy) : http_authenticatable
end
# Find first record based on conditions given (ie by the sign in form).
# This method is always called during an authentication process but
# it may be wrapped as well. For instance, database authenticatable
# provides a `find_for_database_authentication` that wraps a call to
# this method. This allows you to customize both database authenticatable
# or the whole authenticate stack by customize `find_for_authentication.`
#
# Overwrite to add customized conditions, create a join, or maybe use a
# namedscope to filter records while authenticating.
# Example:
#
# def self.find_for_authentication(tainted_conditions)
# find_first_by_auth_conditions(tainted_conditions, active: true)
# end
#
# Finally, notice that Devise also queries for users in other scenarios
# besides authentication, for example when retrieving a user to send
# an e-mail for password reset. In such cases, find_for_authentication
# is not called.
def find_for_authentication(tainted_conditions)
find_first_by_auth_conditions(tainted_conditions)
end
def find_first_by_auth_conditions(tainted_conditions, opts = {})
to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts))
end
# Find or initialize a record setting an error if it can't be found.
def find_or_initialize_with_error_by(attribute, value, error = :invalid) #:nodoc:
find_or_initialize_with_errors([attribute], { attribute => value }, error)
end
# Find or initialize a record with group of attributes based on a list of required attributes.
def find_or_initialize_with_errors(required_attributes, attributes, error = :invalid) #:nodoc:
attributes.try(:permit!)
attributes = attributes.to_h.with_indifferent_access
.slice(*required_attributes)
.delete_if { |key, value| value.blank? }
if attributes.size == required_attributes.size
record = find_first_by_auth_conditions(attributes) and return record
end
new(devise_parameter_filter.filter(attributes)).tap do |record|
required_attributes.each do |key|
record.errors.add(key, attributes[key].blank? ? :blank : error)
end
end
end
protected
def devise_parameter_filter
@devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys)
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/recoverable.rb | lib/devise/models/recoverable.rb | # frozen_string_literal: true
module Devise
module Models
# Recoverable takes care of resetting the user password and send reset instructions.
#
# ==Options
#
# Recoverable adds the following options to +devise+:
#
# * +reset_password_keys+: the keys you want to use when recovering the password for an account
# * +reset_password_within+: the time period within which the password must be reset or the token expires.
# * +sign_in_after_reset_password+: whether or not to sign in the user automatically after a password reset.
#
# == Examples
#
# # resets the user password and save the record, true if valid passwords are given, otherwise false
# User.find(1).reset_password('password123', 'password123')
#
# # creates a new token and send it with instructions about how to reset the password
# User.find(1).send_reset_password_instructions
#
module Recoverable
extend ActiveSupport::Concern
def self.required_fields(klass)
[:reset_password_sent_at, :reset_password_token]
end
included do
before_update :clear_reset_password_token, if: :clear_reset_password_token?
end
# Update password saving the record and clearing token. Returns true if
# the passwords are valid and the record was saved, false otherwise.
def reset_password(new_password, new_password_confirmation)
if new_password.present?
self.password = new_password
self.password_confirmation = new_password_confirmation
save
else
errors.add(:password, :blank)
false
end
end
# Resets reset password token and send reset password instructions by email.
# Returns the token sent in the e-mail.
def send_reset_password_instructions
token = set_reset_password_token
send_reset_password_instructions_notification(token)
token
end
# Checks if the reset password token sent is within the limit time.
# We do this by calculating if the difference between today and the
# sending date does not exceed the confirm in time configured.
# Returns true if the resource is not responding to reset_password_sent_at at all.
# reset_password_within is a model configuration, must always be an integer value.
#
# Example:
#
# # reset_password_within = 1.day and reset_password_sent_at = today
# reset_password_period_valid? # returns true
#
# # reset_password_within = 5.days and reset_password_sent_at = 4.days.ago
# reset_password_period_valid? # returns true
#
# # reset_password_within = 5.days and reset_password_sent_at = 5.days.ago
# reset_password_period_valid? # returns false
#
# # reset_password_within = 0.days
# reset_password_period_valid? # will always return false
#
def reset_password_period_valid?
reset_password_sent_at && reset_password_sent_at.utc >= self.class.reset_password_within.ago.utc
end
protected
# Removes reset_password token
def clear_reset_password_token
self.reset_password_token = nil
self.reset_password_sent_at = nil
end
def set_reset_password_token
raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)
self.reset_password_token = enc
self.reset_password_sent_at = Time.now.utc
save(validate: false)
raw
end
def send_reset_password_instructions_notification(token)
send_devise_notification(:reset_password_instructions, token, {})
end
def clear_reset_password_token?
encrypted_password_changed = devise_respond_to_and_will_save_change_to_attribute?(:encrypted_password)
authentication_keys_changed = self.class.authentication_keys.any? do |attribute|
devise_respond_to_and_will_save_change_to_attribute?(attribute)
end
authentication_keys_changed || encrypted_password_changed
end
module ClassMethods
# Attempt to find a user by password reset token. If a user is found, return it
# If a user is not found, return nil
def with_reset_password_token(token)
reset_password_token = Devise.token_generator.digest(self, :reset_password_token, token)
to_adapter.find_first(reset_password_token: reset_password_token)
end
# Attempt to find a user by its email. If a record is found, send new
# password instructions to it. If user is not found, returns a new user
# with an email not found error.
# Attributes must contain the user's email
def send_reset_password_instructions(attributes = {})
recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
recoverable.send_reset_password_instructions if recoverable.persisted?
recoverable
end
# Attempt to find a user by its reset_password_token to reset its
# password. If a user is found and token is still valid, reset its password and automatically
# try saving the record. If not user is found, returns a new user
# containing an error in reset_password_token attribute.
# Attributes must contain reset_password_token, password and confirmation
def reset_password_by_token(attributes = {})
original_token = attributes[:reset_password_token]
reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token)
recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token)
if recoverable.persisted?
if recoverable.reset_password_period_valid?
recoverable.reset_password(attributes[:password], attributes[:password_confirmation])
else
recoverable.errors.add(:reset_password_token, :expired)
end
end
recoverable.reset_password_token = original_token if recoverable.reset_password_token.present?
recoverable
end
Devise::Models.config(self, :reset_password_keys, :reset_password_within, :sign_in_after_reset_password)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/confirmable.rb | lib/devise/models/confirmable.rb | # frozen_string_literal: true
module Devise
module Models
# Confirmable is responsible to verify if an account is already confirmed to
# sign in, and to send emails with confirmation instructions.
# Confirmation instructions are sent to the user email after creating a
# record and when manually requested by a new confirmation instruction request.
#
# Confirmable tracks the following columns:
#
# * confirmation_token - A unique random token
# * confirmed_at - A timestamp when the user clicked the confirmation link
# * confirmation_sent_at - A timestamp when the confirmation_token was generated (not sent)
# * unconfirmed_email - An email address copied from the email attr. After confirmation
# this value is copied to the email attr then cleared
#
# == Options
#
# Confirmable adds the following options to +devise+:
#
# * +allow_unconfirmed_access_for+: the time you want to allow the user to access their account
# before confirming it. After this period, the user access is denied. You can
# use this to let your user access some features of your application without
# confirming the account, but blocking it after a certain period (ie 7 days).
# By default allow_unconfirmed_access_for is zero, it means users always have to confirm to sign in.
# * +reconfirmable+: requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field to be set up (t.reconfirmable in migrations). Until confirmed, new email is
# stored in unconfirmed email column, and copied to email column on successful
# confirmation. Also, when used in conjunction with `send_email_changed_notification`,
# the notification is sent to the original email when the change is requested,
# not when the unconfirmed email is confirmed.
# * +confirm_within+: the time before a sent confirmation token becomes invalid.
# You can use this to force the user to confirm within a set period of time.
# Confirmable will not generate a new token if a repeat confirmation is requested
# during this time frame, unless the user's email changed too.
#
# == Examples
#
# User.find(1).confirm # returns true unless it's already confirmed
# User.find(1).confirmed? # true/false
# User.find(1).send_confirmation_instructions # manually send instructions
#
module Confirmable
extend ActiveSupport::Concern
included do
before_create :generate_confirmation_token, if: :confirmation_required?
after_create :skip_reconfirmation_in_callback!, if: :send_confirmation_notification?
if Devise::Orm.active_record?(self) # ActiveRecord
after_commit :send_on_create_confirmation_instructions, on: :create, if: :send_confirmation_notification?
after_commit :send_reconfirmation_instructions, on: :update, if: :reconfirmation_required?
else # Mongoid
after_create :send_on_create_confirmation_instructions, if: :send_confirmation_notification?
after_update :send_reconfirmation_instructions, if: :reconfirmation_required?
end
before_update :postpone_email_change_until_confirmation_and_regenerate_confirmation_token, if: :postpone_email_change?
end
def initialize(*args, &block)
@bypass_confirmation_postpone = false
@skip_reconfirmation_in_callback = false
@reconfirmation_required = false
@skip_confirmation_notification = false
@raw_confirmation_token = nil
super
end
def self.required_fields(klass)
required_methods = [:confirmation_token, :confirmed_at, :confirmation_sent_at]
required_methods << :unconfirmed_email if klass.reconfirmable
required_methods
end
# Confirm a user by setting it's confirmed_at to actual time. If the user
# is already confirmed, add an error to email field. If the user is invalid
# add errors
def confirm(args = {})
pending_any_confirmation do
if confirmation_period_expired?
self.errors.add(:email, :confirmation_period_expired,
period: Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago))
return false
end
self.confirmed_at = Time.now.utc
saved = if pending_reconfirmation?
skip_reconfirmation!
self.email = unconfirmed_email
self.unconfirmed_email = nil
# We need to validate in such cases to enforce e-mail uniqueness
save(validate: true)
else
save(validate: args[:ensure_valid] == true)
end
after_confirmation if saved
saved
end
end
# Verifies whether a user is confirmed or not
def confirmed?
!!confirmed_at
end
def pending_reconfirmation?
self.class.reconfirmable && unconfirmed_email.present?
end
# Send confirmation instructions by email
def send_confirmation_instructions
unless @raw_confirmation_token
generate_confirmation_token!
end
opts = pending_reconfirmation? ? { to: unconfirmed_email } : { }
send_devise_notification(:confirmation_instructions, @raw_confirmation_token, opts)
end
def send_reconfirmation_instructions
@reconfirmation_required = false
unless @skip_confirmation_notification
send_confirmation_instructions
end
end
# Resend confirmation token.
# Regenerates the token if the period is expired.
def resend_confirmation_instructions
pending_any_confirmation do
send_confirmation_instructions
end
end
# Overwrites active_for_authentication? for confirmation
# by verifying whether a user is active to sign in or not. If the user
# is already confirmed, it should never be blocked. Otherwise we need to
# calculate if the confirm time has not expired for this user.
def active_for_authentication?
super && (!confirmation_required? || confirmed? || confirmation_period_valid?)
end
# The message to be shown if the account is inactive.
def inactive_message
!confirmed? ? :unconfirmed : super
end
# If you don't want confirmation to be sent on create, neither a code
# to be generated, call skip_confirmation!
def skip_confirmation!
self.confirmed_at = Time.now.utc
end
# Skips sending the confirmation/reconfirmation notification email after_create/after_update. Unlike
# #skip_confirmation!, record still requires confirmation.
def skip_confirmation_notification!
@skip_confirmation_notification = true
end
# If you don't want reconfirmation to be sent, neither a code
# to be generated, call skip_reconfirmation!
def skip_reconfirmation!
@bypass_confirmation_postpone = true
end
protected
# To not require reconfirmation after creating with #save called in a
# callback call skip_create_confirmation!
def skip_reconfirmation_in_callback!
@skip_reconfirmation_in_callback = true
end
# A callback method used to deliver confirmation
# instructions on creation. This can be overridden
# in models to map to a nice sign up e-mail.
def send_on_create_confirmation_instructions
send_confirmation_instructions
end
# Callback to overwrite if confirmation is required or not.
def confirmation_required?
!confirmed?
end
# Checks if the confirmation for the user is within the limit time.
# We do this by calculating if the difference between today and the
# confirmation sent date does not exceed the confirm in time configured.
# allow_unconfirmed_access_for is a model configuration, must always be an integer value.
#
# Example:
#
# # allow_unconfirmed_access_for = 1.day and confirmation_sent_at = today
# confirmation_period_valid? # returns true
#
# # allow_unconfirmed_access_for = 5.days and confirmation_sent_at = 4.days.ago
# confirmation_period_valid? # returns true
#
# # allow_unconfirmed_access_for = 5.days and confirmation_sent_at = 5.days.ago
# confirmation_period_valid? # returns false
#
# # allow_unconfirmed_access_for = 0.days
# confirmation_period_valid? # will always return false
#
# # allow_unconfirmed_access_for = nil
# confirmation_period_valid? # will always return true
#
def confirmation_period_valid?
return true if self.class.allow_unconfirmed_access_for.nil?
return false if self.class.allow_unconfirmed_access_for == 0.days
confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago
end
# Checks if the user confirmation happens before the token becomes invalid
# Examples:
#
# # confirm_within = 3.days and confirmation_sent_at = 2.days.ago
# confirmation_period_expired? # returns false
#
# # confirm_within = 3.days and confirmation_sent_at = 4.days.ago
# confirmation_period_expired? # returns true
#
# # confirm_within = nil
# confirmation_period_expired? # will always return false
#
def confirmation_period_expired?
self.class.confirm_within && self.confirmation_sent_at && (Time.now.utc > self.confirmation_sent_at.utc + self.class.confirm_within)
end
# Checks whether the record requires any confirmation.
def pending_any_confirmation
if (!confirmed? || pending_reconfirmation?)
yield
else
self.errors.add(:email, :already_confirmed)
false
end
end
# Generates a new random token for confirmation, and stores
# the time this token is being generated in confirmation_sent_at
def generate_confirmation_token
if self.confirmation_token && !confirmation_period_expired?
@raw_confirmation_token = self.confirmation_token
else
self.confirmation_token = @raw_confirmation_token = Devise.friendly_token
self.confirmation_sent_at = Time.now.utc
end
end
def generate_confirmation_token!
generate_confirmation_token && save(validate: false)
end
def postpone_email_change_until_confirmation_and_regenerate_confirmation_token
@reconfirmation_required = true
self.unconfirmed_email = self.email
self.email = self.devise_email_in_database
self.confirmation_token = nil
generate_confirmation_token
end
def postpone_email_change?
postpone = self.class.reconfirmable &&
devise_will_save_change_to_email? &&
!@bypass_confirmation_postpone &&
self.email.present? &&
(!@skip_reconfirmation_in_callback || !self.devise_email_in_database.nil?)
@bypass_confirmation_postpone = false
postpone
end
def reconfirmation_required?
self.class.reconfirmable && @reconfirmation_required && (self.email.present? || self.unconfirmed_email.present?)
end
def send_confirmation_notification?
confirmation_required? && !@skip_confirmation_notification && self.email.present?
end
# With reconfirmable, notify the original email when the user first
# requests the email change, instead of when the change is confirmed.
def send_email_changed_notification?
if self.class.reconfirmable
self.class.send_email_changed_notification && reconfirmation_required?
else
super
end
end
# A callback initiated after successfully confirming. This can be
# used to insert your own logic that is only run after the user successfully
# confirms.
#
# Example:
#
# def after_confirmation
# self.update_attribute(:invite_code, nil)
# end
#
def after_confirmation
end
module ClassMethods
# Attempt to find a user by its email. If a record is found, send new
# confirmation instructions to it. If not, try searching for a user by unconfirmed_email
# field. If no user is found, returns a new user with an email not found error.
# Options must contain the user email
def send_confirmation_instructions(attributes = {})
confirmable = find_by_unconfirmed_email_with_errors(attributes) if reconfirmable
unless confirmable.try(:persisted?)
confirmable = find_or_initialize_with_errors(confirmation_keys, attributes, :not_found)
end
confirmable.resend_confirmation_instructions if confirmable.persisted?
confirmable
end
# Find a user by its confirmation token and try to confirm it.
# If no user is found, returns a new user with an error.
# If the user is already confirmed, create an error for the user
# Options must have the confirmation_token
def confirm_by_token(confirmation_token)
# When the `confirmation_token` parameter is blank, if there are any users with a blank
# `confirmation_token` in the database, the first one would be confirmed here.
# The error is being manually added here to ensure no users are confirmed by mistake.
# This was done in the model for convenience, since validation errors are automatically
# displayed in the view.
if confirmation_token.blank?
confirmable = new
confirmable.errors.add(:confirmation_token, :blank)
return confirmable
end
confirmable = find_first_by_auth_conditions(confirmation_token: confirmation_token)
unless confirmable
confirmation_digest = Devise.token_generator.digest(self, :confirmation_token, confirmation_token)
confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_digest)
end
# TODO: replace above lines with
# confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_token)
# after enough time has passed that Devise clients do not use digested tokens
confirmable.confirm if confirmable.persisted?
confirmable
end
# Find a record for confirmation by unconfirmed email field
def find_by_unconfirmed_email_with_errors(attributes = {})
attributes = attributes.slice(*confirmation_keys).permit!.to_h if attributes.respond_to? :permit
unconfirmed_required_attributes = confirmation_keys.map { |k| k == :email ? :unconfirmed_email : k }
unconfirmed_attributes = attributes.symbolize_keys
unconfirmed_attributes[:unconfirmed_email] = unconfirmed_attributes.delete(:email)
find_or_initialize_with_errors(unconfirmed_required_attributes, unconfirmed_attributes, :not_found)
end
Devise::Models.config(self, :allow_unconfirmed_access_for, :confirmation_keys, :reconfirmable, :confirm_within)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/registerable.rb | lib/devise/models/registerable.rb | # frozen_string_literal: true
module Devise
module Models
# Registerable is responsible for everything related to registering a new
# resource (ie user sign up).
module Registerable
extend ActiveSupport::Concern
def self.required_fields(klass)
[]
end
module ClassMethods
# A convenience method that receives both parameters and session to
# initialize a user. This can be used by OAuth, for example, to send
# in the user token and be stored on initialization.
#
# By default discards all information sent by the session by calling
# new with params.
def new_with_session(params, session)
new(params)
end
Devise::Models.config(self, :sign_in_after_change_password)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/database_authenticatable.rb | lib/devise/models/database_authenticatable.rb | # frozen_string_literal: true
require 'devise/strategies/database_authenticatable'
module Devise
module Models
# Authenticatable Module, responsible for hashing the password and
# validating the authenticity of a user while signing in.
#
# This module defines a `password=` method. This method will hash the argument
# and store it in the `encrypted_password` column, bypassing any pre-existing
# `password` column if it exists.
#
# == Options
#
# DatabaseAuthenticatable adds the following options to +devise+:
#
# * +pepper+: a random string used to provide a more secure hash. Use
# `rails secret` to generate new keys.
#
# * +stretches+: the cost given to bcrypt.
#
# * +send_email_changed_notification+: notify original email when it changes.
#
# * +send_password_change_notification+: notify email when password changes.
#
# == Examples
#
# User.find(1).valid_password?('password123') # returns true/false
#
module DatabaseAuthenticatable
extend ActiveSupport::Concern
included do
after_update :send_email_changed_notification, if: :send_email_changed_notification?
after_update :send_password_change_notification, if: :send_password_change_notification?
attr_reader :password, :current_password
attr_accessor :password_confirmation
end
def initialize(*args, &block)
@skip_email_changed_notification = false
@skip_password_change_notification = false
super
end
# Skips sending the email changed notification after_update
def skip_email_changed_notification!
@skip_email_changed_notification = true
end
# Skips sending the password change notification after_update
def skip_password_change_notification!
@skip_password_change_notification = true
end
def self.required_fields(klass)
[:encrypted_password] + klass.authentication_keys
end
# Generates a hashed password based on the given value.
# For legacy reasons, we use `encrypted_password` to store
# the hashed password.
def password=(new_password)
@password = new_password
self.encrypted_password = password_digest(@password) if @password.present?
end
# Verifies whether a password (ie from sign in) is the user password.
def valid_password?(password)
Devise::Encryptor.compare(self.class, encrypted_password, password)
end
# Set password and password confirmation to nil
def clean_up_passwords
self.password = self.password_confirmation = nil
end
# Update record attributes when :current_password matches, otherwise
# returns error on :current_password.
#
# This method also rejects the password field if it is blank (allowing
# users to change relevant information like the e-mail without changing
# their password). In case the password field is rejected, the confirmation
# is also rejected as long as it is also blank.
def update_with_password(params)
current_password = params.delete(:current_password)
if params[:password].blank?
params.delete(:password)
params.delete(:password_confirmation) if params[:password_confirmation].blank?
end
result = if valid_password?(current_password)
update(params)
else
assign_attributes(params)
valid?
errors.add(:current_password, current_password.blank? ? :blank : :invalid)
false
end
clean_up_passwords
result
end
# Updates record attributes without asking for the current password.
# Never allows a change to the current password. If you are using this
# method, you should probably override this method to protect other
# attributes you would not like to be updated without a password.
#
# Example:
#
# def update_without_password(params)
# params.delete(:email)
# super(params)
# end
#
def update_without_password(params)
params.delete(:password)
params.delete(:password_confirmation)
result = update(params)
clean_up_passwords
result
end
# Destroy record when :current_password matches, otherwise returns
# error on :current_password. It also automatically rejects
# :current_password if it is blank.
def destroy_with_password(current_password)
result = if valid_password?(current_password)
destroy
else
valid?
errors.add(:current_password, current_password.blank? ? :blank : :invalid)
false
end
result
end
# A callback initiated after successfully authenticating. This can be
# used to insert your own logic that is only run after the user successfully
# authenticates.
#
# Example:
#
# def after_database_authentication
# self.update_attribute(:invite_code, nil)
# end
#
def after_database_authentication
end
# A reliable way to expose the salt regardless of the implementation.
def authenticatable_salt
encrypted_password[0,29] if encrypted_password
end
# Send notification to user when email changes.
def send_email_changed_notification
send_devise_notification(:email_changed, to: devise_email_before_last_save)
end
# Send notification to user when password changes.
def send_password_change_notification
send_devise_notification(:password_change)
end
protected
# Hashes the password using bcrypt. Custom hash functions should override
# this method to apply their own algorithm.
#
# See https://github.com/heartcombo/devise-encryptable for examples
# of other hashing engines.
def password_digest(password)
Devise::Encryptor.digest(self.class, password)
end
def send_email_changed_notification?
self.class.send_email_changed_notification && devise_saved_change_to_email? && !@skip_email_changed_notification
end
def send_password_change_notification?
self.class.send_password_change_notification && devise_saved_change_to_encrypted_password? && !@skip_password_change_notification
end
module ClassMethods
Devise::Models.config(self, :pepper, :stretches, :send_email_changed_notification, :send_password_change_notification)
# We assume this method already gets the sanitized values from the
# DatabaseAuthenticatable strategy. If you are using this method on
# your own, be sure to sanitize the conditions hash to only include
# the proper fields.
def find_for_database_authentication(conditions)
find_for_authentication(conditions)
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/omniauthable.rb | lib/devise/models/omniauthable.rb | # frozen_string_literal: true
require 'devise/omniauth'
module Devise
module Models
# Adds OmniAuth support to your model.
#
# == Options
#
# Oauthable adds the following options to +devise+:
#
# * +omniauth_providers+: Which providers are available to this model. It expects an array:
#
# devise :database_authenticatable, :omniauthable, omniauth_providers: [:twitter]
#
module Omniauthable
extend ActiveSupport::Concern
def self.required_fields(klass)
[]
end
module ClassMethods
Devise::Models.config(self, :omniauth_providers)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models/trackable.rb | lib/devise/models/trackable.rb | # frozen_string_literal: true
require 'devise/hooks/trackable'
module Devise
module Models
# Track information about your user sign in. It tracks the following columns:
#
# * sign_in_count - Increased every time a sign in is made (by form, openid, oauth)
# * current_sign_in_at - A timestamp updated when the user signs in
# * last_sign_in_at - Holds the timestamp of the previous sign in
# * current_sign_in_ip - The remote ip updated when the user sign in
# * last_sign_in_ip - Holds the remote ip of the previous sign in
#
module Trackable
def self.required_fields(klass)
[:current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count]
end
def update_tracked_fields(request)
old_current, new_current = self.current_sign_in_at, Time.now.utc
self.last_sign_in_at = old_current || new_current
self.current_sign_in_at = new_current
old_current, new_current = self.current_sign_in_ip, extract_ip_from(request)
self.last_sign_in_ip = old_current || new_current
self.current_sign_in_ip = new_current
self.sign_in_count ||= 0
self.sign_in_count += 1
end
def update_tracked_fields!(request)
# We have to check if the user is already persisted before running
# `save` here because invalid users can be saved if we don't.
# See https://github.com/heartcombo/devise/issues/4673 for more details.
return if new_record?
update_tracked_fields(request)
save(validate: false)
end
protected
def extract_ip_from(request)
request.remote_ip
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/omniauth/config.rb | lib/devise/omniauth/config.rb | # frozen_string_literal: true
module Devise
module OmniAuth
class StrategyNotFound < NameError
def initialize(strategy)
@strategy = strategy
super("Could not find a strategy with name `#{strategy}'. " \
"Please ensure it is required or explicitly set it using the :strategy_class option.")
end
end
class Config
attr_accessor :strategy
attr_reader :args, :options, :provider, :strategy_name
def initialize(provider, args)
@provider = provider
@args = args
@options = @args.last.is_a?(Hash) ? @args.last : {}
@strategy = nil
@strategy_name = options[:name] || @provider
@strategy_class = options.delete(:strategy_class)
end
def strategy_class
@strategy_class ||= find_strategy || autoload_strategy
end
def find_strategy
::OmniAuth.strategies.find do |strategy_class|
strategy_class.to_s =~ /#{::OmniAuth::Utils.camelize(strategy_name)}$/ ||
strategy_class.default_options[:name] == strategy_name
end
end
def autoload_strategy
name = ::OmniAuth::Utils.camelize(provider.to_s)
if ::OmniAuth::Strategies.const_defined?(name)
::OmniAuth::Strategies.const_get(name)
else
raise StrategyNotFound, name
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/omniauth/url_helpers.rb | lib/devise/omniauth/url_helpers.rb | # frozen_string_literal: true
module Devise
module OmniAuth
module UrlHelpers
def omniauth_authorize_path(resource_or_scope, provider, *args)
scope = Devise::Mapping.find_scope!(resource_or_scope)
_devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_path", *args)
end
def omniauth_authorize_url(resource_or_scope, provider, *args)
scope = Devise::Mapping.find_scope!(resource_or_scope)
_devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_url", *args)
end
def omniauth_callback_path(resource_or_scope, provider, *args)
scope = Devise::Mapping.find_scope!(resource_or_scope)
_devise_route_context.send("#{scope}_#{provider}_omniauth_callback_path", *args)
end
def omniauth_callback_url(resource_or_scope, provider, *args)
scope = Devise::Mapping.find_scope!(resource_or_scope)
_devise_route_context.send("#{scope}_#{provider}_omniauth_callback_url", *args)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/orm/active_record.rb | lib/devise/orm/active_record.rb | # frozen_string_literal: true
require 'orm_adapter/adapters/active_record'
ActiveSupport.on_load(:active_record) do
extend Devise::Models
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/orm/mongoid.rb | lib/devise/orm/mongoid.rb | # frozen_string_literal: true
ActiveSupport.on_load(:mongoid) do
require 'orm_adapter/adapters/mongoid'
Mongoid::Document::ClassMethods.send :include, Devise::Models
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/strategies/rememberable.rb | lib/devise/strategies/rememberable.rb | # frozen_string_literal: true
require 'devise/strategies/authenticatable'
module Devise
module Strategies
# Remember the user through the remember token. This strategy is responsible
# to verify whether there is a cookie with the remember token, and to
# recreate the user from this cookie if it exists. Must be called *before*
# authenticatable.
class Rememberable < Authenticatable
# A valid strategy for rememberable needs a remember token in the cookies.
def valid?
@remember_cookie = nil
remember_cookie.present?
end
# To authenticate a user we deserialize the cookie and attempt finding
# the record in the database. If the attempt fails, we pass to another
# strategy handle the authentication.
def authenticate!
resource = mapping.to.serialize_from_cookie(*remember_cookie)
unless resource
cookies.delete(remember_key)
return pass
end
if validate(resource)
remember_me(resource) if extend_remember_me?(resource)
resource.after_remembered
success!(resource)
end
end
# No need to clean up the CSRF when using rememberable.
# In fact, cleaning it up here would be a bug because
# rememberable is triggered on GET requests which means
# we would render a page on first access with all csrf
# tokens expired.
def clean_up_csrf?
false
end
private
def extend_remember_me?(resource)
resource.respond_to?(:extend_remember_period) && resource.extend_remember_period
end
def remember_me?
true
end
def remember_key
mapping.to.rememberable_options.fetch(:key, "remember_#{scope}_token")
end
def remember_cookie
@remember_cookie ||= cookies.signed[remember_key]
end
end
end
end
Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable)
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/strategies/base.rb | lib/devise/strategies/base.rb | # frozen_string_literal: true
module Devise
module Strategies
# Base strategy for Devise. Responsible for verifying correct scope and mapping.
class Base < ::Warden::Strategies::Base
# Whenever CSRF cannot be verified, we turn off any kind of storage
def store?
!env["devise.skip_storage"]
end
# Checks if a valid scope was given for devise and find mapping based on this scope.
def mapping
@mapping ||= begin
mapping = Devise.mappings[scope]
raise "Could not find mapping for #{scope}" unless mapping
mapping
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/strategies/authenticatable.rb | lib/devise/strategies/authenticatable.rb | # frozen_string_literal: true
require 'devise/strategies/base'
module Devise
module Strategies
# This strategy should be used as basis for authentication strategies. It retrieves
# parameters both from params or from http authorization headers. See database_authenticatable
# for an example.
class Authenticatable < Base
attr_accessor :authentication_hash, :authentication_type, :password
def store?
super && !mapping.to.skip_session_storage.include?(authentication_type)
end
def valid?
valid_for_params_auth? || valid_for_http_auth?
end
# Override and set to false for things like OmniAuth that technically
# run through Authentication (user_set) very often, which would normally
# reset CSRF data in the session
def clean_up_csrf?
true
end
private
# Receives a resource and check if it is valid by calling valid_for_authentication?
# A block that will be triggered while validating can be optionally
# given as parameter. Check Devise::Models::Authenticatable.valid_for_authentication?
# for more information.
#
# In case the resource can't be validated, it will fail with the given
# unauthenticated_message.
def validate(resource, &block)
result = resource && resource.valid_for_authentication?(&block)
if result
true
else
if resource
fail!(resource.unauthenticated_message)
end
false
end
end
# Get values from params and set in the resource.
def remember_me(resource)
resource.remember_me = remember_me? if resource.respond_to?(:remember_me=)
end
# Should this resource be marked to be remembered?
def remember_me?
valid_params? && Devise::TRUE_VALUES.include?(params_auth_hash[:remember_me])
end
# Check if this is a valid strategy for http authentication by:
#
# * Validating if the model allows http authentication;
# * If any of the authorization headers were sent;
# * If all authentication keys are present;
#
def valid_for_http_auth?
http_authenticatable? && request.authorization && with_authentication_hash(:http_auth, http_auth_hash)
end
# Check if this is a valid strategy for params authentication by:
#
# * Validating if the model allows params authentication;
# * If the request hits the sessions controller through POST;
# * If the params[scope] returns a hash with credentials;
# * If all authentication keys are present;
#
def valid_for_params_auth?
params_authenticatable? && valid_params_request? &&
valid_params? && with_authentication_hash(:params_auth, params_auth_hash)
end
# Check if the model accepts this strategy as http authenticatable.
def http_authenticatable?
mapping.to.http_authenticatable?(authenticatable_name)
end
# Check if the model accepts this strategy as params authenticatable.
def params_authenticatable?
mapping.to.params_authenticatable?(authenticatable_name)
end
# Extract the appropriate subhash for authentication from params.
def params_auth_hash
params[scope]
end
# Extract a hash with attributes:values from the http params.
def http_auth_hash
keys = [http_authentication_key, :password]
Hash[*keys.zip(decode_credentials).flatten]
end
# By default, a request is valid if the controller set the proper env variable.
def valid_params_request?
!!env["devise.allow_params_authentication"]
end
# If the request is valid, finally check if params_auth_hash returns a hash.
def valid_params?
params_auth_hash.is_a?(Hash)
end
# Note: unlike `Model.valid_password?`, this method does not actually
# ensure that the password in the params matches the password stored in
# the database. It only checks if the password is *present*. Do not rely
# on this method for validating that a given password is correct.
def valid_password?
password.present?
end
# Helper to decode credentials from HTTP.
def decode_credentials
return [] unless request.authorization && request.authorization =~ /^Basic (.*)/mi
Base64.decode64($1).split(/:/, 2)
end
# Sets the authentication hash and the password from params_auth_hash or http_auth_hash.
def with_authentication_hash(auth_type, auth_values)
self.authentication_hash, self.authentication_type = {}, auth_type
self.password = auth_values[:password]
parse_authentication_key_values(auth_values, authentication_keys) &&
parse_authentication_key_values(request_values, request_keys)
end
def authentication_keys
@authentication_keys ||= mapping.to.authentication_keys
end
def http_authentication_key
@http_authentication_key ||= mapping.to.http_authentication_key || case authentication_keys
when Array then authentication_keys.first
when Hash then authentication_keys.keys.first
end
end
def request_keys
@request_keys ||= mapping.to.request_keys
end
def request_values
keys = request_keys.respond_to?(:keys) ? request_keys.keys : request_keys
values = keys.map { |k| self.request.send(k) }
Hash[keys.zip(values)]
end
def parse_authentication_key_values(hash, keys)
keys.each do |key, enforce|
value = hash[key].presence
if value
self.authentication_hash[key] = value
else
return false unless enforce == false
end
end
true
end
# Holds the authenticatable name for this class. Devise::Strategies::DatabaseAuthenticatable
# becomes simply :database.
def authenticatable_name
@authenticatable_name ||=
ActiveSupport::Inflector.underscore(self.class.name.split("::").last).
sub("_authenticatable", "").to_sym
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/strategies/database_authenticatable.rb | lib/devise/strategies/database_authenticatable.rb | # frozen_string_literal: true
require 'devise/strategies/authenticatable'
module Devise
module Strategies
# Default strategy for signing in a user, based on their email and password in the database.
class DatabaseAuthenticatable < Authenticatable
def authenticate!
resource = password.present? && mapping.to.find_for_database_authentication(authentication_hash)
hashed = false
if validate(resource){ hashed = true; resource.valid_password?(password) }
remember_me(resource)
resource.after_database_authentication
success!(resource)
end
# In paranoid mode, hash the password even when a resource doesn't exist for the given authentication key.
# This is necessary to prevent enumeration attacks - e.g. the request is faster when a resource doesn't
# exist in the database if the password hashing algorithm is not called.
mapping.to.new.password = password if !hashed && Devise.paranoid
unless resource
Devise.paranoid ? fail(:invalid) : fail(:not_found_in_database)
end
end
end
end
end
Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable)
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/mailers/helpers.rb | lib/devise/mailers/helpers.rb | # frozen_string_literal: true
module Devise
module Mailers
module Helpers
extend ActiveSupport::Concern
included do
include Devise::Controllers::ScopedViews
end
protected
attr_reader :scope_name, :resource
# Configure default email options
def devise_mail(record, action, opts = {}, &block)
initialize_from_record(record)
mail headers_for(action, opts), &block
end
def initialize_from_record(record)
@scope_name = Devise::Mapping.find_scope!(record)
@resource = instance_variable_set("@#{devise_mapping.name}", record)
end
def devise_mapping
@devise_mapping ||= Devise.mappings[scope_name]
end
def headers_for(action, opts)
headers = {
subject: subject_for(action),
to: resource.email,
from: mailer_sender(devise_mapping),
reply_to: mailer_sender(devise_mapping),
template_path: template_paths,
template_name: action
}
# Give priority to the mailer's default if they exists.
headers.delete(:from) if default_params[:from]
headers.delete(:reply_to) if default_params[:reply_to]
headers.merge!(opts)
@email = headers[:to]
headers
end
def mailer_sender(mapping)
if Devise.mailer_sender.is_a?(Proc)
Devise.mailer_sender.call(mapping.name)
else
Devise.mailer_sender
end
end
def template_paths
template_path = _prefixes.dup
template_path.unshift "#{@devise_mapping.scoped_path}/mailer" if self.class.scoped_views?
template_path
end
# Set up a subject doing an I18n lookup. At first, it attempts to set a subject
# based on the current mapping:
#
# en:
# devise:
# mailer:
# confirmation_instructions:
# user_subject: '...'
#
# If one does not exist, it fallbacks to ActionMailer default:
#
# en:
# devise:
# mailer:
# confirmation_instructions:
# subject: '...'
#
def subject_for(key)
I18n.t(:"#{devise_mapping.name}_subject", scope: [:devise, :mailer, key],
default: [:subject, key.to_s.humanize])
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/guides/bug_report_templates/integration_test.rb | guides/bug_report_templates/integration_test.rb | # frozen_string_literal: true
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
# Activate the gem you are reporting the issue against.
gem 'rails', '~> 4.2.0'
gem 'devise', '~> 4.0'
gem 'sqlite3'
gem 'byebug'
end
require 'rack/test'
require 'action_controller/railtie'
require 'active_record'
require 'devise/rails/routes'
require 'devise/rails/warden_compat'
ActiveRecord::Base.establish_connection( adapter: :sqlite3, database: ':memory:')
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :email, null: false
t.string :encrypted_password, null: true
t.timestamps null: false
end
end
end
Devise.setup do |config|
require 'devise/orm/active_record'
config.secret_key = 'secret_key_base'
end
class TestApp < Rails::Application
config.root = File.dirname(__FILE__)
config.session_store :cookie_store, key: 'cookie_store_key'
secrets.secret_token = 'secret_token'
secrets.secret_key_base = 'secret_key_base'
config.eager_load = false
config.middleware.use Warden::Manager do |config|
Devise.warden_config = config
end
config.logger = Logger.new($stdout)
Rails.logger = config.logger
end
Rails.application.initialize!
DeviseCreateUsers.migrate(:up)
class User < ActiveRecord::Base
devise :database_authenticatable
end
Rails.application.routes.draw do
devise_for :users
get '/' => 'test#index'
end
class ApplicationController < ActionController::Base
end
class TestController < ApplicationController
include Rails.application.routes.url_helpers
before_action :authenticate_user!
def index
render plain: 'Home'
end
end
require 'minitest/autorun'
class BugTest < ActionDispatch::IntegrationTest
include Rack::Test::Methods
include Warden::Test::Helpers
def test_returns_success
Warden.test_mode!
login_as User.create!(email: 'test@test.com', password: 'test123456', password_confirmation: 'test123456')
get '/'
assert last_response.ok?
end
private
def app
Rails.application
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/test_helper.rb | test/test_helper.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
ENV["MT_NO_EXPECTATIONS"] = "1"
require 'minitest/autorun'
$LOAD_PATH.unshift(File.join(File.expand_path(__dir__), '..', 'lib'))
require 'liquid.rb'
require 'liquid/profiler'
mode = :strict
if (env_mode = ENV['LIQUID_PARSER_MODE'])
puts "-- #{env_mode.upcase} ERROR MODE"
mode = env_mode.to_sym
end
Liquid::Environment.default.error_mode = mode
if Minitest.const_defined?('Test')
# We're on Minitest 5+. Nothing to do here.
else
# Minitest 4 doesn't have Minitest::Test yet.
Minitest::Test = MiniTest::Unit::TestCase
end
module Minitest
class Test
def fixture(name)
File.join(File.expand_path(__dir__), "fixtures", name)
end
end
module Assertions
include Liquid
def assert_template_result(
expected, template, assigns = {},
message: nil, partials: nil, error_mode: Liquid::Environment.default.error_mode, render_errors: false,
template_factory: nil
)
file_system = StubFileSystem.new(partials || {})
environment = Liquid::Environment.build(file_system: file_system)
template = Liquid::Template.parse(template, line_numbers: true, error_mode: error_mode&.to_sym, environment: environment)
registers = Liquid::Registers.new(file_system: file_system, template_factory: template_factory)
context = Liquid::Context.build(static_environments: assigns, rethrow_errors: !render_errors, registers: registers, environment: environment)
output = template.render(context)
assert_equal(expected, output, message)
end
def assert_match_syntax_error(match, template, error_mode: nil)
exception = assert_raises(Liquid::SyntaxError) do
Template.parse(template, line_numbers: true, error_mode: error_mode&.to_sym).render
end
assert_match(match, exception.message)
end
def assert_syntax_error(template, error_mode: nil)
assert_match_syntax_error("", template, error_mode: error_mode)
end
def assert_usage_increment(name, times: 1)
old_method = Liquid::Usage.method(:increment)
calls = 0
begin
Liquid::Usage.singleton_class.send(:remove_method, :increment)
Liquid::Usage.define_singleton_method(:increment) do |got_name|
calls += 1 if got_name == name
old_method.call(got_name)
end
yield
ensure
Liquid::Usage.singleton_class.send(:remove_method, :increment)
Liquid::Usage.define_singleton_method(:increment, old_method)
end
assert_equal(times, calls, "Number of calls to Usage.increment with #{name.inspect}")
end
def with_global_filter(*globals, &blk)
environment = Liquid::Environment.build do |w|
w.register_filters(globals)
end
Environment.dangerously_override(environment, &blk)
end
def with_error_modes(*modes)
old_mode = Liquid::Environment.default.error_mode
modes.each do |mode|
Liquid::Environment.default.error_mode = mode
yield
end
ensure
Liquid::Environment.default.error_mode = old_mode
end
def with_custom_tag(tag_name, tag_class, &block)
environment = Liquid::Environment.default.dup
environment.register_tag(tag_name, tag_class)
Environment.dangerously_override(environment, &block)
end
end
end
class ThingWithToLiquid
def to_liquid
'foobar'
end
end
class SettingsDrop < Liquid::Drop
def initialize(settings)
super()
@settings = settings
end
def liquid_method_missing(key)
@settings[key]
end
end
class IntegerDrop < Liquid::Drop
def initialize(value)
super()
@value = value.to_i
end
def to_s
@value.to_s
end
def to_liquid_value
@value
end
end
class BooleanDrop < Liquid::Drop
def initialize(value)
super()
@value = value
end
def to_liquid_value
@value
end
def to_s
@value ? "Yay" : "Nay"
end
end
class StringDrop < Liquid::Drop
include Comparable
def initialize(value)
super()
@value = value
end
def to_liquid_value
@value
end
def to_s
@value
end
def to_str
@value
end
def inspect
"#<StringDrop @value=#{@value.inspect}>"
end
def <=>(other)
to_liquid_value <=> Liquid::Utils.to_liquid_value(other)
end
end
class ErrorDrop < Liquid::Drop
def standard_error
raise Liquid::StandardError, 'standard error'
end
def argument_error
raise Liquid::ArgumentError, 'argument error'
end
def syntax_error
raise Liquid::SyntaxError, 'syntax error'
end
def runtime_error
raise 'runtime error'
end
def exception
raise Exception, 'exception'
end
end
class CustomToLiquidDrop < Liquid::Drop
def initialize(value)
@value = value
super()
end
def to_liquid
@value
end
end
class HashWithCustomToS < Hash
def to_s
"kewl"
end
end
class HashWithoutCustomToS < Hash
end
class StubFileSystem
attr_reader :file_read_count
def initialize(values)
@file_read_count = 0
@values = values
end
def read_template_file(template_path)
@file_read_count += 1
@values.fetch(template_path)
end
end
class StubTemplateFactory
attr_reader :count
def initialize
@count = 0
end
def for(template_name)
@count += 1
template = Liquid::Template.new
template.name = "some/path/" + template_name
template
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/trim_mode_test.rb | test/integration/trim_mode_test.rb | # frozen_string_literal: true
require 'test_helper'
class TrimModeTest < Minitest::Test
include Liquid
# Make sure the trim isn't applied to standard output
def test_standard_output
text = <<-END_TEMPLATE
<div>
<p>
{{ 'John' }}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
John
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_variable_output_with_multiple_blank_lines
text = <<-END_TEMPLATE
<div>
<p>
{{- 'John' -}}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>John</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_tag_output_with_multiple_blank_lines
text = <<-END_TEMPLATE
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>yes</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
# Make sure the trim isn't applied to standard tags
def test_standard_tags
whitespace = ' '
text = <<-END_TEMPLATE
<div>
<p>
{% if true %}
yes
{% endif %}
</p>
</div>
END_TEMPLATE
expected = <<~END_EXPECTED
<div>
<p>
#{whitespace}
yes
#{whitespace}
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
text = <<-END_TEMPLATE
<div>
<p>
{% if false %}
no
{% endif %}
</p>
</div>
END_TEMPLATE
expected = <<~END_EXPECTED
<div>
<p>
#{whitespace}
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
# Make sure the trim isn't too agressive
def test_no_trim_output
text = '<p>{{- \'John\' -}}</p>'
expected = '<p>John</p>'
assert_template_result(expected, text)
end
# Make sure the trim isn't too agressive
def test_no_trim_tags
text = '<p>{%- if true -%}yes{%- endif -%}</p>'
expected = '<p>yes</p>'
assert_template_result(expected, text)
text = '<p>{%- if false -%}no{%- endif -%}</p>'
expected = '<p></p>'
assert_template_result(expected, text)
end
def test_single_line_outer_tag
text = '<p> {%- if true %} yes {% endif -%} </p>'
expected = '<p> yes </p>'
assert_template_result(expected, text)
text = '<p> {%- if false %} no {% endif -%} </p>'
expected = '<p></p>'
assert_template_result(expected, text)
end
def test_single_line_inner_tag
text = '<p> {% if true -%} yes {%- endif %} </p>'
expected = '<p> yes </p>'
assert_template_result(expected, text)
text = '<p> {% if false -%} no {%- endif %} </p>'
expected = '<p> </p>'
assert_template_result(expected, text)
end
def test_single_line_post_tag
text = '<p> {% if true -%} yes {% endif -%} </p>'
expected = '<p> yes </p>'
assert_template_result(expected, text)
text = '<p> {% if false -%} no {% endif -%} </p>'
expected = '<p> </p>'
assert_template_result(expected, text)
end
def test_single_line_pre_tag
text = '<p> {%- if true %} yes {%- endif %} </p>'
expected = '<p> yes </p>'
assert_template_result(expected, text)
text = '<p> {%- if false %} no {%- endif %} </p>'
expected = '<p> </p>'
assert_template_result(expected, text)
end
def test_pre_trim_output
text = <<-END_TEMPLATE
<div>
<p>
{{- 'John' }}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>John
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_pre_trim_tags
text = <<-END_TEMPLATE
<div>
<p>
{%- if true %}
yes
{%- endif %}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
yes
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
text = <<-END_TEMPLATE
<div>
<p>
{%- if false %}
no
{%- endif %}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_post_trim_output
text = <<-END_TEMPLATE
<div>
<p>
{{ 'John' -}}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
John</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_post_trim_tags
text = <<-END_TEMPLATE
<div>
<p>
{% if true -%}
yes
{% endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
yes
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
text = <<-END_TEMPLATE
<div>
<p>
{% if false -%}
no
{% endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_pre_and_post_trim_tags
text = <<-END_TEMPLATE
<div>
<p>
{%- if true %}
yes
{% endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
yes
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
text = <<-END_TEMPLATE
<div>
<p>
{%- if false %}
no
{% endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p></p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_post_and_pre_trim_tags
text = <<-END_TEMPLATE
<div>
<p>
{% if true -%}
yes
{%- endif %}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>
yes
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
whitespace = ' '
text = <<-END_TEMPLATE
<div>
<p>
{% if false -%}
no
{%- endif %}
</p>
</div>
END_TEMPLATE
expected = <<~END_EXPECTED
<div>
<p>
#{whitespace}
</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_trim_output
text = <<-END_TEMPLATE
<div>
<p>
{{- 'John' -}}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>John</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_trim_tags
text = <<-END_TEMPLATE
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>yes</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
text = <<-END_TEMPLATE
<div>
<p>
{%- if false -%}
no
{%- endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p></p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_whitespace_trim_output
text = <<-END_TEMPLATE
<div>
<p>
{{- 'John' -}},
{{- '30' -}}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>John,30</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_whitespace_trim_tags
text = <<-END_TEMPLATE
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>yes</p>
</div>
END_EXPECTED
assert_template_result(expected, text)
text = <<-END_TEMPLATE
<div>
<p>
{%- if false -%}
no
{%- endif -%}
</p>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p></p>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_complex_trim_output
text = <<-END_TEMPLATE
<div>
<p>
{{- 'John' -}}
{{- '30' -}}
</p>
<b>
{{ 'John' -}}
{{- '30' }}
</b>
<i>
{{- 'John' }}
{{ '30' -}}
</i>
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div>
<p>John30</p>
<b>
John30
</b>
<i>John
30</i>
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_complex_trim
text = <<-END_TEMPLATE
<div>
{%- if true -%}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
{%- endif -%}
</div>
END_TEMPLATE
expected = <<-END_EXPECTED
<div><p>John</p></div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_right_trim_followed_by_tag
assert_template_result('ab c', '{{ "a" -}}{{ "b" }} c')
end
def test_raw_output
whitespace = ' '
text = <<-END_TEMPLATE
<div>
{% raw %}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
{% endraw %}
</div>
END_TEMPLATE
expected = <<~END_EXPECTED
<div>
#{whitespace}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
#{whitespace}
</div>
END_EXPECTED
assert_template_result(expected, text)
end
def test_pre_trim_blank_preceding_text
assert_template_result("", "\n{%- raw %}{% endraw %}")
assert_template_result("", "\n{%- if true %}{% endif %}")
assert_template_result("BC", "{{ 'B' }} \n{%- if true %}C{% endif %}")
end
def test_bug_compatible_pre_trim
template = Liquid::Template.parse("\n {%- raw %}{% endraw %}", bug_compatible_whitespace_trimming: true)
assert_equal("\n", template.render)
template = Liquid::Template.parse("\n {%- if true %}{% endif %}", bug_compatible_whitespace_trimming: true)
assert_equal("\n", template.render)
template = Liquid::Template.parse("{{ 'B' }} \n{%- if true %}C{% endif %}", bug_compatible_whitespace_trimming: true)
assert_equal("B C", template.render)
template = Liquid::Template.parse("B\n {%- raw %}{% endraw %}", bug_compatible_whitespace_trimming: true)
assert_equal("B", template.render)
template = Liquid::Template.parse("B\n {%- if true %}{% endif %}", bug_compatible_whitespace_trimming: true)
assert_equal("B", template.render)
end
def test_trim_blank
assert_template_result('foobar', 'foo {{-}} bar')
end
end # TrimModeTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tag_test.rb | test/integration/tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class TagTest < Minitest::Test
include Liquid
def test_custom_tags_have_a_default_render_to_output_buffer_method_for_backwards_compatibility
klass1 = Class.new(Tag) do
def render(*)
'hello'
end
end
with_custom_tag('blabla', klass1) do
template = Liquid::Template.parse("{% blabla %}")
assert_equal('hello', template.render)
buf = +''
output = template.render({}, output: buf)
assert_equal('hello', output)
assert_equal('hello', buf)
assert_equal(buf.object_id, output.object_id)
end
klass2 = Class.new(klass1) do
def render(*)
'foo' + super + 'bar'
end
end
with_custom_tag('blabla', klass2) do
template = Liquid::Template.parse("{% blabla %}")
assert_equal('foohellobar', template.render)
buf = +''
output = template.render({}, output: buf)
assert_equal('foohellobar', output)
assert_equal('foohellobar', buf)
assert_equal(buf.object_id, output.object_id)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/parsing_quirks_test.rb | test/integration/parsing_quirks_test.rb | # frozen_string_literal: true
require 'test_helper'
class ParsingQuirksTest < Minitest::Test
include Liquid
def test_parsing_css
text = " div { font-weight: bold; } "
assert_equal(text, Template.parse(text).render!)
end
def test_raise_on_single_close_bracet
assert_raises(SyntaxError) do
Template.parse("text {{method} oh nos!")
end
end
def test_raise_on_label_and_no_close_bracets
assert_raises(SyntaxError) do
Template.parse("TEST {{ ")
end
end
def test_raise_on_label_and_no_close_bracets_percent
assert_raises(SyntaxError) do
Template.parse("TEST {% ")
end
end
def test_error_on_empty_filter
assert(Template.parse("{{test}}"))
with_error_modes(:lax) do
assert(Template.parse("{{|test}}"))
end
with_error_modes(:strict) do
assert_raises(SyntaxError) { Template.parse("{{|test}}") }
assert_raises(SyntaxError) { Template.parse("{{test |a|b|}}") }
end
end
def test_meaningless_parens_error
with_error_modes(:strict) do
assert_raises(SyntaxError) do
markup = "a == 'foo' or (b == 'bar' and c == 'baz') or false"
Template.parse("{% if #{markup} %} YES {% endif %}")
end
end
end
def test_unexpected_characters_syntax_error
with_error_modes(:strict) do
assert_raises(SyntaxError) do
markup = "true && false"
Template.parse("{% if #{markup} %} YES {% endif %}")
end
assert_raises(SyntaxError) do
markup = "false || true"
Template.parse("{% if #{markup} %} YES {% endif %}")
end
end
end
def test_no_error_on_lax_empty_filter
assert(Template.parse("{{test |a|b|}}", error_mode: :lax))
assert(Template.parse("{{test}}", error_mode: :lax))
assert(Template.parse("{{|test|}}", error_mode: :lax))
end
def test_meaningless_parens_lax
with_error_modes(:lax) do
assigns = { 'b' => 'bar', 'c' => 'baz' }
markup = "a == 'foo' or (b == 'bar' and c == 'baz') or false"
assert_template_result(' YES ', "{% if #{markup} %} YES {% endif %}", assigns)
end
end
def test_unexpected_characters_silently_eat_logic_lax
with_error_modes(:lax) do
markup = "true && false"
assert_template_result(' YES ', "{% if #{markup} %} YES {% endif %}")
markup = "false || true"
assert_template_result('', "{% if #{markup} %} YES {% endif %}")
end
end
def test_raise_on_invalid_tag_delimiter
assert_raises(Liquid::SyntaxError) do
Template.new.parse('{% end %}')
end
end
def test_unanchored_filter_arguments
with_error_modes(:lax) do
assert_template_result('hi', "{{ 'hi there' | split$$$:' ' | first }}")
assert_template_result('x', "{{ 'X' | downcase) }}")
# After the messed up quotes a filter without parameters (reverse) should work
# but one with parameters (remove) shouldn't be detected.
assert_template_result('here', "{{ 'hi there' | split:\"t\"\" | reverse | first}}")
assert_template_result('hi ', "{{ 'hi there' | split:\"t\"\" | remove:\"i\" | first}}")
end
end
def test_invalid_variables_work
with_error_modes(:lax) do
assert_template_result('bar', "{% assign 123foo = 'bar' %}{{ 123foo }}")
assert_template_result('123', "{% assign 123 = 'bar' %}{{ 123 }}")
end
end
def test_extra_dots_in_ranges
with_error_modes(:lax) do
assert_template_result('12345', "{% for i in (1...5) %}{{ i }}{% endfor %}")
end
end
def test_blank_variable_markup
assert_template_result('', "{{}}")
end
def test_lookup_on_var_with_literal_name
assigns = { "blank" => { "x" => "result" } }
assert_template_result('result', "{{ blank.x }}", assigns)
assert_template_result('result', "{{ blank['x'] }}", assigns)
end
def test_contains_in_id
assert_template_result(' YES ', '{% if containsallshipments == true %} YES {% endif %}', { 'containsallshipments' => true })
end
def test_incomplete_expression
with_error_modes(:lax) do
assert_template_result("false", "{{ false - }}")
assert_template_result("false", "{{ false > }}")
assert_template_result("false", "{{ false < }}")
assert_template_result("false", "{{ false = }}")
assert_template_result("false", "{{ false ! }}")
assert_template_result("false", "{{ false 1 }}")
assert_template_result("false", "{{ false a }}")
assert_template_result("false", "{% liquid assign foo = false -\n%}{{ foo }}")
assert_template_result("false", "{% liquid assign foo = false >\n%}{{ foo }}")
assert_template_result("false", "{% liquid assign foo = false <\n%}{{ foo }}")
assert_template_result("false", "{% liquid assign foo = false =\n%}{{ foo }}")
assert_template_result("false", "{% liquid assign foo = false !\n%}{{ foo }}")
assert_template_result("false", "{% liquid assign foo = false 1\n%}{{ foo }}")
assert_template_result("false", "{% liquid assign foo = false a\n%}{{ foo }}")
end
end
end # ParsingQuirksTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/template_test.rb | test/integration/template_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'timeout'
class TemplateContextDrop < Liquid::Drop
def liquid_method_missing(method)
method
end
def foo
'fizzbuzz'
end
def baz
@context.registers['lulz']
end
end
class SomethingWithLength < Liquid::Drop
def length
nil
end
end
class ErroneousDrop < Liquid::Drop
def bad_method
raise 'ruby error in drop'
end
end
class DropWithUndefinedMethod < Liquid::Drop
def foo
'foo'
end
end
class TemplateTest < Minitest::Test
include Liquid
def test_instance_assigns_persist_on_same_template_object_between_parses
t = Template.new
assert_equal('from instance assigns', t.parse("{% assign foo = 'from instance assigns' %}{{ foo }}").render!)
assert_equal('from instance assigns', t.parse("{{ foo }}").render!)
end
def test_warnings_is_not_exponential_time
str = "false"
100.times do
str = "{% if true %}true{% else %}#{str}{% endif %}"
end
t = Template.parse(str)
assert_equal([], Timeout.timeout(1) { t.warnings })
end
def test_instance_assigns_persist_on_same_template_parsing_between_renders
t = Template.new.parse("{{ foo }}{% assign foo = 'foo' %}{{ foo }}")
assert_equal('foo', t.render!)
assert_equal('foofoo', t.render!)
end
def test_custom_assigns_do_not_persist_on_same_template
t = Template.new
assert_equal('from custom assigns', t.parse("{{ foo }}").render!('foo' => 'from custom assigns'))
assert_equal('', t.parse("{{ foo }}").render!)
end
def test_custom_assigns_squash_instance_assigns
t = Template.new
assert_equal('from instance assigns', t.parse("{% assign foo = 'from instance assigns' %}{{ foo }}").render!)
assert_equal('from custom assigns', t.parse("{{ foo }}").render!('foo' => 'from custom assigns'))
end
def test_persistent_assigns_squash_instance_assigns
t = Template.new
assert_equal('from instance assigns', t.parse("{% assign foo = 'from instance assigns' %}{{ foo }}").render!)
t.assigns['foo'] = 'from persistent assigns'
assert_equal('from persistent assigns', t.parse("{{ foo }}").render!)
end
def test_lambda_is_called_once_from_persistent_assigns_over_multiple_parses_and_renders
t = Template.new
t.assigns['number'] = -> {
@global ||= 0
@global += 1
}
assert_equal('1', t.parse("{{number}}").render!)
assert_equal('1', t.parse("{{number}}").render!)
assert_equal('1', t.render!)
@global = nil
end
def test_lambda_is_called_once_from_custom_assigns_over_multiple_parses_and_renders
t = Template.new
assigns = {
'number' => -> {
@global ||= 0
@global += 1
},
}
assert_equal('1', t.parse("{{number}}").render!(assigns))
assert_equal('1', t.parse("{{number}}").render!(assigns))
assert_equal('1', t.render!(assigns))
@global = nil
end
def test_resource_limits_works_with_custom_length_method
t = Template.parse("{% assign foo = bar %}")
t.resource_limits.render_length_limit = 42
assert_equal("", t.render!("bar" => SomethingWithLength.new))
end
def test_resource_limits_render_length
t = Template.parse("0123456789")
t.resource_limits.render_length_limit = 9
assert_equal("Liquid error: Memory limits exceeded", t.render)
assert(t.resource_limits.reached?)
t.resource_limits.render_length_limit = 10
assert_equal("0123456789", t.render!)
end
def test_resource_limits_render_score
t = Template.parse("{% for a in (1..10) %} {% for a in (1..10) %} foo {% endfor %} {% endfor %}")
t.resource_limits.render_score_limit = 50
assert_equal("Liquid error: Memory limits exceeded", t.render)
assert(t.resource_limits.reached?)
t = Template.parse("{% for a in (1..100) %} foo {% endfor %}")
t.resource_limits.render_score_limit = 50
assert_equal("Liquid error: Memory limits exceeded", t.render)
assert(t.resource_limits.reached?)
t.resource_limits.render_score_limit = 200
assert_equal(" foo " * 100, t.render!)
refute_nil(t.resource_limits.render_score)
end
def test_resource_limits_aborts_rendering_after_first_error
t = Template.parse("{% for a in (1..100) %} foo1 {% endfor %} bar {% for a in (1..100) %} foo2 {% endfor %}")
t.resource_limits.render_score_limit = 50
assert_equal("Liquid error: Memory limits exceeded", t.render)
assert(t.resource_limits.reached?)
end
def test_resource_limits_hash_in_template_gets_updated_even_if_no_limits_are_set
t = Template.parse("{% for a in (1..100) %}x{% assign foo = 1 %} {% endfor %}")
t.render!
assert(t.resource_limits.assign_score > 0)
assert(t.resource_limits.render_score > 0)
end
def test_render_length_persists_between_blocks
t = Template.parse("{% if true %}aaaa{% endif %}")
t.resource_limits.render_length_limit = 3
assert_equal("Liquid error: Memory limits exceeded", t.render)
t.resource_limits.render_length_limit = 4
assert_equal("aaaa", t.render)
t = Template.parse("{% if true %}aaaa{% endif %}{% if true %}bbb{% endif %}")
t.resource_limits.render_length_limit = 6
assert_equal("Liquid error: Memory limits exceeded", t.render)
t.resource_limits.render_length_limit = 7
assert_equal("aaaabbb", t.render)
t = Template.parse("{% if true %}a{% endif %}{% if true %}b{% endif %}{% if true %}a{% endif %}{% if true %}b{% endif %}{% if true %}a{% endif %}{% if true %}b{% endif %}")
t.resource_limits.render_length_limit = 5
assert_equal("Liquid error: Memory limits exceeded", t.render)
t.resource_limits.render_length_limit = 6
assert_equal("ababab", t.render)
end
def test_render_length_uses_number_of_bytes_not_characters
t = Template.parse("{% if true %}すごい{% endif %}")
t.resource_limits.render_length_limit = 8
assert_equal("Liquid error: Memory limits exceeded", t.render)
t.resource_limits.render_length_limit = 9
assert_equal("すごい", t.render)
end
def test_default_resource_limits_unaffected_by_render_with_context
context = Context.new
t = Template.parse("{% for a in (1..100) %}x{% assign foo = 1 %} {% endfor %}")
t.render!(context)
assert(context.resource_limits.assign_score > 0)
assert(context.resource_limits.render_score > 0)
end
def test_can_use_drop_as_context
t = Template.new
t.registers['lulz'] = 'haha'
drop = TemplateContextDrop.new
assert_equal('fizzbuzz', t.parse('{{foo}}').render!(drop))
assert_equal('bar', t.parse('{{bar}}').render!(drop))
assert_equal('haha', t.parse("{{baz}}").render!(drop))
end
def test_render_bang_force_rethrow_errors_on_passed_context
context = Context.new('drop' => ErroneousDrop.new)
t = Template.new.parse('{{ drop.bad_method }}')
e = assert_raises(RuntimeError) do
t.render!(context)
end
assert_equal('ruby error in drop', e.message)
end
def test_exception_renderer_that_returns_string
exception = nil
handler = ->(e) {
exception = e
'<!-- error -->'
}
output = Template.parse("{{ 1 | divided_by: 0 }}").render({}, exception_renderer: handler)
assert(exception.is_a?(Liquid::ZeroDivisionError))
assert_equal('<!-- error -->', output)
end
def test_exception_renderer_that_raises
exception = nil
assert_raises(Liquid::ZeroDivisionError) do
Template.parse("{{ 1 | divided_by: 0 }}").render({}, exception_renderer: ->(e) {
exception = e
raise
})
end
assert(exception.is_a?(Liquid::ZeroDivisionError))
end
def test_global_filter_option_on_render
global_filter_proc = ->(output) { "#{output} filtered" }
rendered_template = Template.parse("{{name}}").render({ "name" => "bob" }, global_filter: global_filter_proc)
assert_equal('bob filtered', rendered_template)
end
def test_global_filter_option_when_native_filters_exist
global_filter_proc = ->(output) { "#{output} filtered" }
rendered_template = Template.parse("{{name | upcase}}").render({ "name" => "bob" }, global_filter: global_filter_proc)
assert_equal('BOB filtered', rendered_template)
end
def test_undefined_variables
t = Template.parse("{{x}} {{y}} {{z.a}} {{z.b}} {{z.c.d}}")
result = t.render({ 'x' => 33, 'z' => { 'a' => 32, 'c' => { 'e' => 31 } } }, strict_variables: true)
assert_equal('33 32 ', result)
assert_equal(3, t.errors.count)
assert_instance_of(Liquid::UndefinedVariable, t.errors[0])
assert_equal('Liquid error: undefined variable y', t.errors[0].message)
assert_instance_of(Liquid::UndefinedVariable, t.errors[1])
assert_equal('Liquid error: undefined variable b', t.errors[1].message)
assert_instance_of(Liquid::UndefinedVariable, t.errors[2])
assert_equal('Liquid error: undefined variable d', t.errors[2].message)
end
def test_nil_value_does_not_raise
t = Template.parse("some{{x}}thing", error_mode: :strict)
result = t.render!({ 'x' => nil }, strict_variables: true)
assert_equal(0, t.errors.count)
assert_equal('something', result)
end
def test_undefined_variables_raise
t = Template.parse("{{x}} {{y}} {{z.a}} {{z.b}} {{z.c.d}}")
assert_raises(UndefinedVariable) do
t.render!({ 'x' => 33, 'z' => { 'a' => 32, 'c' => { 'e' => 31 } } }, strict_variables: true)
end
end
def test_undefined_drop_methods
d = DropWithUndefinedMethod.new
t = Template.new.parse('{{ foo }} {{ woot }}')
result = t.render(d, strict_variables: true)
assert_equal('foo ', result)
assert_equal(1, t.errors.count)
assert_instance_of(Liquid::UndefinedDropMethod, t.errors[0])
end
def test_undefined_drop_methods_raise
d = DropWithUndefinedMethod.new
t = Template.new.parse('{{ foo }} {{ woot }}')
assert_raises(UndefinedDropMethod) do
t.render!(d, strict_variables: true)
end
end
def test_undefined_filters
t = Template.parse("{{a}} {{x | upcase | somefilter1 | somefilter2 | somefilter3}}")
filters = Module.new do
def somefilter3(v)
"-#{v}-"
end
end
result = t.render({ 'a' => 123, 'x' => 'foo' }, filters: [filters], strict_filters: true)
assert_equal('123 ', result)
assert_equal(1, t.errors.count)
assert_instance_of(Liquid::UndefinedFilter, t.errors[0])
assert_equal('Liquid error: undefined filter somefilter1', t.errors[0].message)
end
def test_undefined_filters_raise
t = Template.parse("{{x | somefilter1 | upcase | somefilter2}}")
assert_raises(UndefinedFilter) do
t.render!({ 'x' => 'foo' }, strict_filters: true)
end
end
def test_using_range_literal_works_as_expected
source = "{% assign foo = (x..y) %}{{ foo }}"
assert_template_result("1..5", source, { "x" => 1, "y" => 5 })
source = "{% assign nums = (x..y) %}{% for num in nums %}{{ num }}{% endfor %}"
assert_template_result("12345", source, { "x" => 1, "y" => 5 })
end
def test_source_string_subclass
string_subclass = Class.new(String) do
# E.g. ActiveSupport::SafeBuffer does this, so don't just rely on to_s to return a String
def to_s
self
end
end
source = string_subclass.new("{% assign x = 2 -%} x= {{- x }}")
assert_instance_of(string_subclass, source)
output = Template.parse(source).render!
assert_equal("x=2", output)
assert_instance_of(String, output)
end
def test_raises_error_with_invalid_utf8
e = assert_raises(TemplateEncodingError) do
Template.parse(<<~LIQUID)
{% comment %}
\xC0
{% endcomment %}
LIQUID
end
assert_equal('Liquid error: Invalid template encoding', e.message)
end
def test_allows_non_string_values_as_source
assert_equal('', Template.parse(nil).render)
assert_equal('1', Template.parse(1).render)
assert_equal('true', Template.parse(true).render)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/variable_test.rb | test/integration/variable_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'timeout'
class VariableTest < Minitest::Test
include Liquid
def test_simple_variable
assert_template_result('worked', "{{test}}", { 'test' => 'worked' })
assert_template_result('worked wonderfully', "{{test}}", { 'test' => 'worked wonderfully' })
end
def test_variable_render_calls_to_liquid
assert_template_result('foobar', '{{ foo }}', { 'foo' => ThingWithToLiquid.new })
end
def test_variable_lookup_calls_to_liquid_value
assert_template_result('1', '{{ foo }}', { 'foo' => IntegerDrop.new('1') })
assert_template_result('2', '{{ list[foo] }}', { 'foo' => IntegerDrop.new('1'), 'list' => [1, 2, 3] })
assert_template_result('one', '{{ list[foo] }}', { 'foo' => IntegerDrop.new('1'), 'list' => { 1 => 'one' } })
assert_template_result('Yay', '{{ foo }}', { 'foo' => BooleanDrop.new(true) })
assert_template_result('YAY', '{{ foo | upcase }}', { 'foo' => BooleanDrop.new(true) })
end
def test_if_tag_calls_to_liquid_value
assert_template_result('one', '{% if foo == 1 %}one{% endif %}', { 'foo' => IntegerDrop.new('1') })
assert_template_result('one', '{% if foo == eqv %}one{% endif %}', { 'foo' => IntegerDrop.new(1), 'eqv' => IntegerDrop.new(1) })
assert_template_result('one', '{% if 0 < foo %}one{% endif %}', { 'foo' => IntegerDrop.new('1') })
assert_template_result('one', '{% if foo > 0 %}one{% endif %}', { 'foo' => IntegerDrop.new('1') })
assert_template_result('one', '{% if b > a %}one{% endif %}', { 'b' => IntegerDrop.new(1), 'a' => IntegerDrop.new(0) })
assert_template_result('true', '{% if foo == true %}true{% endif %}', { 'foo' => BooleanDrop.new(true) })
assert_template_result('true', '{% if foo %}true{% endif %}', { 'foo' => BooleanDrop.new(true) })
assert_template_result('', '{% if foo %}true{% endif %}', { 'foo' => BooleanDrop.new(false) })
assert_template_result('', '{% if foo == true %}True{% endif %}', { 'foo' => BooleanDrop.new(false) })
assert_template_result('', '{% if foo and true %}SHOULD NOT HAPPEN{% endif %}', { 'foo' => BooleanDrop.new(false) })
assert_template_result('one', '{% if a contains x %}one{% endif %}', { 'a' => [1], 'x' => IntegerDrop.new(1) })
end
def test_unless_tag_calls_to_liquid_value
assert_template_result('', '{% unless foo %}true{% endunless %}', { 'foo' => BooleanDrop.new(true) })
assert_template_result('true', '{% unless foo %}true{% endunless %}', { 'foo' => BooleanDrop.new(false) })
end
def test_case_tag_calls_to_liquid_value
assert_template_result('One', '{% case foo %}{% when 1 %}One{% endcase %}', { 'foo' => IntegerDrop.new('1') })
end
def test_simple_with_whitespaces
assert_template_result(" worked ", " {{ test }} ", { "test" => "worked" })
assert_template_result(" worked wonderfully ", " {{ test }} ", { "test" => "worked wonderfully" })
end
def test_expression_with_whitespace_in_square_brackets
assert_template_result('result', "{{ a[ 'b' ] }}", { 'a' => { 'b' => 'result' } })
assert_template_result('result', "{{ a[ [ 'b' ] ] }}", { 'b' => 'c', 'a' => { 'c' => 'result' } })
end
def test_ignore_unknown
assert_template_result("", "{{ test }}")
end
def test_using_blank_as_variable_name
assert_template_result("", "{% assign foo = blank %}{{ foo }}")
end
def test_using_empty_as_variable_name
assert_template_result("", "{% assign foo = empty %}{{ foo }}")
end
def test_hash_scoping
assert_template_result('worked', "{{ test.test }}", { 'test' => { 'test' => 'worked' } })
assert_template_result('worked', "{{ test . test }}", { 'test' => { 'test' => 'worked' } })
end
def test_false_renders_as_false
assert_template_result("false", "{{ foo }}", { 'foo' => false })
assert_template_result("false", "{{ false }}")
end
def test_nil_renders_as_empty_string
assert_template_result("", "{{ nil }}")
assert_template_result("cat", "{{ nil | append: 'cat' }}")
end
def test_preset_assigns
template = Template.parse(%({{ test }}))
template.assigns['test'] = 'worked'
assert_equal('worked', template.render!)
end
def test_reuse_parsed_template
template = Template.parse(%({{ greeting }} {{ name }}))
template.assigns['greeting'] = 'Goodbye'
assert_equal('Hello Tobi', template.render!('greeting' => 'Hello', 'name' => 'Tobi'))
assert_equal('Hello ', template.render!('greeting' => 'Hello', 'unknown' => 'Tobi'))
assert_equal('Hello Brian', template.render!('greeting' => 'Hello', 'name' => 'Brian'))
assert_equal('Goodbye Brian', template.render!('name' => 'Brian'))
assert_equal({ 'greeting' => 'Goodbye' }, template.assigns)
end
def test_assigns_not_polluted_from_template
template = Template.parse(%({{ test }}{% assign test = 'bar' %}{{ test }}))
template.assigns['test'] = 'baz'
assert_equal('bazbar', template.render!)
assert_equal('bazbar', template.render!)
assert_equal('foobar', template.render!('test' => 'foo'))
assert_equal('bazbar', template.render!)
end
def test_hash_with_default_proc
template = Template.parse(%(Hello {{ test }}))
assigns = Hash.new { |_h, k| raise "Unknown variable '#{k}'" }
assigns['test'] = 'Tobi'
assert_equal('Hello Tobi', template.render!(assigns))
assigns.delete('test')
e = assert_raises(RuntimeError) do
template.render!(assigns)
end
assert_equal("Unknown variable 'test'", e.message)
end
def test_multiline_variable
assert_template_result("worked", "{{\ntest\n}}", { "test" => "worked" })
end
def test_render_symbol
assert_template_result('bar', '{{ foo }}', { 'foo' => :bar })
end
def test_nested_array
assert_template_result('', '{{ foo }}', { 'foo' => [[nil]] })
end
def test_dynamic_find_var
assert_template_result('bar', '{{ [key] }}', { 'key' => 'foo', 'foo' => 'bar' })
end
def test_raw_value_variable
assert_template_result('bar', '{{ [key] }}', { 'key' => 'foo', 'foo' => 'bar' })
end
def test_dynamic_find_var_with_drop
assert_template_result(
'bar',
'{{ [list[settings.zero]] }}',
{
'list' => ['foo'],
'settings' => SettingsDrop.new("zero" => 0),
'foo' => 'bar',
},
)
assert_template_result(
'foo',
'{{ [list[settings.zero]["foo"]] }}',
{
'list' => [{ 'foo' => 'bar' }],
'settings' => SettingsDrop.new("zero" => 0),
'bar' => 'foo',
},
)
end
def test_double_nested_variable_lookup
assert_template_result(
'bar',
'{{ list[list[settings.zero]]["foo"] }}',
{
'list' => [1, { 'foo' => 'bar' }],
'settings' => SettingsDrop.new("zero" => 0),
'bar' => 'foo',
},
)
end
def test_variable_lookup_should_not_hang_with_invalid_syntax
Timeout.timeout(1) do
assert_template_result(
'bar',
"{{['foo'}}",
{
'foo' => 'bar',
},
error_mode: :lax,
)
end
very_long_key = "1234567890" * 100
template_list = [
"{{['#{very_long_key}']}}", # valid
"{{['#{very_long_key}'}}", # missing closing bracket
"{{[['#{very_long_key}']}}", # extra open bracket
]
template_list.each do |template|
Timeout.timeout(1) do
assert_template_result(
'bar',
template,
{
very_long_key => 'bar',
},
error_mode: :lax,
)
end
end
end
def test_filter_with_single_trailing_comma
template = '{{ "hello" | append: "world", }}'
with_error_modes(:strict) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/is not a valid expression/, error.message)
end
with_error_modes(:strict2) do
assert_template_result('helloworld', template)
end
end
def test_multiple_filters_with_trailing_commas
template = '{{ "hello" | append: "1", | append: "2", }}'
with_error_modes(:strict) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/is not a valid expression/, error.message)
end
with_error_modes(:strict2) do
assert_template_result('hello12', template)
end
end
def test_filter_with_colon_but_no_arguments
template = '{{ "test" | upcase: }}'
with_error_modes(:strict) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/is not a valid expression/, error.message)
end
with_error_modes(:strict2) do
assert_template_result('TEST', template)
end
end
def test_filter_chain_with_colon_no_args
template = '{{ "test" | append: "x" | upcase: }}'
with_error_modes(:strict) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/is not a valid expression/, error.message)
end
with_error_modes(:strict2) do
assert_template_result('TESTX', template)
end
end
def test_combining_trailing_comma_and_empty_args
template = '{{ "test" | append: "x", | upcase: }}'
with_error_modes(:strict) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/is not a valid expression/, error.message)
end
with_error_modes(:strict2) do
assert_template_result('TESTX', template)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/blank_test.rb | test/integration/blank_test.rb | # frozen_string_literal: true
require 'test_helper'
class FoobarTag < Liquid::Tag
def render_to_output_buffer(_context, output)
output << ' '
output
end
end
class BlankTest < Minitest::Test
include Liquid
N = 10
def wrap_in_for(body)
"{% for i in (1..#{N}) %}#{body}{% endfor %}"
end
def wrap_in_if(body)
"{% if true %}#{body}{% endif %}"
end
def wrap(body)
wrap_in_for(body) + wrap_in_if(body)
end
def test_new_tags_are_not_blank_by_default
with_custom_tag('foobar', FoobarTag) do
assert_equal(" " * N, Liquid::Template.parse(wrap_in_for("{% foobar %}")).render!)
end
end
def test_loops_are_blank
assert_template_result("", wrap_in_for(" "))
end
def test_if_else_are_blank
assert_template_result("", "{% if true %} {% elsif false %} {% else %} {% endif %}")
end
def test_unless_is_blank
assert_template_result("", wrap("{% unless true %} {% endunless %}"))
end
def test_mark_as_blank_only_during_parsing
assert_template_result(" " * (N + 1), wrap(" {% if false %} this never happens, but still, this block is not blank {% endif %}"))
end
def test_comments_are_blank
assert_template_result("", wrap(" {% comment %} whatever {% endcomment %} "))
end
def test_captures_are_blank
assert_template_result("", wrap(" {% capture foo %} whatever {% endcapture %} "))
end
def test_nested_blocks_are_blank_but_only_if_all_children_are
assert_template_result("", wrap(wrap(" ")))
assert_template_result(
"\n but this is not " * (N + 1),
wrap('{% if true %} {% comment %} this is blank {% endcomment %} {% endif %}
{% if true %} but this is not {% endif %}'),
)
end
def test_assigns_are_blank
assert_template_result("", wrap(' {% assign foo = "bar" %} '))
end
def test_whitespace_is_blank
assert_template_result("", wrap(" "))
assert_template_result("", wrap("\t"))
end
def test_whitespace_is_not_blank_if_other_stuff_is_present
body = " x "
assert_template_result(body * (N + 1), wrap(body))
end
def test_increment_is_not_blank
assert_template_result(" 0" * 2 * (N + 1), wrap("{% assign foo = 0 %} {% increment foo %} {% decrement foo %}"))
end
def test_cycle_is_not_blank
assert_template_result(" " * ((N + 1) / 2) + " ", wrap("{% cycle ' ', ' ' %}"))
end
def test_raw_is_not_blank
assert_template_result(" " * (N + 1), wrap(" {% raw %} {% endraw %}"))
end
def test_include_is_blank
assert_template_result(
"foobar" * (N + 1),
wrap("{% include 'foobar' %}"),
partials: { 'foobar' => 'foobar' },
)
assert_template_result(
" foobar " * (N + 1),
wrap("{% include ' foobar ' %}"),
partials: { ' foobar ' => ' foobar ' },
)
assert_template_result(
" " * (N + 1),
wrap(" {% include ' ' %} "),
partials: { ' ' => ' ' },
)
end
def test_case_is_blank
assert_template_result("", wrap(" {% assign foo = 'bar' %} {% case foo %} {% when 'bar' %} {% when 'whatever' %} {% else %} {% endcase %} "))
assert_template_result("", wrap(" {% assign foo = 'else' %} {% case foo %} {% when 'bar' %} {% when 'whatever' %} {% else %} {% endcase %} "))
assert_template_result(" x " * (N + 1), wrap(" {% assign foo = 'else' %} {% case foo %} {% when 'bar' %} {% when 'whatever' %} {% else %} x {% endcase %} "))
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/expression_test.rb | test/integration/expression_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'lru_redux'
class ExpressionTest < Minitest::Test
def test_keyword_literals
assert_template_result("true", "{{ true }}")
assert_expression_result(true, "true")
end
def test_string
assert_template_result("single quoted", "{{'single quoted'}}")
assert_template_result("double quoted", '{{"double quoted"}}')
assert_template_result("spaced", "{{ 'spaced' }}")
assert_template_result("spaced2", "{{ 'spaced2' }}")
assert_template_result("emoji🔥", "{{ 'emoji🔥' }}")
end
def test_int
assert_template_result("456", "{{ 456 }}")
assert_expression_result(123, "123")
assert_expression_result(12, "012")
end
def test_float
assert_template_result("-17.42", "{{ -17.42 }}")
assert_template_result("2.5", "{{ 2.5 }}")
with_error_modes(:lax) do
assert_expression_result(0.0, "0.....5")
assert_expression_result(0.0, "-0..1")
end
assert_expression_result(1.5, "1.5")
# this is a unfortunate quirky behavior of Liquid
result = Expression.parse(".5")
assert_kind_of(Liquid::VariableLookup, result)
result = Expression.parse("-.5")
assert_kind_of(Liquid::VariableLookup, result)
end
def test_range
assert_template_result("3..4", "{{ ( 3 .. 4 ) }}")
assert_expression_result(1..2, "(1..2)")
assert_match_syntax_error(
"Liquid syntax error (line 1): Invalid expression type 'false' in range expression",
"{{ (false..true) }}",
)
assert_match_syntax_error(
"Liquid syntax error (line 1): Invalid expression type '(1..2)' in range expression",
"{{ ((1..2)..3) }}",
)
end
def test_quirky_negative_sign_expression_markup
result = Expression.parse("-", nil)
assert(result.is_a?(VariableLookup))
assert_equal("-", result.name)
# for this template, the expression markup is "-"
assert_template_result(
"",
"{{ - 'theme.css' - }}",
error_mode: :lax,
)
end
def test_expression_cache
skip("Liquid-C does not support Expression caching") if defined?(Liquid::C) && Liquid::C.enabled
cache = {}
template = <<~LIQUID
{% assign x = 1 %}
{{ x }}
{% assign x = 2 %}
{{ x }}
{% assign y = 1 %}
{{ y }}
LIQUID
Liquid::Template.parse(template, expression_cache: cache).render
assert_equal(
["1", "2", "x", "y"],
cache.to_a.map { _1[0] }.sort,
)
end
def test_expression_cache_with_true_boolean
skip("Liquid-C does not support Expression caching") if defined?(Liquid::C) && Liquid::C.enabled
template = <<~LIQUID
{% assign x = 1 %}
{{ x }}
{% assign x = 2 %}
{{ x }}
{% assign y = 1 %}
{{ y }}
LIQUID
parse_context = ParseContext.new(expression_cache: true)
Liquid::Template.parse(template, parse_context).render
cache = parse_context.instance_variable_get(:@expression_cache)
assert_equal(
["1", "2", "x", "y"],
cache.to_a.map { _1[0] }.sort,
)
end
def test_expression_cache_with_lru_redux
skip("Liquid-C does not support Expression caching") if defined?(Liquid::C) && Liquid::C.enabled
cache = LruRedux::Cache.new(10)
template = <<~LIQUID
{% assign x = 1 %}
{{ x }}
{% assign x = 2 %}
{{ x }}
{% assign y = 1 %}
{{ y }}
LIQUID
Liquid::Template.parse(template, expression_cache: cache).render
assert_equal(
["1", "2", "x", "y"],
cache.to_a.map { _1[0] }.sort,
)
end
def test_disable_expression_cache
skip("Liquid-C does not support Expression caching") if defined?(Liquid::C) && Liquid::C.enabled
template = <<~LIQUID
{% assign x = 1 %}
{{ x }}
{% assign x = 2 %}
{{ x }}
{% assign y = 1 %}
{{ y }}
LIQUID
parse_context = Liquid::ParseContext.new(expression_cache: false)
Liquid::Template.parse(template, parse_context).render
assert(parse_context.instance_variable_get(:@expression_cache).nil?)
end
def test_safe_parse_with_variable_lookup
parse_context = Liquid::ParseContext.new
parser = parse_context.new_parser('product.title')
result = Liquid::Expression.safe_parse(parser)
assert_instance_of(Liquid::VariableLookup, result)
assert_equal('product', result.name)
assert_equal(['title'], result.lookups)
end
def test_safe_parse_with_number
parse_context = Liquid::ParseContext.new
parser = parse_context.new_parser('42')
result = Liquid::Expression.safe_parse(parser)
assert_equal(42, result)
end
def test_safe_parse_raises_syntax_error_for_invalid_expression
parse_context = Liquid::ParseContext.new
parser = parse_context.new_parser('')
error = assert_raises(Liquid::SyntaxError) do
Liquid::Expression.safe_parse(parser)
end
assert_match(/is not a valid expression/, error.message)
end
private
def assert_expression_result(expect, markup, **assigns)
liquid = "{% if expect == #{markup} %}pass{% else %}got {{ #{markup} }}{% endif %}"
assert_template_result("pass", liquid, { "expect" => expect, **assigns })
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/document_test.rb | test/integration/document_test.rb | # frozen_string_literal: true
require 'test_helper'
class DocumentTest < Minitest::Test
include Liquid
def test_unexpected_outer_tag
source = "{% else %}"
assert_match_syntax_error("Liquid syntax error (line 1): Unexpected outer 'else' tag", source)
end
def test_unknown_tag
source = "{% foo %}"
assert_match_syntax_error("Liquid syntax error (line 1): Unknown tag 'foo'", source)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/filter_kwarg_test.rb | test/integration/filter_kwarg_test.rb | # frozen_string_literal: true
require 'test_helper'
class FilterKwargTest < Minitest::Test
module KwargFilter
def html_tag(_tag, attributes)
attributes
.map { |key, value| "#{key}='#{value}'" }
.join(' ')
end
end
include Liquid
def test_can_parse_data_kwargs
with_global_filter(KwargFilter) do
assert_equal(
"data-src='src' data-widths='100, 200'",
Template.parse("{{ 'img' | html_tag: data-src: 'src', data-widths: '100, 200' }}").render(nil, nil),
)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/hash_ordering_test.rb | test/integration/hash_ordering_test.rb | # frozen_string_literal: true
require 'test_helper'
class HashOrderingTest < Minitest::Test
module MoneyFilter
def money(input)
format(' %d$ ', input)
end
end
module CanadianMoneyFilter
def money(input)
format(' %d$ CAD ', input)
end
end
include Liquid
def test_global_register_order
with_global_filter(MoneyFilter, CanadianMoneyFilter) do
assert_equal(" 1000$ CAD ", Template.parse("{{1000 | money}}").render(nil, nil))
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/capture_test.rb | test/integration/capture_test.rb | # frozen_string_literal: true
require 'test_helper'
class CaptureTest < Minitest::Test
include Liquid
def test_captures_block_content_in_variable
assert_template_result("test string", "{% capture 'var' %}test string{% endcapture %}{{var}}", {})
end
def test_capture_with_hyphen_in_variable_name
template_source = <<~END_TEMPLATE
{% capture this-thing %}Print this-thing{% endcapture -%}
{{ this-thing -}}
END_TEMPLATE
assert_template_result("Print this-thing", template_source)
end
def test_capture_to_variable_from_outer_scope_if_existing
template_source = <<~END_TEMPLATE
{% assign var = '' -%}
{% if true -%}
{% capture var %}first-block-string{% endcapture -%}
{% endif -%}
{% if true -%}
{% capture var %}test-string{% endcapture -%}
{% endif -%}
{{var-}}
END_TEMPLATE
assert_template_result("test-string", template_source)
end
def test_assigning_from_capture
template_source = <<~END_TEMPLATE
{% assign first = '' -%}
{% assign second = '' -%}
{% for number in (1..3) -%}
{% capture first %}{{number}}{% endcapture -%}
{% assign second = first -%}
{% endfor -%}
{{ first }}-{{ second -}}
END_TEMPLATE
assert_template_result("3-3", template_source)
end
def test_increment_assign_score_by_bytes_not_characters
t = Template.parse("{% capture foo %}すごい{% endcapture %}")
t.render!
assert_equal(9, t.resource_limits.assign_score)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/filter_test.rb | test/integration/filter_test.rb | # frozen_string_literal: true
require 'test_helper'
module MoneyFilter
def money(input)
format(' %d$ ', input)
end
def money_with_underscore(input)
format(' %d$ ', input)
end
end
module CanadianMoneyFilter
def money(input)
format(' %d$ CAD ', input)
end
end
module SubstituteFilter
def substitute(input, params = {})
input.gsub(/%\{(\w+)\}/) { |_match| params[Regexp.last_match(1)] }
end
end
class FiltersTest < Minitest::Test
include Liquid
module OverrideObjectMethodFilter
def tap(_input)
"tap overridden"
end
end
def setup
@context = Context.new
end
def test_local_filter
@context['var'] = 1000
@context.add_filters(MoneyFilter)
assert_equal(' 1000$ ', Template.parse("{{var | money}}").render(@context))
end
def test_underscore_in_filter_name
@context['var'] = 1000
@context.add_filters(MoneyFilter)
assert_equal(' 1000$ ', Template.parse("{{var | money_with_underscore}}").render(@context))
end
def test_second_filter_overwrites_first
@context['var'] = 1000
@context.add_filters(MoneyFilter)
@context.add_filters(CanadianMoneyFilter)
assert_equal(' 1000$ CAD ', Template.parse("{{var | money}}").render(@context))
end
def test_size
assert_template_result("4", "{{var | size}}", { "var" => 'abcd' })
end
def test_join
assert_template_result("1 2 3 4", "{{var | join}}", { "var" => [1, 2, 3, 4] })
end
def test_sort
assert_template_result("1 2 3 4", "{{numbers | sort | join}}", { "numbers" => [2, 1, 4, 3] })
assert_template_result(
"alphabetic as expected",
"{{words | sort | join}}",
{ "words" => ['expected', 'as', 'alphabetic'] },
)
assert_template_result("3", "{{value | sort}}", { "value" => 3 })
assert_template_result('are flower', "{{arrays | sort | join}}", { 'arrays' => ['flower', 'are'] })
assert_template_result(
"Expected case sensitive",
"{{case_sensitive | sort | join}}",
{ "case_sensitive" => ["sensitive", "Expected", "case"] },
)
end
def test_sort_natural
# Test strings
assert_template_result(
"Assert case Insensitive",
"{{words | sort_natural | join}}",
{ "words" => ["case", "Assert", "Insensitive"] },
)
# Test hashes
assert_template_result(
"A b C",
"{{hashes | sort_natural: 'a' | map: 'a' | join}}",
{ "hashes" => [{ "a" => "A" }, { "a" => "b" }, { "a" => "C" }] },
)
# Test objects
@context['objects'] = [TestObject.new('A'), TestObject.new('b'), TestObject.new('C')]
assert_equal('A b C', Template.parse("{{objects | sort_natural: 'a' | map: 'a' | join}}").render(@context))
end
def test_compact
# Test strings
assert_template_result(
"a b c",
"{{words | compact | join}}",
{ "words" => ['a', nil, 'b', nil, 'c'] },
)
# Test hashes
assert_template_result(
"A C",
"{{hashes | compact: 'a' | map: 'a' | join}}",
{ "hashes" => [{ "a" => "A" }, { "a" => nil }, { "a" => "C" }] },
)
# Test objects
@context['objects'] = [TestObject.new('A'), TestObject.new(nil), TestObject.new('C')]
assert_equal('A C', Template.parse("{{objects | compact: 'a' | map: 'a' | join}}").render(@context))
end
def test_strip_html
assert_template_result("bla blub", "{{ var | strip_html }}", { "var" => "<b>bla blub</a>" })
end
def test_strip_html_ignore_comments_with_html
assert_template_result(
"bla blub",
"{{ var | strip_html }}",
{ "var" => "<!-- split and some <ul> tag --><b>bla blub</a>" },
)
end
def test_capitalize
assert_template_result("Blub", "{{ var | capitalize }}", { "var" => "blub" })
end
def test_nonexistent_filter_is_ignored
assert_template_result("1000", "{{ var | xyzzy }}", { "var" => 1000 })
end
def test_filter_with_keyword_arguments
@context['surname'] = 'john'
@context['input'] = 'hello %{first_name}, %{last_name}'
@context.add_filters(SubstituteFilter)
output = Template.parse(%({{ input | substitute: first_name: surname, last_name: 'doe' }})).render(@context)
assert_equal('hello john, doe', output)
end
def test_override_object_method_in_filter
assert_equal("tap overridden", Template.parse("{{var | tap}}").render!({ 'var' => 1000 }, filters: [OverrideObjectMethodFilter]))
# tap still treated as a non-existent filter
assert_equal("1000", Template.parse("{{var | tap}}").render!('var' => 1000))
end
def test_liquid_argument_error
source = "{{ '' | size: 'too many args' }}"
exc = assert_raises(Liquid::ArgumentError) do
Template.parse(source).render!
end
assert_match(/\ALiquid error: wrong number of arguments /, exc.message)
assert_equal(exc.message, Template.parse(source).render)
end
end
class FiltersInTemplate < Minitest::Test
include Liquid
def test_local_global
with_global_filter(MoneyFilter) do
assert_equal(" 1000$ ", Template.parse("{{1000 | money}}").render!(nil, nil))
assert_equal(" 1000$ CAD ", Template.parse("{{1000 | money}}").render!(nil, filters: CanadianMoneyFilter))
assert_equal(" 1000$ CAD ", Template.parse("{{1000 | money}}").render!(nil, filters: [CanadianMoneyFilter]))
end
end
def test_local_filter_with_deprecated_syntax
assert_equal(" 1000$ CAD ", Template.parse("{{1000 | money}}").render!(nil, CanadianMoneyFilter))
assert_equal(" 1000$ CAD ", Template.parse("{{1000 | money}}").render!(nil, [CanadianMoneyFilter]))
end
end # FiltersTest
class TestObject < Liquid::Drop
attr_accessor :a
def initialize(a)
@a = a
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/context_test.rb | test/integration/context_test.rb | # frozen_string_literal: true
require 'test_helper'
class HundredCentes
def to_liquid
100
end
end
class CentsDrop < Liquid::Drop
def amount
HundredCentes.new
end
def non_zero?
true
end
end
class ContextSensitiveDrop < Liquid::Drop
def test
@context['test']
end
end
class Category
attr_accessor :name
def initialize(name)
@name = name
end
def to_liquid
CategoryDrop.new(self)
end
end
class ProductsDrop < Liquid::Drop
def initialize(products)
@products = products
end
def size
@products.size
end
def to_liquid
if @context["forloop"]
@products.first(@context["forloop"].length)
else
@products
end
end
end
class CategoryDrop < Liquid::Drop
attr_accessor :category, :context
def initialize(category)
@category = category
end
end
class CounterDrop < Liquid::Drop
def count
@count ||= 0
@count += 1
end
end
class ArrayLike
def fetch(index)
end
def [](index)
@counts ||= []
@counts[index] ||= 0
@counts[index] += 1
end
def to_liquid
self
end
end
class ContextTest < Minitest::Test
include Liquid
def setup
@context = Liquid::Context.new
end
def test_variables
@context['string'] = 'string'
assert_equal('string', @context['string'])
@context['num'] = 5
assert_equal(5, @context['num'])
@context['time'] = Time.parse('2006-06-06 12:00:00')
assert_equal(Time.parse('2006-06-06 12:00:00'), @context['time'])
@context['date'] = Date.today
assert_equal(Date.today, @context['date'])
now = Time.now
@context['datetime'] = now
assert_equal(now, @context['datetime'])
@context['bool'] = true
assert_equal(true, @context['bool'])
@context['bool'] = false
assert_equal(false, @context['bool'])
@context['nil'] = nil
assert_nil(@context['nil'])
assert_nil(@context['nil'])
end
def test_variables_not_existing
assert_template_result("true", "{% if does_not_exist == nil %}true{% endif %}")
end
def test_scoping
@context.push
@context.pop
assert_raises(Liquid::ContextError) do
@context.pop
end
assert_raises(Liquid::ContextError) do
@context.push
@context.pop
@context.pop
end
end
def test_length_query
assert_template_result(
"true",
"{% if numbers.size == 4 %}true{% endif %}",
{ "numbers" => [1, 2, 3, 4] },
)
assert_template_result(
"true",
"{% if numbers.size == 4 %}true{% endif %}",
{ "numbers" => { 1 => 1, 2 => 2, 3 => 3, 4 => 4 } },
)
assert_template_result(
"true",
"{% if numbers.size == 1000 %}true{% endif %}",
{ "numbers" => { 1 => 1, 2 => 2, 3 => 3, 4 => 4, 'size' => 1000 } },
)
end
def test_hyphenated_variable
assert_template_result("godz", "{{ oh-my }}", { "oh-my" => 'godz' })
end
def test_add_filter
filter = Module.new do
def hi(output)
output + ' hi!'
end
end
context = Context.new
context.add_filters(filter)
assert_equal('hi? hi!', context.invoke(:hi, 'hi?'))
context = Context.new
assert_equal('hi?', context.invoke(:hi, 'hi?'))
context.add_filters(filter)
assert_equal('hi? hi!', context.invoke(:hi, 'hi?'))
end
def test_only_intended_filters_make_it_there
filter = Module.new do
def hi(output)
output + ' hi!'
end
end
context = Context.new
assert_equal("Wookie", context.invoke("hi", "Wookie"))
context.add_filters(filter)
assert_equal("Wookie hi!", context.invoke("hi", "Wookie"))
end
def test_add_item_in_outer_scope
@context['test'] = 'test'
@context.push
assert_equal('test', @context['test'])
@context.pop
assert_equal('test', @context['test'])
end
def test_add_item_in_inner_scope
@context.push
@context['test'] = 'test'
assert_equal('test', @context['test'])
@context.pop
assert_nil(@context['test'])
end
def test_hierachical_data
assigns = { 'hash' => { "name" => 'tobi' } }
assert_template_result("tobi", "{{ hash.name }}", assigns)
assert_template_result("tobi", '{{ hash["name"] }}', assigns)
end
def test_keywords
assert_template_result("pass", "{% if true == expect %}pass{% endif %}", { "expect" => true })
assert_template_result("pass", "{% if false == expect %}pass{% endif %}", { "expect" => false })
end
def test_digits
assert_template_result("pass", "{% if 100 == expect %}pass{% endif %}", { "expect" => 100 })
assert_template_result("pass", "{% if 100.00 == expect %}pass{% endif %}", { "expect" => 100.00 })
end
def test_strings
assert_template_result("hello!", '{{ "hello!" }}')
assert_template_result("hello!", "{{ 'hello!' }}")
end
def test_merge
@context.merge("test" => "test")
assert_equal('test', @context['test'])
@context.merge("test" => "newvalue", "foo" => "bar")
assert_equal('newvalue', @context['test'])
assert_equal('bar', @context['foo'])
end
def test_array_notation
assigns = { "test" => ["a", "b"] }
assert_template_result("a", "{{ test[0] }}", assigns)
assert_template_result("b", "{{ test[1] }}", assigns)
assert_template_result("pass", "{% if test[2] == nil %}pass{% endif %}", assigns)
end
def test_recoursive_array_notation
assigns = { "test" => { 'test' => [1, 2, 3, 4, 5] } }
assert_template_result("1", "{{ test.test[0] }}", assigns)
assigns = { "test" => [{ 'test' => 'worked' }] }
assert_template_result("worked", "{{ test[0].test }}", assigns)
end
def test_hash_to_array_transition
assigns = {
'colors' => {
'Blue' => ['003366', '336699', '6699CC', '99CCFF'],
'Green' => ['003300', '336633', '669966', '99CC99'],
'Yellow' => ['CC9900', 'FFCC00', 'FFFF99', 'FFFFCC'],
'Red' => ['660000', '993333', 'CC6666', 'FF9999'],
},
}
assert_template_result("003366", "{{ colors.Blue[0] }}", assigns)
assert_template_result("FF9999", "{{ colors.Red[3] }}", assigns)
end
def test_try_first
assigns = { 'test' => [1, 2, 3, 4, 5] }
assert_template_result("1", "{{ test.first }}", assigns)
assert_template_result("pass", "{% if test.last == 5 %}pass{% endif %}", assigns)
assigns = { "test" => { "test" => [1, 2, 3, 4, 5] } }
assert_template_result("1", "{{ test.test.first }}", assigns)
assert_template_result("5", "{{ test.test.last }}", assigns)
assigns = { "test" => [1] }
assert_template_result("1", "{{ test.first }}", assigns)
assert_template_result("1", "{{ test.last }}", assigns)
end
def test_access_hashes_with_hash_notation
assigns = { 'products' => { 'count' => 5, 'tags' => ['deepsnow', 'freestyle'] } }
assert_template_result("5", '{{ products["count"] }}', assigns)
assert_template_result("deepsnow", '{{ products["tags"][0] }}', assigns)
assert_template_result("deepsnow", '{{ products["tags"].first }}', assigns)
assigns = { 'product' => { 'variants' => [{ 'title' => 'draft151cm' }, { 'title' => 'element151cm' }] } }
assert_template_result("draft151cm", '{{ product["variants"][0]["title"] }}', assigns)
assert_template_result("element151cm", '{{ product["variants"][1]["title"] }}', assigns)
assert_template_result("draft151cm", '{{ product["variants"].first["title"] }}', assigns)
assert_template_result("element151cm", '{{ product["variants"].last["title"] }}', assigns)
end
def test_access_variable_with_hash_notation
assert_template_result('baz', '{{ ["foo"] }}', { "foo" => "baz" })
assert_template_result('baz', '{{ [bar] }}', { 'foo' => 'baz', 'bar' => 'foo' })
end
def test_access_hashes_with_hash_access_variables
assigns = {
'var' => 'tags',
'nested' => { 'var' => 'tags' },
'products' => { 'count' => 5, 'tags' => ['deepsnow', 'freestyle'] },
}
assert_template_result('deepsnow', '{{ products[var].first }}', assigns)
assert_template_result('freestyle', '{{ products[nested.var].last }}', assigns)
end
def test_hash_notation_only_for_hash_access
assigns = { "array" => [1, 2, 3, 4, 5] }
assert_template_result("1", "{{ array.first }}", assigns)
assert_template_result("pass", '{% if array["first"] == nil %}pass{% endif %}', assigns)
assert_template_result("Hello", '{{ hash["first"] }}', { "hash" => { "first" => "Hello" } })
end
def test_first_can_appear_in_middle_of_callchain
assigns = { "product" => { 'variants' => [{ 'title' => 'draft151cm' }, { 'title' => 'element151cm' }] } }
assert_template_result('draft151cm', '{{ product.variants[0].title }}', assigns)
assert_template_result('element151cm', '{{ product.variants[1].title }}', assigns)
assert_template_result('draft151cm', '{{ product.variants.first.title }}', assigns)
assert_template_result('element151cm', '{{ product.variants.last.title }}', assigns)
end
def test_cents
@context.merge("cents" => HundredCentes.new)
assert_equal(100, @context['cents'])
end
def test_nested_cents
@context.merge("cents" => { 'amount' => HundredCentes.new })
assert_equal(100, @context['cents.amount'])
@context.merge("cents" => { 'cents' => { 'amount' => HundredCentes.new } })
assert_equal(100, @context['cents.cents.amount'])
end
def test_cents_through_drop
@context.merge("cents" => CentsDrop.new)
assert_equal(100, @context['cents.amount'])
end
def test_nested_cents_through_drop
@context.merge("vars" => { "cents" => CentsDrop.new })
assert_equal(100, @context['vars.cents.amount'])
end
def test_drop_methods_with_question_marks
@context.merge("cents" => CentsDrop.new)
assert(@context['cents.non_zero?'])
end
def test_context_from_within_drop
@context.merge("test" => '123', "vars" => ContextSensitiveDrop.new)
assert_equal('123', @context['vars.test'])
end
def test_nested_context_from_within_drop
@context.merge("test" => '123', "vars" => { "local" => ContextSensitiveDrop.new })
assert_equal('123', @context['vars.local.test'])
end
def test_ranges
assert_template_result("1..5", '{{ (1..5) }}')
assert_template_result("pass", '{% if (1..5) == expect %}pass{% endif %}', { "expect" => (1..5) })
assigns = { "test" => '5' }
assert_template_result("1..5", "{{ (1..test) }}", assigns)
assert_template_result("5..5", "{{ (test..test) }}", assigns)
end
def test_cents_through_drop_nestedly
@context.merge("cents" => { "cents" => CentsDrop.new })
assert_equal(100, @context['cents.cents.amount'])
@context.merge("cents" => { "cents" => { "cents" => CentsDrop.new } })
assert_equal(100, @context['cents.cents.cents.amount'])
end
def test_drop_with_variable_called_only_once
@context['counter'] = CounterDrop.new
assert_equal(1, @context['counter.count'])
assert_equal(2, @context['counter.count'])
assert_equal(3, @context['counter.count'])
end
def test_drop_with_key_called_only_once
@context['counter'] = CounterDrop.new
assert_equal(1, @context['counter["count"]'])
assert_equal(2, @context['counter["count"]'])
assert_equal(3, @context['counter["count"]'])
end
def test_proc_as_variable
@context['dynamic'] = proc { 'Hello' }
assert_equal('Hello', @context['dynamic'])
end
def test_lambda_as_variable
@context['dynamic'] = proc { 'Hello' }
assert_equal('Hello', @context['dynamic'])
end
def test_nested_lambda_as_variable
@context['dynamic'] = { "lambda" => proc { 'Hello' } }
assert_equal('Hello', @context['dynamic.lambda'])
end
def test_array_containing_lambda_as_variable
@context['dynamic'] = [1, 2, proc { 'Hello' }, 4, 5]
assert_equal('Hello', @context['dynamic[2]'])
end
def test_lambda_is_called_once
@global = 0
@context['callcount'] = proc {
@global += 1
@global.to_s
}
assert_equal('1', @context['callcount'])
assert_equal('1', @context['callcount'])
assert_equal('1', @context['callcount'])
end
def test_nested_lambda_is_called_once
@global = 0
@context['callcount'] = {
"lambda" => proc {
@global += 1
@global.to_s
},
}
assert_equal('1', @context['callcount.lambda'])
assert_equal('1', @context['callcount.lambda'])
assert_equal('1', @context['callcount.lambda'])
end
def test_lambda_in_array_is_called_once
@global = 0
p = proc {
@global += 1
@global.to_s
}
@context['callcount'] = [1, 2, p, 4, 5]
assert_equal('1', @context['callcount[2]'])
assert_equal('1', @context['callcount[2]'])
assert_equal('1', @context['callcount[2]'])
end
def test_access_to_context_from_proc
@context.registers[:magic] = 345392
@context['magic'] = proc { @context.registers[:magic] }
assert_equal(345392, @context['magic'])
end
def test_to_liquid_and_context_at_first_level
@context['category'] = Category.new("foobar")
assert_kind_of(CategoryDrop, @context['category'])
assert_equal(@context, @context['category'].context)
end
def test_interrupt_avoids_object_allocations
@context.interrupt? # ruby 3.0.0 allocates on the first call
assert_no_object_allocations do
@context.interrupt?
end
end
def test_context_initialization_with_a_proc_in_environment
contx = Context.new([test: ->(c) { c['poutine'] }], test: :foo)
assert(contx)
assert_nil(contx['poutine'])
end
def test_apply_global_filter
global_filter_proc = ->(output) { "#{output} filtered" }
context = Context.new
context.global_filter = global_filter_proc
assert_equal('hi filtered', context.apply_global_filter('hi'))
end
def test_static_environments_are_read_with_lower_priority_than_environments
context = Context.build(
static_environments: { 'shadowed' => 'static', 'unshadowed' => 'static' },
environments: { 'shadowed' => 'dynamic' },
)
assert_equal('dynamic', context['shadowed'])
assert_equal('static', context['unshadowed'])
end
def test_apply_global_filter_when_no_global_filter_exist
context = Context.new
assert_equal('hi', context.apply_global_filter('hi'))
end
def test_new_isolated_subcontext_does_not_inherit_variables
super_context = Context.new
super_context['my_variable'] = 'some value'
subcontext = super_context.new_isolated_subcontext
assert_nil(subcontext['my_variable'])
end
def test_new_isolated_subcontext_inherits_static_environment
super_context = Context.build(static_environments: { 'my_environment_value' => 'my value' })
subcontext = super_context.new_isolated_subcontext
assert_equal('my value', subcontext['my_environment_value'])
end
def test_new_isolated_subcontext_inherits_resource_limits
resource_limits = ResourceLimits.new({})
super_context = Context.new({}, {}, {}, false, resource_limits)
subcontext = super_context.new_isolated_subcontext
assert_equal(resource_limits, subcontext.resource_limits)
end
def test_new_isolated_subcontext_inherits_exception_renderer
super_context = Context.new
super_context.exception_renderer = ->(_e) { 'my exception message' }
subcontext = super_context.new_isolated_subcontext
assert_equal('my exception message', subcontext.handle_error(Liquid::Error.new))
end
def test_new_isolated_subcontext_does_not_inherit_non_static_registers
registers = {
my_register: :my_value,
}
super_context = Context.new({}, {}, Registers.new(registers))
super_context.registers[:my_register] = :my_alt_value
subcontext = super_context.new_isolated_subcontext
assert_equal(:my_value, subcontext.registers[:my_register])
end
def test_new_isolated_subcontext_inherits_static_registers
super_context = Context.build(registers: { my_register: :my_value })
subcontext = super_context.new_isolated_subcontext
assert_equal(:my_value, subcontext.registers[:my_register])
end
def test_new_isolated_subcontext_registers_do_not_pollute_context
super_context = Context.build(registers: { my_register: :my_value })
subcontext = super_context.new_isolated_subcontext
subcontext.registers[:my_register] = :my_alt_value
assert_equal(:my_value, super_context.registers[:my_register])
end
def test_new_isolated_subcontext_inherits_filters
my_filter = Module.new do
def my_filter(*)
'my filter result'
end
end
super_context = Context.new
super_context.add_filters([my_filter])
subcontext = super_context.new_isolated_subcontext
template = Template.parse('{{ 123 | my_filter }}')
assert_equal('my filter result', template.render(subcontext))
end
def test_disables_tag_specified
context = Context.new
context.with_disabled_tags(%w(foo bar)) do
assert_equal(true, context.tag_disabled?("foo"))
assert_equal(true, context.tag_disabled?("bar"))
assert_equal(false, context.tag_disabled?("unknown"))
end
end
def test_disables_nested_tags
context = Context.new
context.with_disabled_tags(["foo"]) do
context.with_disabled_tags(["foo"]) do
assert_equal(true, context.tag_disabled?("foo"))
assert_equal(false, context.tag_disabled?("bar"))
end
context.with_disabled_tags(["bar"]) do
assert_equal(true, context.tag_disabled?("foo"))
assert_equal(true, context.tag_disabled?("bar"))
context.with_disabled_tags(["foo"]) do
assert_equal(true, context.tag_disabled?("foo"))
assert_equal(true, context.tag_disabled?("bar"))
end
end
assert_equal(true, context.tag_disabled?("foo"))
assert_equal(false, context.tag_disabled?("bar"))
end
end
def test_override_global_filter
global = Module.new do
def notice(output)
"Global #{output}"
end
end
local = Module.new do
def notice(output)
"Local #{output}"
end
end
with_global_filter(global) do
assert_equal('Global test', Template.parse("{{'test' | notice }}").render!)
assert_equal('Local test', Template.parse("{{'test' | notice }}").render!({}, filters: [local]))
end
end
def test_has_key_will_not_add_an_error_for_missing_keys
with_error_modes(:strict) do
context = Context.new
context.key?('unknown')
assert_empty(context.errors)
end
end
def test_key_lookup_will_raise_for_missing_keys_when_strict_variables_is_enabled
context = Context.new
context.strict_variables = true
assert_raises(Liquid::UndefinedVariable) do
context['unknown']
end
end
def test_has_key_will_not_raise_for_missing_keys_when_strict_variables_is_enabled
context = Context.new
context.strict_variables = true
refute(context.key?('unknown'))
assert_empty(context.errors)
end
def test_context_always_uses_static_registers
registers = {
my_register: :my_value,
}
c = Context.new({}, {}, registers)
assert_instance_of(Registers, c.registers)
assert_equal(:my_value, c.registers[:my_register])
r = Registers.new(registers)
c = Context.new({}, {}, r)
assert_instance_of(Registers, c.registers)
assert_equal(:my_value, c.registers[:my_register])
end
def test_variable_to_liquid_returns_contextual_drop
context = {
"products" => ProductsDrop.new(["A", "B", "C", "D", "E"]),
}
template = Liquid::Template.parse(<<~LIQUID)
{%- for i in (1..3) -%}
for_loop_products_count: {{ products | size }}
{% endfor %}
unscoped_products_count: {{ products | size }}
LIQUID
result = template.render(context)
assert_includes(result, "for_loop_products_count: 3")
assert_includes(result, "unscoped_products_count: 5")
end
def test_new_isolated_context_inherits_parent_environment
global_environment = Liquid::Environment.build(tags: {})
context = Context.build(environment: global_environment)
subcontext = context.new_isolated_subcontext
assert_equal(global_environment, subcontext.environment)
end
def test_newly_built_context_inherits_parent_environment
global_environment = Liquid::Environment.build(tags: {})
context = Context.build(environment: global_environment)
assert_equal(global_environment, context.environment)
assert(context.environment.tags.each.to_a.empty?)
end
private
def assert_no_object_allocations
unless RUBY_ENGINE == 'ruby'
skip("stackprof needed to count object allocations")
end
require 'stackprof'
profile = StackProf.run(mode: :object) do
yield
end
assert_equal(0, profile[:samples])
end
end # ContextTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/hash_rendering_test.rb | test/integration/hash_rendering_test.rb | # frozen_string_literal: true
require 'test_helper'
class HashRenderingTest < Minitest::Test
def test_render_empty_hash
assert_template_result("{}", "{{ my_hash }}", { "my_hash" => {} })
end
def test_render_hash_with_string_keys_and_values
assert_template_result("{\"key1\"=>\"value1\", \"key2\"=>\"value2\"}", "{{ my_hash }}", { "my_hash" => { "key1" => "value1", "key2" => "value2" } })
end
def test_render_hash_with_symbol_keys_and_integer_values
assert_template_result("{:key1=>1, :key2=>2}", "{{ my_hash }}", { "my_hash" => { key1: 1, key2: 2 } })
end
def test_render_nested_hash
assert_template_result("{\"outer\"=>{\"inner\"=>\"value\"}}", "{{ my_hash }}", { "my_hash" => { "outer" => { "inner" => "value" } } })
end
def test_render_hash_with_array_values
assert_template_result("{\"numbers\"=>[1, 2, 3]}", "{{ my_hash }}", { "my_hash" => { "numbers" => [1, 2, 3] } })
end
def test_render_recursive_hash
recursive_hash = { "self" => {} }
recursive_hash["self"]["self"] = recursive_hash
assert_template_result("{\"self\"=>{\"self\"=>{...}}}", "{{ my_hash }}", { "my_hash" => recursive_hash })
end
def test_hash_with_downcase_filter
assert_template_result("{\"key\"=>\"value\", \"anotherkey\"=>\"anothervalue\"}", "{{ my_hash | downcase }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_upcase_filter
assert_template_result("{\"KEY\"=>\"VALUE\", \"ANOTHERKEY\"=>\"ANOTHERVALUE\"}", "{{ my_hash | upcase }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_strip_filter
assert_template_result("{\"Key\"=>\"Value\", \"AnotherKey\"=>\"AnotherValue\"}", "{{ my_hash | strip }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_escape_filter
assert_template_result("{"Key"=>"Value", "AnotherKey"=>"AnotherValue"}", "{{ my_hash | escape }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_url_encode_filter
assert_template_result("%7B%22Key%22%3D%3E%22Value%22%2C+%22AnotherKey%22%3D%3E%22AnotherValue%22%7D", "{{ my_hash | url_encode }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_strip_html_filter
assert_template_result("{\"Key\"=>\"Value\", \"AnotherKey\"=>\"AnotherValue\"}", "{{ my_hash | strip_html }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_truncate__20_filter
assert_template_result("{\"Key\"=>\"Value\", ...", "{{ my_hash | truncate: 20 }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_replace___key____replaced_key__filter
assert_template_result("{\"Key\"=>\"Value\", \"AnotherKey\"=>\"AnotherValue\"}", "{{ my_hash | replace: 'key', 'replaced_key' }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_append____appended_text__filter
assert_template_result("{\"Key\"=>\"Value\", \"AnotherKey\"=>\"AnotherValue\"} appended text", "{{ my_hash | append: ' appended text' }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_hash_with_prepend___prepended_text___filter
assert_template_result("prepended text {\"Key\"=>\"Value\", \"AnotherKey\"=>\"AnotherValue\"}", "{{ my_hash | prepend: 'prepended text ' }}", { "my_hash" => { "Key" => "Value", "AnotherKey" => "AnotherValue" } })
end
def test_render_hash_with_array_values_empty
assert_template_result("{\"numbers\"=>[]}", "{{ my_hash }}", { "my_hash" => { "numbers" => [] } })
end
def test_render_hash_with_array_values_hash
assert_template_result("{\"numbers\"=>[{:foo=>42}]}", "{{ my_hash }}", { "my_hash" => { "numbers" => [{ foo: 42 }] } })
end
def test_join_filter_with_hash
array = [{ "key1" => "value1" }, { "key2" => "value2" }]
glue = { "lol" => "wut" }
assert_template_result("{\"key1\"=>\"value1\"}{\"lol\"=>\"wut\"}{\"key2\"=>\"value2\"}", "{{ my_array | join: glue }}", { "my_array" => array, "glue" => glue })
end
def test_render_hash_with_hash_key
assert_template_result("{{\"foo\"=>\"bar\"}=>42}", "{{ my_hash }}", { "my_hash" => { Hash["foo" => "bar"] => 42 } })
end
def test_rendering_hash_with_custom_to_s_method_uses_custom_to_s
assert_template_result("kewl", "{{ my_hash }}", { "my_hash" => HashWithCustomToS.new })
end
def test_rendering_hash_without_custom_to_s_uses_default_inspect
my_hash = HashWithoutCustomToS.new
my_hash[:foo] = :bar
assert_template_result("{:foo=>:bar}", "{{ my_hash }}", { "my_hash" => my_hash })
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/security_test.rb | test/integration/security_test.rb | # frozen_string_literal: true
require 'test_helper'
module SecurityFilter
def add_one(input)
"#{input} + 1"
end
end
class SecurityTest < Minitest::Test
include Liquid
def setup
@assigns = {}
end
def test_no_instance_eval
text = %( {{ '1+1' | instance_eval }} )
expected = %( 1+1 )
assert_equal(expected, Template.parse(text).render!(@assigns))
end
def test_no_existing_instance_eval
text = %( {{ '1+1' | __instance_eval__ }} )
expected = %( 1+1 )
assert_equal(expected, Template.parse(text).render!(@assigns))
end
def test_no_instance_eval_after_mixing_in_new_filter
text = %( {{ '1+1' | instance_eval }} )
expected = %( 1+1 )
assert_equal(expected, Template.parse(text).render!(@assigns))
end
def test_no_instance_eval_later_in_chain
text = %( {{ '1+1' | add_one | instance_eval }} )
expected = %( 1+1 + 1 )
assert_equal(expected, Template.parse(text).render!(@assigns, filters: SecurityFilter))
end
def test_does_not_permanently_add_filters_to_symbol_table
current_symbols = Symbol.all_symbols
# MRI imprecisely marks objects found on the C stack, which can result
# in uninitialized memory being marked. This can even result in the test failing
# deterministically for a given compilation of ruby. Using a separate thread will
# keep these writes of the symbol pointer on a separate stack that will be garbage
# collected after Thread#join.
Thread.new do
test = %( {{ "some_string" | a_bad_filter }} )
Template.parse(test).render!
nil
end.join
GC.start
assert_equal([], Symbol.all_symbols - current_symbols)
end
def test_does_not_add_drop_methods_to_symbol_table
current_symbols = Symbol.all_symbols
assigns = { 'drop' => Drop.new }
assert_equal("", Template.parse("{{ drop.custom_method_1 }}", assigns).render!)
assert_equal("", Template.parse("{{ drop.custom_method_2 }}", assigns).render!)
assert_equal("", Template.parse("{{ drop.custom_method_3 }}", assigns).render!)
assert_equal([], Symbol.all_symbols - current_symbols)
end
def test_max_depth_nested_blocks_does_not_raise_exception
depth = Liquid::Block::MAX_DEPTH
code = "{% if true %}" * depth + "rendered" + "{% endif %}" * depth
assert_equal("rendered", Template.parse(code).render!)
end
def test_more_than_max_depth_nested_blocks_raises_exception
depth = Liquid::Block::MAX_DEPTH + 1
code = "{% if true %}" * depth + "rendered" + "{% endif %}" * depth
assert_raises(Liquid::StackLevelError) do
Template.parse(code).render!
end
end
end # SecurityTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/output_test.rb | test/integration/output_test.rb | # frozen_string_literal: true
require 'test_helper'
module FunnyFilter
def make_funny(_input)
'LOL'
end
def cite_funny(input)
"LOL: #{input}"
end
def add_smiley(input, smiley = ":-)")
"#{input} #{smiley}"
end
def add_tag(input, tag = "p", id = "foo")
%(<#{tag} id="#{id}">#{input}</#{tag}>)
end
def paragraph(input)
"<p>#{input}</p>"
end
def link_to(name, url)
%(<a href="#{url}">#{name}</a>)
end
end
class OutputTest < Minitest::Test
include Liquid
def setup
@assigns = {
'car' => { 'bmw' => 'good', 'gm' => 'bad' },
}
end
def test_variable
assert_template_result(" bmw ", " {{best_cars}} ", { "best_cars" => "bmw" })
end
def test_variable_traversing_with_two_brackets
source = "{{ site.data.menu[include.menu][include.locale] }}"
assert_template_result("it works!", source, {
"site" => { "data" => { "menu" => { "foo" => { "bar" => "it works!" } } } },
"include" => { "menu" => "foo", "locale" => "bar" },
})
end
def test_variable_traversing
source = " {{car.bmw}} {{car.gm}} {{car.bmw}} "
assert_template_result(" good bad good ", source, @assigns)
end
def test_variable_piping
text = %( {{ car.gm | make_funny }} )
expected = %( LOL )
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_variable_piping_with_input
text = %( {{ car.gm | cite_funny }} )
expected = %( LOL: bad )
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_variable_piping_with_args
text = %! {{ car.gm | add_smiley : ':-(' }} !
expected = %| bad :-( |
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_variable_piping_with_no_args
text = %( {{ car.gm | add_smiley }} )
expected = %| bad :-) |
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_multiple_variable_piping_with_args
text = %! {{ car.gm | add_smiley : ':-(' | add_smiley : ':-('}} !
expected = %| bad :-( :-( |
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_variable_piping_with_multiple_args
text = %( {{ car.gm | add_tag : 'span', 'bar'}} )
expected = %( <span id="bar">bad</span> )
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_variable_piping_with_variable_args
text = %( {{ car.gm | add_tag : 'span', car.bmw}} )
expected = %( <span id="good">bad</span> )
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
def test_multiple_pipings
assigns = { 'best_cars' => 'bmw' }
text = %( {{ best_cars | cite_funny | paragraph }} )
expected = %( <p>LOL: bmw</p> )
assert_equal(expected, Template.parse(text).render!(assigns, filters: [FunnyFilter]))
end
def test_link_to
text = %( {{ 'Typo' | link_to: 'http://typo.leetsoft.com' }} )
expected = %( <a href="http://typo.leetsoft.com">Typo</a> )
assert_equal(expected, Template.parse(text).render!(@assigns, filters: [FunnyFilter]))
end
end # OutputTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/assign_test.rb | test/integration/assign_test.rb | # frozen_string_literal: true
require 'test_helper'
class AssignTest < Minitest::Test
include Liquid
def test_assign_with_hyphen_in_variable_name
template_source = <<~END_TEMPLATE
{% assign this-thing = 'Print this-thing' -%}
{{ this-thing -}}
END_TEMPLATE
assert_template_result("Print this-thing", template_source)
end
def test_assigned_variable
assert_template_result(
'.foo.',
'{% assign foo = values %}.{{ foo[0] }}.',
{ 'values' => %w(foo bar baz) },
)
assert_template_result(
'.bar.',
'{% assign foo = values %}.{{ foo[1] }}.',
{ 'values' => %w(foo bar baz) },
)
end
def test_assign_with_filter
assert_template_result(
'.bar.',
'{% assign foo = values | split: "," %}.{{ foo[1] }}.',
{ 'values' => "foo,bar,baz" },
)
end
def test_assign_syntax_error
assert_match_syntax_error(/assign/, '{% assign foo not values %}.')
end
def test_assign_uses_error_mode
assert_match_syntax_error(
"Expected dotdot but found pipe in ",
"{% assign foo = ('X' | downcase) %}",
error_mode: :strict,
)
assert_template_result("", "{% assign foo = ('X' | downcase) %}", error_mode: :lax)
end
def test_expression_with_whitespace_in_square_brackets
source = "{% assign r = a[ 'b' ] %}{{ r }}"
assert_template_result('result', source, { 'a' => { 'b' => 'result' } })
end
def test_assign_score_exceeding_resource_limit
t = Template.parse("{% assign foo = 42 %}{% assign bar = 23 %}")
t.resource_limits.assign_score_limit = 1
assert_equal("Liquid error: Memory limits exceeded", t.render)
assert(t.resource_limits.reached?)
t.resource_limits.assign_score_limit = 2
assert_equal("", t.render!)
refute_nil(t.resource_limits.assign_score)
end
def test_assign_score_exceeding_limit_from_composite_object
t = Template.parse("{% assign foo = 'aaaa' | reverse %}")
t.resource_limits.assign_score_limit = 3
assert_equal("Liquid error: Memory limits exceeded", t.render)
assert(t.resource_limits.reached?)
t.resource_limits.assign_score_limit = 5
assert_equal("", t.render!)
end
def test_assign_score_of_int
assert_equal(1, assign_score_of(123))
end
def test_assign_score_of_string_counts_bytes
assert_equal(3, assign_score_of('123'))
assert_equal(5, assign_score_of('12345'))
assert_equal(9, assign_score_of('すごい'))
end
def test_assign_score_of_array
assert_equal(1, assign_score_of([]))
assert_equal(2, assign_score_of([123]))
assert_equal(6, assign_score_of([123, 'abcd']))
end
def test_assign_score_of_hash
assert_equal(1, assign_score_of({}))
assert_equal(5, assign_score_of('int' => 123))
assert_equal(12, assign_score_of('int' => 123, 'str' => 'abcd'))
end
private
class ObjectWrapperDrop < Liquid::Drop
def initialize(obj)
@obj = obj
end
def value
@obj
end
end
def assign_score_of(obj)
context = Liquid::Context.new('drop' => ObjectWrapperDrop.new(obj))
Liquid::Template.parse('{% assign obj = drop.value %}').render!(context)
context.resource_limits.assign_score
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/block_test.rb | test/integration/block_test.rb | # frozen_string_literal: true
require 'test_helper'
class BlockTest < Minitest::Test
include Liquid
def test_unexpected_end_tag
source = '{% if true %}{% endunless %}'
assert_match_syntax_error("Liquid syntax error (line 1): 'endunless' is not a valid delimiter for if tags. use endif", source)
end
def test_with_custom_tag
with_custom_tag('testtag', Block) do
assert(Liquid::Template.parse("{% testtag %} {% endtesttag %}"))
end
end
def test_custom_block_tags_have_a_default_render_to_output_buffer_method_for_backwards_compatibility
klass1 = Class.new(Block) do
def render(*)
'hello'
end
end
with_custom_tag('blabla', klass1) do
template = Liquid::Template.parse("{% blabla %} bla {% endblabla %}")
assert_equal('hello', template.render)
buf = +''
output = template.render({}, output: buf)
assert_equal('hello', output)
assert_equal('hello', buf)
assert_equal(buf.object_id, output.object_id)
end
klass2 = Class.new(klass1) do
def render(*)
'foo' + super + 'bar'
end
end
with_custom_tag('blabla', klass2) do
template = Liquid::Template.parse("{% blabla %} foo {% endblabla %}")
assert_equal('foohellobar', template.render)
buf = +''
output = template.render({}, output: buf)
assert_equal('foohellobar', output)
assert_equal('foohellobar', buf)
assert_equal(buf.object_id, output.object_id)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/error_handling_test.rb | test/integration/error_handling_test.rb | # frozen_string_literal: true
require 'test_helper'
class ErrorHandlingTest < Minitest::Test
include Liquid
def test_templates_parsed_with_line_numbers_renders_them_in_errors
template = <<-LIQUID
Hello,
{{ errors.standard_error }} will raise a standard error.
Bla bla test.
{{ errors.syntax_error }} will raise a syntax error.
This is an argument error: {{ errors.argument_error }}
Bla.
LIQUID
expected = <<-TEXT
Hello,
Liquid error (line 3): standard error will raise a standard error.
Bla bla test.
Liquid syntax error (line 7): syntax error will raise a syntax error.
This is an argument error: Liquid error (line 9): argument error
Bla.
TEXT
output = Liquid::Template.parse(template, line_numbers: true).render('errors' => ErrorDrop.new)
assert_equal(expected, output)
end
def test_standard_error
template = Liquid::Template.parse(' {{ errors.standard_error }} ')
assert_equal(' Liquid error: standard error ', template.render('errors' => ErrorDrop.new))
assert_equal(1, template.errors.size)
assert_equal(StandardError, template.errors.first.class)
end
def test_syntax
template = Liquid::Template.parse(' {{ errors.syntax_error }} ')
assert_equal(' Liquid syntax error: syntax error ', template.render('errors' => ErrorDrop.new))
assert_equal(1, template.errors.size)
assert_equal(SyntaxError, template.errors.first.class)
end
def test_argument
template = Liquid::Template.parse(' {{ errors.argument_error }} ')
assert_equal(' Liquid error: argument error ', template.render('errors' => ErrorDrop.new))
assert_equal(1, template.errors.size)
assert_equal(ArgumentError, template.errors.first.class)
end
def test_missing_endtag_parse_time_error
assert_match_syntax_error(/: 'for' tag was never closed\z/, ' {% for a in b %} ... ')
end
def test_unrecognized_operator
with_error_modes(:strict) do
assert_raises(SyntaxError) do
Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ')
end
end
end
def test_lax_unrecognized_operator
template = Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', error_mode: :lax)
assert_equal(' Liquid error: Unknown operator =! ', template.render)
assert_equal(1, template.errors.size)
assert_equal(Liquid::ArgumentError, template.errors.first.class)
end
def test_with_line_numbers_adds_numbers_to_parser_errors
source = <<~LIQUID
foobar
{% "cat" | foobar %}
bla
LIQUID
assert_match_syntax_error(/Liquid syntax error \(line 3\)/, source)
end
def test_with_line_numbers_adds_numbers_to_parser_errors_with_whitespace_trim
source = <<~LIQUID
foobar
{%- "cat" | foobar -%}
bla
LIQUID
assert_match_syntax_error(/Liquid syntax error \(line 3\)/, source)
end
def test_parsing_warn_with_line_numbers_adds_numbers_to_lexer_errors
template = Liquid::Template.parse(
'
foobar
{% if 1 =! 2 %}ok{% endif %}
bla
',
error_mode: :warn,
line_numbers: true,
)
assert_equal(
['Liquid syntax error (line 4): Unexpected character = in "1 =! 2"'],
template.warnings.map(&:message),
)
end
def test_parsing_strict_with_line_numbers_adds_numbers_to_lexer_errors
err = assert_raises(SyntaxError) do
Liquid::Template.parse(
'
foobar
{% if 1 =! 2 %}ok{% endif %}
bla
',
error_mode: :strict,
line_numbers: true,
)
end
assert_equal('Liquid syntax error (line 4): Unexpected character = in "1 =! 2"', err.message)
end
def test_syntax_errors_in_nested_blocks_have_correct_line_number
source = <<~LIQUID
foobar
{% if 1 != 2 %}
{% foo %}
{% endif %}
bla
LIQUID
assert_match_syntax_error("Liquid syntax error (line 4): Unknown tag 'foo'", source)
end
def test_strict_error_messages
err = assert_raises(SyntaxError) do
Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', error_mode: :strict)
end
assert_equal('Liquid syntax error: Unexpected character = in "1 =! 2"', err.message)
err = assert_raises(SyntaxError) do
Liquid::Template.parse('{{%%%}}', error_mode: :strict)
end
assert_equal('Liquid syntax error: Unexpected character % in "{{%%%}}"', err.message)
end
def test_warnings
template = Liquid::Template.parse('{% if ~~~ %}{{%%%}}{% else %}{{ hello. }}{% endif %}', error_mode: :warn)
assert_equal(3, template.warnings.size)
assert_equal('Unexpected character ~ in "~~~"', template.warnings[0].to_s(false))
assert_equal('Unexpected character % in "{{%%%}}"', template.warnings[1].to_s(false))
assert_equal('Expected id but found end_of_string in "{{ hello. }}"', template.warnings[2].to_s(false))
assert_equal('', template.render)
end
def test_warning_line_numbers
template = Liquid::Template.parse("{% if ~~~ %}\n{{%%%}}{% else %}\n{{ hello. }}{% endif %}", error_mode: :warn, line_numbers: true)
assert_equal('Liquid syntax error (line 1): Unexpected character ~ in "~~~"', template.warnings[0].message)
assert_equal('Liquid syntax error (line 2): Unexpected character % in "{{%%%}}"', template.warnings[1].message)
assert_equal('Liquid syntax error (line 3): Expected id but found end_of_string in "{{ hello. }}"', template.warnings[2].message)
assert_equal(3, template.warnings.size)
assert_equal([1, 2, 3], template.warnings.map(&:line_number))
end
# Liquid should not catch Exceptions that are not subclasses of StandardError, like Interrupt and NoMemoryError
def test_exceptions_propagate
assert_raises(Exception) do
template = Liquid::Template.parse('{{ errors.exception }}')
template.render('errors' => ErrorDrop.new)
end
end
def test_default_exception_renderer_with_internal_error
template = Liquid::Template.parse('This is a runtime error: {{ errors.runtime_error }}', line_numbers: true)
output = template.render('errors' => ErrorDrop.new)
assert_equal('This is a runtime error: Liquid error (line 1): internal', output)
assert_equal([Liquid::InternalError], template.errors.map(&:class))
end
def test_setting_default_exception_renderer
exceptions = []
default_exception_renderer = ->(e) {
exceptions << e
''
}
env = Liquid::Environment.build(exception_renderer: default_exception_renderer)
template = Liquid::Template.parse('This is a runtime error: {{ errors.argument_error }}', environment: env)
output = template.render('errors' => ErrorDrop.new)
assert_equal('This is a runtime error: ', output)
assert_equal([Liquid::ArgumentError], template.errors.map(&:class))
end
def test_setting_exception_renderer_on_environment
exceptions = []
exception_renderer = ->(e) do
exceptions << e
''
end
environment = Liquid::Environment.build(exception_renderer: exception_renderer)
template = Liquid::Template.parse('This is a runtime error: {{ errors.argument_error }}', environment: environment)
output = template.render('errors' => ErrorDrop.new)
assert_equal('This is a runtime error: ', output)
assert_equal([Liquid::ArgumentError], template.errors.map(&:class))
end
def test_exception_renderer_exposing_non_liquid_error
template = Liquid::Template.parse('This is a runtime error: {{ errors.runtime_error }}', line_numbers: true)
exceptions = []
handler = ->(e) {
exceptions << e
e.cause
}
output = template.render({ 'errors' => ErrorDrop.new }, exception_renderer: handler)
assert_equal('This is a runtime error: runtime error', output)
assert_equal([Liquid::InternalError], exceptions.map(&:class))
assert_equal(exceptions, template.errors)
assert_equal('#<RuntimeError: runtime error>', exceptions.first.cause.inspect)
end
class TestFileSystem
def read_template_file(_template_path)
"{{ errors.argument_error }}"
end
end
def test_included_template_name_with_line_numbers
environment = Liquid::Environment.build(file_system: TestFileSystem.new)
template = Liquid::Template.parse("Argument error:\n{% include 'product' %}", line_numbers: true, environment: environment)
page = template.render('errors' => ErrorDrop.new)
assert_equal("Argument error:\nLiquid error (product line 1): argument error", page)
assert_equal("product", template.errors.first.template_name)
end
def test_bug_compatible_silencing_of_errors_in_blank_nodes
output = Liquid::Template.parse("{% assign x = 0 %}{% if 1 < '2' %}not blank{% assign x = 3 %}{% endif %}{{ x }}").render
assert_equal("Liquid error: comparison of Integer with String failed0", output)
output = Liquid::Template.parse("{% assign x = 0 %}{% if 1 < '2' %}{% assign x = 3 %}{% endif %}{{ x }}").render
assert_equal("0", output)
end
def test_syntax_error_is_raised_with_template_name
file_system = StubFileSystem.new("snippet" => "1\n2\n{{ 1")
context = Liquid::Context.build(
registers: { file_system: file_system },
)
template = Template.parse(
'{% render "snippet" %}',
line_numbers: true,
)
template.name = "template/index"
assert_equal(
"Liquid syntax error (snippet line 3): Variable '{{' was not properly terminated with regexp: /\\}\\}/",
template.render(context),
)
end
def test_syntax_error_is_raised_with_template_name_from_template_factory
file_system = StubFileSystem.new("snippet" => "1\n2\n{{ 1")
context = Liquid::Context.build(
registers: {
file_system: file_system,
template_factory: StubTemplateFactory.new,
},
)
template = Template.parse(
'{% render "snippet" %}',
line_numbers: true,
)
template.name = "template/index"
assert_equal(
"Liquid syntax error (some/path/snippet line 3): Variable '{{' was not properly terminated with regexp: /\\}\\}/",
template.render(context),
)
end
def test_error_is_raised_during_parse_with_template_name
depth = Liquid::Block::MAX_DEPTH + 1
code = "{% if true %}" * depth + "rendered" + "{% endif %}" * depth
template = Template.parse("{% render 'snippet' %}", line_numbers: true)
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new("snippet" => code),
template_factory: StubTemplateFactory.new,
},
)
assert_equal("Liquid error (some/path/snippet line 1): Nesting too deep", template.render(context))
end
def test_internal_error_is_raised_with_template_name
template = Template.new
template.parse(
"{% render 'snippet' %}",
line_numbers: true,
)
template.name = "template/index"
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new({}),
},
)
assert_equal(
"Liquid error (template/index line 1): internal",
template.render(context),
)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/profiler_test.rb | test/integration/profiler_test.rb | # frozen_string_literal: true
require 'test_helper'
class ProfilerTest < Minitest::Test
class TestDrop < Liquid::Drop
def initialize(value)
super()
@value = value
end
def to_s
artificial_execution_time
@value
end
private
# Monotonic clock precision fluctuate based on the operating system
# By introducing a small sleep we ensure ourselves to register a non zero unit of time
def artificial_execution_time
sleep(Process.clock_getres(Process::CLOCK_MONOTONIC))
end
end
include Liquid
class ProfilingFileSystem
def read_template_file(template_path)
"Rendering template {% assign template_name = '#{template_path}'%}\n{{ template_name }}"
end
end
def setup
Liquid::Environment.default.file_system = ProfilingFileSystem.new
end
def test_template_allows_flagging_profiling
t = Template.parse("{{ 'a string' | upcase }}")
t.render!
assert_nil(t.profiler)
end
def test_parse_makes_available_simple_profiling
t = Template.parse("{{ 'a string' | upcase }}", profile: true)
t.render!
assert_equal(1, t.profiler.length)
node = t.profiler[0]
assert_equal(" 'a string' | upcase ", node.code)
end
def test_render_ignores_raw_strings_when_profiling
t = Template.parse("This is raw string\nstuff\nNewline", profile: true)
t.render!
assert_equal(0, t.profiler.length)
end
def test_profiling_includes_line_numbers_of_liquid_nodes
t = Template.parse("{{ 'a string' | upcase }}\n{% increment test %}", profile: true)
t.render!
assert_equal(2, t.profiler.length)
# {{ 'a string' | upcase }}
assert_equal(1, t.profiler[0].line_number)
# {{ increment test }}
assert_equal(2, t.profiler[1].line_number)
end
def test_profiling_includes_line_numbers_of_included_partials
t = Template.parse("{% include 'a_template' %}", profile: true)
t.render!
included_children = t.profiler[0].children
# {% assign template_name = 'a_template' %}
assert_equal(1, included_children[0].line_number)
# {{ template_name }}
assert_equal(2, included_children[1].line_number)
end
def test_profiling_render_tag
t = Template.parse("{% render 'a_template' %}", profile: true)
t.render!
render_children = t.profiler[0].children
render_children.each do |timing|
assert_equal('a_template', timing.partial)
end
assert_equal([1, 2], render_children.map(&:line_number))
end
def test_profiling_times_the_rendering_of_tokens
t = Template.parse("{% include 'a_template' %}", profile: true)
t.render!
node = t.profiler[0]
refute_nil(node.render_time)
end
def test_profiling_times_the_entire_render
t = Template.parse("{% include 'a_template' %}", profile: true)
t.render!
assert(t.profiler.total_render_time >= 0, "Total render time was not calculated")
end
class SleepTag < Liquid::Tag
def initialize(tag_name, markup, parse_context)
super
@duration = Float(markup)
end
def render_to_output_buffer(_context, _output)
sleep(@duration)
end
end
def test_profiling_multiple_renders
with_custom_tag('sleep', SleepTag) do
context = Liquid::Context.new
t = Liquid::Template.parse("{% sleep 0.001 %}", profile: true)
context.template_name = 'index'
t.render!(context)
context.template_name = 'layout'
first_render_time = context.profiler.total_time
t.render!(context)
profiler = context.profiler
children = profiler.children
assert_operator(first_render_time, :>=, 0.001)
assert_operator(profiler.total_time, :>=, 0.001 + first_render_time)
assert_equal(["index", "layout"], children.map(&:template_name))
assert_equal([nil, nil], children.map(&:code))
assert_equal(profiler.total_time, children.map(&:total_time).reduce(&:+))
end
end
def test_profiling_uses_include_to_mark_children
t = Template.parse("{{ 'a string' | upcase }}\n{% include 'a_template' %}", profile: true)
t.render!
include_node = t.profiler[1]
assert_equal(2, include_node.children.length)
end
def test_profiling_marks_children_with_the_name_of_included_partial
t = Template.parse("{{ 'a string' | upcase }}\n{% include 'a_template' %}", profile: true)
t.render!
include_node = t.profiler[1]
include_node.children.each do |child|
assert_equal("a_template", child.partial)
end
end
def test_profiling_supports_multiple_templates
t = Template.parse("{{ 'a string' | upcase }}\n{% include 'a_template' %}\n{% include 'b_template' %}", profile: true)
t.render!
a_template = t.profiler[1]
a_template.children.each do |child|
assert_equal("a_template", child.partial)
end
b_template = t.profiler[2]
b_template.children.each do |child|
assert_equal("b_template", child.partial)
end
end
def test_profiling_supports_rendering_the_same_partial_multiple_times
t = Template.parse("{{ 'a string' | upcase }}\n{% include 'a_template' %}\n{% include 'a_template' %}", profile: true)
t.render!
a_template1 = t.profiler[1]
a_template1.children.each do |child|
assert_equal("a_template", child.partial)
end
a_template2 = t.profiler[2]
a_template2.children.each do |child|
assert_equal("a_template", child.partial)
end
end
def test_can_iterate_over_each_profiling_entry
t = Template.parse("{{ 'a string' | upcase }}\n{% increment test %}", profile: true)
t.render!
timing_count = 0
t.profiler.each do |_timing|
timing_count += 1
end
assert_equal(2, timing_count)
end
def test_profiling_marks_children_of_if_blocks
t = Template.parse("{% if true %} {% increment test %} {{ test }} {% endif %}", profile: true)
t.render!
assert_equal(1, t.profiler.length)
assert_equal(2, t.profiler[0].children.length)
end
def test_profiling_marks_children_of_for_blocks
t = Template.parse("{% for item in collection %} {{ item }} {% endfor %}", profile: true)
t.render!("collection" => ["one", "two"])
assert_equal(1, t.profiler.length)
# Will profile each invocation of the for block
assert_equal(2, t.profiler[0].children.length)
end
def test_profiling_supports_self_time
t = Template.parse("{% for item in collection %} {{ item }} {% endfor %}", profile: true)
collection = [
TestDrop.new("one"),
TestDrop.new("two"),
]
output = t.render!("collection" => collection)
assert_equal(" one two ", output)
leaf = t.profiler[0].children[0]
assert_operator(leaf.self_time, :>, 0.0)
end
def test_profiling_supports_total_time
t = Template.parse("{% if true %} {{ test }} {% endif %}", profile: true)
output = t.render!("test" => TestDrop.new("one"))
assert_equal(" one ", output)
assert_operator(t.profiler[0].total_time, :>, 0.0)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/standard_filter_test.rb | test/integration/standard_filter_test.rb | # encoding: utf-8
# frozen_string_literal: true
require 'test_helper'
class TestThing
attr_reader :foo
def initialize
@foo = 0
end
def to_s
"woot: #{@foo}"
end
def [](_whatever)
to_s
end
def to_liquid
@foo += 1
self
end
end
class TestDrop < Liquid::Drop
def initialize(value:)
@value = value
end
attr_reader :value
def registers
"{#{@value.inspect}=>#{@context.registers[@value].inspect}}"
end
end
class TestModel
def initialize(value:)
@value = value
end
def to_liquid
TestDrop.new(value: @value)
end
end
class TestEnumerable < Liquid::Drop
include Enumerable
def each(&block)
[{ "foo" => 1, "bar" => 2 }, { "foo" => 2, "bar" => 1 }, { "foo" => 3, "bar" => 3 }].each(&block)
end
end
class NumberLikeThing < Liquid::Drop
def initialize(amount)
@amount = amount
end
def to_number
@amount
end
end
class StandardFiltersTest < Minitest::Test
Filters = Class.new(Liquid::StrainerTemplate)
Filters.add_filter(Liquid::StandardFilters)
include Liquid
def setup
@filters = Filters.new(Context.new)
end
def test_size
assert_equal(3, @filters.size([1, 2, 3]))
assert_equal(0, @filters.size([]))
assert_equal(0, @filters.size(nil))
end
def test_downcase
assert_equal('testing', @filters.downcase("Testing"))
assert_equal('', @filters.downcase(nil))
end
def test_upcase
assert_equal('TESTING', @filters.upcase("Testing"))
assert_equal('', @filters.upcase(nil))
end
def test_slice
assert_equal('oob', @filters.slice('foobar', 1, 3))
assert_equal('oobar', @filters.slice('foobar', 1, 1000))
assert_equal('', @filters.slice('foobar', 1, 0))
assert_equal('o', @filters.slice('foobar', 1, 1))
assert_equal('bar', @filters.slice('foobar', 3, 3))
assert_equal('ar', @filters.slice('foobar', -2, 2))
assert_equal('ar', @filters.slice('foobar', -2, 1000))
assert_equal('r', @filters.slice('foobar', -1))
assert_equal('', @filters.slice(nil, 0))
assert_equal('', @filters.slice('foobar', 100, 10))
assert_equal('', @filters.slice('foobar', -100, 10))
assert_equal('oob', @filters.slice('foobar', '1', '3'))
assert_raises(Liquid::ArgumentError) do
@filters.slice('foobar', nil)
end
assert_raises(Liquid::ArgumentError) do
@filters.slice('foobar', 0, "")
end
assert_equal("", @filters.slice("foobar", 0, -(1 << 64)))
assert_equal("foobar", @filters.slice("foobar", 0, 1 << 63))
assert_equal("", @filters.slice("foobar", 1 << 63, 6))
assert_equal("", @filters.slice("foobar", -(1 << 63), 6))
end
def test_slice_on_arrays
input = 'foobar'.split('')
assert_equal(%w(o o b), @filters.slice(input, 1, 3))
assert_equal(%w(o o b a r), @filters.slice(input, 1, 1000))
assert_equal(%w(), @filters.slice(input, 1, 0))
assert_equal(%w(o), @filters.slice(input, 1, 1))
assert_equal(%w(b a r), @filters.slice(input, 3, 3))
assert_equal(%w(a r), @filters.slice(input, -2, 2))
assert_equal(%w(a r), @filters.slice(input, -2, 1000))
assert_equal(%w(r), @filters.slice(input, -1))
assert_equal(%w(), @filters.slice(input, 100, 10))
assert_equal(%w(), @filters.slice(input, -100, 10))
assert_equal([], @filters.slice(input, 0, -(1 << 64)))
assert_equal(input, @filters.slice(input, 0, 1 << 63))
assert_equal([], @filters.slice(input, 1 << 63, 6))
assert_equal([], @filters.slice(input, -(1 << 63), 6))
end
def test_find_on_empty_array
assert_nil(@filters.find([], 'foo', 'bar'))
end
def test_find_index_on_empty_array
assert_nil(@filters.find_index([], 'foo', 'bar'))
end
def test_has_on_empty_array
refute(@filters.has([], 'foo', 'bar'))
end
def test_truncate
assert_equal('1234...', @filters.truncate('1234567890', 7))
assert_equal('1234567890', @filters.truncate('1234567890', 20))
assert_equal('...', @filters.truncate('1234567890', 0))
assert_equal('1234567890', @filters.truncate('1234567890'))
assert_equal("测试...", @filters.truncate("测试测试测试测试", 5))
assert_equal('12341', @filters.truncate("1234567890", 5, 1))
assert_equal("foobar", @filters.truncate("foobar", 1 << 63))
assert_equal("...", @filters.truncate("foobar", -(1 << 63)))
end
def test_split
assert_equal(['12', '34'], @filters.split('12~34', '~'))
assert_equal(['A? ', ' ,Z'], @filters.split('A? ~ ~ ~ ,Z', '~ ~ ~'))
assert_equal(['A?Z'], @filters.split('A?Z', '~'))
assert_equal([], @filters.split(nil, ' '))
assert_equal(['A', 'Z'], @filters.split('A1Z', 1))
end
def test_escape
assert_equal('<strong>', @filters.escape('<strong>'))
assert_equal('1', @filters.escape(1))
assert_equal('2001-02-03', @filters.escape(Date.new(2001, 2, 3)))
assert_nil(@filters.escape(nil))
end
def test_h
assert_equal('<strong>', @filters.h('<strong>'))
assert_equal('1', @filters.h(1))
assert_equal('2001-02-03', @filters.h(Date.new(2001, 2, 3)))
assert_nil(@filters.h(nil))
end
def test_escape_once
assert_equal('<strong>Hulk</strong>', @filters.escape_once('<strong>Hulk</strong>'))
end
def test_base64_encode
assert_equal('b25lIHR3byB0aHJlZQ==', @filters.base64_encode('one two three'))
assert_equal('', @filters.base64_encode(nil))
end
def test_base64_decode
decoded = @filters.base64_decode('b25lIHR3byB0aHJlZQ==')
assert_equal('one two three', decoded)
assert_equal(Encoding::UTF_8, decoded.encoding)
decoded = @filters.base64_decode('4pyF')
assert_equal('✅', decoded)
assert_equal(Encoding::UTF_8, decoded.encoding)
decoded = @filters.base64_decode("/w==")
assert_equal(Encoding::ASCII_8BIT, decoded.encoding)
assert_equal((+"\xFF").force_encoding(Encoding::ASCII_8BIT), decoded)
exception = assert_raises(Liquid::ArgumentError) do
@filters.base64_decode("invalidbase64")
end
assert_equal('Liquid error: invalid base64 provided to base64_decode', exception.message)
end
def test_base64_url_safe_encode
assert_equal(
'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXogQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVogMTIzNDU2Nzg5MCAhQCMkJV4mKigpLT1fKy8_Ljo7W117fVx8',
@filters.base64_url_safe_encode('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 !@#$%^&*()-=_+/?.:;[]{}\|'),
)
assert_equal('', @filters.base64_url_safe_encode(nil))
end
def test_base64_url_safe_decode
decoded = @filters.base64_url_safe_decode('YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXogQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVogMTIzNDU2Nzg5MCAhQCMkJV4mKigpLT1fKy8_Ljo7W117fVx8')
assert_equal(
'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 !@#$%^&*()-=_+/?.:;[]{}\|',
decoded,
)
assert_equal(Encoding::UTF_8, decoded.encoding)
decoded = @filters.base64_url_safe_decode('4pyF')
assert_equal('✅', decoded)
assert_equal(Encoding::UTF_8, decoded.encoding)
decoded = @filters.base64_url_safe_decode("_w==")
assert_equal(Encoding::ASCII_8BIT, decoded.encoding)
assert_equal((+"\xFF").force_encoding(Encoding::ASCII_8BIT), decoded)
exception = assert_raises(Liquid::ArgumentError) do
@filters.base64_url_safe_decode("invalidbase64")
end
assert_equal('Liquid error: invalid base64 provided to base64_url_safe_decode', exception.message)
end
def test_url_encode
assert_equal('foo%2B1%40example.com', @filters.url_encode('foo+1@example.com'))
assert_equal('1', @filters.url_encode(1))
assert_equal('2001-02-03', @filters.url_encode(Date.new(2001, 2, 3)))
assert_nil(@filters.url_encode(nil))
end
def test_url_decode
assert_equal('foo bar', @filters.url_decode('foo+bar'))
assert_equal('foo bar', @filters.url_decode('foo%20bar'))
assert_equal('foo+1@example.com', @filters.url_decode('foo%2B1%40example.com'))
assert_equal('1', @filters.url_decode(1))
assert_equal('2001-02-03', @filters.url_decode(Date.new(2001, 2, 3)))
assert_nil(@filters.url_decode(nil))
exception = assert_raises(Liquid::ArgumentError) do
@filters.url_decode('%ff')
end
assert_equal('Liquid error: invalid byte sequence in UTF-8', exception.message)
end
def test_truncatewords
assert_equal('one two three', @filters.truncatewords('one two three', 4))
assert_equal('one two...', @filters.truncatewords('one two three', 2))
assert_equal('one two three', @filters.truncatewords('one two three'))
assert_equal(
'Two small (13” x 5.5” x 10” high) baskets fit inside one large basket (13”...',
@filters.truncatewords('Two small (13” x 5.5” x 10” high) baskets fit inside one large basket (13” x 16” x 10.5” high) with cover.', 15),
)
assert_equal("测试测试测试测试", @filters.truncatewords('测试测试测试测试', 5))
assert_equal('one two1', @filters.truncatewords("one two three", 2, 1))
assert_equal('one two three...', @filters.truncatewords("one two\tthree\nfour", 3))
assert_equal('one two...', @filters.truncatewords("one two three four", 2))
assert_equal('one...', @filters.truncatewords("one two three four", 0))
assert_equal('one two three four', @filters.truncatewords("one two three four", 1 << 31))
assert_equal('one...', @filters.truncatewords("one two three four", -(1 << 32)))
end
def test_strip_html
assert_equal('test', @filters.strip_html("<div>test</div>"))
assert_equal('test', @filters.strip_html("<div id='test'>test</div>"))
assert_equal('', @filters.strip_html("<script type='text/javascript'>document.write('some stuff');</script>"))
assert_equal('', @filters.strip_html("<style type='text/css'>foo bar</style>"))
assert_equal('test', @filters.strip_html("<div\nclass='multiline'>test</div>"))
assert_equal('test', @filters.strip_html("<!-- foo bar \n test -->test"))
assert_equal('', @filters.strip_html(nil))
# Quirk of the existing implementation
assert_equal('foo;', @filters.strip_html("<<<script </script>script>foo;</script>"))
end
def test_join
assert_equal('1 2 3 4', @filters.join([1, 2, 3, 4]))
assert_equal('1 - 2 - 3 - 4', @filters.join([1, 2, 3, 4], ' - '))
assert_equal('1121314', @filters.join([1, 2, 3, 4], 1))
end
def test_join_calls_to_liquid_on_each_element
assert_equal('i did it, i did it', @filters.join([CustomToLiquidDrop.new('i did it'), CustomToLiquidDrop.new('i did it')], ", "))
end
def test_sort
assert_equal([1, 2, 3, 4], @filters.sort([4, 3, 2, 1]))
assert_equal([{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }], @filters.sort([{ "a" => 4 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a"))
end
def test_sort_with_nils
assert_equal([1, 2, 3, 4, nil], @filters.sort([nil, 4, 3, 2, 1]))
assert_equal([{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }, {}], @filters.sort([{ "a" => 4 }, { "a" => 3 }, {}, { "a" => 1 }, { "a" => 2 }], "a"))
end
def test_sort_when_property_is_sometimes_missing_puts_nils_last
input = [
{ "price" => 4, "handle" => "alpha" },
{ "handle" => "beta" },
{ "price" => 1, "handle" => "gamma" },
{ "handle" => "delta" },
{ "price" => 2, "handle" => "epsilon" },
]
expectation = [
{ "price" => 1, "handle" => "gamma" },
{ "price" => 2, "handle" => "epsilon" },
{ "price" => 4, "handle" => "alpha" },
{ "handle" => "beta" },
{ "handle" => "delta" },
]
assert_equal(expectation, @filters.sort(input, "price"))
end
def test_sort_natural
assert_equal(["a", "B", "c", "D"], @filters.sort_natural(["c", "D", "a", "B"]))
assert_equal([{ "a" => "a" }, { "a" => "B" }, { "a" => "c" }, { "a" => "D" }], @filters.sort_natural([{ "a" => "D" }, { "a" => "c" }, { "a" => "a" }, { "a" => "B" }], "a"))
end
def test_sort_natural_with_nils
assert_equal(["a", "B", "c", "D", nil], @filters.sort_natural([nil, "c", "D", "a", "B"]))
assert_equal([{ "a" => "a" }, { "a" => "B" }, { "a" => "c" }, { "a" => "D" }, {}], @filters.sort_natural([{ "a" => "D" }, { "a" => "c" }, {}, { "a" => "a" }, { "a" => "B" }], "a"))
end
def test_sort_natural_when_property_is_sometimes_missing_puts_nils_last
input = [
{ "price" => "4", "handle" => "alpha" },
{ "handle" => "beta" },
{ "price" => "1", "handle" => "gamma" },
{ "handle" => "delta" },
{ "price" => 2, "handle" => "epsilon" },
]
expectation = [
{ "price" => "1", "handle" => "gamma" },
{ "price" => 2, "handle" => "epsilon" },
{ "price" => "4", "handle" => "alpha" },
{ "handle" => "beta" },
{ "handle" => "delta" },
]
assert_equal(expectation, @filters.sort_natural(input, "price"))
end
def test_sort_natural_case_check
input = [
{ "key" => "X" },
{ "key" => "Y" },
{ "key" => "Z" },
{ "fake" => "t" },
{ "key" => "a" },
{ "key" => "b" },
{ "key" => "c" },
]
expectation = [
{ "key" => "a" },
{ "key" => "b" },
{ "key" => "c" },
{ "key" => "X" },
{ "key" => "Y" },
{ "key" => "Z" },
{ "fake" => "t" },
]
assert_equal(expectation, @filters.sort_natural(input, "key"))
assert_equal(["a", "b", "c", "X", "Y", "Z"], @filters.sort_natural(["X", "Y", "Z", "a", "b", "c"]))
end
def test_sort_empty_array
assert_equal([], @filters.sort([], "a"))
end
def test_sort_invalid_property
foo = [
[1],
[2],
[3],
]
assert_raises(Liquid::ArgumentError) do
@filters.sort(foo, "bar")
end
end
def test_sort_natural_empty_array
assert_equal([], @filters.sort_natural([], "a"))
end
def test_sort_natural_invalid_property
foo = [
[1],
[2],
[3],
]
assert_raises(Liquid::ArgumentError) do
@filters.sort_natural(foo, "bar")
end
end
def test_legacy_sort_hash
assert_equal([{ a: 1, b: 2 }], @filters.sort(a: 1, b: 2))
end
def test_numerical_vs_lexicographical_sort
assert_equal([2, 10], @filters.sort([10, 2]))
assert_equal([{ "a" => 2 }, { "a" => 10 }], @filters.sort([{ "a" => 10 }, { "a" => 2 }], "a"))
assert_equal(["10", "2"], @filters.sort(["10", "2"]))
assert_equal([{ "a" => "10" }, { "a" => "2" }], @filters.sort([{ "a" => "10" }, { "a" => "2" }], "a"))
end
def test_uniq
assert_equal(["foo"], @filters.uniq("foo"))
assert_equal([1, 3, 2, 4], @filters.uniq([1, 1, 3, 2, 3, 1, 4, 3, 2, 1]))
assert_equal([{ "a" => 1 }, { "a" => 3 }, { "a" => 2 }], @filters.uniq([{ "a" => 1 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a"))
test_drop = TestDrop.new(value: "test")
test_drop_alternate = TestDrop.new(value: "test")
assert_equal([test_drop], @filters.uniq([test_drop, test_drop_alternate], 'value'))
end
def test_uniq_empty_array
assert_equal([], @filters.uniq([], "a"))
end
def test_uniq_invalid_property
foo = [
[1],
[2],
[3],
]
assert_raises(Liquid::ArgumentError) do
@filters.uniq(foo, "bar")
end
end
def test_compact_empty_array
assert_equal([], @filters.compact([], "a"))
end
def test_compact_invalid_property
foo = [
[1],
[2],
[3],
]
assert_raises(Liquid::ArgumentError) do
@filters.compact(foo, "bar")
end
end
def test_reverse
assert_equal([4, 3, 2, 1], @filters.reverse([1, 2, 3, 4]))
end
def test_legacy_reverse_hash
assert_equal([{ a: 1, b: 2 }], @filters.reverse(a: 1, b: 2))
end
def test_map
assert_equal([1, 2, 3, 4], @filters.map([{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }], 'a'))
assert_template_result(
'abc',
"{{ ary | map:'foo' | map:'bar' }}",
{ 'ary' => [{ 'foo' => { 'bar' => 'a' } }, { 'foo' => { 'bar' => 'b' } }, { 'foo' => { 'bar' => 'c' } }] },
)
end
def test_map_doesnt_call_arbitrary_stuff
assert_template_result("", '{{ "foo" | map: "__id__" }}')
assert_template_result("", '{{ "foo" | map: "inspect" }}')
end
def test_map_calls_to_liquid
t = TestThing.new
assert_template_result("woot: 1", '{{ foo | map: "whatever" }}', { "foo" => [t] })
end
def test_map_calls_context=
model = TestModel.new(value: :test)
template = Template.parse('{{ foo | map: "registers" }}')
template.registers[:test] = 1234
template.assigns['foo'] = [model]
assert_template_result("{:test=>1234}", template.render!)
end
def test_map_on_hashes
assert_template_result(
"4217",
'{{ thing | map: "foo" | map: "bar" }}',
{ "thing" => { "foo" => [{ "bar" => 42 }, { "bar" => 17 }] } },
)
end
def test_legacy_map_on_hashes_with_dynamic_key
template = "{% assign key = 'foo' %}{{ thing | map: key | map: 'bar' }}"
hash = { "foo" => { "bar" => 42 } }
assert_template_result("42", template, { "thing" => hash })
end
def test_sort_calls_to_liquid
t = TestThing.new
Liquid::Template.parse('{{ foo | sort: "whatever" }}').render("foo" => [t])
assert(t.foo > 0)
end
def test_map_over_proc
drop = TestDrop.new(value: "testfoo")
p = proc { drop }
output = Liquid::Template.parse('{{ procs | map: "value" }}').render!({ "procs" => [p] })
assert_equal("testfoo", output)
end
def test_map_over_drops_returning_procs
drops = [
{
"proc" => -> { "foo" },
},
{
"proc" => -> { "bar" },
},
]
output = Liquid::Template.parse('{{ drops | map: "proc" }}').render!({ "drops" => drops })
assert_equal("foobar", output)
end
def test_map_works_on_enumerables
output = Liquid::Template.parse('{{ foo | map: "foo" }}').render!({ "foo" => TestEnumerable.new })
assert_equal("123", output)
end
def test_map_returns_empty_on_2d_input_array
foo = [
[1],
[2],
[3],
]
assert_raises(Liquid::ArgumentError) do
@filters.map(foo, "bar")
end
end
def test_map_with_value_property
array = [
{ "handle" => "alpha", "value" => "A" },
{ "handle" => "beta", "value" => "B" },
{ "handle" => "gamma", "value" => "C" }
]
assert_template_result("A B C", "{{ array | map: 'value' | join: ' ' }}", { "array" => array })
end
def test_map_returns_input_with_no_property
foo = [
[1],
[2],
[3],
]
assert_raises(Liquid::ArgumentError) do
@filters.map(foo, nil)
end
end
def test_sort_works_on_enumerables
assert_template_result("213", '{{ foo | sort: "bar" | map: "foo" }}', { "foo" => TestEnumerable.new })
end
def test_first_and_last_call_to_liquid
assert_template_result('foobar', '{{ foo | first }}', { 'foo' => [ThingWithToLiquid.new] })
assert_template_result('foobar', '{{ foo | last }}', { 'foo' => [ThingWithToLiquid.new] })
end
def test_truncate_calls_to_liquid
assert_template_result("wo...", '{{ foo | truncate: 5 }}', { "foo" => TestThing.new })
end
def test_date
assert_equal('May', @filters.date(Time.parse("2006-05-05 10:00:00"), "%B"))
assert_equal('June', @filters.date(Time.parse("2006-06-05 10:00:00"), "%B"))
assert_equal('July', @filters.date(Time.parse("2006-07-05 10:00:00"), "%B"))
assert_equal('May', @filters.date("2006-05-05 10:00:00", "%B"))
assert_equal('June', @filters.date("2006-06-05 10:00:00", "%B"))
assert_equal('July', @filters.date("2006-07-05 10:00:00", "%B"))
assert_equal('2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", ""))
assert_equal('2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", ""))
assert_equal('2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", ""))
assert_equal('2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", nil))
assert_equal('07/05/2006', @filters.date("2006-07-05 10:00:00", "%m/%d/%Y"))
assert_equal("07/16/2004", @filters.date("Fri Jul 16 01:00:00 2004", "%m/%d/%Y"))
assert_equal(Date.today.year.to_s, @filters.date('now', '%Y'))
assert_equal(Date.today.year.to_s, @filters.date('today', '%Y'))
assert_equal(Date.today.year.to_s, @filters.date('Today', '%Y'))
assert_nil(@filters.date(nil, "%B"))
assert_equal('', @filters.date('', "%B"))
with_timezone("UTC") do
assert_equal("07/05/2006", @filters.date(1152098955, "%m/%d/%Y"))
assert_equal("07/05/2006", @filters.date("1152098955", "%m/%d/%Y"))
end
end
def test_first_last
assert_equal(1, @filters.first([1, 2, 3]))
assert_equal(3, @filters.last([1, 2, 3]))
assert_nil(@filters.first([]))
assert_nil(@filters.last([]))
end
def test_first_last_on_strings
# Ruby's String class does not have first/last methods by default.
# ActiveSupport adds String#first and String#last to return the first/last character.
# Liquid must work without ActiveSupport, so the first/last filters handle strings specially.
#
# This enables template patterns like:
# {{ product.title | first }} => "S" (for "Snowboard")
# {{ customer.name | last }} => "h" (for "Smith")
#
# Note: ActiveSupport returns "" for empty strings, not nil.
assert_equal('f', @filters.first('foo'))
assert_equal('o', @filters.last('foo'))
assert_equal('', @filters.first(''))
assert_equal('', @filters.last(''))
end
def test_first_last_on_unicode_strings
# Unicode strings should return the first/last grapheme cluster (character),
# not the first/last byte. Ruby's String#[] handles this correctly with index 0/-1.
# This ensures international text works properly:
# {{ korean_name | first }} => "고" (not a partial byte sequence)
assert_equal('고', @filters.first('고스트빈'))
assert_equal('빈', @filters.last('고스트빈'))
end
def test_first_last_on_strings_via_template
# Integration test to verify the filter works end-to-end in templates.
# Empty strings return empty output (nil renders as empty string).
assert_template_result('f', '{{ name | first }}', { 'name' => 'foo' })
assert_template_result('o', '{{ name | last }}', { 'name' => 'foo' })
assert_template_result('', '{{ name | first }}', { 'name' => '' })
assert_template_result('', '{{ name | last }}', { 'name' => '' })
end
def test_replace
assert_equal('b b b b', @filters.replace('a a a a', 'a', 'b'))
assert_equal('2 2 2 2', @filters.replace('1 1 1 1', 1, 2))
assert_equal('1 1 1 1', @filters.replace('1 1 1 1', 2, 3))
assert_template_result('2 2 2 2', "{{ '1 1 1 1' | replace: '1', 2 }}")
assert_equal('b a a a', @filters.replace_first('a a a a', 'a', 'b'))
assert_equal('2 1 1 1', @filters.replace_first('1 1 1 1', 1, 2))
assert_equal('1 1 1 1', @filters.replace_first('1 1 1 1', 2, 3))
assert_template_result('2 1 1 1', "{{ '1 1 1 1' | replace_first: '1', 2 }}")
assert_equal('a a a b', @filters.replace_last('a a a a', 'a', 'b'))
assert_equal('1 1 1 2', @filters.replace_last('1 1 1 1', 1, 2))
assert_equal('1 1 1 1', @filters.replace_last('1 1 1 1', 2, 3))
assert_template_result('1 1 1 2', "{{ '1 1 1 1' | replace_last: '1', 2 }}")
end
def test_remove
assert_equal(' ', @filters.remove("a a a a", 'a'))
assert_template_result(' ', "{{ '1 1 1 1' | remove: 1 }}")
assert_equal('b a a', @filters.remove_first("a b a a", 'a '))
assert_template_result(' 1 1 1', "{{ '1 1 1 1' | remove_first: 1 }}")
assert_equal('a a b', @filters.remove_last("a a b a", ' a'))
assert_template_result('1 1 1 ', "{{ '1 1 1 1' | remove_last: 1 }}")
end
def test_pipes_in_string_arguments
assert_template_result('foobar', "{{ 'foo|bar' | remove: '|' }}")
end
def test_strip
assert_template_result('ab c', "{{ source | strip }}", { 'source' => " ab c " })
assert_template_result('ab c', "{{ source | strip }}", { 'source' => " \tab c \n \t" })
end
def test_lstrip
assert_template_result('ab c ', "{{ source | lstrip }}", { 'source' => " ab c " })
assert_template_result("ab c \n \t", "{{ source | lstrip }}", { 'source' => " \tab c \n \t" })
end
def test_rstrip
assert_template_result(" ab c", "{{ source | rstrip }}", { 'source' => " ab c " })
assert_template_result(" \tab c", "{{ source | rstrip }}", { 'source' => " \tab c \n \t" })
end
def test_strip_newlines
assert_template_result('abc', "{{ source | strip_newlines }}", { 'source' => "a\nb\nc" })
assert_template_result('abc', "{{ source | strip_newlines }}", { 'source' => "a\r\nb\nc" })
end
def test_newlines_to_br
assert_template_result("a<br />\nb<br />\nc", "{{ source | newline_to_br }}", { 'source' => "a\nb\nc" })
assert_template_result("a<br />\nb<br />\nc", "{{ source | newline_to_br }}", { 'source' => "a\r\nb\nc" })
end
def test_plus
assert_template_result("2", "{{ 1 | plus:1 }}")
assert_template_result("2.0", "{{ '1' | plus:'1.0' }}")
assert_template_result("5", "{{ price | plus:'2' }}", { 'price' => NumberLikeThing.new(3) })
end
def test_minus
assert_template_result("4", "{{ input | minus:operand }}", { 'input' => 5, 'operand' => 1 })
assert_template_result("2.3", "{{ '4.3' | minus:'2' }}")
assert_template_result("5", "{{ price | minus:'2' }}", { 'price' => NumberLikeThing.new(7) })
end
def test_abs
assert_template_result("17", "{{ 17 | abs }}")
assert_template_result("17", "{{ -17 | abs }}")
assert_template_result("17", "{{ '17' | abs }}")
assert_template_result("17", "{{ '-17' | abs }}")
assert_template_result("0", "{{ 0 | abs }}")
assert_template_result("0", "{{ '0' | abs }}")
assert_template_result("17.42", "{{ 17.42 | abs }}")
assert_template_result("17.42", "{{ -17.42 | abs }}")
assert_template_result("17.42", "{{ '17.42' | abs }}")
assert_template_result("17.42", "{{ '-17.42' | abs }}")
end
def test_times
assert_template_result("12", "{{ 3 | times:4 }}")
assert_template_result("0", "{{ 'foo' | times:4 }}")
assert_template_result("6", "{{ '2.1' | times:3 | replace: '.','-' | plus:0}}")
assert_template_result("7.25", "{{ 0.0725 | times:100 }}")
assert_template_result("-7.25", '{{ "-0.0725" | times:100 }}')
assert_template_result("7.25", '{{ "-0.0725" | times: -100 }}')
assert_template_result("4", "{{ price | times:2 }}", { 'price' => NumberLikeThing.new(2) })
end
def test_divided_by
assert_template_result("4", "{{ 12 | divided_by:3 }}")
assert_template_result("4", "{{ 14 | divided_by:3 }}")
assert_template_result("5", "{{ 15 | divided_by:3 }}")
assert_equal("Liquid error: divided by 0", Template.parse("{{ 5 | divided_by:0 }}").render)
assert_template_result("0.5", "{{ 2.0 | divided_by:4 }}")
assert_raises(Liquid::ZeroDivisionError) do
assert_template_result("4", "{{ 1 | modulo: 0 }}")
end
assert_template_result("5", "{{ price | divided_by:2 }}", { 'price' => NumberLikeThing.new(10) })
end
def test_modulo
assert_template_result("1", "{{ 3 | modulo:2 }}")
assert_raises(Liquid::ZeroDivisionError) do
assert_template_result("4", "{{ 1 | modulo: 0 }}")
end
assert_template_result("1", "{{ price | modulo:2 }}", { 'price' => NumberLikeThing.new(3) })
end
def test_round
assert_template_result("5", "{{ input | round }}", { 'input' => 4.6 })
assert_template_result("4", "{{ '4.3' | round }}")
assert_template_result("4.56", "{{ input | round: 2 }}", { 'input' => 4.5612 })
assert_raises(Liquid::FloatDomainError) do
assert_template_result("4", "{{ 1.0 | divided_by: 0.0 | round }}")
end
assert_template_result("5", "{{ price | round }}", { 'price' => NumberLikeThing.new(4.6) })
assert_template_result("4", "{{ price | round }}", { 'price' => NumberLikeThing.new(4.3) })
end
def test_ceil
assert_template_result("5", "{{ input | ceil }}", { 'input' => 4.6 })
assert_template_result("5", "{{ '4.3' | ceil }}")
assert_raises(Liquid::FloatDomainError) do
assert_template_result("4", "{{ 1.0 | divided_by: 0.0 | ceil }}")
end
assert_template_result("5", "{{ price | ceil }}", { 'price' => NumberLikeThing.new(4.6) })
end
def test_floor
assert_template_result("4", "{{ input | floor }}", { 'input' => 4.6 })
assert_template_result("4", "{{ '4.3' | floor }}")
assert_raises(Liquid::FloatDomainError) do
assert_template_result("4", "{{ 1.0 | divided_by: 0.0 | floor }}")
end
assert_template_result("5", "{{ price | floor }}", { 'price' => NumberLikeThing.new(5.4) })
end
def test_at_most
assert_template_result("4", "{{ 5 | at_most:4 }}")
assert_template_result("5", "{{ 5 | at_most:5 }}")
assert_template_result("5", "{{ 5 | at_most:6 }}")
assert_template_result("4.5", "{{ 4.5 | at_most:5 }}")
assert_template_result("5", "{{ width | at_most:5 }}", { 'width' => NumberLikeThing.new(6) })
assert_template_result("4", "{{ width | at_most:5 }}", { 'width' => NumberLikeThing.new(4) })
assert_template_result("4", "{{ 5 | at_most: width }}", { 'width' => NumberLikeThing.new(4) })
end
def test_at_least
assert_template_result("5", "{{ 5 | at_least:4 }}")
assert_template_result("5", "{{ 5 | at_least:5 }}")
assert_template_result("6", "{{ 5 | at_least:6 }}")
assert_template_result("5", "{{ 4.5 | at_least:5 }}")
assert_template_result("6", "{{ width | at_least:5 }}", { 'width' => NumberLikeThing.new(6) })
assert_template_result("5", "{{ width | at_least:5 }}", { 'width' => NumberLikeThing.new(4) })
assert_template_result("6", "{{ 5 | at_least: width }}", { 'width' => NumberLikeThing.new(6) })
end
def test_append
assigns = { 'a' => 'bc', 'b' => 'd' }
assert_template_result('bcd', "{{ a | append: 'd'}}", assigns)
assert_template_result('bcd', "{{ a | append: b}}", assigns)
end
def test_concat
assert_equal([1, 2, 3, 4], @filters.concat([1, 2], [3, 4]))
assert_equal([1, 2, 'a'], @filters.concat([1, 2], ['a']))
assert_equal([1, 2, 10], @filters.concat([1, 2], [10]))
assert_raises(Liquid::ArgumentError, "concat filter requires an array argument") do
@filters.concat([1, 2], 10)
end
end
def test_prepend
assigns = { 'a' => 'bc', 'b' => 'a' }
assert_template_result('abc', "{{ a | prepend: 'a'}}", assigns)
assert_template_result('abc', "{{ a | prepend: b}}", assigns)
end
def test_default
assert_equal("foo", @filters.default("foo", "bar"))
assert_equal("bar", @filters.default(nil, "bar"))
assert_equal("bar", @filters.default("", "bar"))
assert_equal("bar", @filters.default(false, "bar"))
assert_equal("bar", @filters.default([], "bar"))
assert_equal("bar", @filters.default({}, "bar"))
assert_template_result('bar', "{{ false | default: 'bar' }}")
assert_template_result('bar', "{{ drop | default: 'bar' }}", { 'drop' => BooleanDrop.new(false) })
assert_template_result('Yay', "{{ drop | default: 'bar' }}", { 'drop' => BooleanDrop.new(true) })
end
def test_default_handle_false
assert_equal("foo", @filters.default("foo", "bar", "allow_false" => true))
assert_equal("bar", @filters.default(nil, "bar", "allow_false" => true))
assert_equal("bar", @filters.default("", "bar", "allow_false" => true))
assert_equal(false, @filters.default(false, "bar", "allow_false" => true))
assert_equal("bar", @filters.default([], "bar", "allow_false" => true))
assert_equal("bar", @filters.default({}, "bar", "allow_false" => true))
assert_template_result('false', "{{ false | default: 'bar', allow_false: true }}")
assert_template_result('Nay', "{{ drop | default: 'bar', allow_false: true }}", { 'drop' => BooleanDrop.new(false) })
assert_template_result('Yay', "{{ drop | default: 'bar', allow_false: true }}", { 'drop' => BooleanDrop.new(true) })
end
def test_cannot_access_private_methods
assert_template_result('a', "{{ 'a' | to_number }}")
end
def test_date_raises_nothing
assert_template_result('', "{{ '' | date: '%D' }}")
assert_template_result('abc', "{{ 'abc' | date: '%D' }}")
end
def test_reject
array = [
{ "handle" => "alpha", "ok" => true },
{ "handle" => "beta", "ok" => false },
{ "handle" => "gamma", "ok" => false },
{ "handle" => "delta", "ok" => true },
]
template = "{{ array | reject: 'ok' | map: 'handle' | join: ' ' }}"
expected_output = "beta gamma"
assert_template_result(expected_output, template, { "array" => array })
end
def test_reject_with_value
array = [
{ "handle" => "alpha", "ok" => true },
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | true |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/drop_test.rb | test/integration/drop_test.rb | # frozen_string_literal: true
require 'test_helper'
class ContextDrop < Liquid::Drop
def scopes
@context.scopes.size
end
def scopes_as_array
(1..@context.scopes.size).to_a
end
def loop_pos
@context['forloop.index']
end
def liquid_method_missing(method)
@context[method]
end
end
class ProductDrop < Liquid::Drop
class TextDrop < Liquid::Drop
def array
['text1', 'text2']
end
def text
'text1'
end
end
class CatchallDrop < Liquid::Drop
def liquid_method_missing(method)
"catchall_method: #{method}"
end
end
def texts
TextDrop.new
end
def catchall
CatchallDrop.new
end
def context
ContextDrop.new
end
protected
def callmenot
"protected"
end
end
class EnumerableDrop < Liquid::Drop
def liquid_method_missing(method)
method
end
def size
3
end
def first
1
end
def count
3
end
def min
1
end
def max
3
end
def each
yield 1
yield 2
yield 3
end
end
class RealEnumerableDrop < Liquid::Drop
include Enumerable
def liquid_method_missing(method)
method
end
def each
yield 1
yield 2
yield 3
end
end
class DropsTest < Minitest::Test
include Liquid
def test_product_drop
tpl = Liquid::Template.parse(' ')
assert_equal(' ', tpl.render!('product' => ProductDrop.new))
end
def test_drop_does_only_respond_to_whitelisted_methods
assert_equal("", Liquid::Template.parse("{{ product.inspect }}").render!('product' => ProductDrop.new))
assert_equal("", Liquid::Template.parse("{{ product.pretty_inspect }}").render!('product' => ProductDrop.new))
assert_equal("", Liquid::Template.parse("{{ product.whatever }}").render!('product' => ProductDrop.new))
assert_equal("", Liquid::Template.parse('{{ product | map: "inspect" }}').render!('product' => ProductDrop.new))
assert_equal("", Liquid::Template.parse('{{ product | map: "pretty_inspect" }}').render!('product' => ProductDrop.new))
assert_equal("", Liquid::Template.parse('{{ product | map: "whatever" }}').render!('product' => ProductDrop.new))
end
def test_drops_respond_to_to_liquid
assert_equal("text1", Liquid::Template.parse("{{ product.to_liquid.texts.text }}").render!('product' => ProductDrop.new))
assert_equal("text1", Liquid::Template.parse('{{ product | map: "to_liquid" | map: "texts" | map: "text" }}').render!('product' => ProductDrop.new))
end
def test_text_drop
output = Liquid::Template.parse(' {{ product.texts.text }} ').render!('product' => ProductDrop.new)
assert_equal(' text1 ', output)
end
def test_catchall_unknown_method
output = Liquid::Template.parse(' {{ product.catchall.unknown }} ').render!('product' => ProductDrop.new)
assert_equal(' catchall_method: unknown ', output)
end
def test_catchall_integer_argument_drop
output = Liquid::Template.parse(' {{ product.catchall[8] }} ').render!('product' => ProductDrop.new)
assert_equal(' catchall_method: 8 ', output)
end
def test_text_array_drop
output = Liquid::Template.parse('{% for text in product.texts.array %} {{text}} {% endfor %}').render!('product' => ProductDrop.new)
assert_equal(' text1 text2 ', output)
end
def test_context_drop
output = Liquid::Template.parse(' {{ context.bar }} ').render!('context' => ContextDrop.new, 'bar' => "carrot")
assert_equal(' carrot ', output)
end
def test_context_drop_array_with_map
output = Liquid::Template.parse(' {{ contexts | map: "bar" }} ').render!('contexts' => [ContextDrop.new, ContextDrop.new], 'bar' => "carrot")
assert_equal(' carrotcarrot ', output)
end
def test_nested_context_drop
output = Liquid::Template.parse(' {{ product.context.foo }} ').render!('product' => ProductDrop.new, 'foo' => "monkey")
assert_equal(' monkey ', output)
end
def test_protected
output = Liquid::Template.parse(' {{ product.callmenot }} ').render!('product' => ProductDrop.new)
assert_equal(' ', output)
end
def test_object_methods_not_allowed
[:dup, :clone, :singleton_class, :eval, :class_eval, :inspect].each do |method|
output = Liquid::Template.parse(" {{ product.#{method} }} ").render!('product' => ProductDrop.new)
assert_equal(' ', output)
end
end
def test_scope
assert_equal('1', Liquid::Template.parse('{{ context.scopes }}').render!('context' => ContextDrop.new))
assert_equal('2', Liquid::Template.parse('{%for i in dummy%}{{ context.scopes }}{%endfor%}').render!('context' => ContextDrop.new, 'dummy' => [1]))
assert_equal('3', Liquid::Template.parse('{%for i in dummy%}{%for i in dummy%}{{ context.scopes }}{%endfor%}{%endfor%}').render!('context' => ContextDrop.new, 'dummy' => [1]))
end
def test_scope_though_proc
assert_equal('1', Liquid::Template.parse('{{ s }}').render!('context' => ContextDrop.new, 's' => proc { |c| c['context.scopes'] }))
assert_equal('2', Liquid::Template.parse('{%for i in dummy%}{{ s }}{%endfor%}').render!('context' => ContextDrop.new, 's' => proc { |c| c['context.scopes'] }, 'dummy' => [1]))
assert_equal('3', Liquid::Template.parse('{%for i in dummy%}{%for i in dummy%}{{ s }}{%endfor%}{%endfor%}').render!('context' => ContextDrop.new, 's' => proc { |c| c['context.scopes'] }, 'dummy' => [1]))
end
def test_scope_with_assigns
assert_equal('variable', Liquid::Template.parse('{% assign a = "variable"%}{{a}}').render!('context' => ContextDrop.new))
assert_equal('variable', Liquid::Template.parse('{% assign a = "variable"%}{%for i in dummy%}{{a}}{%endfor%}').render!('context' => ContextDrop.new, 'dummy' => [1]))
assert_equal('test', Liquid::Template.parse('{% assign header_gif = "test"%}{{header_gif}}').render!('context' => ContextDrop.new))
assert_equal('test', Liquid::Template.parse("{% assign header_gif = 'test'%}{{header_gif}}").render!('context' => ContextDrop.new))
end
def test_scope_from_tags
assert_equal('1', Liquid::Template.parse('{% for i in context.scopes_as_array %}{{i}}{% endfor %}').render!('context' => ContextDrop.new, 'dummy' => [1]))
assert_equal('12', Liquid::Template.parse('{%for a in dummy%}{% for i in context.scopes_as_array %}{{i}}{% endfor %}{% endfor %}').render!('context' => ContextDrop.new, 'dummy' => [1]))
assert_equal('123', Liquid::Template.parse('{%for a in dummy%}{%for a in dummy%}{% for i in context.scopes_as_array %}{{i}}{% endfor %}{% endfor %}{% endfor %}').render!('context' => ContextDrop.new, 'dummy' => [1]))
end
def test_access_context_from_drop
assert_equal('123', Liquid::Template.parse('{%for a in dummy%}{{ context.loop_pos }}{% endfor %}').render!('context' => ContextDrop.new, 'dummy' => [1, 2, 3]))
end
def test_enumerable_drop
assert_equal('123', Liquid::Template.parse('{% for c in collection %}{{c}}{% endfor %}').render!('collection' => EnumerableDrop.new))
end
def test_enumerable_drop_size
assert_equal('3', Liquid::Template.parse('{{collection.size}}').render!('collection' => EnumerableDrop.new))
end
def test_enumerable_drop_will_invoke_liquid_method_missing_for_clashing_method_names
["select", "each", "map", "cycle"].each do |method|
assert_equal(method.to_s, Liquid::Template.parse("{{collection.#{method}}}").render!('collection' => EnumerableDrop.new))
assert_equal(method.to_s, Liquid::Template.parse("{{collection[\"#{method}\"]}}").render!('collection' => EnumerableDrop.new))
assert_equal(method.to_s, Liquid::Template.parse("{{collection.#{method}}}").render!('collection' => RealEnumerableDrop.new))
assert_equal(method.to_s, Liquid::Template.parse("{{collection[\"#{method}\"]}}").render!('collection' => RealEnumerableDrop.new))
end
end
def test_some_enumerable_methods_still_get_invoked
[:count, :max].each do |method|
assert_equal("3", Liquid::Template.parse("{{collection.#{method}}}").render!('collection' => RealEnumerableDrop.new))
assert_equal("3", Liquid::Template.parse("{{collection[\"#{method}\"]}}").render!('collection' => RealEnumerableDrop.new))
assert_equal("3", Liquid::Template.parse("{{collection.#{method}}}").render!('collection' => EnumerableDrop.new))
assert_equal("3", Liquid::Template.parse("{{collection[\"#{method}\"]}}").render!('collection' => EnumerableDrop.new))
end
assert_equal("yes", Liquid::Template.parse("{% if collection contains 3 %}yes{% endif %}").render!('collection' => RealEnumerableDrop.new))
[:min, :first].each do |method|
assert_equal("1", Liquid::Template.parse("{{collection.#{method}}}").render!('collection' => RealEnumerableDrop.new))
assert_equal("1", Liquid::Template.parse("{{collection[\"#{method}\"]}}").render!('collection' => RealEnumerableDrop.new))
assert_equal("1", Liquid::Template.parse("{{collection.#{method}}}").render!('collection' => EnumerableDrop.new))
assert_equal("1", Liquid::Template.parse("{{collection[\"#{method}\"]}}").render!('collection' => EnumerableDrop.new))
end
end
def test_empty_string_value_access
assert_equal('', Liquid::Template.parse('{{ product[value] }}').render!('product' => ProductDrop.new, 'value' => ''))
end
def test_nil_value_access
assert_equal('', Liquid::Template.parse('{{ product[value] }}').render!('product' => ProductDrop.new, 'value' => nil))
end
def test_default_to_s_on_drops
assert_equal('ProductDrop', Liquid::Template.parse("{{ product }}").render!('product' => ProductDrop.new))
assert_equal('EnumerableDrop', Liquid::Template.parse('{{ collection }}').render!('collection' => EnumerableDrop.new))
end
def test_invokable_methods
assert_equal(%w(to_liquid catchall context texts).to_set, ProductDrop.invokable_methods)
assert_equal(%w(to_liquid scopes_as_array loop_pos scopes).to_set, ContextDrop.invokable_methods)
assert_equal(%w(to_liquid size max min first count).to_set, EnumerableDrop.invokable_methods)
assert_equal(%w(to_liquid max min sort count first).to_set, RealEnumerableDrop.invokable_methods)
end
end # DropsTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/include_tag_test.rb | test/integration/tags/include_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class TestFileSystem
PARTIALS = {
"nested_template" => "{% include 'header' %} {% include 'body' %} {% include 'footer' %}",
"body" => "body {% include 'body_detail' %}",
}
def read_template_file(template_path)
PARTIALS[template_path] || template_path
end
end
class OtherFileSystem
def read_template_file(_template_path)
'from OtherFileSystem'
end
end
class CountingFileSystem
attr_reader :count
def read_template_file(_template_path)
@count ||= 0
@count += 1
'from CountingFileSystem'
end
end
class CustomInclude < Liquid::Tag
Syntax = /(#{Liquid::QuotedFragment}+)(\s+(?:with|for)\s+(#{Liquid::QuotedFragment}+))?/o
def initialize(tag_name, markup, tokens)
markup =~ Syntax
@template_name = Regexp.last_match(1)
super
end
def parse(tokens)
end
def render_to_output_buffer(_context, output)
output << @template_name[1..-2]
output
end
end
class IncludeTagTest < Minitest::Test
include Liquid
def test_include_tag_looks_for_file_system_in_registers_first
assert_equal(
'from OtherFileSystem',
Template.parse("{% include 'pick_a_source' %}").render!({}, registers: { file_system: OtherFileSystem.new }),
)
end
def test_include_tag_with
assert_template_result(
"Product: Draft 151cm ",
"{% include 'product' with products[0] %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: { "product" => "Product: {{ product.title }} " },
)
end
def test_include_tag_with_alias
assert_template_result(
"Product: Draft 151cm ",
"{% include 'product_alias' with products[0] as product %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: { "product_alias" => "Product: {{ product.title }} " },
)
end
def test_include_tag_for_alias
assert_template_result(
"Product: Draft 151cm Product: Element 155cm ",
"{% include 'product_alias' for products as product %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: { "product_alias" => "Product: {{ product.title }} " },
)
end
def test_include_tag_with_default_name
assert_template_result(
"Product: Draft 151cm ",
"{% include 'product' %}",
{ "product" => { 'title' => 'Draft 151cm' } },
partials: { "product" => "Product: {{ product.title }} " },
)
end
def test_include_tag_for
assert_template_result(
"Product: Draft 151cm Product: Element 155cm ",
"{% include 'product' for products %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: { "product" => "Product: {{ product.title }} " },
)
end
def test_include_tag_with_local_variables
assert_template_result(
"Locale: test123 ",
"{% include 'locale_variables' echo1: 'test123' %}",
partials: { "locale_variables" => "Locale: {{echo1}} {{echo2}}" },
)
end
def test_include_tag_with_multiple_local_variables
assert_template_result(
"Locale: test123 test321",
"{% include 'locale_variables' echo1: 'test123', echo2: 'test321' %}",
partials: { "locale_variables" => "Locale: {{echo1}} {{echo2}}" },
)
end
def test_include_tag_with_multiple_local_variables_from_context
assert_template_result(
"Locale: test123 test321",
"{% include 'locale_variables' echo1: echo1, echo2: more_echos.echo2 %}",
{ 'echo1' => 'test123', 'more_echos' => { "echo2" => 'test321' } },
partials: { "locale_variables" => "Locale: {{echo1}} {{echo2}}" },
)
end
def test_included_templates_assigns_variables
assert_template_result(
"bar",
"{% include 'assignments' %}{{ foo }}",
partials: { 'assignments' => "{% assign foo = 'bar' %}" },
)
end
def test_nested_include_tag
partials = { "body" => "body {% include 'body_detail' %}", "body_detail" => "body_detail" }
assert_template_result("body body_detail", "{% include 'body' %}", partials: partials)
partials = partials.merge({
"nested_template" => "{% include 'header' %} {% include 'body' %} {% include 'footer' %}",
"header" => "header",
"footer" => "footer",
})
assert_template_result("header body body_detail footer", "{% include 'nested_template' %}", partials: partials)
end
def test_nested_include_with_variable
partials = {
"nested_product_template" => "Product: {{ nested_product_template.title }} {%include 'details'%} ",
"details" => "details",
}
assert_template_result(
"Product: Draft 151cm details ",
"{% include 'nested_product_template' with product %}",
{ "product" => { "title" => 'Draft 151cm' } },
partials: partials,
)
assert_template_result(
"Product: Draft 151cm details Product: Element 155cm details ",
"{% include 'nested_product_template' for products %}",
{ "products" => [{ "title" => 'Draft 151cm' }, { "title" => 'Element 155cm' }] },
partials: partials,
)
end
def test_recursively_included_template_does_not_produce_endless_loop
infinite_file_system = Class.new do
def read_template_file(_template_path)
"-{% include 'loop' %}"
end
end
env = Liquid::Environment.build(file_system: infinite_file_system.new)
assert_raises(Liquid::StackLevelError) do
Template.parse("{% include 'loop' %}", environment: env).render!
end
end
def test_dynamically_choosen_template
assert_template_result(
"Test123",
"{% include template %}",
{ "template" => 'Test123' },
partials: { "Test123" => "Test123" },
)
assert_template_result(
"Test321",
"{% include template %}",
{ "template" => 'Test321' },
partials: { "Test321" => "Test321" },
)
assert_template_result(
"Product: Draft 151cm ",
"{% include template for product %}",
{ "template" => 'product', 'product' => { 'title' => 'Draft 151cm' } },
partials: { "product" => "Product: {{ product.title }} " },
)
end
def test_strict2_parsing_errors
with_error_modes(:lax, :strict) do
assert_template_result(
'hello value1 value2',
'{% include "snippet" !!! arg1: "value1" ~~~ arg2: "value2" %}',
partials: { 'snippet' => 'hello {{ arg1 }} {{ arg2 }}' },
)
end
with_error_modes(:strict2) do
assert_syntax_error(
'{% include "snippet" !!! arg1: "value1" ~~~ arg2: "value2" %}',
)
assert_syntax_error(
'{% include "snippet" | filter %}',
)
end
end
def test_optional_commas
partials = { 'snippet' => 'hello {{ arg1 }} {{ arg2 }}' }
assert_template_result('hello value1 value2', '{% include "snippet", arg1: "value1", arg2: "value2" %}', partials: partials)
assert_template_result('hello value1 value2', '{% include "snippet" arg1: "value1", arg2: "value2" %}', partials: partials)
assert_template_result('hello value1 value2', '{% include "snippet" arg1: "value1" arg2: "value2" %}', partials: partials)
end
def test_include_tag_caches_second_read_of_same_partial
file_system = CountingFileSystem.new
environment = Liquid::Environment.build(file_system: file_system)
assert_equal(
'from CountingFileSystemfrom CountingFileSystem',
Template.parse("{% include 'pick_a_source' %}{% include 'pick_a_source' %}", environment: environment).render!({}, registers: { file_system: file_system }),
)
assert_equal(1, file_system.count)
end
def test_include_tag_doesnt_cache_partials_across_renders
file_system = CountingFileSystem.new
assert_equal(
'from CountingFileSystem',
Template.parse("{% include 'pick_a_source' %}").render!({}, registers: { file_system: file_system }),
)
assert_equal(1, file_system.count)
assert_equal(
'from CountingFileSystem',
Template.parse("{% include 'pick_a_source' %}").render!({}, registers: { file_system: file_system }),
)
assert_equal(2, file_system.count)
end
def test_include_tag_within_if_statement
assert_template_result(
"foo_if_true",
"{% if true %}{% include 'foo_if_true' %}{% endif %}",
partials: { "foo_if_true" => "foo_if_true" },
)
end
def test_custom_include_tag
original_tag = Liquid::Template.tags['include']
Liquid::Template.tags['include'] = CustomInclude
begin
assert_equal(
"custom_foo",
Template.parse("{% include 'custom_foo' %}").render!,
)
ensure
Liquid::Template.tags['include'] = original_tag
end
end
def test_custom_include_tag_within_if_statement
original_tag = Liquid::Template.tags['include']
Liquid::Template.tags['include'] = CustomInclude
begin
assert_equal(
"custom_foo_if_true",
Template.parse("{% if true %}{% include 'custom_foo_if_true' %}{% endif %}").render!,
)
ensure
Liquid::Template.tags['include'] = original_tag
end
end
def test_does_not_add_error_in_strict_mode_for_missing_variable
env = Liquid::Environment.build(file_system: TestFileSystem.new)
a = Liquid::Template.parse(' {% include "nested_template" %}', environment: env)
a.render!
assert_empty(a.errors)
end
def test_passing_options_to_included_templates
env = Liquid::Environment.build(file_system: TestFileSystem.new)
assert_raises(Liquid::SyntaxError) do
Template.parse("{% include template %}", error_mode: :strict, environment: env).render!("template" => '{{ "X" || downcase }}')
end
with_error_modes(:lax) do
assert_equal('x', Template.parse("{% include template %}", error_mode: :strict, include_options_blacklist: true, environment: env).render!("template" => '{{ "X" || downcase }}'))
end
assert_raises(Liquid::SyntaxError) do
Template.parse("{% include template %}", error_mode: :strict, include_options_blacklist: [:locale], environment: env).render!("template" => '{{ "X" || downcase }}')
end
with_error_modes(:lax) do
assert_equal('x', Template.parse("{% include template %}", error_mode: :strict, include_options_blacklist: [:error_mode], environment: env).render!("template" => '{{ "X" || downcase }}'))
end
end
def test_render_raise_argument_error_when_template_is_undefined
assert_template_result(
"Liquid error (line 1): Argument error in tag 'include' - Illegal template name",
"{% include undefined_variable %}",
render_errors: true,
)
assert_template_result(
"Liquid error (line 1): Argument error in tag 'include' - Illegal template name",
"{% include nil %}",
render_errors: true,
)
end
def test_render_raise_argument_error_when_template_is_not_a_string
assert_template_result(
"Liquid error (line 1): Argument error in tag 'include' - Illegal template name",
"{% include 123 %}",
render_errors: true,
)
end
def test_including_via_variable_value
assert_template_result(
"from TestFileSystem",
"{% assign page = 'pick_a_source' %}{% include page %}",
partials: { "pick_a_source" => "from TestFileSystem" },
)
partials = { "product" => "Product: {{ product.title }} " }
assert_template_result(
"Product: Draft 151cm ",
"{% assign page = 'product' %}{% include page %}",
{ "product" => { 'title' => 'Draft 151cm' } },
partials: partials,
)
assert_template_result(
"Product: Draft 151cm ",
"{% assign page = 'product' %}{% include page for foo %}",
{ "foo" => { 'title' => 'Draft 151cm' } },
partials: partials,
)
end
def test_including_with_strict_variables
env = Liquid::Environment.build(
file_system: StubFileSystem.new('simple' => 'simple'),
)
template = Liquid::Template.parse("{% include 'simple' %}", error_mode: :warn, environment: env)
template.render(nil, strict_variables: true)
assert_equal([], template.errors)
end
def test_break_through_include
assert_template_result("1", "{% for i in (1..3) %}{{ i }}{% break %}{{ i }}{% endfor %}")
assert_template_result(
"1",
"{% for i in (1..3) %}{{ i }}{% include 'break' %}{{ i }}{% endfor %}",
partials: { 'break' => "{% break %}" },
)
end
def test_render_tag_renders_error_with_template_name
assert_template_result(
'Liquid error (foo line 1): standard error',
"{% include 'foo' with errors %}",
{ 'errors' => ErrorDrop.new },
partials: { 'foo' => '{{ foo.standard_error }}' },
render_errors: true,
)
end
def test_render_tag_renders_error_with_template_name_from_template_factory
assert_template_result(
'Liquid error (some/path/foo line 1): standard error',
"{% include 'foo' with errors %}",
{ 'errors' => ErrorDrop.new },
partials: { 'foo' => '{{ foo.standard_error }}' },
template_factory: StubTemplateFactory.new,
render_errors: true,
)
end
def test_include_template_with_invalid_expression
template = "{% include foo=>bar %}"
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
def test_include_with_invalid_expression
template = '{% include "snippet" with foo=>bar %}'
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
def test_include_attribute_with_invalid_expression
template = '{% include "snippet", key: foo=>bar %}'
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
end # IncludeTagTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/unless_else_tag_test.rb | test/integration/tags/unless_else_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class UnlessElseTagTest < Minitest::Test
include Liquid
def test_unless
assert_template_result(' ', ' {% unless true %} this text should not go into the output {% endunless %} ')
assert_template_result(
' this text should go into the output ',
' {% unless false %} this text should go into the output {% endunless %} ',
)
assert_template_result(' you rock ?', '{% unless true %} you suck {% endunless %} {% unless false %} you rock {% endunless %}?')
end
def test_unless_else
assert_template_result(' YES ', '{% unless true %} NO {% else %} YES {% endunless %}')
assert_template_result(' YES ', '{% unless false %} YES {% else %} NO {% endunless %}')
assert_template_result(' YES ', '{% unless "foo" %} NO {% else %} YES {% endunless %}')
end
def test_unless_in_loop
assert_template_result('23', '{% for i in choices %}{% unless i %}{{ forloop.index }}{% endunless %}{% endfor %}', { 'choices' => [1, nil, false] })
end
def test_unless_else_in_loop
assert_template_result(' TRUE 2 3 ', '{% for i in choices %}{% unless i %} {{ forloop.index }} {% else %} TRUE {% endunless %}{% endfor %}', { 'choices' => [1, nil, false] })
end
end # UnlessElseTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/render_tag_test.rb | test/integration/tags/render_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class RenderTagTest < Minitest::Test
include Liquid
def test_render_with_no_arguments
assert_template_result(
'rendered content',
'{% render "source" %}',
partials: { 'source' => 'rendered content' },
)
end
def test_render_tag_looks_for_file_system_in_registers_first
assert_template_result(
'from register file system',
'{% render "pick_a_source" %}',
partials: { 'pick_a_source' => 'from register file system' },
)
end
def test_render_passes_named_arguments_into_inner_scope
assert_template_result(
'My Product',
'{% render "product", inner_product: outer_product %}',
{ 'outer_product' => { 'title' => 'My Product' } },
partials: { 'product' => '{{ inner_product.title }}' },
)
end
def test_render_accepts_literals_as_arguments
assert_template_result(
'123',
'{% render "snippet", price: 123 %}',
partials: { 'snippet' => '{{ price }}' },
)
end
def test_render_accepts_multiple_named_arguments
assert_template_result(
'1 2',
'{% render "snippet", one: 1, two: 2 %}',
partials: { 'snippet' => '{{ one }} {{ two }}' },
)
end
def test_render_does_not_inherit_parent_scope_variables
assert_template_result(
'',
'{% assign outer_variable = "should not be visible" %}{% render "snippet" %}',
partials: { 'snippet' => '{{ outer_variable }}' },
)
end
def test_render_does_not_inherit_variable_with_same_name_as_snippet
assert_template_result(
'',
"{% assign snippet = 'should not be visible' %}{% render 'snippet' %}",
partials: { 'snippet' => '{{ snippet }}' },
)
end
def test_render_does_not_mutate_parent_scope
assert_template_result(
'',
"{% render 'snippet' %}{{ inner }}",
partials: { 'snippet' => '{% assign inner = 1 %}' },
)
end
def test_nested_render_tag
assert_template_result(
'one two',
"{% render 'one' %}",
partials: {
'one' => "one {% render 'two' %}",
'two' => 'two',
},
)
end
def test_recursively_rendered_template_does_not_produce_endless_loop
env = Liquid::Environment.build(
file_system: StubFileSystem.new('loop' => '{% render "loop" %}'),
)
assert_raises(Liquid::StackLevelError) do
Template.parse('{% render "loop" %}', environment: env).render!
end
end
def test_sub_contexts_count_towards_the_same_recursion_limit
env = Liquid::Environment.build(
file_system: StubFileSystem.new('loop_render' => '{% render "loop_render" %}'),
)
assert_raises(Liquid::StackLevelError) do
Template.parse('{% render "loop_render" %}', environment: env).render!
end
end
def test_dynamically_choosen_templates_are_not_allowed
assert_syntax_error("{% assign name = 'snippet' %}{% render name %}")
end
def test_strict2_parsing_errors
with_error_modes(:lax, :strict) do
assert_template_result(
'hello value1 value2',
'{% render "snippet" !!! arg1: "value1" ~~~ arg2: "value2" %}',
partials: { 'snippet' => 'hello {{ arg1 }} {{ arg2 }}' },
)
end
with_error_modes(:strict2) do
assert_syntax_error(
'{% render "snippet" !!! arg1: "value1" ~~~ arg2: "value2" %}',
)
assert_syntax_error(
'{% render "snippet" | filter %}',
)
end
end
def test_optional_commas
partials = { 'snippet' => 'hello {{ arg1 }} {{ arg2 }}' }
assert_template_result('hello value1 value2', '{% render "snippet", arg1: "value1", arg2: "value2" %}', partials: partials)
assert_template_result('hello value1 value2', '{% render "snippet" arg1: "value1", arg2: "value2" %}', partials: partials)
assert_template_result('hello value1 value2', '{% render "snippet" arg1: "value1" arg2: "value2" %}', partials: partials)
end
def test_render_tag_caches_second_read_of_same_partial
file_system = StubFileSystem.new('snippet' => 'echo')
assert_equal(
'echoecho',
Template.parse('{% render "snippet" %}{% render "snippet" %}')
.render!({}, registers: { file_system: file_system }),
)
assert_equal(1, file_system.file_read_count)
end
def test_render_tag_doesnt_cache_partials_across_renders
file_system = StubFileSystem.new('snippet' => 'my message')
assert_equal(
'my message',
Template.parse('{% include "snippet" %}').render!({}, registers: { file_system: file_system }),
)
assert_equal(1, file_system.file_read_count)
assert_equal(
'my message',
Template.parse('{% include "snippet" %}').render!({}, registers: { file_system: file_system }),
)
assert_equal(2, file_system.file_read_count)
end
def test_render_tag_within_if_statement
assert_template_result(
'my message',
'{% if true %}{% render "snippet" %}{% endif %}',
partials: { 'snippet' => 'my message' },
)
end
def test_break_through_render
options = { partials: { 'break' => '{% break %}' } }
assert_template_result('1', '{% for i in (1..3) %}{{ i }}{% break %}{{ i }}{% endfor %}', **options)
assert_template_result('112233', '{% for i in (1..3) %}{{ i }}{% render "break" %}{{ i }}{% endfor %}', **options)
end
def test_increment_is_isolated_between_renders
assert_template_result(
'010',
'{% increment %}{% increment %}{% render "incr" %}',
partials: { 'incr' => '{% increment %}' },
)
end
def test_decrement_is_isolated_between_renders
assert_template_result(
'-1-2-1',
'{% decrement %}{% decrement %}{% render "decr" %}',
partials: { 'decr' => '{% decrement %}' },
)
end
def test_includes_will_not_render_inside_render_tag
assert_template_result(
'Liquid error (test_include line 1): include usage is not allowed in this context',
'{% render "test_include" %}',
render_errors: true,
partials: {
'foo' => 'bar',
'test_include' => '{% include "foo" %}',
},
)
end
def test_includes_will_not_render_inside_nested_sibling_tags
assert_template_result(
"Liquid error (test_include line 1): include usage is not allowed in this context" \
"Liquid error (nested_render_with_sibling_include line 1): include usage is not allowed in this context",
'{% render "nested_render_with_sibling_include" %}',
partials: {
'foo' => 'bar',
'nested_render_with_sibling_include' => '{% render "test_include" %}{% include "foo" %}',
'test_include' => '{% include "foo" %}',
},
render_errors: true,
)
end
def test_render_tag_with
assert_template_result(
"Product: Draft 151cm ",
"{% render 'product' with products[0] %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: {
'product' => "Product: {{ product.title }} ",
'product_alias' => "Product: {{ product.title }} ",
},
)
end
def test_render_tag_with_alias
assert_template_result(
"Product: Draft 151cm ",
"{% render 'product_alias' with products[0] as product %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: {
'product' => "Product: {{ product.title }} ",
'product_alias' => "Product: {{ product.title }} ",
},
)
end
def test_render_tag_for_alias
assert_template_result(
"Product: Draft 151cm Product: Element 155cm ",
"{% render 'product_alias' for products as product %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: {
'product' => "Product: {{ product.title }} ",
'product_alias' => "Product: {{ product.title }} ",
},
)
end
def test_render_tag_for
assert_template_result(
"Product: Draft 151cm Product: Element 155cm ",
"{% render 'product' for products %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: {
'product' => "Product: {{ product.title }} ",
'product_alias' => "Product: {{ product.title }} ",
},
)
end
def test_render_tag_forloop
assert_template_result(
"Product: Draft 151cm first index:1 Product: Element 155cm last index:2 ",
"{% render 'product' for products %}",
{ "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }] },
partials: {
'product' => "Product: {{ product.title }} {% if forloop.first %}first{% endif %} {% if forloop.last %}last{% endif %} index:{{ forloop.index }} ",
},
)
end
def test_render_tag_for_drop
assert_template_result(
"123",
"{% render 'loop' for loop as value %}",
{ "loop" => TestEnumerable.new },
partials: {
'loop' => "{{ value.foo }}",
},
)
end
def test_render_tag_with_drop
assert_template_result(
"TestEnumerable",
"{% render 'loop' with loop as value %}",
{ "loop" => TestEnumerable.new },
partials: {
'loop' => "{{ value }}",
},
)
end
def test_render_tag_renders_error_with_template_name
assert_template_result(
'Liquid error (foo line 1): standard error',
"{% render 'foo' with errors %}",
{ 'errors' => ErrorDrop.new },
partials: { 'foo' => '{{ foo.standard_error }}' },
render_errors: true,
)
end
def test_render_tag_renders_error_with_template_name_from_template_factory
assert_template_result(
'Liquid error (some/path/foo line 1): standard error',
"{% render 'foo' with errors %}",
{ 'errors' => ErrorDrop.new },
partials: { 'foo' => '{{ foo.standard_error }}' },
template_factory: StubTemplateFactory.new,
render_errors: true,
)
end
def test_render_with_invalid_expression
template = '{% render "snippet" with foo=>bar %}'
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
def test_render_attribute_with_invalid_expression
template = '{% render "snippet", key: foo=>bar %}'
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/break_tag_test.rb | test/integration/tags/break_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class BreakTagTest < Minitest::Test
include Liquid
# tests that no weird errors are raised if break is called outside of a
# block
def test_break_with_no_block
assigns = { 'i' => 1 }
markup = 'before{% break %}after'
expected = 'before'
assert_template_result(expected, markup, assigns)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/if_else_tag_test.rb | test/integration/tags/if_else_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class IfElseTagTest < Minitest::Test
include Liquid
def test_if
assert_template_result(' ', ' {% if false %} this text should not go into the output {% endif %} ')
assert_template_result(
' this text should go into the output ',
' {% if true %} this text should go into the output {% endif %} ',
)
assert_template_result(' you rock ?', '{% if false %} you suck {% endif %} {% if true %} you rock {% endif %}?')
end
def test_literal_comparisons
assert_template_result(' NO ', '{% assign v = false %}{% if v %} YES {% else %} NO {% endif %}')
assert_template_result(' YES ', '{% assign v = nil %}{% if v == nil %} YES {% else %} NO {% endif %}')
end
def test_if_else
assert_template_result(' YES ', '{% if false %} NO {% else %} YES {% endif %}')
assert_template_result(' YES ', '{% if true %} YES {% else %} NO {% endif %}')
assert_template_result(' YES ', '{% if "foo" %} YES {% else %} NO {% endif %}')
end
def test_if_boolean
assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => true })
end
def test_if_or
assert_template_result(' YES ', '{% if a or b %} YES {% endif %}', { 'a' => true, 'b' => true })
assert_template_result(' YES ', '{% if a or b %} YES {% endif %}', { 'a' => true, 'b' => false })
assert_template_result(' YES ', '{% if a or b %} YES {% endif %}', { 'a' => false, 'b' => true })
assert_template_result('', '{% if a or b %} YES {% endif %}', { 'a' => false, 'b' => false })
assert_template_result(' YES ', '{% if a or b or c %} YES {% endif %}', { 'a' => false, 'b' => false, 'c' => true })
assert_template_result('', '{% if a or b or c %} YES {% endif %}', { 'a' => false, 'b' => false, 'c' => false })
end
def test_if_or_with_operators
assert_template_result(' YES ', '{% if a == true or b == true %} YES {% endif %}', { 'a' => true, 'b' => true })
assert_template_result(' YES ', '{% if a == true or b == false %} YES {% endif %}', { 'a' => true, 'b' => true })
assert_template_result('', '{% if a == false or b == false %} YES {% endif %}', { 'a' => true, 'b' => true })
end
def test_comparison_of_strings_containing_and_or_or
awful_markup = "a == 'and' and b == 'or' and c == 'foo and bar' and d == 'bar or baz' and e == 'foo' and foo and bar"
assigns = { 'a' => 'and', 'b' => 'or', 'c' => 'foo and bar', 'd' => 'bar or baz', 'e' => 'foo', 'foo' => true, 'bar' => true }
assert_template_result(' YES ', "{% if #{awful_markup} %} YES {% endif %}", assigns)
end
def test_comparison_of_expressions_starting_with_and_or_or
assigns = { 'order' => { 'items_count' => 0 }, 'android' => { 'name' => 'Roy' } }
assert_template_result(
"YES",
"{% if android.name == 'Roy' %}YES{% endif %}",
assigns,
)
assert_template_result(
"YES",
"{% if order.items_count == 0 %}YES{% endif %}",
assigns,
)
end
def test_if_and
assert_template_result(' YES ', '{% if true and true %} YES {% endif %}')
assert_template_result('', '{% if false and true %} YES {% endif %}')
assert_template_result('', '{% if true and false %} YES {% endif %}')
end
def test_hash_miss_generates_false
assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => {} })
end
def test_if_from_variable
assert_template_result('', '{% if var %} NO {% endif %}', { 'var' => false })
assert_template_result('', '{% if var %} NO {% endif %}', { 'var' => nil })
assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => { 'bar' => false } })
assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => {} })
assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => nil })
assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => true })
assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => "text" })
assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => true })
assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => 1 })
assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => {} })
assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => [] })
assert_template_result(' YES ', '{% if "foo" %} YES {% endif %}')
assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => true } })
assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => "text" } })
assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => 1 } })
assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => {} } })
assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => [] } })
assert_template_result(' YES ', '{% if var %} NO {% else %} YES {% endif %}', { 'var' => false })
assert_template_result(' YES ', '{% if var %} NO {% else %} YES {% endif %}', { 'var' => nil })
assert_template_result(' YES ', '{% if var %} YES {% else %} NO {% endif %}', { 'var' => true })
assert_template_result(' YES ', '{% if "foo" %} YES {% else %} NO {% endif %}', { 'var' => "text" })
assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'foo' => { 'bar' => false } })
assert_template_result(' YES ', '{% if foo.bar %} YES {% else %} NO {% endif %}', { 'foo' => { 'bar' => true } })
assert_template_result(' YES ', '{% if foo.bar %} YES {% else %} NO {% endif %}', { 'foo' => { 'bar' => "text" } })
assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'foo' => { 'notbar' => true } })
assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'foo' => {} })
assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'notfoo' => { 'bar' => true } })
end
def test_nested_if
assert_template_result('', '{% if false %}{% if false %} NO {% endif %}{% endif %}')
assert_template_result('', '{% if false %}{% if true %} NO {% endif %}{% endif %}')
assert_template_result('', '{% if true %}{% if false %} NO {% endif %}{% endif %}')
assert_template_result(' YES ', '{% if true %}{% if true %} YES {% endif %}{% endif %}')
assert_template_result(' YES ', '{% if true %}{% if true %} YES {% else %} NO {% endif %}{% else %} NO {% endif %}')
assert_template_result(' YES ', '{% if true %}{% if false %} NO {% else %} YES {% endif %}{% else %} NO {% endif %}')
assert_template_result(' YES ', '{% if false %}{% if true %} NO {% else %} NONO {% endif %}{% else %} YES {% endif %}')
end
def test_comparisons_on_null
assert_template_result('', '{% if null < 10 %} NO {% endif %}')
assert_template_result('', '{% if null <= 10 %} NO {% endif %}')
assert_template_result('', '{% if null >= 10 %} NO {% endif %}')
assert_template_result('', '{% if null > 10 %} NO {% endif %}')
assert_template_result('', '{% if 10 < null %} NO {% endif %}')
assert_template_result('', '{% if 10 <= null %} NO {% endif %}')
assert_template_result('', '{% if 10 >= null %} NO {% endif %}')
assert_template_result('', '{% if 10 > null %} NO {% endif %}')
end
def test_else_if
assert_template_result('0', '{% if 0 == 0 %}0{% elsif 1 == 1%}1{% else %}2{% endif %}')
assert_template_result('1', '{% if 0 != 0 %}0{% elsif 1 == 1%}1{% else %}2{% endif %}')
assert_template_result('2', '{% if 0 != 0 %}0{% elsif 1 != 1%}1{% else %}2{% endif %}')
assert_template_result('elsif', '{% if false %}if{% elsif true %}elsif{% endif %}')
end
def test_syntax_error_no_variable
assert_raises(SyntaxError) { assert_template_result('', '{% if jerry == 1 %}') }
end
def test_syntax_error_no_expression
assert_raises(SyntaxError) { assert_template_result('', '{% if %}') }
end
def test_if_with_custom_condition
original_op = Condition.operators['contains']
Condition.operators['contains'] = :[]
assert_template_result('yes', %({% if 'bob' contains 'o' %}yes{% endif %}))
assert_template_result('no', %({% if 'bob' contains 'f' %}yes{% else %}no{% endif %}))
ensure
Condition.operators['contains'] = original_op
end
def test_operators_are_ignored_unless_isolated
original_op = Condition.operators['contains']
Condition.operators['contains'] = :[]
assert_template_result(
'yes',
%({% if 'gnomeslab-and-or-liquid' contains 'gnomeslab-and-or-liquid' %}yes{% endif %}),
)
ensure
Condition.operators['contains'] = original_op
end
def test_operators_are_whitelisted
assert_raises(SyntaxError) do
assert_template_result('', %({% if 1 or throw or or 1 %}yes{% endif %}))
end
end
def test_multiple_conditions
tpl = "{% if a or b and c %}true{% else %}false{% endif %}"
tests = {
[true, true, true] => true,
[true, true, false] => true,
[true, false, true] => true,
[true, false, false] => true,
[false, true, true] => true,
[false, true, false] => false,
[false, false, true] => false,
[false, false, false] => false,
}
tests.each do |vals, expected|
a, b, c = vals
assigns = { 'a' => a, 'b' => b, 'c' => c }
assert_template_result(expected.to_s, tpl, assigns, message: assigns.to_s)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/statements_test.rb | test/integration/tags/statements_test.rb | # frozen_string_literal: true
require 'test_helper'
class StatementsTest < Minitest::Test
include Liquid
def test_true_eql_true
text = ' {% if true == true %} true {% else %} false {% endif %} '
assert_template_result(' true ', text)
end
def test_true_not_eql_true
text = ' {% if true != true %} true {% else %} false {% endif %} '
assert_template_result(' false ', text)
end
def test_true_lq_true
text = ' {% if 0 > 0 %} true {% else %} false {% endif %} '
assert_template_result(' false ', text)
end
def test_one_lq_zero
text = ' {% if 1 > 0 %} true {% else %} false {% endif %} '
assert_template_result(' true ', text)
end
def test_zero_lq_one
text = ' {% if 0 < 1 %} true {% else %} false {% endif %} '
assert_template_result(' true ', text)
end
def test_zero_lq_or_equal_one
text = ' {% if 0 <= 0 %} true {% else %} false {% endif %} '
assert_template_result(' true ', text)
end
def test_zero_lq_or_equal_one_involving_nil
text = ' {% if null <= 0 %} true {% else %} false {% endif %} '
assert_template_result(' false ', text)
text = ' {% if 0 <= null %} true {% else %} false {% endif %} '
assert_template_result(' false ', text)
end
def test_zero_lqq_or_equal_one
text = ' {% if 0 >= 0 %} true {% else %} false {% endif %} '
assert_template_result(' true ', text)
end
def test_strings
text = " {% if 'test' == 'test' %} true {% else %} false {% endif %} "
assert_template_result(' true ', text)
end
def test_strings_not_equal
text = " {% if 'test' != 'test' %} true {% else %} false {% endif %} "
assert_template_result(' false ', text)
end
def test_var_strings_equal
text = ' {% if var == "hello there!" %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'var' => 'hello there!' })
end
def test_var_strings_are_not_equal
text = ' {% if "hello there!" == var %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'var' => 'hello there!' })
end
def test_var_and_long_string_are_equal
text = " {% if var == 'hello there!' %} true {% else %} false {% endif %} "
assert_template_result(' true ', text, { 'var' => 'hello there!' })
end
def test_var_and_long_string_are_equal_backwards
text = " {% if 'hello there!' == var %} true {% else %} false {% endif %} "
assert_template_result(' true ', text, { 'var' => 'hello there!' })
end
# def test_is_nil
# text = %| {% if var != nil %} true {% else %} false {% end %} |
# @template.assigns = { 'var' => 'hello there!'}
# expected = %| true |
# assert_equal expected, @template.parse(text)
# end
def test_is_collection_empty
text = ' {% if array == empty %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'array' => [] })
end
def test_is_not_collection_empty
text = ' {% if array == empty %} true {% else %} false {% endif %} '
assert_template_result(' false ', text, { 'array' => [1, 2, 3] })
end
def test_nil
text = ' {% if var == nil %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'var' => nil })
text = ' {% if var == null %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'var' => nil })
end
def test_not_nil
text = ' {% if var != nil %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'var' => 1 })
text = ' {% if var != null %} true {% else %} false {% endif %} '
assert_template_result(' true ', text, { 'var' => 1 })
end
end # StatementsTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/echo_test.rb | test/integration/tags/echo_test.rb | # frozen_string_literal: true
require 'test_helper'
class EchoTest < Minitest::Test
include Liquid
def test_echo_outputs_its_input
assert_template_result('BAR', <<~LIQUID, { 'variable-name' => 'bar' })
{%- echo variable-name | upcase -%}
LIQUID
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/liquid_tag_test.rb | test/integration/tags/liquid_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class LiquidTagTest < Minitest::Test
include Liquid
def test_liquid_tag
assert_template_result('1 2 3', <<~LIQUID, { 'array' => [1, 2, 3] })
{%- liquid
echo array | join: " "
-%}
LIQUID
assert_template_result('1 2 3', <<~LIQUID, { 'array' => [1, 2, 3] })
{%- liquid
for value in array
echo value
unless forloop.last
echo " "
endunless
endfor
-%}
LIQUID
assert_template_result('4 8 12 6', <<~LIQUID, { 'array' => [1, 2, 3] })
{%- liquid
for value in array
assign double_value = value | times: 2
echo double_value | times: 2
unless forloop.last
echo " "
endunless
endfor
echo " "
echo double_value
-%}
LIQUID
assert_template_result('abc', <<~LIQUID)
{%- liquid echo "a" -%}
b
{%- liquid echo "c" -%}
LIQUID
end
def test_liquid_tag_errors
assert_match_syntax_error("syntax error (line 1): Unknown tag 'error'", <<~LIQUID)
{%- liquid error no such tag -%}
LIQUID
assert_match_syntax_error("syntax error (line 7): Unknown tag 'error'", <<~LIQUID)
{{ test }}
{%-
liquid
for value in array
error no such tag
endfor
-%}
LIQUID
assert_match_syntax_error("syntax error (line 2): Unknown tag '!!! the guards are vigilant'", <<~LIQUID)
{%- liquid
!!! the guards are vigilant
-%}
LIQUID
assert_match_syntax_error("syntax error (line 4): 'for' tag was never closed", <<~LIQUID)
{%- liquid
for value in array
echo 'forgot to close the for tag'
-%}
LIQUID
end
def test_line_number_is_correct_after_a_blank_token
assert_match_syntax_error("syntax error (line 3): Unknown tag 'error'", "{% liquid echo ''\n\n error %}")
assert_match_syntax_error("syntax error (line 3): Unknown tag 'error'", "{% liquid echo ''\n \n error %}")
end
def test_nested_liquid_tag
assert_template_result('good', <<~LIQUID)
{%- if true %}
{%- liquid
echo "good"
%}
{%- endif -%}
LIQUID
end
def test_cannot_open_blocks_living_past_a_liquid_tag
assert_match_syntax_error("syntax error (line 3): 'if' tag was never closed", <<~LIQUID)
{%- liquid
if true
-%}
{%- endif -%}
LIQUID
end
def test_cannot_close_blocks_created_before_a_liquid_tag
assert_match_syntax_error("syntax error (line 3): 'endif' is not a valid delimiter for liquid tags. use %}", <<~LIQUID)
{%- if true -%}
42
{%- liquid endif -%}
LIQUID
end
def test_liquid_tag_in_raw
assert_template_result("{% liquid echo 'test' %}\n", <<~LIQUID)
{% raw %}{% liquid echo 'test' %}{% endraw %}
LIQUID
end
def test_nested_liquid_tags
assert_template_result('good', <<~LIQUID)
{%- liquid
liquid
if true
echo "good"
endif
-%}
LIQUID
end
def test_nested_liquid_tags_on_same_line
assert_template_result('good', <<~LIQUID)
{%- liquid liquid liquid echo "good" -%}
LIQUID
end
def test_nested_liquid_liquid_is_not_skipped_if_used_in_non_tag_position
assert_template_result('liquid', <<~LIQUID, { 'liquid' => 'liquid' })
{%- liquid liquid liquid echo liquid -%}
LIQUID
end
def test_next_liquid_with_unclosed_if_tag
assert_match_syntax_error("Liquid syntax error (line 2): 'if' tag was never closed", <<~LIQUID)
{%- liquid
liquid if true
echo "good"
endif
-%}
LIQUID
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/raw_tag_test.rb | test/integration/tags/raw_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class RawTagTest < Minitest::Test
include Liquid
def test_tag_in_raw
assert_template_result(
'{% comment %} test {% endcomment %}',
'{% raw %}{% comment %} test {% endcomment %}{% endraw %}',
)
end
def test_output_in_raw
assert_template_result('>{{ test }}<', '> {%- raw -%}{{ test }}{%- endraw -%} <')
assert_template_result("> inner <", "> {%- raw -%} inner {%- endraw %} <")
assert_template_result("> inner <", "> {%- raw -%} inner {%- endraw -%} <")
assert_template_result("{Hello}", "{% raw %}{{% endraw %}Hello{% raw %}}{% endraw %}")
end
def test_open_tag_in_raw
assert_template_result(' Foobar {% invalid ', '{% raw %} Foobar {% invalid {% endraw %}')
assert_template_result(' Foobar invalid %} ', '{% raw %} Foobar invalid %} {% endraw %}')
assert_template_result(' Foobar {{ invalid ', '{% raw %} Foobar {{ invalid {% endraw %}')
assert_template_result(' Foobar invalid }} ', '{% raw %} Foobar invalid }} {% endraw %}')
assert_template_result(' Foobar {% invalid {% {% endraw ', '{% raw %} Foobar {% invalid {% {% endraw {% endraw %}')
assert_template_result(' Foobar {% {% {% ', '{% raw %} Foobar {% {% {% {% endraw %}')
assert_template_result(' test {% raw %} {% endraw %}', '{% raw %} test {% raw %} {% {% endraw %}endraw %}')
assert_template_result(' Foobar {{ invalid 1', '{% raw %} Foobar {{ invalid {% endraw %}{{ 1 }}')
assert_template_result(' Foobar {% foo {% bar %}', '{% raw %} Foobar {% foo {% bar %}{% endraw %}')
end
def test_invalid_raw
assert_match_syntax_error(/tag was never closed/, '{% raw %} foo')
assert_match_syntax_error(/Valid syntax/, '{% raw } foo {% endraw %}')
assert_match_syntax_error(/Valid syntax/, '{% raw } foo %}{% endraw %}')
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/table_row_test.rb | test/integration/tags/table_row_test.rb | # frozen_string_literal: true
require 'test_helper'
class TableRowTest < Minitest::Test
include Liquid
class ArrayDrop < Liquid::Drop
include Enumerable
def initialize(array)
@array = array
end
def each(&block)
@array.each(&block)
end
end
def test_table_row
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
'{% tablerow n in numbers cols:3%} {{n}} {% endtablerow %}',
{ 'numbers' => [1, 2, 3, 4, 5, 6] },
)
assert_template_result(
"<tr class=\"row1\">\n</tr>\n",
'{% tablerow n in numbers cols:3%} {{n}} {% endtablerow %}',
{ 'numbers' => [] },
)
end
def test_table_row_with_different_cols
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td><td class=\"col4\"> 4 </td><td class=\"col5\"> 5 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 6 </td></tr>\n",
'{% tablerow n in numbers cols:5%} {{n}} {% endtablerow %}',
{ 'numbers' => [1, 2, 3, 4, 5, 6] },
)
end
def test_table_col_counter
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\">1</td><td class=\"col2\">2</td></tr>\n<tr class=\"row2\"><td class=\"col1\">1</td><td class=\"col2\">2</td></tr>\n<tr class=\"row3\"><td class=\"col1\">1</td><td class=\"col2\">2</td></tr>\n",
'{% tablerow n in numbers cols:2%}{{tablerowloop.col}}{% endtablerow %}',
{ 'numbers' => [1, 2, 3, 4, 5, 6] },
)
end
def test_quoted_fragment
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
"{% tablerow n in collections.frontpage cols:3%} {{n}} {% endtablerow %}",
{ 'collections' => { 'frontpage' => [1, 2, 3, 4, 5, 6] } },
)
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
"{% tablerow n in collections['frontpage'] cols:3%} {{n}} {% endtablerow %}",
{ 'collections' => { 'frontpage' => [1, 2, 3, 4, 5, 6] } },
)
end
def test_enumerable_drop
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
'{% tablerow n in numbers cols:3%} {{n}} {% endtablerow %}',
{ 'numbers' => ArrayDrop.new([1, 2, 3, 4, 5, 6]) },
)
end
def test_offset_and_limit
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
'{% tablerow n in numbers cols:3 offset:1 limit:6%} {{n}} {% endtablerow %}',
{ 'numbers' => [0, 1, 2, 3, 4, 5, 6, 7] },
)
end
def test_blank_string_not_iterable
assert_template_result(
"<tr class=\"row1\">\n</tr>\n",
"{% tablerow char in characters cols:3 %}I WILL NOT BE OUTPUT{% endtablerow %}",
{ 'characters' => '' },
)
end
def test_cols_nil_constant_same_as_evaluated_nil_expression
expect = "<tr class=\"row1\">\n" \
"<td class=\"col1\">false</td>" \
"<td class=\"col2\">false</td>" \
"</tr>\n"
assert_template_result(
expect,
"{% tablerow i in (1..2) cols:nil %}{{ tablerowloop.col_last }}{% endtablerow %}",
)
assert_template_result(
expect,
"{% tablerow i in (1..2) cols:var %}{{ tablerowloop.col_last }}{% endtablerow %}",
{ "var" => nil },
)
end
def test_nil_limit_is_treated_as_zero
expect = "<tr class=\"row1\">\n" \
"</tr>\n"
assert_template_result(
expect,
"{% tablerow i in (1..2) limit:nil %}{{ i }}{% endtablerow %}",
)
assert_template_result(
expect,
"{% tablerow i in (1..2) limit:var %}{{ i }}{% endtablerow %}",
{ "var" => nil },
)
end
def test_nil_offset_is_treated_as_zero
expect = "<tr class=\"row1\">\n" \
"<td class=\"col1\">1:false</td>" \
"<td class=\"col2\">2:true</td>" \
"</tr>\n"
assert_template_result(
expect,
"{% tablerow i in (1..2) offset:nil %}{{ i }}:{{ tablerowloop.col_last }}{% endtablerow %}",
)
assert_template_result(
expect,
"{% tablerow i in (1..2) offset:var %}{{ i }}:{{ tablerowloop.col_last }}{% endtablerow %}",
{ "var" => nil },
)
end
def test_tablerow_loop_drop_attributes
template = <<~LIQUID.chomp
{% tablerow i in (1..2) %}
col: {{ tablerowloop.col }}
col0: {{ tablerowloop.col0 }}
col_first: {{ tablerowloop.col_first }}
col_last: {{ tablerowloop.col_last }}
first: {{ tablerowloop.first }}
index: {{ tablerowloop.index }}
index0: {{ tablerowloop.index0 }}
last: {{ tablerowloop.last }}
length: {{ tablerowloop.length }}
rindex: {{ tablerowloop.rindex }}
rindex0: {{ tablerowloop.rindex0 }}
row: {{ tablerowloop.row }}
{% endtablerow %}
LIQUID
expected_output = <<~OUTPUT
<tr class="row1">
<td class="col1">
col: 1
col0: 0
col_first: true
col_last: false
first: true
index: 1
index0: 0
last: false
length: 2
rindex: 2
rindex0: 1
row: 1
</td><td class="col2">
col: 2
col0: 1
col_first: false
col_last: true
first: false
index: 2
index0: 1
last: true
length: 2
rindex: 1
rindex0: 0
row: 1
</td></tr>
OUTPUT
assert_template_result(expected_output, template)
end
def test_table_row_renders_correct_error_message_for_invalid_parameters
assert_template_result(
"Liquid error (line 1): invalid integer",
'{% tablerow n in (1...10) limit:true %} {{n}} {% endtablerow %}',
error_mode: :warn,
render_errors: true,
)
assert_template_result(
"Liquid error (line 1): invalid integer",
'{% tablerow n in (1...10) offset:true %} {{n}} {% endtablerow %}',
error_mode: :warn,
render_errors: true,
)
assert_template_result(
"Liquid error (line 1): invalid integer",
'{% tablerow n in (1...10) cols:true %} {{n}} {% endtablerow %}',
render_errors: true,
error_mode: :warn,
)
end
def test_table_row_handles_interrupts
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td></tr>\n",
'{% tablerow n in (1..3) cols:2 %} {{n}} {% break %} {{n}} {% endtablerow %}',
)
assert_template_result(
"<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 3 </td></tr>\n",
'{% tablerow n in (1..3) cols:2 %} {{n}} {% continue %} {{n}} {% endtablerow %}',
)
end
def test_table_row_does_not_leak_interrupts
template = <<~LIQUID
{% for i in (1..2) -%}
{% for j in (1..2) -%}
{% tablerow k in (1..3) %}{% break %}{% endtablerow -%}
loop j={{ j }}
{% endfor -%}
loop i={{ i }}
{% endfor -%}
after loop
LIQUID
expected = <<~STR
<tr class="row1">
<td class="col1"></td></tr>
loop j=1
<tr class="row1">
<td class="col1"></td></tr>
loop j=2
loop i=1
<tr class="row1">
<td class="col1"></td></tr>
loop j=1
<tr class="row1">
<td class="col1"></td></tr>
loop j=2
loop i=2
after loop
STR
assert_template_result(
expected,
template,
)
end
def test_tablerow_with_cols_attribute_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in (1..6) cols: 3 %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>
<tr class="row2"><td class="col1">4</td><td class="col2">5</td><td class="col3">6</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template)
end
end
def test_tablerow_with_limit_attribute_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in (1..10) limit: 3 %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template)
end
end
def test_tablerow_with_offset_attribute_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in (1..5) offset: 2 %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">3</td><td class="col2">4</td><td class="col3">5</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template)
end
end
def test_tablerow_with_range_attribute_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in (1..3) range: (1..10) %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template)
end
end
def test_tablerow_with_multiple_attributes_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in (1..10) cols: 2, limit: 4, offset: 1 %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">2</td><td class="col2">3</td></tr>
<tr class="row2"><td class="col1">4</td><td class="col2">5</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template)
end
end
def test_tablerow_with_variable_collection_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow n in numbers cols: 2 %}{{ n }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td></tr>
<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template, { 'numbers' => [1, 2, 3, 4] })
end
end
def test_tablerow_with_dotted_access_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow n in obj.numbers cols: 2 %}{{ n }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td></tr>
<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template, { 'obj' => { 'numbers' => [1, 2, 3, 4] } })
end
end
def test_tablerow_with_bracketed_access_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow n in obj["numbers"] cols: 2 %}{{ n }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">10</td><td class="col2">20</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template, { 'obj' => { 'numbers' => [10, 20] } })
end
end
def test_tablerow_without_attributes_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in (1..3) %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template)
end
end
def test_tablerow_without_in_keyword_in_strict2_mode
template = '{% tablerow i (1..10) %}{{ i }}{% endtablerow %}'
with_error_modes(:strict2) do
error = assert_raises(SyntaxError) { Template.parse(template) }
assert_equal("Liquid syntax error: For loops require an 'in' clause in \"i (1..10)\"", error.message)
end
end
def test_tablerow_with_multiple_invalid_attributes_reports_first_in_strict2_mode
template = '{% tablerow i in (1..10) invalid1: 5, invalid2: 10 %}{{ i }}{% endtablerow %}'
with_error_modes(:strict2) do
error = assert_raises(SyntaxError) { Template.parse(template) }
assert_equal("Liquid syntax error: Invalid attribute 'invalid1' in tablerow loop. Valid attributes are cols, limit, offset, and range in \"i in (1..10) invalid1: 5, invalid2: 10\"", error.message)
end
end
def test_tablerow_with_empty_collection_in_strict2_mode
template = <<~LIQUID.chomp
{% tablerow i in empty_array cols: 2 %}{{ i }}{% endtablerow %}
LIQUID
expected = <<~OUTPUT
<tr class="row1">
</tr>
OUTPUT
with_error_modes(:strict2) do
assert_template_result(expected, template, { 'empty_array' => [] })
end
end
def test_tablerow_with_invalid_attribute_strict_vs_strict2
template = '{% tablerow i in (1..5) invalid_attr: 10 %}{{ i }}{% endtablerow %}'
expected = <<~OUTPUT
<tr class="row1">
<td class="col1">1</td><td class="col2">2</td><td class="col3">3</td><td class="col4">4</td><td class="col5">5</td></tr>
OUTPUT
with_error_modes(:lax, :strict) do
assert_template_result(expected, template)
end
with_error_modes(:strict2) do
error = assert_raises(SyntaxError) { Template.parse(template) }
assert_match(/Invalid attribute 'invalid_attr'/, error.message)
end
end
def test_tablerow_with_invalid_expression_strict_vs_strict2
template = '{% tablerow i in (1..5) limit: foo=>bar %}{{ i }}{% endtablerow %}'
with_error_modes(:lax, :strict) do
expected = <<~OUTPUT
<tr class="row1">
</tr>
OUTPUT
assert_template_result(expected, template)
end
with_error_modes(:strict2) do
error = assert_raises(SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/for_tag_test.rb | test/integration/tags/for_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class ThingWithValue < Liquid::Drop
def value
3
end
end
class ForTagTest < Minitest::Test
include Liquid
def test_for
assert_template_result(' yo yo yo yo ', '{%for item in array%} yo {%endfor%}', { 'array' => [1, 2, 3, 4] })
assert_template_result('yoyo', '{%for item in array%}yo{%endfor%}', { 'array' => [1, 2] })
assert_template_result(' yo ', '{%for item in array%} yo {%endfor%}', { 'array' => [1] })
assert_template_result('', '{%for item in array%}{%endfor%}', { 'array' => [1, 2] })
expected = <<HERE
yo
yo
yo
HERE
template = <<~HERE
{%for item in array%}
yo
{%endfor%}
HERE
assert_template_result(expected, template, { 'array' => [1, 2, 3] })
end
def test_for_reversed
assigns = { 'array' => [1, 2, 3] }
assert_template_result('321', '{%for item in array reversed %}{{item}}{%endfor%}', assigns)
end
def test_for_with_range
assert_template_result(' 1 2 3 ', '{%for item in (1..3) %} {{item}} {%endfor%}')
assert_raises(Liquid::ArgumentError) do
Template.parse('{% for i in (a..2) %}{% endfor %}').render!("a" => [1, 2])
end
assert_template_result(' 0 1 2 3 ', '{% for item in (a..3) %} {{item}} {% endfor %}', { "a" => "invalid integer" })
end
def test_for_with_variable_range
assert_template_result(' 1 2 3 ', '{%for item in (1..foobar) %} {{item}} {%endfor%}', { "foobar" => 3 })
end
def test_for_with_hash_value_range
foobar = { "value" => 3 }
assert_template_result(' 1 2 3 ', '{%for item in (1..foobar.value) %} {{item}} {%endfor%}', { "foobar" => foobar })
end
def test_for_with_drop_value_range
foobar = ThingWithValue.new
assert_template_result(' 1 2 3 ', '{%for item in (1..foobar.value) %} {{item}} {%endfor%}', { "foobar" => foobar })
end
def test_for_with_variable
assert_template_result(' 1 2 3 ', '{%for item in array%} {{item}} {%endfor%}', { 'array' => [1, 2, 3] })
assert_template_result('123', '{%for item in array%}{{item}}{%endfor%}', { 'array' => [1, 2, 3] })
assert_template_result('123', '{% for item in array %}{{item}}{% endfor %}', { 'array' => [1, 2, 3] })
assert_template_result('abcd', '{%for item in array%}{{item}}{%endfor%}', { 'array' => ['a', 'b', 'c', 'd'] })
assert_template_result('a b c', '{%for item in array%}{{item}}{%endfor%}', { 'array' => ['a', ' ', 'b', ' ', 'c'] })
assert_template_result('abc', '{%for item in array%}{{item}}{%endfor%}', { 'array' => ['a', '', 'b', '', 'c'] })
end
def test_for_helpers
assigns = { 'array' => [1, 2, 3] }
assert_template_result(
' 1/3 2/3 3/3 ',
'{%for item in array%} {{forloop.index}}/{{forloop.length}} {%endfor%}',
assigns,
)
assert_template_result(' 1 2 3 ', '{%for item in array%} {{forloop.index}} {%endfor%}', assigns)
assert_template_result(' 0 1 2 ', '{%for item in array%} {{forloop.index0}} {%endfor%}', assigns)
assert_template_result(' 2 1 0 ', '{%for item in array%} {{forloop.rindex0}} {%endfor%}', assigns)
assert_template_result(' 3 2 1 ', '{%for item in array%} {{forloop.rindex}} {%endfor%}', assigns)
assert_template_result(' true false false ', '{%for item in array%} {{forloop.first}} {%endfor%}', assigns)
assert_template_result(' false false true ', '{%for item in array%} {{forloop.last}} {%endfor%}', assigns)
end
def test_for_and_if
assigns = { 'array' => [1, 2, 3] }
assert_template_result(
'+--',
'{%for item in array%}{% if forloop.first %}+{% else %}-{% endif %}{%endfor%}',
assigns,
)
end
def test_for_else
assert_template_result('+++', '{%for item in array%}+{%else%}-{%endfor%}', { 'array' => [1, 2, 3] })
assert_template_result('-', '{%for item in array%}+{%else%}-{%endfor%}', { 'array' => [] })
assert_template_result('-', '{%for item in array%}+{%else%}-{%endfor%}', { 'array' => nil })
end
def test_limiting
assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] }
assert_template_result('12', '{%for i in array limit:2 %}{{ i }}{%endfor%}', assigns)
assert_template_result('1234', '{%for i in array limit:4 %}{{ i }}{%endfor%}', assigns)
assert_template_result('3456', '{%for i in array limit:4 offset:2 %}{{ i }}{%endfor%}', assigns)
assert_template_result('3456', '{%for i in array limit: 4 offset: 2 %}{{ i }}{%endfor%}', assigns)
assert_template_result('3456', '{%for i in array, limit: 4, offset: 2 %}{{ i }}{%endfor%}', assigns)
end
def test_limiting_with_invalid_limit
assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] }
template = <<-MKUP
{% for i in array limit: true offset: 1 %}
{{ i }}
{% endfor %}
MKUP
exception = assert_raises(Liquid::ArgumentError) do
Template.parse(template).render!(assigns)
end
assert_equal("Liquid error: invalid integer", exception.message)
end
def test_limiting_with_invalid_offset
assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] }
template = <<-MKUP
{% for i in array limit: 1 offset: true %}
{{ i }}
{% endfor %}
MKUP
exception = assert_raises(Liquid::ArgumentError) do
Template.parse(template).render!(assigns)
end
assert_equal("Liquid error: invalid integer", exception.message)
end
def test_dynamic_variable_limiting
assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] }
assigns['limit'] = 2
assigns['offset'] = 2
assert_template_result('34', '{%for i in array limit: limit offset: offset %}{{ i }}{%endfor%}', assigns)
end
def test_nested_for
assigns = { 'array' => [[1, 2], [3, 4], [5, 6]] }
assert_template_result('123456', '{%for item in array%}{%for i in item%}{{ i }}{%endfor%}{%endfor%}', assigns)
end
def test_offset_only
assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] }
assert_template_result('890', '{%for i in array offset:7 %}{{ i }}{%endfor%}', assigns)
end
def test_pause_resume
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } }
markup = <<-MKUP
{%for i in array.items limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
MKUP
expected = <<-XPCTD
123
next
456
next
789
XPCTD
assert_template_result(expected, markup, assigns)
end
def test_pause_resume_limit
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } }
markup = <<-MKUP
{%for i in array.items limit:3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit:3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit:1 %}{{i}}{%endfor%}
MKUP
expected = <<-XPCTD
123
next
456
next
7
XPCTD
assert_template_result(expected, markup, assigns)
end
def test_pause_resume_big_limit
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } }
markup = <<-MKUP
{%for i in array.items limit:3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit:3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit:1000 %}{{i}}{%endfor%}
MKUP
expected = <<-XPCTD
123
next
456
next
7890
XPCTD
assert_template_result(expected, markup, assigns)
end
def test_pause_resume_big_offset
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } }
markup = '{%for i in array.items limit:3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit:3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit:3 offset:1000 %}{{i}}{%endfor%}'
expected = '123
next
456
next
'
assert_template_result(expected, markup, assigns)
end
def test_for_with_break
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } }
markup = '{% for i in array.items %}{% break %}{% endfor %}'
expected = ""
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{{ i }}{% break %}{% endfor %}'
expected = "1"
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{% break %}{{ i }}{% endfor %}'
expected = ""
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{{ i }}{% if i > 3 %}{% break %}{% endif %}{% endfor %}'
expected = "1234"
assert_template_result(expected, markup, assigns)
# tests to ensure it only breaks out of the local for loop
# and not all of them.
assigns = { 'array' => [[1, 2], [3, 4], [5, 6]] }
markup = '{% for item in array %}' \
'{% for i in item %}' \
'{% if i == 1 %}' \
'{% break %}' \
'{% endif %}' \
'{{ i }}' \
'{% endfor %}' \
'{% endfor %}'
expected = '3456'
assert_template_result(expected, markup, assigns)
# test break does nothing when unreached
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5] } }
markup = '{% for i in array.items %}{% if i == 9999 %}{% break %}{% endif %}{{ i }}{% endfor %}'
expected = '12345'
assert_template_result(expected, markup, assigns)
end
def test_for_with_break_after_nested_loop
source = <<~LIQUID.chomp
{% for i in (1..2) -%}
{% for j in (1..2) -%}
{{ i }}-{{ j }},
{%- endfor -%}
{% break -%}
{% endfor -%}
after
LIQUID
assert_template_result("1-1,1-2,after", source)
end
def test_for_with_continue
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5] } }
markup = '{% for i in array.items %}{% continue %}{% endfor %}'
expected = ""
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{{ i }}{% continue %}{% endfor %}'
expected = "12345"
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{% continue %}{{ i }}{% endfor %}'
expected = ""
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{% if i > 3 %}{% continue %}{% endif %}{{ i }}{% endfor %}'
expected = "123"
assert_template_result(expected, markup, assigns)
markup = '{% for i in array.items %}{% if i == 3 %}{% continue %}{% else %}{{ i }}{% endif %}{% endfor %}'
expected = "1245"
assert_template_result(expected, markup, assigns)
# tests to ensure it only continues the local for loop and not all of them.
assigns = { 'array' => [[1, 2], [3, 4], [5, 6]] }
markup = '{% for item in array %}' \
'{% for i in item %}' \
'{% if i == 1 %}' \
'{% continue %}' \
'{% endif %}' \
'{{ i }}' \
'{% endfor %}' \
'{% endfor %}'
expected = '23456'
assert_template_result(expected, markup, assigns)
# test continue does nothing when unreached
assigns = { 'array' => { 'items' => [1, 2, 3, 4, 5] } }
markup = '{% for i in array.items %}{% if i == 9999 %}{% continue %}{% endif %}{{ i }}{% endfor %}'
expected = '12345'
assert_template_result(expected, markup, assigns)
end
def test_for_tag_string
# ruby 1.8.7 "String".each => Enumerator with single "String" element.
# ruby 1.9.3 no longer supports .each on String though we mimic
# the functionality for backwards compatibility
assert_template_result(
'test string',
'{%for val in string%}{{val}}{%endfor%}',
{ 'string' => "test string" },
)
assert_template_result(
'test string',
'{%for val in string limit:1%}{{val}}{%endfor%}',
{ 'string' => "test string" },
)
assert_template_result(
'val-string-1-1-0-1-0-true-true-test string',
'{%for val in string%}' \
'{{forloop.name}}-' \
'{{forloop.index}}-' \
'{{forloop.length}}-' \
'{{forloop.index0}}-' \
'{{forloop.rindex}}-' \
'{{forloop.rindex0}}-' \
'{{forloop.first}}-' \
'{{forloop.last}}-' \
'{{val}}{%endfor%}',
{ 'string' => "test string" },
)
end
def test_for_parentloop_references_parent_loop
assert_template_result(
'1.1 1.2 1.3 2.1 2.2 2.3 ',
'{% for inner in outer %}{% for k in inner %}' \
'{{ forloop.parentloop.index }}.{{ forloop.index }} ' \
'{% endfor %}{% endfor %}',
{ 'outer' => [[1, 1, 1], [1, 1, 1]] },
)
end
def test_for_parentloop_nil_when_not_present
assert_template_result(
'.1 .2 ',
'{% for inner in outer %}' \
'{{ forloop.parentloop.index }}.{{ forloop.index }} ' \
'{% endfor %}',
{ 'outer' => [[1, 1, 1], [1, 1, 1]] },
)
end
def test_inner_for_over_empty_input
assert_template_result('oo', '{% for a in (1..2) %}o{% for b in empty %}{% endfor %}{% endfor %}')
end
def test_blank_string_not_iterable
assert_template_result('', "{% for char in characters %}I WILL NOT BE OUTPUT{% endfor %}", { 'characters' => '' })
end
def test_bad_variable_naming_in_for_loop
assert_raises(Liquid::SyntaxError) do
Liquid::Template.parse('{% for a/b in x %}{% endfor %}')
end
end
def test_spacing_with_variable_naming_in_for_loop
expected = '12345'
template = '{% for item in items %}{{item}}{% endfor %}'
assigns = { 'items' => [1, 2, 3, 4, 5] }
assert_template_result(expected, template, assigns)
end
class LoaderDrop < Liquid::Drop
attr_accessor :each_called, :load_slice_called
def initialize(data)
@data = data
end
def each
@each_called = true
@data.each { |el| yield el }
end
def load_slice(from, to)
@load_slice_called = true
@data[(from..to - 1)]
end
end
def test_iterate_with_each_when_no_limit_applied
loader = LoaderDrop.new([1, 2, 3, 4, 5])
assigns = { 'items' => loader }
expected = '12345'
template = '{% for item in items %}{{item}}{% endfor %}'
assert_template_result(expected, template, assigns)
assert(loader.each_called)
assert(!loader.load_slice_called)
end
def test_iterate_with_load_slice_when_limit_applied
loader = LoaderDrop.new([1, 2, 3, 4, 5])
assigns = { 'items' => loader }
expected = '1'
template = '{% for item in items limit:1 %}{{item}}{% endfor %}'
assert_template_result(expected, template, assigns)
assert(!loader.each_called)
assert(loader.load_slice_called)
end
def test_iterate_with_load_slice_when_limit_and_offset_applied
loader = LoaderDrop.new([1, 2, 3, 4, 5])
assigns = { 'items' => loader }
expected = '34'
template = '{% for item in items offset:2 limit:2 %}{{item}}{% endfor %}'
assert_template_result(expected, template, assigns)
assert(!loader.each_called)
assert(loader.load_slice_called)
end
def test_iterate_with_load_slice_returns_same_results_as_without
loader = LoaderDrop.new([1, 2, 3, 4, 5])
loader_assigns = { 'items' => loader }
array_assigns = { 'items' => [1, 2, 3, 4, 5] }
expected = '34'
template = '{% for item in items offset:2 limit:2 %}{{item}}{% endfor %}'
assert_template_result(expected, template, loader_assigns)
assert_template_result(expected, template, array_assigns)
end
def test_for_cleans_up_registers
context = Context.new(ErrorDrop.new)
assert_raises(StandardError) do
Liquid::Template.parse('{% for i in (1..2) %}{{ standard_error }}{% endfor %}').render!(context)
end
assert(context.registers[:for_stack].empty?)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/increment_tag_test.rb | test/integration/tags/increment_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class IncrementTagTest < Minitest::Test
include Liquid
def test_inc
assert_template_result('0 1', '{%increment port %} {{ port }}')
assert_template_result(' 0 1 2', '{{port}} {%increment port %} {%increment port%} {{port}}')
assert_template_result(
'0 0 1 2 1',
'{%increment port %} {%increment starboard%} ' \
'{%increment port %} {%increment port%} ' \
'{%increment starboard %}',
)
end
def test_dec
assert_template_result('-1 -1', '{%decrement port %} {{ port }}', { 'port' => 10 })
assert_template_result(' -1 -2 -2', '{{port}} {%decrement port %} {%decrement port%} {{port}}')
assert_template_result(
'0 1 2 0 3 1 1 3',
'{%increment starboard %} {%increment starboard%} {%increment starboard%} ' \
'{%increment port %} {%increment starboard%} ' \
'{%increment port %} {%decrement port%} ' \
'{%decrement starboard %}',
)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/standard_tag_test.rb | test/integration/tags/standard_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class StandardTagTest < Minitest::Test
include Liquid
def test_no_transform
assert_template_result(
'this text should come out of the template without change...',
'this text should come out of the template without change...',
)
assert_template_result('blah', 'blah')
assert_template_result('<blah>', '<blah>')
assert_template_result('|,.:', '|,.:')
assert_template_result('', '')
text = %(this shouldnt see any transformation either but has multiple lines
as you can clearly see here ...)
assert_template_result(text, text)
end
def test_has_a_block_which_does_nothing
assert_template_result(
%(the comment block should be removed .. right?),
%(the comment block should be removed {%comment%} be gone.. {%endcomment%} .. right?),
)
assert_template_result('', '{%comment%}{%endcomment%}')
assert_template_result('', '{%comment%}{% endcomment %}')
assert_template_result('', '{% comment %}{%endcomment%}')
assert_template_result('', '{% comment %}{% endcomment %}')
assert_template_result('', '{%comment%}comment{%endcomment%}')
assert_template_result('', '{% comment %}comment{% endcomment %}')
assert_template_result('', '{% comment %} 1 {% comment %} 2 {% endcomment %} 3 {% endcomment %}')
assert_template_result('', '{%comment%}{%blabla%}{%endcomment%}')
assert_template_result('', '{% comment %}{% blabla %}{% endcomment %}')
assert_template_result('', '{%comment%}{% endif %}{%endcomment%}')
assert_template_result('', '{% comment %}{% endwhatever %}{% endcomment %}')
assert_template_result('', '{% comment %}{% raw %} {{%%%%}} }} { {% endcomment %} {% comment {% endraw %} {% endcomment %}')
assert_template_result('', '{% comment %}{% " %}{% endcomment %}')
assert_template_result('', '{% comment %}{%%}{% endcomment %}')
assert_template_result('foobar', 'foo{%comment%}comment{%endcomment%}bar')
assert_template_result('foobar', 'foo{% comment %}comment{% endcomment %}bar')
assert_template_result('foobar', 'foo{%comment%} comment {%endcomment%}bar')
assert_template_result('foobar', 'foo{% comment %} comment {% endcomment %}bar')
assert_template_result('foo bar', 'foo {%comment%} {%endcomment%} bar')
assert_template_result('foo bar', 'foo {%comment%}comment{%endcomment%} bar')
assert_template_result('foo bar', 'foo {%comment%} comment {%endcomment%} bar')
assert_template_result('foobar', 'foo{%comment%}
{%endcomment%}bar')
end
def test_hyphenated_assign
assigns = { 'a-b' => '1' }
assert_template_result('a-b:1 a-b:2', 'a-b:{{a-b}} {%assign a-b = 2 %}a-b:{{a-b}}', assigns)
end
def test_assign_with_colon_and_spaces
assigns = { 'var' => { 'a:b c' => { 'paged' => '1' } } }
assert_template_result('var2: 1', '{%assign var2 = var["a:b c"].paged %}var2: {{var2}}', assigns)
end
def test_capture
assigns = { 'var' => 'content' }
assert_template_result(
'content foo content foo ',
'{{ var2 }}{% capture var2 %}{{ var }} foo {% endcapture %}{{ var2 }}{{ var2 }}',
assigns,
)
end
def test_capture_detects_bad_syntax
assert_raises(SyntaxError) do
assert_template_result(
'content foo content foo ',
'{{ var2 }}{% capture %}{{ var }} foo {% endcapture %}{{ var2 }}{{ var2 }}',
{ 'var' => 'content' },
)
end
end
def test_case
assigns = { 'condition' => 2 }
assert_template_result(
' its 2 ',
'{% case condition %}{% when 1 %} its 1 {% when 2 %} its 2 {% endcase %}',
assigns,
)
assigns = { 'condition' => 1 }
assert_template_result(
' its 1 ',
'{% case condition %}{% when 1 %} its 1 {% when 2 %} its 2 {% endcase %}',
assigns,
)
assigns = { 'condition' => 3 }
assert_template_result(
'',
'{% case condition %}{% when 1 %} its 1 {% when 2 %} its 2 {% endcase %}',
assigns,
)
assigns = { 'condition' => "string here" }
assert_template_result(
' hit ',
'{% case condition %}{% when "string here" %} hit {% endcase %}',
assigns,
)
assigns = { 'condition' => "bad string here" }
assert_template_result(
'',
'{% case condition %}{% when "string here" %} hit {% endcase %}',
assigns,
)
end
def test_case_with_else
assigns = { 'condition' => 5 }
assert_template_result(
' hit ',
'{% case condition %}{% when 5 %} hit {% else %} else {% endcase %}',
assigns,
)
assigns = { 'condition' => 6 }
assert_template_result(
' else ',
'{% case condition %}{% when 5 %} hit {% else %} else {% endcase %}',
assigns,
)
assigns = { 'condition' => 6 }
assert_template_result(
' else ',
'{% case condition %} {% when 5 %} hit {% else %} else {% endcase %}',
assigns,
)
end
def test_case_on_size
assert_template_result('', '{% case a.size %}{% when 1 %}1{% when 2 %}2{% endcase %}', { 'a' => [] })
assert_template_result('1', '{% case a.size %}{% when 1 %}1{% when 2 %}2{% endcase %}', { 'a' => [1] })
assert_template_result('2', '{% case a.size %}{% when 1 %}1{% when 2 %}2{% endcase %}', { 'a' => [1, 1] })
assert_template_result('', '{% case a.size %}{% when 1 %}1{% when 2 %}2{% endcase %}', { 'a' => [1, 1, 1] })
assert_template_result('', '{% case a.size %}{% when 1 %}1{% when 2 %}2{% endcase %}', { 'a' => [1, 1, 1, 1] })
assert_template_result('', '{% case a.size %}{% when 1 %}1{% when 2 %}2{% endcase %}', { 'a' => [1, 1, 1, 1, 1] })
end
def test_case_on_size_with_else
assert_template_result(
'else',
'{% case a.size %}{% when 1 %}1{% when 2 %}2{% else %}else{% endcase %}',
{ 'a' => [] },
)
assert_template_result(
'1',
'{% case a.size %}{% when 1 %}1{% when 2 %}2{% else %}else{% endcase %}',
{ 'a' => [1] },
)
assert_template_result(
'2',
'{% case a.size %}{% when 1 %}1{% when 2 %}2{% else %}else{% endcase %}',
{ 'a' => [1, 1] },
)
assert_template_result(
'else',
'{% case a.size %}{% when 1 %}1{% when 2 %}2{% else %}else{% endcase %}',
{ 'a' => [1, 1, 1] },
)
assert_template_result(
'else',
'{% case a.size %}{% when 1 %}1{% when 2 %}2{% else %}else{% endcase %}',
{ 'a' => [1, 1, 1, 1] },
)
assert_template_result(
'else',
'{% case a.size %}{% when 1 %}1{% when 2 %}2{% else %}else{% endcase %}',
{ 'a' => [1, 1, 1, 1, 1] },
)
end
def test_case_on_length_with_else
assert_template_result(
'else',
'{% case a.empty? %}{% when true %}true{% when false %}false{% else %}else{% endcase %}',
{},
)
assert_template_result(
'false',
'{% case false %}{% when true %}true{% when false %}false{% else %}else{% endcase %}',
{},
)
assert_template_result(
'true',
'{% case true %}{% when true %}true{% when false %}false{% else %}else{% endcase %}',
{},
)
assert_template_result(
'else',
'{% case NULL %}{% when true %}true{% when false %}false{% else %}else{% endcase %}',
{},
)
end
def test_assign_from_case
# Example from the shopify forums
code = "{% case collection.handle %}{% when 'menswear-jackets' %}{% assign ptitle = 'menswear' %}{% when 'menswear-t-shirts' %}{% assign ptitle = 'menswear' %}{% else %}{% assign ptitle = 'womenswear' %}{% endcase %}{{ ptitle }}"
assert_template_result("menswear", code, { "collection" => { 'handle' => 'menswear-jackets' } })
assert_template_result("menswear", code, { "collection" => { 'handle' => 'menswear-t-shirts' } })
assert_template_result("womenswear", code, { "collection" => { 'handle' => 'x' } })
assert_template_result("womenswear", code, { "collection" => { 'handle' => 'y' } })
assert_template_result("womenswear", code, { "collection" => { 'handle' => 'z' } })
end
def test_case_when_or
code = '{% case condition %}{% when 1 or 2 or 3 %} its 1 or 2 or 3 {% when 4 %} its 4 {% endcase %}'
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 1 })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 2 })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 3 })
assert_template_result(' its 4 ', code, { 'condition' => 4 })
assert_template_result('', code, { 'condition' => 5 })
code = '{% case condition %}{% when 1 or "string" or null %} its 1 or 2 or 3 {% when 4 %} its 4 {% endcase %}'
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 1 })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 'string' })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => nil })
assert_template_result('', code, { 'condition' => 'something else' })
end
def test_case_when_comma
code = '{% case condition %}{% when 1, 2, 3 %} its 1 or 2 or 3 {% when 4 %} its 4 {% endcase %}'
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 1 })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 2 })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 3 })
assert_template_result(' its 4 ', code, { 'condition' => 4 })
assert_template_result('', code, { 'condition' => 5 })
code = '{% case condition %}{% when 1, "string", null %} its 1 or 2 or 3 {% when 4 %} its 4 {% endcase %}'
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 1 })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => 'string' })
assert_template_result(' its 1 or 2 or 3 ', code, { 'condition' => nil })
assert_template_result('', code, { 'condition' => 'something else' })
end
def test_case_when_comma_and_blank_body
code = '{% case condition %}{% when 1, 2 %} {% assign r = "result" %} {% endcase %}{{ r }}'
assert_template_result('result', code, { 'condition' => 2 })
end
def test_assign
assert_template_result('variable', '{% assign a = "variable"%}{{a}}')
end
def test_assign_unassigned
assigns = { 'var' => 'content' }
assert_template_result('var2: var2:content', 'var2:{{var2}} {%assign var2 = var%} var2:{{var2}}', assigns)
end
def test_assign_an_empty_string
assert_template_result('', '{% assign a = ""%}{{a}}')
end
def test_assign_is_global
assert_template_result('variable', '{%for i in (1..2) %}{% assign a = "variable"%}{% endfor %}{{a}}')
end
def test_case_detects_bad_syntax
assert_raises(SyntaxError) do
assert_template_result('', '{% case false %}{% when %}true{% endcase %}', {})
end
assert_raises(SyntaxError) do
assert_template_result('', '{% case false %}{% huh %}true{% endcase %}', {})
end
end
def test_cycle
assert_template_result('one', '{%cycle "one", "two"%}')
assert_template_result('one two', '{%cycle "one", "two"%} {%cycle "one", "two"%}')
assert_template_result(' two', '{%cycle "", "two"%} {%cycle "", "two"%}')
assert_template_result('one two one', '{%cycle "one", "two"%} {%cycle "one", "two"%} {%cycle "one", "two"%}')
assert_template_result(
'text-align: left text-align: right',
'{%cycle "text-align: left", "text-align: right" %} {%cycle "text-align: left", "text-align: right"%}',
)
end
def test_multiple_cycles
assert_template_result(
'1 2 1 1 2 3 1',
'{%cycle 1,2%} {%cycle 1,2%} {%cycle 1,2%} {%cycle 1,2,3%} {%cycle 1,2,3%} {%cycle 1,2,3%} {%cycle 1,2,3%}',
)
end
def test_multiple_named_cycles
assert_template_result(
'one one two two one one',
'{%cycle 1: "one", "two" %} {%cycle 2: "one", "two" %} {%cycle 1: "one", "two" %} {%cycle 2: "one", "two" %} {%cycle 1: "one", "two" %} {%cycle 2: "one", "two" %}',
)
end
def test_multiple_named_cycles_with_names_from_context
assigns = { "var1" => 1, "var2" => 2 }
assert_template_result(
'one one two two one one',
'{%cycle var1: "one", "two" %} {%cycle var2: "one", "two" %} {%cycle var1: "one", "two" %} {%cycle var2: "one", "two" %} {%cycle var1: "one", "two" %} {%cycle var2: "one", "two" %}',
assigns,
)
end
def test_size_of_array
assigns = { "array" => [1, 2, 3, 4] }
assert_template_result('array has 4 elements', "array has {{ array.size }} elements", assigns)
end
def test_size_of_hash
assigns = { "hash" => { a: 1, b: 2, c: 3, d: 4 } }
assert_template_result('hash has 4 elements', "hash has {{ hash.size }} elements", assigns)
end
def test_illegal_symbols
assert_template_result('', '{% if true == empty %}?{% endif %}', {})
assert_template_result('', '{% if true == null %}?{% endif %}', {})
assert_template_result('', '{% if empty == true %}?{% endif %}', {})
assert_template_result('', '{% if null == true %}?{% endif %}', {})
end
def test_ifchanged
assigns = { 'array' => [1, 1, 2, 2, 3, 3] }
assert_template_result('123', '{%for item in array%}{%ifchanged%}{{item}}{% endifchanged %}{%endfor%}', assigns)
assigns = { 'array' => [1, 1, 1, 1] }
assert_template_result('1', '{%for item in array%}{%ifchanged%}{{item}}{% endifchanged %}{%endfor%}', assigns)
end
def test_multiline_tag
assert_template_result('0 1 2 3', "0{%\nfor i in (1..3)\n%} {{\ni\n}}{%\nendfor\n%}")
end
end # StandardTagTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/continue_tag_test.rb | test/integration/tags/continue_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class ContinueTagTest < Minitest::Test
include Liquid
# tests that no weird errors are raised if continue is called outside of a
# block
def test_continue_with_no_block
assigns = {}
markup = '{% continue %}'
expected = ''
assert_template_result(expected, markup, assigns)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/cycle_tag_test.rb | test/integration/tags/cycle_tag_test.rb | # frozen_string_literal: true
require 'test_helper'
class CycleTagTest < Minitest::Test
def test_simple_cycle_inside_for_loop
template = <<~LIQUID
{%- for i in (1..3) -%}
{%- cycle '1', '2', '3' -%}
{%- endfor -%}
LIQUID
assert_template_result("123", template)
end
def test_cycle_with_variables_inside_for_loop
template = <<~LIQUID
{%- assign a = 1 -%}
{%- assign b = 2 -%}
{%- assign c = 3 -%}
{%- for i in (1..3) -%}
{% cycle a, b, c %}
{%- endfor -%}
LIQUID
assert_template_result("123", template)
end
def test_cycle_named_groups_string
template = <<~LIQUID
{%- for i in (1..3) -%}
{%- cycle 'placeholder1': 1, 2, 3 -%}
{%- cycle 'placeholder2': 1, 2, 3 -%}
{%- endfor -%}
LIQUID
assert_template_result("112233", template)
end
def test_cycle_named_groups_vlookup
template = <<~LIQUID
{%- assign placeholder1 = 'placeholder1' -%}
{%- assign placeholder2 = 'placeholder2' -%}
{%- for i in (1..3) -%}
{%- cycle placeholder1: 1, 2, 3 -%}
{%- cycle placeholder2: 1, 2, 3 -%}
{%- endfor -%}
LIQUID
assert_template_result("112233", template)
end
def test_unnamed_cycle_have_independent_counters_when_used_with_lookups
template = <<~LIQUID
{%- assign a = "1" -%}
{%- for i in (1..3) -%}
{%- cycle a, "2" -%}
{%- cycle a, "2" -%}
{%- endfor -%}
LIQUID
assert_template_result("112211", template)
end
def test_unnamed_cycle_dependent_counter_when_used_with_literal_values
template = <<~LIQUID
{%- cycle "1", "2" -%}
{%- cycle "1", "2" -%}
{%- cycle "1", "2" -%}
LIQUID
assert_template_result("121", template)
end
def test_optional_trailing_comma
template = <<~LIQUID
{%- cycle "1", "2", -%}
{%- cycle "1", "2", -%}
{%- cycle "1", "2", -%}
{%- cycle "1", -%}
LIQUID
assert_template_result("1211", template)
end
def test_cycle_tag_without_arguments
error = assert_raises(Liquid::SyntaxError) do
Template.parse("{% cycle %}")
end
assert_match(/Syntax Error in 'cycle' - Valid syntax: cycle \[name :\] var/, error.message)
end
def test_cycle_tag_with_error_mode
# QuotedFragment is more permissive than what Parser#expression allows.
template1 = "{% assign 5 = 'b' %}{% cycle .5, .4 %}"
template2 = "{% cycle .5: 'a', 'b' %}"
with_error_modes(:lax, :strict) do
assert_template_result("b", template1)
assert_template_result("a", template2)
end
with_error_modes(:strict2) do
error1 = assert_raises(Liquid::SyntaxError) { Template.parse(template1) }
error2 = assert_raises(Liquid::SyntaxError) { Template.parse(template2) }
expected_error = /Liquid syntax error: \[:dot, "."\] is not a valid expression/
assert_match(expected_error, error1.message)
assert_match(expected_error, error2.message)
end
end
def test_cycle_with_trailing_elements
assignments = "{% assign a = 'A' %}{% assign n = 'N' %}"
template1 = "#{assignments}{% cycle 'a' 'b', 'c' %}"
template2 = "#{assignments}{% cycle name: 'a' 'b', 'c' %}"
template3 = "#{assignments}{% cycle name: 'a', 'b' 'c' %}"
template4 = "#{assignments}{% cycle n e: 'a', 'b', 'c' %}"
template5 = "#{assignments}{% cycle n e 'a', 'b', 'c' %}"
with_error_modes(:lax, :strict) do
assert_template_result("a", template1)
assert_template_result("a", template2)
assert_template_result("a", template3)
assert_template_result("N", template4)
assert_template_result("N", template5)
end
with_error_modes(:strict2) do
error1 = assert_raises(Liquid::SyntaxError) { Template.parse(template1) }
error2 = assert_raises(Liquid::SyntaxError) { Template.parse(template2) }
error3 = assert_raises(Liquid::SyntaxError) { Template.parse(template3) }
error4 = assert_raises(Liquid::SyntaxError) { Template.parse(template4) }
error5 = assert_raises(Liquid::SyntaxError) { Template.parse(template5) }
expected_error = /Expected end_of_string but found/
assert_match(expected_error, error1.message)
assert_match(expected_error, error2.message)
assert_match(expected_error, error3.message)
assert_match(expected_error, error4.message)
assert_match(expected_error, error5.message)
end
end
def test_cycle_name_with_invalid_expression
template = <<~LIQUID
{% for i in (1..3) %}
{% cycle foo=>bar: "a", "b" %}
{% endfor %}
LIQUID
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
def test_cycle_variable_with_invalid_expression
template = <<~LIQUID
{% for i in (1..3) %}
{% cycle foo=>bar, "a", "b" %}
{% endfor %}
LIQUID
with_error_modes(:lax, :strict) do
refute_nil(Template.parse(template))
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tags/inline_comment_test.rb | test/integration/tags/inline_comment_test.rb | # frozen_string_literal: true
require 'test_helper'
class InlineCommentTest < Minitest::Test
include Liquid
def test_inline_comment_returns_nothing
assert_template_result('', '{%- # this is an inline comment -%}')
assert_template_result('', '{%-# this is an inline comment -%}')
assert_template_result('', '{% # this is an inline comment %}')
assert_template_result('', '{%# this is an inline comment %}')
end
def test_inline_comment_does_not_require_a_space_after_the_pound_sign
assert_template_result('', '{%#this is an inline comment%}')
end
def test_liquid_inline_comment_returns_nothing
assert_template_result('Hey there, how are you doing today?', <<~LIQUID)
{%- liquid
# This is how you'd write a block comment in a liquid tag.
# It looks a lot like what you'd have in ruby.
# You can use it as inline documentation in your
# liquid blocks to explain why you're doing something.
echo "Hey there, "
# It won't affect the output.
echo "how are you doing today?"
-%}
LIQUID
end
def test_inline_comment_can_be_written_on_multiple_lines
assert_template_result('', <<~LIQUID)
{%-
# That kind of block comment is also allowed.
# It would only be a stylistic difference.
# Much like JavaScript's /* */ comments and their
# leading * on new lines.
-%}
LIQUID
end
def test_inline_comment_multiple_pound_signs
assert_template_result('', <<~LIQUID)
{%- liquid
######################################
# We support comments like this too. #
######################################
-%}
LIQUID
end
def test_inline_comments_require_the_pound_sign_on_every_new_line
assert_match_syntax_error("Each line of comments must be prefixed by the '#' character", <<~LIQUID)
{%-
# some comment
echo 'hello world'
-%}
LIQUID
end
def test_inline_comment_does_not_support_nested_tags
assert_template_result(' -%}', "{%- # {% echo 'hello world' %} -%}")
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/integration/tag/disableable_test.rb | test/integration/tag/disableable_test.rb | # frozen_string_literal: true
require 'test_helper'
class TagDisableableTest < Minitest::Test
include Liquid
module RenderTagName
def render(_context)
tag_name
end
end
class Custom < Tag
prepend Liquid::Tag::Disableable
include RenderTagName
end
class Custom2 < Tag
prepend Liquid::Tag::Disableable
include RenderTagName
end
class DisableCustom < Block
disable_tags "custom"
end
class DisableBoth < Block
disable_tags "custom", "custom2"
end
def test_block_tag_disabling_nested_tag
with_disableable_tags do
with_custom_tag('disable', DisableCustom) do
output = Template.parse('{% disable %}{% custom %};{% custom2 %}{% enddisable %}').render
assert_equal('Liquid error: custom usage is not allowed in this context;custom2', output)
end
end
end
def test_block_tag_disabling_multiple_nested_tags
with_disableable_tags do
with_custom_tag('disable', DisableBoth) do
output = Template.parse('{% disable %}{% custom %};{% custom2 %}{% enddisable %}').render
assert_equal('Liquid error: custom usage is not allowed in this context;Liquid error: custom2 usage is not allowed in this context', output)
end
end
end
private
def with_disableable_tags
with_custom_tag('custom', Custom) do
with_custom_tag('custom2', Custom2) do
yield
end
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/block_unit_test.rb | test/unit/block_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class BlockUnitTest < Minitest::Test
include Liquid
def test_blankspace
template = Liquid::Template.parse(" ")
assert_equal([" "], template.root.nodelist)
end
def test_variable_beginning
template = Liquid::Template.parse("{{funk}} ")
assert_equal(2, template.root.nodelist.size)
assert_equal(Variable, template.root.nodelist[0].class)
assert_equal(String, template.root.nodelist[1].class)
end
def test_variable_end
template = Liquid::Template.parse(" {{funk}}")
assert_equal(2, template.root.nodelist.size)
assert_equal(String, template.root.nodelist[0].class)
assert_equal(Variable, template.root.nodelist[1].class)
end
def test_variable_middle
template = Liquid::Template.parse(" {{funk}} ")
assert_equal(3, template.root.nodelist.size)
assert_equal(String, template.root.nodelist[0].class)
assert_equal(Variable, template.root.nodelist[1].class)
assert_equal(String, template.root.nodelist[2].class)
end
def test_variable_with_multibyte_character
template = Liquid::Template.parse("{{ '❤️' }}")
assert_equal(1, template.root.nodelist.size)
assert_equal(Variable, template.root.nodelist[0].class)
end
def test_variable_many_embedded_fragments
template = Liquid::Template.parse(" {{funk}} {{so}} {{brother}} ")
assert_equal(7, template.root.nodelist.size)
assert_equal(
[String, Variable, String, Variable, String, Variable, String],
block_types(template.root.nodelist),
)
end
def test_comment_tag_with_block
template = Liquid::Template.parse(" {% comment %} {% endcomment %} ")
assert_equal([String, Comment, String], block_types(template.root.nodelist))
assert_equal(3, template.root.nodelist.size)
end
def test_doc_tag_with_block
template = Liquid::Template.parse(" {% doc %} {% enddoc %} ")
assert_equal([String, Doc, String], block_types(template.root.nodelist))
assert_equal(3, template.root.nodelist.size)
end
private
def block_types(nodelist)
nodelist.collect(&:class)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tokenizer_unit_test.rb | test/unit/tokenizer_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class TokenizerTest < Minitest::Test
def test_tokenize_strings
assert_equal([' '], tokenize(' '))
assert_equal(['hello world'], tokenize('hello world'))
assert_equal(['{}'], tokenize('{}'))
end
def test_tokenize_variables
assert_equal(['{{funk}}'], tokenize('{{funk}}'))
assert_equal([' ', '{{funk}}', ' '], tokenize(' {{funk}} '))
assert_equal([' ', '{{funk}}', ' ', '{{so}}', ' ', '{{brother}}', ' '], tokenize(' {{funk}} {{so}} {{brother}} '))
assert_equal([' ', '{{ funk }}', ' '], tokenize(' {{ funk }} '))
end
def test_tokenize_blocks
assert_equal(['{%comment%}'], tokenize('{%comment%}'))
assert_equal([' ', '{%comment%}', ' '], tokenize(' {%comment%} '))
assert_equal([' ', '{%comment%}', ' ', '{%endcomment%}', ' '], tokenize(' {%comment%} {%endcomment%} '))
assert_equal([' ', '{% comment %}', ' ', '{% endcomment %}', ' '], tokenize(" {% comment %} {% endcomment %} "))
end
def test_calculate_line_numbers_per_token_with_profiling
assert_equal([1], tokenize_line_numbers("{{funk}}"))
assert_equal([1, 1, 1], tokenize_line_numbers(" {{funk}} "))
assert_equal([1, 2, 2], tokenize_line_numbers("\n{{funk}}\n"))
assert_equal([1, 1, 3], tokenize_line_numbers(" {{\n funk \n}} "))
end
def test_tokenize_with_nil_source_returns_empty_array
assert_equal([], tokenize(nil))
end
def test_incomplete_curly_braces
assert_equal(["{{.}", " "], tokenize('{{.} '))
assert_equal(["{{}", "%}"], tokenize('{{}%}'))
assert_equal(["{{}}", "}"], tokenize('{{}}}'))
end
def test_unmatching_start_and_end
assert_equal(["{{%}"], tokenize('{{%}'))
assert_equal(["{{%%%}}"], tokenize('{{%%%}}'))
assert_equal(["{%", "}}"], tokenize('{%}}'))
assert_equal(["{%%}", "}"], tokenize('{%%}}'))
end
private
def new_tokenizer(source, parse_context: Liquid::ParseContext.new, start_line_number: nil)
parse_context.new_tokenizer(source, start_line_number: start_line_number)
end
def tokenize(source)
tokenizer = new_tokenizer(source)
tokens = []
# shift is private in Liquid::C::Tokenizer, since it is only for unit testing
while (t = tokenizer.send(:shift))
tokens << t
end
tokens
end
def tokenize_line_numbers(source)
tokenizer = new_tokenizer(source, start_line_number: 1)
line_numbers = []
loop do
line_number = tokenizer.line_number
if tokenizer.send(:shift)
line_numbers << line_number
else
break
end
end
line_numbers
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/strainer_template_unit_test.rb | test/unit/strainer_template_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class StrainerTemplateUnitTest < Minitest::Test
include Liquid
def test_add_filter_when_wrong_filter_class
c = Context.new
s = c.strainer
wrong_filter = lambda(&:reverse)
exception = assert_raises(TypeError) do
s.class.add_filter(wrong_filter)
end
assert_equal(exception.message, "wrong argument type Proc (expected Module)")
end
module PrivateMethodOverrideFilter
private
def public_filter
"overriden as private"
end
end
def test_add_filter_raises_when_module_privately_overrides_registered_public_methods
error = assert_raises(Liquid::MethodOverrideError) do
Liquid::Environment.build do |env|
env.register_filter(PublicMethodOverrideFilter)
env.register_filter(PrivateMethodOverrideFilter)
end
end
assert_equal('Liquid error: Filter overrides registered public methods as non public: public_filter', error.message)
end
module ProtectedMethodOverrideFilter
protected
def public_filter
"overriden as protected"
end
end
def test_add_filter_raises_when_module_overrides_registered_public_method_as_protected
error = assert_raises(Liquid::MethodOverrideError) do
Liquid::Environment.build do |env|
env.register_filter(PublicMethodOverrideFilter)
env.register_filter(ProtectedMethodOverrideFilter)
end
end
assert_equal('Liquid error: Filter overrides registered public methods as non public: public_filter', error.message)
end
module PublicMethodOverrideFilter
def public_filter
"public"
end
end
def test_add_filter_does_not_raise_when_module_overrides_previously_registered_method
with_global_filter do
context = Context.new
context.add_filters([PublicMethodOverrideFilter])
strainer = context.strainer
assert(strainer.class.send(:filter_methods).include?('public_filter'))
end
end
def test_add_filter_does_not_include_already_included_module
mod = Module.new do
class << self
attr_accessor :include_count
def included(_mod)
self.include_count += 1
end
end
self.include_count = 0
end
strainer = Context.new.strainer
strainer.class.add_filter(mod)
strainer.class.add_filter(mod)
assert_equal(1, mod.include_count)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/i18n_unit_test.rb | test/unit/i18n_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class I18nUnitTest < Minitest::Test
include Liquid
def setup
@i18n = I18n.new(fixture("en_locale.yml"))
end
def test_simple_translate_string
assert_equal("less is more", @i18n.translate("simple"))
end
def test_nested_translate_string
assert_equal("something wasn't right", @i18n.translate("errors.syntax.oops"))
end
def test_single_string_interpolation
assert_equal("something different", @i18n.translate("whatever", something: "different"))
end
# def test_raises_translation_error_on_undefined_interpolation_key
# assert_raises I18n::TranslationError do
# @i18n.translate("whatever", :oopstypos => "yes")
# end
# end
def test_raises_unknown_translation
assert_raises(I18n::TranslationError) do
@i18n.translate("doesnt_exist")
end
end
def test_sets_default_path_to_en
assert_equal(I18n::DEFAULT_LOCALE, I18n.new.path)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/lexer_unit_test.rb | test/unit/lexer_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class LexerUnitTest < Minitest::Test
include Liquid
def test_strings
assert_equal(
[[:string, %('this is a test""')], [:string, %("wat 'lol'")], [:end_of_string]],
tokenize(%( 'this is a test""' "wat 'lol'")),
)
end
def test_integer
assert_equal(
[[:id, 'hi'], [:number, '50'], [:end_of_string]],
tokenize('hi 50'),
)
end
def test_float
assert_equal(
[[:id, 'hi'], [:number, '5.0'], [:end_of_string]],
tokenize('hi 5.0'),
)
end
def test_comparison
assert_equal(
[[:comparison, '=='], [:comparison, '<>'], [:comparison, 'contains'], [:end_of_string]],
tokenize('== <> contains '),
)
end
def test_comparison_without_whitespace
assert_equal(
[[:number, '1'], [:comparison, '>'], [:number, '0'], [:end_of_string]],
tokenize('1>0'),
)
end
def test_comparison_with_negative_number
assert_equal(
[[:number, '1'], [:comparison, '>'], [:number, '-1'], [:end_of_string]],
tokenize('1>-1'),
)
end
def test_raise_for_invalid_comparison
assert_raises(SyntaxError) do
tokenize('1>!1')
end
assert_raises(SyntaxError) do
tokenize('1=<1')
end
assert_raises(SyntaxError) do
tokenize('1!!1')
end
end
def test_specials
assert_equal(
[[:pipe, '|'], [:dot, '.'], [:colon, ':'], [:end_of_string]],
tokenize('| .:'),
)
assert_equal(
[[:open_square, '['], [:comma, ','], [:close_square, ']'], [:end_of_string]],
tokenize('[,]'),
)
end
def test_fancy_identifiers
assert_equal([[:id, 'hi'], [:id, 'five?'], [:end_of_string]], tokenize('hi five?'))
assert_equal([[:number, '2'], [:id, 'foo'], [:end_of_string]], tokenize('2foo'))
end
def test_whitespace
assert_equal(
[[:id, 'five'], [:pipe, '|'], [:comparison, '=='], [:end_of_string]],
tokenize("five|\n\t =="),
)
end
def test_unexpected_character
assert_raises(SyntaxError) do
tokenize("%")
end
end
def test_negative_numbers
assert_equal(
[[:id, 'foo'], [:pipe, '|'], [:id, 'default'], [:colon, ":"], [:number, '-1'], [:end_of_string]],
tokenize("foo | default: -1"),
)
end
def test_greater_than_two_digits
assert_equal(
[[:id, 'foo'], [:comparison, '>'], [:number, '12'], [:end_of_string]],
tokenize("foo > 12"),
)
end
def test_error_with_utf8_character
error = assert_raises(SyntaxError) do
tokenize("1 < 1Ø")
end
assert_equal(
'Liquid syntax error: Unexpected character Ø',
error.message,
)
end
def test_contains_as_attribute_name
assert_equal(
[[:id, "a"], [:dot, "."], [:id, "contains"], [:dot, "."], [:id, "b"], [:end_of_string]],
tokenize("a.contains.b"),
)
end
def test_tokenize_incomplete_expression
assert_equal([[:id, "false"], [:dash, "-"], [:end_of_string]], tokenize("false -"))
assert_equal([[:id, "false"], [:comparison, "<"], [:end_of_string]], tokenize("false <"))
assert_equal([[:id, "false"], [:comparison, ">"], [:end_of_string]], tokenize("false >"))
assert_equal([[:id, "false"], [:number, "1"], [:end_of_string]], tokenize("false 1"))
end
def test_error_with_invalid_utf8
error = assert_raises(SyntaxError) do
tokenize("\x00\xff")
end
assert_equal(
'Liquid syntax error: Invalid byte sequence in UTF-8',
error.message,
)
end
private
def tokenize(input)
Lexer.tokenize(StringScanner.new(input))
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/condition_unit_test.rb | test/unit/condition_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class ConditionUnitTest < Minitest::Test
include Liquid
def setup
@context = Liquid::Context.new
end
def test_basic_condition
assert_equal(false, Condition.new(1, '==', 2).evaluate(Context.new))
assert_equal(true, Condition.new(1, '==', 1).evaluate(Context.new))
end
def test_default_operators_evalute_true
assert_evaluates_true(1, '==', 1)
assert_evaluates_true(1, '!=', 2)
assert_evaluates_true(1, '<>', 2)
assert_evaluates_true(1, '<', 2)
assert_evaluates_true(2, '>', 1)
assert_evaluates_true(1, '>=', 1)
assert_evaluates_true(2, '>=', 1)
assert_evaluates_true(1, '<=', 2)
assert_evaluates_true(1, '<=', 1)
# negative numbers
assert_evaluates_true(1, '>', -1)
assert_evaluates_true(-1, '<', 1)
assert_evaluates_true(1.0, '>', -1.0)
assert_evaluates_true(-1.0, '<', 1.0)
end
def test_default_operators_evalute_false
assert_evaluates_false(1, '==', 2)
assert_evaluates_false(1, '!=', 1)
assert_evaluates_false(1, '<>', 1)
assert_evaluates_false(1, '<', 0)
assert_evaluates_false(2, '>', 4)
assert_evaluates_false(1, '>=', 3)
assert_evaluates_false(2, '>=', 4)
assert_evaluates_false(1, '<=', 0)
assert_evaluates_false(1, '<=', 0)
end
def test_contains_works_on_strings
assert_evaluates_true('bob', 'contains', 'o')
assert_evaluates_true('bob', 'contains', 'b')
assert_evaluates_true('bob', 'contains', 'bo')
assert_evaluates_true('bob', 'contains', 'ob')
assert_evaluates_true('bob', 'contains', 'bob')
assert_evaluates_false('bob', 'contains', 'bob2')
assert_evaluates_false('bob', 'contains', 'a')
assert_evaluates_false('bob', 'contains', '---')
end
def test_contains_binary_encoding_compatibility_with_utf8
assert_evaluates_true('🙈'.b, 'contains', '🙈')
assert_evaluates_true('🙈', 'contains', '🙈'.b)
end
def test_invalid_comparation_operator
assert_evaluates_argument_error(1, '~~', 0)
end
def test_comparation_of_int_and_str
assert_evaluates_argument_error('1', '>', 0)
assert_evaluates_argument_error('1', '<', 0)
assert_evaluates_argument_error('1', '>=', 0)
assert_evaluates_argument_error('1', '<=', 0)
end
def test_hash_compare_backwards_compatibility
assert_nil(Condition.new({}, '>', 2).evaluate(Context.new))
assert_nil(Condition.new(2, '>', {}).evaluate(Context.new))
assert_equal(false, Condition.new({}, '==', 2).evaluate(Context.new))
assert_equal(true, Condition.new({ 'a' => 1 }, '==', 'a' => 1).evaluate(Context.new))
assert_equal(true, Condition.new({ 'a' => 2 }, 'contains', 'a').evaluate(Context.new))
end
def test_contains_works_on_arrays
@context = Liquid::Context.new
@context['array'] = [1, 2, 3, 4, 5]
array_expr = VariableLookup.new("array")
assert_evaluates_false(array_expr, 'contains', 0)
assert_evaluates_true(array_expr, 'contains', 1)
assert_evaluates_true(array_expr, 'contains', 2)
assert_evaluates_true(array_expr, 'contains', 3)
assert_evaluates_true(array_expr, 'contains', 4)
assert_evaluates_true(array_expr, 'contains', 5)
assert_evaluates_false(array_expr, 'contains', 6)
assert_evaluates_false(array_expr, 'contains', "1")
end
def test_contains_returns_false_for_nil_operands
@context = Liquid::Context.new
assert_evaluates_false(VariableLookup.new('not_assigned'), 'contains', '0')
assert_evaluates_false(0, 'contains', VariableLookup.new('not_assigned'))
end
def test_contains_return_false_on_wrong_data_type
assert_evaluates_false(1, 'contains', 0)
end
def test_contains_with_string_left_operand_coerces_right_operand_to_string
assert_evaluates_true(' 1 ', 'contains', 1)
assert_evaluates_false(' 1 ', 'contains', 2)
end
def test_or_condition
condition = Condition.new(1, '==', 2)
assert_equal(false, condition.evaluate(Context.new))
condition.or(Condition.new(2, '==', 1))
assert_equal(false, condition.evaluate(Context.new))
condition.or(Condition.new(1, '==', 1))
assert_equal(true, condition.evaluate(Context.new))
end
def test_and_condition
condition = Condition.new(1, '==', 1)
assert_equal(true, condition.evaluate(Context.new))
condition.and(Condition.new(2, '==', 2))
assert_equal(true, condition.evaluate(Context.new))
condition.and(Condition.new(2, '==', 1))
assert_equal(false, condition.evaluate(Context.new))
end
def test_should_allow_custom_proc_operator
Condition.operators['starts_with'] = proc { |_cond, left, right| left =~ /^#{right}/ }
assert_evaluates_true('bob', 'starts_with', 'b')
assert_evaluates_false('bob', 'starts_with', 'o')
ensure
Condition.operators.delete('starts_with')
end
def test_left_or_right_may_contain_operators
@context = Liquid::Context.new
@context['one'] = @context['another'] = "gnomeslab-and-or-liquid"
assert_evaluates_true(VariableLookup.new("one"), '==', VariableLookup.new("another"))
end
def test_default_context_is_deprecated
if Gem::Version.new(Liquid::VERSION) >= Gem::Version.new('6.0.0')
flunk("Condition#evaluate without a context argument is to be removed")
end
_out, err = capture_io do
assert_equal(true, Condition.new(1, '==', 1).evaluate)
end
expected = "DEPRECATION WARNING: Condition#evaluate without a context argument is deprecated " \
"and will be removed from Liquid 6.0.0."
assert_includes(err.lines.map(&:strip), expected)
end
def test_parse_expression_in_strict_mode
environment = Environment.build(error_mode: :strict)
parse_context = ParseContext.new(environment: environment)
result = Condition.parse_expression(parse_context, 'product.title')
assert_instance_of(VariableLookup, result)
assert_equal('product', result.name)
assert_equal(['title'], result.lookups)
end
def test_parse_expression_in_strict2_mode_raises_internal_error
environment = Environment.build(error_mode: :strict2)
parse_context = ParseContext.new(environment: environment)
error = assert_raises(Liquid::InternalError) do
Condition.parse_expression(parse_context, 'product.title')
end
assert_match(/unsafe parse_expression cannot be used in strict2 mode/, error.message)
end
def test_parse_expression_with_safe_true_in_strict2_mode
environment = Environment.build(error_mode: :strict2)
parse_context = ParseContext.new(environment: environment)
result = Condition.parse_expression(parse_context, 'product.title', safe: true)
assert_instance_of(VariableLookup, result)
assert_equal('product', result.name)
assert_equal(['title'], result.lookups)
end
# Tests for blank? comparison without ActiveSupport
#
# Ruby's standard library does not include blank? on String, Array, Hash, etc.
# ActiveSupport adds blank? but Liquid must work without it. These tests verify
# that Liquid implements blank? semantics internally for use in templates like:
# {% if x == blank %}...{% endif %}
#
# The blank? semantics match ActiveSupport's behavior:
# - nil and false are blank
# - Strings are blank if empty or contain only whitespace
# - Arrays and Hashes are blank if empty
# - true and numbers are never blank
def test_blank_with_whitespace_string
# Template authors expect " " to be blank since it has no visible content.
# This matches ActiveSupport's String#blank? which returns true for whitespace-only strings.
@context['whitespace'] = ' '
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_true(VariableLookup.new('whitespace'), '==', blank_literal)
end
def test_blank_with_empty_string
# An empty string has no content, so it should be considered blank.
# This is the most basic case of a blank string.
@context['empty_string'] = ''
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_true(VariableLookup.new('empty_string'), '==', blank_literal)
end
def test_blank_with_empty_array
# Empty arrays have no elements, so they are blank.
# Useful for checking if a collection has items: {% if products == blank %}
@context['empty_array'] = []
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_true(VariableLookup.new('empty_array'), '==', blank_literal)
end
def test_blank_with_empty_hash
# Empty hashes have no key-value pairs, so they are blank.
# Useful for checking if settings/options exist: {% if settings == blank %}
@context['empty_hash'] = {}
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_true(VariableLookup.new('empty_hash'), '==', blank_literal)
end
def test_blank_with_nil
# nil represents "nothing" and is the canonical blank value.
# Unassigned variables resolve to nil, so this enables: {% if missing_var == blank %}
@context['nil_value'] = nil
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_true(VariableLookup.new('nil_value'), '==', blank_literal)
end
def test_blank_with_false
# false is considered blank to match ActiveSupport semantics.
# This allows {% if some_flag == blank %} to work when flag is false.
@context['false_value'] = false
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_true(VariableLookup.new('false_value'), '==', blank_literal)
end
def test_not_blank_with_true
# true is a definite value, not blank.
# Ensures {% if flag == blank %} works correctly for boolean flags.
@context['true_value'] = true
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_false(VariableLookup.new('true_value'), '==', blank_literal)
end
def test_not_blank_with_number
# Numbers (including zero) are never blank - they represent actual values.
# 0 is a valid quantity, not the absence of a value.
@context['number'] = 42
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_false(VariableLookup.new('number'), '==', blank_literal)
end
def test_not_blank_with_string_content
# A string with actual content is not blank.
# This is the expected behavior for most template string comparisons.
@context['string'] = 'hello'
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_false(VariableLookup.new('string'), '==', blank_literal)
end
def test_not_blank_with_non_empty_array
# An array with elements has content, so it's not blank.
# Enables patterns like {% unless products == blank %}Show products{% endunless %}
@context['array'] = [1, 2, 3]
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_false(VariableLookup.new('array'), '==', blank_literal)
end
def test_not_blank_with_non_empty_hash
# A hash with key-value pairs has content, so it's not blank.
# Useful for checking if configuration exists: {% if config != blank %}
@context['hash'] = { 'a' => 1 }
blank_literal = Condition.class_variable_get(:@@method_literals)['blank']
assert_evaluates_false(VariableLookup.new('hash'), '==', blank_literal)
end
# Tests for empty? comparison without ActiveSupport
#
# empty? is distinct from blank? - it only checks if a collection has zero elements.
# For strings, empty? checks length == 0, NOT whitespace content.
# Ruby's standard library has empty? on String, Array, and Hash, but Liquid
# provides a fallback implementation for consistency.
def test_empty_with_empty_string
# An empty string ("") has length 0, so it's empty.
# Different from blank - empty is a stricter check.
@context['empty_string'] = ''
empty_literal = Condition.class_variable_get(:@@method_literals)['empty']
assert_evaluates_true(VariableLookup.new('empty_string'), '==', empty_literal)
end
def test_empty_with_whitespace_string_not_empty
# Whitespace strings have length > 0, so they are NOT empty.
# This is the key difference between empty and blank:
# " ".empty? => false, but " ".blank? => true
@context['whitespace'] = ' '
empty_literal = Condition.class_variable_get(:@@method_literals)['empty']
assert_evaluates_false(VariableLookup.new('whitespace'), '==', empty_literal)
end
def test_empty_with_empty_array
# An array with no elements is empty.
# [].empty? => true
@context['empty_array'] = []
empty_literal = Condition.class_variable_get(:@@method_literals)['empty']
assert_evaluates_true(VariableLookup.new('empty_array'), '==', empty_literal)
end
def test_empty_with_empty_hash
# A hash with no key-value pairs is empty.
# {}.empty? => true
@context['empty_hash'] = {}
empty_literal = Condition.class_variable_get(:@@method_literals)['empty']
assert_evaluates_true(VariableLookup.new('empty_hash'), '==', empty_literal)
end
def test_nil_is_not_empty
# nil is NOT empty - empty? checks if a collection has zero elements.
# nil is not a collection, so it cannot be empty.
# This differs from blank: nil IS blank, but nil is NOT empty.
@context['nil_value'] = nil
empty_literal = Condition.class_variable_get(:@@method_literals)['empty']
assert_evaluates_false(VariableLookup.new('nil_value'), '==', empty_literal)
end
private
def assert_evaluates_true(left, op, right)
assert(
Condition.new(left, op, right).evaluate(@context),
"Evaluated false: #{left.inspect} #{op} #{right.inspect}",
)
end
def assert_evaluates_false(left, op, right)
assert(
!Condition.new(left, op, right).evaluate(@context),
"Evaluated true: #{left.inspect} #{op} #{right.inspect}",
)
end
def assert_evaluates_argument_error(left, op, right)
assert_raises(Liquid::ArgumentError) do
Condition.new(left, op, right).evaluate(@context)
end
end
end # ConditionTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/parse_context_unit_test.rb | test/unit/parse_context_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class ParseContextUnitTest < Minitest::Test
include Liquid
def test_safe_parse_expression_with_variable_lookup
parser_strict = strict_parse_context.new_parser('product.title')
result_strict = strict_parse_context.safe_parse_expression(parser_strict)
parser_strict2 = strict2_parse_context.new_parser('product.title')
result_strict2 = strict2_parse_context.safe_parse_expression(parser_strict2)
assert_instance_of(VariableLookup, result_strict)
assert_equal('product', result_strict.name)
assert_equal(['title'], result_strict.lookups)
assert_instance_of(VariableLookup, result_strict2)
assert_equal('product', result_strict2.name)
assert_equal(['title'], result_strict2.lookups)
end
def test_safe_parse_expression_raises_syntax_error_for_invalid_expression
parser_strict = strict_parse_context.new_parser('')
parser_strict2 = strict2_parse_context.new_parser('')
error_strict = assert_raises(Liquid::SyntaxError) do
strict_parse_context.safe_parse_expression(parser_strict)
end
assert_match(/is not a valid expression/, error_strict.message)
error_strict2 = assert_raises(Liquid::SyntaxError) do
strict2_parse_context.safe_parse_expression(parser_strict2)
end
assert_match(/is not a valid expression/, error_strict2.message)
end
def test_parse_expression_with_variable_lookup
result_strict = strict_parse_context.parse_expression('product.title')
assert_instance_of(VariableLookup, result_strict)
assert_equal('product', result_strict.name)
assert_equal(['title'], result_strict.lookups)
error = assert_raises(Liquid::InternalError) do
strict2_parse_context.parse_expression('product.title')
end
assert_match(/unsafe parse_expression cannot be used in strict2 mode/, error.message)
end
def test_parse_expression_with_safe_true
result_strict = strict_parse_context.parse_expression('product.title', safe: true)
assert_instance_of(VariableLookup, result_strict)
assert_equal('product', result_strict.name)
assert_equal(['title'], result_strict.lookups)
result_strict2 = strict2_parse_context.parse_expression('product.title', safe: true)
assert_instance_of(VariableLookup, result_strict2)
assert_equal('product', result_strict2.name)
assert_equal(['title'], result_strict2.lookups)
end
def test_parse_expression_with_empty_string
result_strict = strict_parse_context.parse_expression('')
assert_nil(result_strict)
error = assert_raises(Liquid::InternalError) do
strict2_parse_context.parse_expression('')
end
assert_match(/unsafe parse_expression cannot be used in strict2 mode/, error.message)
end
def test_parse_expression_with_empty_string_and_safe_true
result_strict = strict_parse_context.parse_expression('', safe: true)
assert_nil(result_strict)
result_strict2 = strict2_parse_context.parse_expression('', safe: true)
assert_nil(result_strict2)
end
def test_safe_parse_expression_advances_parser_pointer
parser = strict2_parse_context.new_parser('foo, bar')
# safe_parse_expression consumes "foo"
first_result = strict2_parse_context.safe_parse_expression(parser)
assert_instance_of(VariableLookup, first_result)
assert_equal('foo', first_result.name)
parser.consume(:comma)
# safe_parse_expression consumes "bar"
second_result = strict2_parse_context.safe_parse_expression(parser)
assert_instance_of(VariableLookup, second_result)
assert_equal('bar', second_result.name)
parser.consume(:end_of_string)
end
def test_parse_expression_with_whitespace_in_strict2_mode
result = strict2_parse_context.parse_expression(' ', safe: true)
assert_nil(result)
end
private
def strict_parse_context
@strict_parse_context ||= ParseContext.new(
environment: Environment.build(error_mode: :strict),
)
end
def strict2_parse_context
@strict2_parse_context ||= ParseContext.new(
environment: Environment.build(error_mode: :strict2),
)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/parser_unit_test.rb | test/unit/parser_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class ParserUnitTest < Minitest::Test
include Liquid
def test_consume
p = new_parser("wat: 7")
assert_equal('wat', p.consume(:id))
assert_equal(':', p.consume(:colon))
assert_equal('7', p.consume(:number))
end
def test_jump
p = new_parser("wat: 7")
p.jump(2)
assert_equal('7', p.consume(:number))
end
def test_consume?
p = new_parser("wat: 7")
assert_equal('wat', p.consume?(:id))
assert_equal(false, p.consume?(:dot))
assert_equal(':', p.consume(:colon))
assert_equal('7', p.consume?(:number))
end
def test_id?
p = new_parser("wat 6 Peter Hegemon")
assert_equal('wat', p.id?('wat'))
assert_equal(false, p.id?('endgame'))
assert_equal('6', p.consume(:number))
assert_equal('Peter', p.id?('Peter'))
assert_equal(false, p.id?('Achilles'))
end
def test_look
p = new_parser("wat 6 Peter Hegemon")
assert_equal(true, p.look(:id))
assert_equal('wat', p.consume(:id))
assert_equal(false, p.look(:comparison))
assert_equal(true, p.look(:number))
assert_equal(true, p.look(:id, 1))
assert_equal(false, p.look(:number, 1))
end
def test_expressions
p = new_parser("hi.there hi?[5].there? hi.there.bob")
assert_equal('hi.there', p.expression)
assert_equal('hi?[5].there?', p.expression)
assert_equal('hi.there.bob', p.expression)
p = new_parser("567 6.0 'lol' \"wut\"")
assert_equal('567', p.expression)
assert_equal('6.0', p.expression)
assert_equal("'lol'", p.expression)
assert_equal('"wut"', p.expression)
end
def test_ranges
p = new_parser("(5..7) (1.5..9.6) (young..old) (hi[5].wat..old)")
assert_equal('(5..7)', p.expression)
assert_equal('(1.5..9.6)', p.expression)
assert_equal('(young..old)', p.expression)
assert_equal('(hi[5].wat..old)', p.expression)
end
def test_arguments
p = new_parser("filter: hi.there[5], keyarg: 7")
assert_equal('filter', p.consume(:id))
assert_equal(':', p.consume(:colon))
assert_equal('hi.there[5]', p.argument)
assert_equal(',', p.consume(:comma))
assert_equal('keyarg: 7', p.argument)
end
def test_invalid_expression
assert_raises(SyntaxError) do
p = new_parser("==")
p.expression
end
end
private
def new_parser(str)
Parser.new(StringScanner.new(str))
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/variable_unit_test.rb | test/unit/variable_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class VariableUnitTest < Minitest::Test
include Liquid
def test_variable
var = create_variable('hello')
assert_equal(VariableLookup.new('hello'), var.name)
end
def test_filters
var = create_variable('hello | textileze')
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['textileze', []]], var.filters)
var = create_variable('hello | textileze | paragraph')
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['textileze', []], ['paragraph', []]], var.filters)
var = create_variable(%( hello | strftime: '%Y'))
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['strftime', ['%Y']]], var.filters)
var = create_variable(%( 'typo' | link_to: 'Typo', true ))
assert_equal('typo', var.name)
assert_equal([['link_to', ['Typo', true]]], var.filters)
var = create_variable(%( 'typo' | link_to: 'Typo', false ))
assert_equal('typo', var.name)
assert_equal([['link_to', ['Typo', false]]], var.filters)
var = create_variable(%( 'foo' | repeat: 3 ))
assert_equal('foo', var.name)
assert_equal([['repeat', [3]]], var.filters)
var = create_variable(%( 'foo' | repeat: 3, 3 ))
assert_equal('foo', var.name)
assert_equal([['repeat', [3, 3]]], var.filters)
var = create_variable(%( 'foo' | repeat: 3, 3, 3 ))
assert_equal('foo', var.name)
assert_equal([['repeat', [3, 3, 3]]], var.filters)
var = create_variable(%( hello | strftime: '%Y, okay?'))
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['strftime', ['%Y, okay?']]], var.filters)
var = create_variable(%( hello | things: "%Y, okay?", 'the other one'))
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['things', ['%Y, okay?', 'the other one']]], var.filters)
end
def test_filter_with_date_parameter
var = create_variable(%( '2006-06-06' | date: "%m/%d/%Y"))
assert_equal('2006-06-06', var.name)
assert_equal([['date', ['%m/%d/%Y']]], var.filters)
end
def test_filters_without_whitespace
var = create_variable('hello | textileze | paragraph')
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['textileze', []], ['paragraph', []]], var.filters)
var = create_variable('hello|textileze|paragraph')
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['textileze', []], ['paragraph', []]], var.filters)
var = create_variable("hello|replace:'foo','bar'|textileze")
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['replace', ['foo', 'bar']], ['textileze', []]], var.filters)
end
def test_symbol
var = create_variable("http://disney.com/logo.gif | image: 'med' ", error_mode: :lax)
assert_equal(VariableLookup.new('http://disney.com/logo.gif'), var.name)
assert_equal([['image', ['med']]], var.filters)
end
def test_string_to_filter
var = create_variable("'http://disney.com/logo.gif' | image: 'med' ")
assert_equal('http://disney.com/logo.gif', var.name)
assert_equal([['image', ['med']]], var.filters)
end
def test_string_single_quoted
var = create_variable(%( "hello" ))
assert_equal('hello', var.name)
end
def test_string_double_quoted
var = create_variable(%( 'hello' ))
assert_equal('hello', var.name)
end
def test_integer
var = create_variable(%( 1000 ))
assert_equal(1000, var.name)
end
def test_float
var = create_variable(%( 1000.01 ))
assert_equal(1000.01, var.name)
end
def test_dashes
assert_equal(VariableLookup.new('foo-bar'), create_variable('foo-bar').name)
assert_equal(VariableLookup.new('foo-bar-2'), create_variable('foo-bar-2').name)
with_error_modes(:strict) do
assert_raises(Liquid::SyntaxError) { create_variable('foo - bar') }
assert_raises(Liquid::SyntaxError) { create_variable('-foo') }
assert_raises(Liquid::SyntaxError) { create_variable('2foo') }
end
end
def test_string_with_special_chars
var = create_variable(%( 'hello! $!@.;"ddasd" ' ))
assert_equal('hello! $!@.;"ddasd" ', var.name)
end
def test_string_dot
var = create_variable(%( test.test ))
assert_equal(VariableLookup.new('test.test'), var.name)
end
def test_filter_with_keyword_arguments
var = create_variable(%( hello | things: greeting: "world", farewell: 'goodbye'))
assert_equal(VariableLookup.new('hello'), var.name)
assert_equal([['things', [], { 'greeting' => 'world', 'farewell' => 'goodbye' }]], var.filters)
end
def test_lax_filter_argument_parsing
var = create_variable(%( number_of_comments | pluralize: 'comment': 'comments' ), error_mode: :lax)
assert_equal(VariableLookup.new('number_of_comments'), var.name)
assert_equal([['pluralize', ['comment', 'comments']]], var.filters)
# missing does not throws error
create_variable(%(n | f1: ,), error_mode: :lax)
create_variable(%(n | f1: ,| f2), error_mode: :lax)
# arg does not require colon, but ignores args :O, also ignores first kwarg since it splits on ':'
var = create_variable(%(n | f1 1 | f2 k1: v1), error_mode: :lax)
assert_equal([['f1', []], ['f2', [VariableLookup.new('v1')]]], var.filters)
# positional and kwargs parsing
var = create_variable(%(n | filter: 1, 2, 3 | filter2: k1: 1, k2: 2), error_mode: :lax)
assert_equal([['filter', [1, 2, 3]], ['filter2', [], { "k1" => 1, "k2" => 2 }]], var.filters)
# positional and kwargs intermixed (pos1, key1: val1, pos2)
var = create_variable(%(n | link_to: class: "black", "https://example.com", title: "title"), error_mode: :lax)
assert_equal([['link_to', ["https://example.com"], { "class" => "black", "title" => "title" }]], var.filters)
end
def test_strict_filter_argument_parsing
with_error_modes(:strict) do
assert_raises(SyntaxError) do
create_variable(%( number_of_comments | pluralize: 'comment': 'comments' ))
end
end
end
def test_strict2_filter_argument_parsing
with_error_modes(:strict2) do
# optional colon
var = create_variable(%(n | f1 | f2:))
assert_equal([['f1', []], ['f2', []]], var.filters)
# missing argument throws error
assert_raises(SyntaxError) { create_variable(%(n | f1: ,)) }
assert_raises(SyntaxError) { create_variable(%(n | f1: ,| f2)) }
# arg requires colon
assert_raises(SyntaxError) { create_variable(%(n | f1 1)) }
# trailing comma doesn't throw
create_variable(%(n | f1: 1, 2, 3, | f2:))
# missing comma throws error
assert_raises(SyntaxError) { create_variable(%(n | filter: 1 2, 3)) }
# positional and kwargs parsing
var = create_variable(%(n | filter: 1, 2, 3 | filter2: k1: 1, k2: 2))
assert_equal([['filter', [1, 2, 3]], ['filter2', [], { "k1" => 1, "k2" => 2 }]], var.filters)
# positional and kwargs mixed
var = create_variable(%(n | filter: 'a', 'b', key1: 1, key2: 2, 'c'))
assert_equal([["filter", ["a", "b", "c"], { "key1" => 1, "key2" => 2 }]], var.filters)
# positional and kwargs intermixed (pos1, key1: val1, pos2)
var = create_variable(%(n | link_to: class: "black", "https://example.com", title: "title"))
assert_equal([['link_to', ["https://example.com"], { "class" => "black", "title" => "title" }]], var.filters)
# string key throws
assert_raises(SyntaxError) { create_variable(%(n | pluralize: 'comment': 'comments')) }
end
end
def test_output_raw_source_of_variable
var = create_variable(%( name_of_variable | upcase ))
assert_equal(" name_of_variable | upcase ", var.raw)
end
def test_variable_lookup_interface
lookup = VariableLookup.new('a.b.c')
assert_equal('a', lookup.name)
assert_equal(['b', 'c'], lookup.lookups)
end
private
def create_variable(markup, options = {})
Variable.new(markup, ParseContext.new(options))
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/regexp_unit_test.rb | test/unit/regexp_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'timeout'
class RegexpUnitTest < Minitest::Test
include Liquid
def test_empty
assert_equal([], ''.scan(QuotedFragment))
end
def test_quote
assert_equal(['"arg 1"'], '"arg 1"'.scan(QuotedFragment))
end
def test_words
assert_equal(['arg1', 'arg2'], 'arg1 arg2'.scan(QuotedFragment))
end
def test_tags
assert_equal(['<tr>', '</tr>'], '<tr> </tr>'.scan(QuotedFragment))
assert_equal(['<tr></tr>'], '<tr></tr>'.scan(QuotedFragment))
assert_equal(['<style', 'class="hello">', '</style>'], %(<style class="hello">' </style>).scan(QuotedFragment))
end
def test_double_quoted_words
assert_equal(['arg1', 'arg2', '"arg 3"'], 'arg1 arg2 "arg 3"'.scan(QuotedFragment))
end
def test_single_quoted_words
assert_equal(['arg1', 'arg2', "'arg 3'"], 'arg1 arg2 \'arg 3\''.scan(QuotedFragment))
end
def test_quoted_words_in_the_middle
assert_equal(['arg1', 'arg2', '"arg 3"', 'arg4'], 'arg1 arg2 "arg 3" arg4 '.scan(QuotedFragment))
end
def test_variable_parser
assert_equal(['var'], 'var'.scan(VariableParser))
assert_equal(['[var]'], '[var]'.scan(VariableParser))
assert_equal(['var', 'method'], 'var.method'.scan(VariableParser))
assert_equal(['var', '[method]'], 'var[method]'.scan(VariableParser))
assert_equal(['var', '[method]', '[0]'], 'var[method][0]'.scan(VariableParser))
assert_equal(['var', '["method"]', '[0]'], 'var["method"][0]'.scan(VariableParser))
assert_equal(['var', '[method]', '[0]', 'method'], 'var[method][0].method'.scan(VariableParser))
end
def test_variable_parser_with_large_input
Timeout.timeout(1) { assert_equal(['[var]'], '[var]'.scan(VariableParser)) }
very_long_string = "foo" * 1000
# valid dynamic lookup
Timeout.timeout(1) { assert_equal(["[#{very_long_string}]"], "[#{very_long_string}]".scan(VariableParser)) }
# invalid dynamic lookup with missing closing bracket
Timeout.timeout(1) { assert_equal([very_long_string], "[#{very_long_string}".scan(VariableParser)) }
end
end # RegexpTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/environment_test.rb | test/unit/environment_test.rb | # frozen_string_literal: true
require 'test_helper'
class EnvironmentTest < Minitest::Test
include Liquid
class UnsubscribeFooter < Liquid::Tag
def render(_context)
'Unsubscribe Footer'
end
end
def test_custom_tag
email_environment = Liquid::Environment.build do |environment|
environment.register_tag("unsubscribe_footer", UnsubscribeFooter)
end
assert(email_environment.tags["unsubscribe_footer"])
assert(email_environment.tag_for_name("unsubscribe_footer"))
template = Liquid::Template.parse("{% unsubscribe_footer %}", environment: email_environment)
assert_equal('Unsubscribe Footer', template.render)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/template_unit_test.rb | test/unit/template_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class TemplateUnitTest < Minitest::Test
include Liquid
def test_sets_default_localization_in_document
t = Template.new
t.parse('{%comment%}{%endcomment%}')
assert_instance_of(I18n, t.root.nodelist[0].options[:locale])
end
def test_sets_default_localization_in_context_with_quick_initialization
t = Template.new
t.parse('{%comment%}{%endcomment%}', locale: I18n.new(fixture("en_locale.yml")))
locale = t.root.nodelist[0].options[:locale]
assert_instance_of(I18n, locale)
assert_equal(fixture("en_locale.yml"), locale.path)
end
class FakeTag; end
def test_tags_can_be_looped_over
with_custom_tag('fake', FakeTag) do
result = Template.tags.map { |name, klass| [name, klass] }
assert(result.include?(["fake", TemplateUnitTest::FakeTag]))
end
end
class TemplateSubclass < Liquid::Template
end
def test_template_inheritance
assert_equal("foo", TemplateSubclass.parse("foo").render)
end
def test_invalid_utf8
input = "\xff\x00"
error = assert_raises(SyntaxError) do
Liquid::Tokenizer.new(source: input, string_scanner: StringScanner.new(input))
end
assert_equal(
'Liquid syntax error: Invalid byte sequence in UTF-8',
error.message,
)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/template_factory_unit_test.rb | test/unit/template_factory_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class TemplateFactoryUnitTest < Minitest::Test
include Liquid
def test_for_returns_liquid_template_instance
template = TemplateFactory.new.for("anything")
assert_instance_of(Liquid::Template, template)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/registers_unit_test.rb | test/unit/registers_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class RegistersUnitTest < Minitest::Test
include Liquid
def test_set
static_register = Registers.new(a: 1, b: 2)
static_register[:b] = 22
static_register[:c] = 33
assert_equal(1, static_register[:a])
assert_equal(22, static_register[:b])
assert_equal(33, static_register[:c])
end
def test_get_missing_key
static_register = Registers.new
assert_nil(static_register[:missing])
end
def test_delete
static_register = Registers.new(a: 1, b: 2)
static_register[:b] = 22
static_register[:c] = 33
assert_nil(static_register.delete(:a))
assert_equal(22, static_register.delete(:b))
assert_equal(33, static_register.delete(:c))
assert_nil(static_register[:c])
assert_nil(static_register.delete(:d))
end
def test_fetch
static_register = Registers.new(a: 1, b: 2)
static_register[:b] = 22
static_register[:c] = 33
assert_equal(1, static_register.fetch(:a))
assert_equal(1, static_register.fetch(:a, "default"))
assert_equal(22, static_register.fetch(:b))
assert_equal(22, static_register.fetch(:b, "default"))
assert_equal(33, static_register.fetch(:c))
assert_equal(33, static_register.fetch(:c, "default"))
assert_raises(KeyError) do
static_register.fetch(:d)
end
assert_equal("default", static_register.fetch(:d, "default"))
result = static_register.fetch(:d) { "default" }
assert_equal("default", result)
result = static_register.fetch(:d, "default 1") { "default 2" }
assert_equal("default 2", result)
end
def test_key
static_register = Registers.new(a: 1, b: 2)
static_register[:b] = 22
static_register[:c] = 33
assert_equal(true, static_register.key?(:a))
assert_equal(true, static_register.key?(:b))
assert_equal(true, static_register.key?(:c))
assert_equal(false, static_register.key?(:d))
end
def test_static_register_can_be_frozen
static_register = Registers.new(a: 1)
static_register.static.freeze
assert_raises(RuntimeError) do
static_register.static[:a] = "foo"
end
assert_raises(RuntimeError) do
static_register.static[:b] = "foo"
end
assert_raises(RuntimeError) do
static_register.static.delete(:a)
end
assert_raises(RuntimeError) do
static_register.static.delete(:c)
end
end
def test_new_static_retains_static
static_register = Registers.new(a: 1, b: 2)
static_register[:b] = 22
static_register[:c] = 33
new_static_register = Registers.new(static_register)
new_static_register[:b] = 222
newest_static_register = Registers.new(new_static_register)
newest_static_register[:c] = 333
assert_equal(1, static_register[:a])
assert_equal(22, static_register[:b])
assert_equal(33, static_register[:c])
assert_equal(1, new_static_register[:a])
assert_equal(222, new_static_register[:b])
assert_nil(new_static_register[:c])
assert_equal(1, newest_static_register[:a])
assert_equal(2, newest_static_register[:b])
assert_equal(333, newest_static_register[:c])
end
def test_multiple_instances_are_unique
static_register_1 = Registers.new(a: 1, b: 2)
static_register_1[:b] = 22
static_register_1[:c] = 33
static_register_2 = Registers.new(a: 10, b: 20)
static_register_2[:b] = 220
static_register_2[:c] = 330
assert_equal({ a: 1, b: 2 }, static_register_1.static)
assert_equal(1, static_register_1[:a])
assert_equal(22, static_register_1[:b])
assert_equal(33, static_register_1[:c])
assert_equal({ a: 10, b: 20 }, static_register_2.static)
assert_equal(10, static_register_2[:a])
assert_equal(220, static_register_2[:b])
assert_equal(330, static_register_2[:c])
end
def test_initialization_reused_static_same_memory_object
static_register_1 = Registers.new(a: 1, b: 2)
static_register_1[:b] = 22
static_register_1[:c] = 33
static_register_2 = Registers.new(static_register_1)
assert_equal(1, static_register_2[:a])
assert_equal(2, static_register_2[:b])
assert_nil(static_register_2[:c])
static_register_1.static[:b] = 222
static_register_1.static[:c] = 333
assert_same(static_register_1.static, static_register_2.static)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/partial_cache_unit_test.rb | test/unit/partial_cache_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class PartialCacheUnitTest < Minitest::Test
def test_uses_the_file_system_register_if_present
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new('my_partial' => 'my partial body'),
},
)
partial = Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new,
)
assert_equal('my partial body', partial.render)
end
def test_reads_from_the_file_system_only_once_per_file
file_system = StubFileSystem.new('my_partial' => 'some partial body')
context = Liquid::Context.build(
registers: { file_system: file_system },
)
2.times do
Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new,
)
end
assert_equal(1, file_system.file_read_count)
end
def test_cache_state_is_stored_per_context
parse_context = Liquid::ParseContext.new
shared_file_system = StubFileSystem.new(
'my_partial' => 'my shared value',
)
context_one = Liquid::Context.build(
registers: {
file_system: shared_file_system,
},
)
context_two = Liquid::Context.build(
registers: {
file_system: shared_file_system,
},
)
2.times do
Liquid::PartialCache.load(
'my_partial',
context: context_one,
parse_context: parse_context,
)
end
Liquid::PartialCache.load(
'my_partial',
context: context_two,
parse_context: parse_context,
)
assert_equal(2, shared_file_system.file_read_count)
end
def test_cache_is_not_broken_when_a_different_parse_context_is_used
file_system = StubFileSystem.new('my_partial' => 'some partial body')
context = Liquid::Context.build(
registers: { file_system: file_system },
)
Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new(my_key: 'value one'),
)
Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new(my_key: 'value two'),
)
# Technically what we care about is that the file was parsed twice,
# but measuring file reads is an OK proxy for this.
assert_equal(1, file_system.file_read_count)
end
def test_uses_default_template_factory_when_no_template_factory_found_in_register
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new('my_partial' => 'my partial body'),
},
)
partial = Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new,
)
assert_equal('my partial body', partial.render)
end
def test_uses_template_factory_register_if_present
template_factory = StubTemplateFactory.new
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new('my_partial' => 'my partial body'),
template_factory: template_factory,
},
)
partial = Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new,
)
assert_equal('my partial body', partial.render)
assert_equal(1, template_factory.count)
end
def test_cache_state_is_shared_for_subcontexts
parse_context = Liquid::ParseContext.new
shared_file_system = StubFileSystem.new(
'my_partial' => 'my shared value',
)
context = Liquid::Context.build(
registers: Liquid::Registers.new(
file_system: shared_file_system,
),
)
subcontext = context.new_isolated_subcontext
assert_equal(subcontext.registers[:cached_partials].object_id, context.registers[:cached_partials].object_id)
2.times do
Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: parse_context,
)
Liquid::PartialCache.load(
'my_partial',
context: subcontext,
parse_context: parse_context,
)
end
assert_equal(1, shared_file_system.file_read_count)
end
def test_uses_template_name_from_template_factory
template_factory = StubTemplateFactory.new
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new('my_partial' => 'my partial body'),
template_factory: template_factory,
},
)
partial = Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new,
)
assert_equal('some/path/my_partial', partial.name)
end
def test_includes_error_mode_into_template_cache
template_factory = StubTemplateFactory.new
context = Liquid::Context.build(
registers: {
file_system: StubFileSystem.new('my_partial' => 'my partial body'),
template_factory: template_factory,
},
)
[:lax, :warn, :strict, :strict2].each do |error_mode|
Liquid::PartialCache.load(
'my_partial',
context: context,
parse_context: Liquid::ParseContext.new(error_mode: error_mode),
)
end
assert_equal(
["my_partial:lax", "my_partial:warn", "my_partial:strict", "my_partial:strict2"],
context.registers[:cached_partials].keys,
)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/environment_filter_test.rb | test/unit/environment_filter_test.rb | # frozen_string_literal: true
require 'test_helper'
class EnvironmentFilterTest < Minitest::Test
include Liquid
module AccessScopeFilters
def public_filter
"public"
end
def private_filter
"private"
end
private :private_filter
end
module LateAddedFilter
def late_added_filter(_input)
"filtered"
end
end
def setup
@environment = Liquid::Environment.build do |env|
env.register_filter(AccessScopeFilters)
end
@context = Context.build(environment: @environment)
end
def test_strainer
strainer = @environment.create_strainer(@context)
assert_equal(5, strainer.invoke('size', 'input'))
assert_equal("public", strainer.invoke("public_filter"))
end
def test_strainer_raises_argument_error
strainer = @environment.create_strainer(@context)
assert_raises(Liquid::ArgumentError) do
strainer.invoke("public_filter", 1)
end
end
def test_strainer_argument_error_contains_backtrace
strainer = @environment.create_strainer(@context)
exception = assert_raises(Liquid::ArgumentError) do
strainer.invoke("public_filter", 1)
end
assert_match(
/\ALiquid error: wrong number of arguments \((1 for 0|given 1, expected 0)\)\z/,
exception.message,
)
source = AccessScopeFilters.instance_method(:public_filter).source_location
assert_equal(source[0..1].map(&:to_s), exception.backtrace[0].split(':')[0..1])
end
def test_strainer_only_invokes_public_filter_methods
strainer = @environment.create_strainer(@context)
assert_equal(false, strainer.class.invokable?('__test__'))
assert_equal(false, strainer.class.invokable?('test'))
assert_equal(false, strainer.class.invokable?('instance_eval'))
assert_equal(false, strainer.class.invokable?('__send__'))
assert_equal(true, strainer.class.invokable?('size')) # from the standard lib
end
def test_strainer_returns_nil_if_no_filter_method_found
strainer = @environment.create_strainer(@context)
assert_nil(strainer.invoke("private_filter"))
assert_nil(strainer.invoke("undef_the_filter"))
end
def test_strainer_returns_first_argument_if_no_method_and_arguments_given
strainer = @environment.create_strainer(@context)
assert_equal("password", strainer.invoke("undef_the_method", "password"))
end
def test_strainer_only_allows_methods_defined_in_filters
strainer = @environment.create_strainer(@context)
assert_equal("1 + 1", strainer.invoke("instance_eval", "1 + 1"))
assert_equal("puts", strainer.invoke("__send__", "puts", "Hi Mom"))
assert_equal("has_method?", strainer.invoke("invoke", "has_method?", "invoke"))
end
def test_strainer_uses_a_class_cache_to_avoid_method_cache_invalidation
a = Module.new
b = Module.new
strainer = @environment.create_strainer(@context, [a, b])
assert_kind_of(StrainerTemplate, strainer)
assert_kind_of(a, strainer)
assert_kind_of(b, strainer)
assert_kind_of(Liquid::StandardFilters, strainer)
end
def test_add_global_filter_clears_cache
assert_equal('input', @environment.create_strainer(@context).invoke('late_added_filter', 'input'))
@environment.register_filter(LateAddedFilter)
assert_equal('filtered', @environment.create_strainer(nil).invoke('late_added_filter', 'input'))
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tag_unit_test.rb | test/unit/tag_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class TagUnitTest < Minitest::Test
include Liquid
def test_tag
tag = Tag.parse('tag', "", new_tokenizer, ParseContext.new)
assert_equal('liquid::tag', tag.name)
assert_equal('', tag.render(Context.new))
end
def test_return_raw_text_of_tag
tag = Tag.parse("long_tag", "param1, param2, param3", new_tokenizer, ParseContext.new)
assert_equal("long_tag param1, param2, param3", tag.raw)
end
def test_tag_name_should_return_name_of_the_tag
tag = Tag.parse("some_tag", "", new_tokenizer, ParseContext.new)
assert_equal('some_tag', tag.tag_name)
end
class CustomTag < Liquid::Tag
def render(_context); end
end
def test_tag_render_to_output_buffer_nil_value
custom_tag = CustomTag.parse("some_tag", "", new_tokenizer, ParseContext.new)
assert_equal('some string', custom_tag.render_to_output_buffer(Context.new, "some string"))
end
private
def new_tokenizer
Tokenizer.new(
source: "",
string_scanner: StringScanner.new(""),
)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/parse_tree_visitor_test.rb | test/unit/parse_tree_visitor_test.rb | # frozen_string_literal: true
require 'test_helper'
class ParseTreeVisitorTest < Minitest::Test
include Liquid
def test_variable
assert_equal(
["test"],
visit(%({{ test }})),
)
end
def test_varible_with_filter
assert_equal(
["test", "infilter"],
visit(%({{ test | split: infilter }})),
)
end
def test_dynamic_variable
assert_equal(
["test", "inlookup"],
visit(%({{ test[inlookup] }})),
)
end
def test_echo
assert_equal(
["test"],
visit(%({% echo test %})),
)
end
def test_if_condition
assert_equal(
["test"],
visit(%({% if test %}{% endif %})),
)
end
def test_complex_if_condition
assert_equal(
["test"],
visit(%({% if 1 == 1 and 2 == test %}{% endif %})),
)
end
def test_if_body
assert_equal(
["test"],
visit(%({% if 1 == 1 %}{{ test }}{% endif %})),
)
end
def test_unless_condition
assert_equal(
["test"],
visit(%({% unless test %}{% endunless %})),
)
end
def test_complex_unless_condition
assert_equal(
["test"],
visit(%({% unless 1 == 1 and 2 == test %}{% endunless %})),
)
end
def test_unless_body
assert_equal(
["test"],
visit(%({% unless 1 == 1 %}{{ test }}{% endunless %})),
)
end
def test_elsif_condition
assert_equal(
["test"],
visit(%({% if 1 == 1 %}{% elsif test %}{% endif %})),
)
end
def test_complex_elsif_condition
assert_equal(
["test"],
visit(%({% if 1 == 1 %}{% elsif 1 == 1 and 2 == test %}{% endif %})),
)
end
def test_elsif_body
assert_equal(
["test"],
visit(%({% if 1 == 1 %}{% elsif 2 == 2 %}{{ test }}{% endif %})),
)
end
def test_else_body
assert_equal(
["test"],
visit(%({% if 1 == 1 %}{% else %}{{ test }}{% endif %})),
)
end
def test_case_left
assert_equal(
["test"],
visit(%({% case test %}{% endcase %})),
)
end
def test_case_condition
assert_equal(
["test"],
visit(%({% case 1 %}{% when test %}{% endcase %})),
)
end
def test_case_when_body
assert_equal(
["test"],
visit(%({% case 1 %}{% when 2 %}{{ test }}{% endcase %})),
)
end
def test_case_else_body
assert_equal(
["test"],
visit(%({% case 1 %}{% else %}{{ test }}{% endcase %})),
)
end
def test_for_in
assert_equal(
["test"],
visit(%({% for x in test %}{% endfor %})),
)
end
def test_for_limit
assert_equal(
["test"],
visit(%({% for x in (1..5) limit: test %}{% endfor %})),
)
end
def test_for_offset
assert_equal(
["test"],
visit(%({% for x in (1..5) offset: test %}{% endfor %})),
)
end
def test_for_body
assert_equal(
["test"],
visit(%({% for x in (1..5) %}{{ test }}{% endfor %})),
)
end
def test_for_range
assert_equal(
["test"],
visit(%({% for x in (1..test) %}{% endfor %})),
)
end
def test_tablerow_in
assert_equal(
["test"],
visit(%({% tablerow x in test %}{% endtablerow %})),
)
end
def test_tablerow_limit
assert_equal(
["test"],
visit(%({% tablerow x in (1..5) limit: test %}{% endtablerow %})),
)
end
def test_tablerow_offset
assert_equal(
["test"],
visit(%({% tablerow x in (1..5) offset: test %}{% endtablerow %})),
)
end
def test_tablerow_body
assert_equal(
["test"],
visit(%({% tablerow x in (1..5) %}{{ test }}{% endtablerow %})),
)
end
def test_cycle
assert_equal(
["test"],
visit(%({% cycle test %})),
)
end
def test_assign
assert_equal(
["test"],
visit(%({% assign x = test %})),
)
end
def test_capture
assert_equal(
["test"],
visit(%({% capture x %}{{ test }}{% endcapture %})),
)
end
def test_include
assert_equal(
["test"],
visit(%({% include test %})),
)
end
def test_include_with
assert_equal(
["test"],
visit(%({% include "hai" with test %})),
)
end
def test_include_for
assert_equal(
["test"],
visit(%({% include "hai" for test %})),
)
end
def test_render_with
assert_equal(
["test"],
visit(%({% render "hai" with test %})),
)
end
def test_render_for
assert_equal(
["test"],
visit(%({% render "hai" for test %})),
)
end
def test_preserve_tree_structure
assert_equal(
[[nil, [
[nil, [[nil, [["other", []]]]]],
["test", []],
["xs", []],
]]],
traversal(%({% for x in xs offset: test %}{{ other }}{% endfor %})).visit,
)
end
private
def traversal(template)
ParseTreeVisitor
.for(Template.parse(template).root)
.add_callback_for(VariableLookup) { |node| node.name } # rubocop:disable Style/SymbolProc
end
def visit(template)
traversal(template).visit.flatten.compact
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/file_system_unit_test.rb | test/unit/file_system_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class FileSystemUnitTest < Minitest::Test
include Liquid
def test_default
assert_raises(FileSystemError) do
BlankFileSystem.new.read_template_file("dummy")
end
end
def test_local
file_system = Liquid::LocalFileSystem.new("/some/path")
assert_equal("/some/path/_mypartial.liquid", file_system.full_path("mypartial"))
assert_equal("/some/path/dir/_mypartial.liquid", file_system.full_path("dir/mypartial"))
assert_raises(FileSystemError) do
file_system.full_path("../dir/mypartial")
end
assert_raises(FileSystemError) do
file_system.full_path("/dir/../../dir/mypartial")
end
assert_raises(FileSystemError) do
file_system.full_path("/etc/passwd")
end
end
def test_custom_template_filename_patterns
file_system = Liquid::LocalFileSystem.new("/some/path", "%s.html")
assert_equal("/some/path/mypartial.html", file_system.full_path("mypartial"))
assert_equal("/some/path/dir/mypartial.html", file_system.full_path("dir/mypartial"))
end
end # FileSystemTest
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tags/if_tag_unit_test.rb | test/unit/tags/if_tag_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class IfTagUnitTest < Minitest::Test
def test_if_nodelist
template = Liquid::Template.parse('{% if true %}IF{% else %}ELSE{% endif %}')
assert_equal(['IF', 'ELSE'], template.root.nodelist[0].nodelist.map(&:nodelist).flatten)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tags/doc_tag_unit_test.rb | test/unit/tags/doc_tag_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class DocTagUnitTest < Minitest::Test
def test_doc_tag
template = <<~LIQUID.chomp
{% doc %}
Renders loading-spinner.
@param {string} foo - some foo
@param {string} [bar] - optional bar
@example
{% render 'loading-spinner', foo: 'foo' %}
{% render 'loading-spinner', foo: 'foo', bar: 'bar' %}
{% enddoc %}
LIQUID
assert_template_result('', template)
end
def test_doc_tag_body_content
doc_content = " Documentation content\n @param {string} foo - test\n"
template_source = "{% doc %}#{doc_content}{% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal(doc_content, doc_tag.nodelist.first.to_s)
end
def test_doc_tag_does_not_support_extra_arguments
error = assert_raises(Liquid::SyntaxError) do
template = <<~LIQUID.chomp
{% doc extra %}
{% enddoc %}
LIQUID
Liquid::Template.parse(template)
end
exp_error = "Liquid syntax error: Syntax Error in 'doc' - Valid syntax: {% doc %}{% enddoc %}"
act_error = error.message
assert_equal(exp_error, act_error)
end
def test_doc_tag_must_support_valid_tags
assert_match_syntax_error("Liquid syntax error (line 1): 'doc' tag was never closed", '{% doc %} foo')
assert_match_syntax_error("Liquid syntax error (line 1): Syntax Error in 'doc' - Valid syntax: {% doc %}{% enddoc %}", '{% doc } foo {% enddoc %}')
assert_match_syntax_error("Liquid syntax error (line 1): Syntax Error in 'doc' - Valid syntax: {% doc %}{% enddoc %}", '{% doc } foo %}{% enddoc %}')
end
def test_doc_tag_ignores_liquid_nodes
template = <<~LIQUID.chomp
{% doc %}
{% if true %}
{% if ... %}
{%- for ? -%}
{% while true %}
{%
unless if
%}
{% endcase %}
{% enddoc %}
LIQUID
assert_template_result('', template)
end
def test_doc_tag_ignores_unclosed_liquid_tags
template = <<~LIQUID.chomp
{% doc %}
{% if true %}
{% enddoc %}
LIQUID
assert_template_result('', template)
end
def test_doc_tag_does_not_allow_nested_docs
error = assert_raises(Liquid::SyntaxError) do
template = <<~LIQUID.chomp
{% doc %}
{% doc %}
{% doc %}
{% enddoc %}
LIQUID
Liquid::Template.parse(template)
end
exp_error = "Liquid syntax error: Syntax Error in 'doc' - Nested doc tags are not allowed"
act_error = error.message
assert_equal(exp_error, act_error)
end
def test_doc_tag_ignores_nested_raw_tags
template = <<~LIQUID.chomp
{% doc %}
{% raw %}
{% enddoc %}
LIQUID
assert_template_result('', template)
end
def test_doc_tag_ignores_unclosed_assign
template = <<~LIQUID.chomp
{% doc %}
{% assign foo = "1"
{% enddoc %}
LIQUID
assert_template_result('', template)
end
def test_doc_tag_ignores_malformed_syntax
template = <<~LIQUID.chomp
{% doc %}
{% {{ {%- enddoc %}
LIQUID
assert_template_result('', template)
end
def test_doc_tag_captures_token_before_enddoc
template_source = "{% doc %}{{ incomplete{% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal("{{ incomplete", doc_tag.nodelist.first.to_s)
end
def test_doc_tag_preserves_error_line_numbers
template = Liquid::Template.parse(<<~LIQUID.chomp, line_numbers: true)
{% doc %}
{% if true %}
{% enddoc %}
{{ errors.standard_error }}
LIQUID
expected = <<~TEXT.chomp
Liquid error (line 4): standard error
TEXT
assert_equal(expected, template.render('errors' => ErrorDrop.new))
end
def test_doc_tag_whitespace_control
# Basic whitespace control
assert_template_result("Hello!", " {%- doc -%}123{%- enddoc -%}Hello!")
assert_template_result("Hello!", "{%- doc -%}123{%- enddoc -%} Hello!")
assert_template_result("Hello!", " {%- doc -%}123{%- enddoc -%} Hello!")
assert_template_result("Hello!", <<~LIQUID.chomp)
{%- doc %}Whitespace control!{% enddoc -%}
Hello!
LIQUID
end
def test_doc_tag_delimiter_handling
assert_template_result('', <<~LIQUID.chomp)
{%- if true -%}
{%- doc -%}
{%- docEXTRA -%}wut{% enddocEXTRA -%}xyz
{%- enddoc -%}
{%- endif -%}
LIQUID
assert_template_result('', "{% doc %}123{% enddoc xyz %}")
assert_template_result('', "{% doc %}123{% enddoc\txyz %}")
assert_template_result('', "{% doc %}123{% enddoc\nxyz %}")
assert_template_result('', "{% doc %}123{% enddoc\n xyz enddoc %}")
end
def test_doc_tag_visitor
template_source = '{% doc %}{% enddoc %}'
assert_equal(
[Liquid::Doc],
visit(template_source),
)
end
def test_doc_tag_blank_with_empty_content
template_source = "{% doc %}{% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal(true, doc_tag.blank?)
end
def test_doc_tag_blank_with_content
template_source = "{% doc %}Some documentation{% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal(false, doc_tag.blank?)
end
def test_doc_tag_blank_with_whitespace_only
template_source = "{% doc %} {% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal(false, doc_tag.blank?)
end
def test_doc_tag_nodelist_returns_array_with_body
doc_content = "Documentation content\n@param {string} foo"
template_source = "{% doc %}#{doc_content}{% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal([doc_content], doc_tag.nodelist)
assert_equal(1, doc_tag.nodelist.length)
assert_equal(doc_content, doc_tag.nodelist.first)
end
def test_doc_tag_nodelist_with_empty_content
template_source = "{% doc %}{% enddoc %}"
doc_tag = nil
ParseTreeVisitor
.for(Template.parse(template_source).root)
.add_callback_for(Liquid::Doc) do |tag|
doc_tag = tag
end
.visit
assert_equal([""], doc_tag.nodelist)
assert_equal(1, doc_tag.nodelist.length)
end
private
def traversal(template)
ParseTreeVisitor
.for(Template.parse(template).root)
.add_callback_for(Liquid::Doc) do |tag|
tag_class = tag.class
tag_class
end
end
def visit(template)
traversal(template).visit.flatten.compact
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tags/case_tag_unit_test.rb | test/unit/tags/case_tag_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class CaseTagUnitTest < Minitest::Test
include Liquid
def test_case_nodelist
template = Liquid::Template.parse('{% case var %}{% when true %}WHEN{% else %}ELSE{% endcase %}')
assert_equal(['WHEN', 'ELSE'], template.root.nodelist[0].nodelist.map(&:nodelist).flatten)
end
def test_case_with_trailing_element
template = <<~LIQUID
{%- case 1 bar -%}
{%- when 1 -%}
one
{%- else -%}
two
{%- endcase -%}
LIQUID
with_error_modes(:lax, :strict) do
assert_template_result("one", template)
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Expected end_of_string but found/, error.message)
end
end
def test_case_when_with_trailing_element
template = <<~LIQUID
{%- case 1 -%}
{%- when 1 bar -%}
one
{%- else -%}
two
{%- endcase -%}
LIQUID
with_error_modes(:lax, :strict) do
assert_template_result("one", template)
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Expected end_of_string but found/, error.message)
end
end
def test_case_when_with_comma
template = <<~LIQUID
{%- case 1 -%}
{%- when 2, 1 -%}
one
{%- else -%}
two
{%- endcase -%}
LIQUID
with_error_modes(:lax, :strict, :strict2) do
assert_template_result("one", template)
end
end
def test_case_when_with_or
template = <<~LIQUID
{%- case 1 -%}
{%- when 2 or 1 -%}
one
{%- else -%}
two
{%- endcase -%}
LIQUID
with_error_modes(:lax, :strict, :strict2) do
assert_template_result("one", template)
end
end
def test_case_when_empty
template = <<~LIQUID
{%- case x -%}
{%- when 2 or empty -%}
2 or empty
{%- else -%}
not 2 or empty
{%- endcase -%}
LIQUID
with_error_modes(:lax, :strict, :strict2) do
assert_template_result("2 or empty", template, { 'x' => 2 })
assert_template_result("2 or empty", template, { 'x' => {} })
assert_template_result("2 or empty", template, { 'x' => [] })
assert_template_result("not 2 or empty", template, { 'x' => { 'a' => 'b' } })
assert_template_result("not 2 or empty", template, { 'x' => ['a'] })
assert_template_result("not 2 or empty", template, { 'x' => 4 })
end
end
def test_case_with_invalid_expression
template = <<~LIQUID
{%- case foo=>bar -%}
{%- when 'baz' -%}
one
{%- else -%}
two
{%- endcase -%}
LIQUID
assigns = { 'foo' => { 'bar' => 'baz' } }
with_error_modes(:lax, :strict) do
assert_template_result("one", template, assigns)
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
def test_case_when_with_invalid_expression
template = <<~LIQUID
{%- case 'baz' -%}
{%- when foo=>bar -%}
one
{%- else -%}
two
{%- endcase -%}
LIQUID
assigns = { 'foo' => { 'bar' => 'baz' } }
with_error_modes(:lax, :strict) do
assert_template_result("one", template, assigns)
end
with_error_modes(:strict2) do
error = assert_raises(Liquid::SyntaxError) { Template.parse(template) }
assert_match(/Unexpected character =/, error.message)
end
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tags/for_tag_unit_test.rb | test/unit/tags/for_tag_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class ForTagUnitTest < Minitest::Test
def test_for_nodelist
template = Liquid::Template.parse('{% for item in items %}FOR{% endfor %}')
assert_equal(['FOR'], template.root.nodelist[0].nodelist.map(&:nodelist).flatten)
end
def test_for_else_nodelist
template = Liquid::Template.parse('{% for item in items %}FOR{% else %}ELSE{% endfor %}')
assert_equal(['FOR', 'ELSE'], template.root.nodelist[0].nodelist.map(&:nodelist).flatten)
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/test/unit/tags/comment_tag_unit_test.rb | test/unit/tags/comment_tag_unit_test.rb | # frozen_string_literal: true
require 'test_helper'
class CommentTagUnitTest < Minitest::Test
def test_comment_inside_liquid_tag
assert_template_result("", <<~LIQUID.chomp)
{% liquid
if 1 != 1
comment
else
echo 123
endcomment
endif
%}
LIQUID
end
def test_does_not_parse_nodes_inside_a_comment
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% if true %}
{% if ... %}
{%- for ? -%}
{% while true %}
{%
unless if
%}
{% endcase %}
{% endcomment %}
LIQUID
end
def test_allows_unclosed_tags
assert_template_result('', <<~LIQUID.chomp)
{% comment %}
{% if true %}
{% endcomment %}
LIQUID
end
def test_open_tags_in_comment
assert_template_result('', <<~LIQUID.chomp)
{% comment %}
{% assign a = 123 {% comment %}
{% endcomment %}
LIQUID
assert_raises(Liquid::SyntaxError) do
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% assign foo = "1"
{% endcomment %}
LIQUID
end
assert_raises(Liquid::SyntaxError) do
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% comment %}
{% invalid
{% endcomment %}
{% endcomment %}
LIQUID
end
assert_raises(Liquid::SyntaxError) do
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% {{ {%- endcomment %}
LIQUID
end
end
def test_child_comment_tags_need_to_be_closed
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% comment %}
{% comment %}{% endcomment %}
{% endcomment %}
{% endcomment %}
LIQUID
assert_raises(Liquid::SyntaxError) do
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% comment %}
{% comment %}
{% endcomment %}
{% endcomment %}
LIQUID
end
end
def test_child_raw_tags_need_to_be_closed
assert_template_result("", <<~LIQUID.chomp)
{% comment %}
{% raw %}
{% endcomment %}
{% endraw %}
{% endcomment %}
LIQUID
assert_raises(Liquid::SyntaxError) do
Liquid::Template.parse(<<~LIQUID.chomp)
{% comment %}
{% raw %}
{% endcomment %}
{% endcomment %}
LIQUID
end
end
def test_error_line_number_is_correct
template = Liquid::Template.parse(<<~LIQUID.chomp, line_numbers: true)
{% comment %}
{% if true %}
{% endcomment %}
{{ errors.standard_error }}
LIQUID
output = template.render('errors' => ErrorDrop.new)
expected = <<~TEXT.chomp
Liquid error (line 4): standard error
TEXT
assert_equal(expected, output)
end
def test_comment_tag_delimiter_with_extra_strings
assert_template_result(
'',
<<~LIQUID.chomp,
{% comment %}
{% comment %}
{% endcomment
{% if true %}
{% endif %}
{% endcomment %}
LIQUID
)
end
def test_nested_comment_tag_with_extra_strings
assert_template_result(
'',
<<~LIQUID.chomp,
{% comment %}
{% comment
{% assign foo = 1 %}
{% endcomment
{% assign foo = 1 %}
{% endcomment %}
LIQUID
)
end
def test_ignores_delimiter_with_extra_strings
assert_template_result(
'',
<<~LIQUID.chomp,
{% if true %}
{% comment %}
{% commentXXXXX %}wut{% endcommentXXXXX %}
{% endcomment %}
{% endif %}
LIQUID
)
end
def test_delimiter_can_have_extra_strings
assert_template_result('', "{% comment %}123{% endcomment xyz %}")
assert_template_result('', "{% comment %}123{% endcomment\txyz %}")
assert_template_result('', "{% comment %}123{% endcomment\nxyz %}")
assert_template_result('', "{% comment %}123{% endcomment\n xyz endcomment %}")
assert_template_result('', "{%comment}{% assign a = 1 %}{%endcomment}{% endif %}")
end
def test_with_whitespace_control
assert_template_result("Hello!", " {%- comment -%}123{%- endcomment -%}Hello!")
assert_template_result("Hello!", "{%- comment -%}123{%- endcomment -%} Hello!")
assert_template_result("Hello!", " {%- comment -%}123{%- endcomment -%} Hello!")
assert_template_result("Hello!", <<~LIQUID.chomp)
{%- comment %}Whitespace control!{% endcomment -%}
Hello!
LIQUID
end
def test_dont_override_liquid_tag_whitespace_control
assert_template_result("Hello!World!", <<~LIQUID.chomp)
Hello!
{%- liquid
comment
this is inside a liquid tag
endcomment
-%}
World!
LIQUID
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/benchmark.rb | performance/benchmark.rb | # frozen_string_literal: true
require 'benchmark/ips'
require_relative 'theme_runner'
RubyVM::YJIT.enable if defined?(RubyVM::YJIT)
Liquid::Environment.default.error_mode = ARGV.first.to_sym if ARGV.first
profiler = ThemeRunner.new
Benchmark.ips do |x|
x.time = 20
x.warmup = 10
puts
puts "Running benchmark for #{x.time} seconds (with #{x.warmup} seconds warmup)."
puts
phase = ENV["PHASE"] || "all"
x.report("tokenize:") { profiler.tokenize } if phase == "all" || phase == "tokenize"
x.report("parse:") { profiler.compile } if phase == "all" || phase == "parse"
x.report("render:") { profiler.render } if phase == "all" || phase == "render"
x.report("parse & render:") { profiler.run } if phase == "all" || phase == "run"
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/memory_profile.rb | performance/memory_profile.rb | # frozen_string_literal: true
require 'benchmark/ips'
require 'memory_profiler'
require 'terminal-table'
require_relative 'theme_runner'
class Profiler
LOG_LABEL = "Profiling: ".rjust(14).freeze
REPORTS_DIR = File.expand_path('.memprof', __dir__).freeze
def self.run
puts
yield new
end
def initialize
@allocated = []
@retained = []
@headings = []
end
def profile(phase, &block)
print(LOG_LABEL)
print("#{phase}.. ".ljust(10))
report = MemoryProfiler.report(&block)
puts 'Done.'
@headings << phase.capitalize
@allocated << "#{report.scale_bytes(report.total_allocated_memsize)} (#{report.total_allocated} objects)"
@retained << "#{report.scale_bytes(report.total_retained_memsize)} (#{report.total_retained} objects)"
return if ENV['CI']
require 'fileutils'
report_file = File.join(REPORTS_DIR, "#{sanitize(phase)}.txt")
FileUtils.mkdir_p(REPORTS_DIR)
report.pretty_print(to_file: report_file, scale_bytes: true)
end
def tabulate
table = Terminal::Table.new(headings: @headings.unshift('Phase')) do |t|
t << @allocated.unshift('Total allocated')
t << @retained.unshift('Total retained')
end
puts
puts table
puts "\nDetailed report(s) saved to #{REPORTS_DIR}/" unless ENV['CI']
end
def sanitize(string)
string.downcase.gsub(/[\W]/, '-').squeeze('-')
end
end
Liquid::Template.error_mode = ARGV.first.to_sym if ARGV.first
runner = ThemeRunner.new
Profiler.run do |x|
x.profile('parse') { runner.compile }
x.profile('render') { runner.render }
x.tabulate
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/profile.rb | performance/profile.rb | # frozen_string_literal: true
require 'stackprof'
require_relative 'theme_runner'
Liquid::Template.error_mode = ARGV.first.to_sym if ARGV.first
profiler = ThemeRunner.new
profiler.run
[:cpu, :object].each do |profile_type|
puts "Profiling in #{profile_type} mode..."
results = StackProf.run(mode: profile_type) do
200.times do
profiler.run
end
end
if profile_type == :cpu && (graph_filename = ENV['GRAPH_FILENAME'])
File.open(graph_filename, 'w') do |f|
StackProf::Report.new(results).print_graphviz(nil, f)
end
end
StackProf::Report.new(results).print_text(false, 20)
File.write(ENV['FILENAME'] + "." + profile_type.to_s, Marshal.dump(results)) if ENV['FILENAME']
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/theme_runner.rb | performance/theme_runner.rb | # frozen_string_literal: true
# This profiler run simulates Shopify.
# We are looking in the tests directory for liquid files and render them within the designated layout file.
# We will also export a substantial database to liquid which the templates can render values of.
# All this is to make the benchmark as non synthetic as possible. All templates and tests are lifted from
# direct real-world usage and the profiler measures code that looks very similar to the way it looks in
# Shopify which is likely the biggest user of liquid in the world which something to the tune of several
# million Template#render calls a day.
require_relative 'shopify/liquid'
require_relative 'shopify/database'
class ThemeRunner
class FileSystem
def initialize(path)
@path = path
end
# Called by Liquid to retrieve a template file
def read_template_file(template_path)
File.read(@path + '/' + template_path + '.liquid')
end
end
# Initialize a new liquid ThemeRunner instance
# Will load all templates into memory, do this now so that we don't profile IO.
def initialize
@tests = Dir[__dir__ + '/tests/**/*.liquid'].collect do |test|
next if File.basename(test) == 'theme.liquid'
theme_path = File.dirname(test) + '/theme.liquid'
{
liquid: File.read(test),
layout: (File.file?(theme_path) ? File.read(theme_path) : nil),
template_name: test,
}
end.compact
compile_all_tests
end
# `compile` will test just the compilation portion of liquid without any templates
def compile
@tests.each do |test_hash|
Liquid::Template.new.parse(test_hash[:liquid])
Liquid::Template.new.parse(test_hash[:layout])
end
end
# `tokenize` will just test the tokenizen portion of liquid without any templates
def tokenize
ss = StringScanner.new("")
@tests.each do |test_hash|
tokenizer = Liquid::Tokenizer.new(
source: test_hash[:liquid],
string_scanner: ss,
line_numbers: true,
)
while tokenizer.shift; end
end
end
# `run` is called to benchmark rendering and compiling at the same time
def run
each_test do |liquid, layout, assigns, page_template, template_name|
compile_and_render(liquid, layout, assigns, page_template, template_name)
end
end
# `render` is called to benchmark just the render portion of liquid
def render
@compiled_tests.each do |test|
tmpl = test[:tmpl]
assigns = test[:assigns]
layout = test[:layout]
if layout
assigns['content_for_layout'] = tmpl.render!(assigns)
layout.render!(assigns)
else
tmpl.render!(assigns)
end
end
end
private
def render_layout(template, layout, assigns)
assigns['content_for_layout'] = template.render!(assigns)
layout&.render!(assigns)
end
def compile_and_render(template, layout, assigns, page_template, template_file)
compiled_test = compile_test(template, layout, assigns, page_template, template_file)
render_layout(compiled_test[:tmpl], compiled_test[:layout], compiled_test[:assigns])
end
def compile_all_tests
@compiled_tests = []
each_test do |liquid, layout, assigns, page_template, template_name|
@compiled_tests << compile_test(liquid, layout, assigns, page_template, template_name)
end
@compiled_tests
end
def compile_test(template, layout, assigns, page_template, template_file)
tmpl = init_template(page_template, template_file)
parsed_template = tmpl.parse(template).dup
if layout
parsed_layout = tmpl.parse(layout)
{ tmpl: parsed_template, assigns: assigns, layout: parsed_layout }
else
{ tmpl: parsed_template, assigns: assigns }
end
end
# utility method with similar functionality needed in `compile_all_tests` and `run`
def each_test
# Dup assigns because will make some changes to them
assigns = Database.tables.dup
@tests.each do |test_hash|
# Compute page_template outside of profiler run, uninteresting to profiler
page_template = File.basename(test_hash[:template_name], File.extname(test_hash[:template_name]))
yield(test_hash[:liquid], test_hash[:layout], assigns, page_template, test_hash[:template_name])
end
end
# set up a new Liquid::Template object for use in `compile_and_render` and `compile_test`
def init_template(page_template, template_file)
tmpl = Liquid::Template.new
tmpl.assigns['page_title'] = 'Page title'
tmpl.assigns['template'] = page_template
tmpl.registers[:file_system] = ThemeRunner::FileSystem.new(File.dirname(template_file))
tmpl
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/paginate.rb | performance/shopify/paginate.rb | # frozen_string_literal: true
class Paginate < Liquid::Block
Syntax = /(#{Liquid::QuotedFragment})\s*(by\s*(\d+))?/
def initialize(tag_name, markup, options)
super
if markup =~ Syntax
@collection_name = Regexp.last_match(1)
@page_size = if Regexp.last_match(2)
Regexp.last_match(3).to_i
else
20
end
@attributes = { 'window_size' => 3 }
markup.scan(Liquid::TagAttributes) do |key, value|
@attributes[key] = value
end
else
raise SyntaxError, "Syntax Error in tag 'paginate' - Valid syntax: paginate [collection] by number"
end
end
def render_to_output_buffer(context, output)
@context = context
context.stack do
current_page = context['current_page'].to_i
pagination = {
'page_size' => @page_size,
'current_page' => 5,
'current_offset' => @page_size * 5,
}
context['paginate'] = pagination
collection_size = context[@collection_name].size
raise ArgumentError, "Cannot paginate array '#{@collection_name}'. Not found." if collection_size.nil?
page_count = (collection_size.to_f / @page_size.to_f).to_f.ceil + 1
pagination['items'] = collection_size
pagination['pages'] = page_count - 1
pagination['previous'] = link('« Previous', current_page - 1) if 1 < current_page
pagination['next'] = link('Next »', current_page + 1) if page_count > current_page + 1
pagination['parts'] = []
hellip_break = false
if page_count > 2
1.upto(page_count - 1) do |page|
if current_page == page
pagination['parts'] << no_link(page)
elsif page == 1
pagination['parts'] << link(page, page)
elsif page == page_count - 1
pagination['parts'] << link(page, page)
elsif page <= current_page - @attributes['window_size'] || page >= current_page + @attributes['window_size']
next if hellip_break
pagination['parts'] << no_link('…')
hellip_break = true
next
else
pagination['parts'] << link(page, page)
end
hellip_break = false
end
end
super
end
end
private
def no_link(title)
{ 'title' => title, 'is_link' => false }
end
def link(title, page)
{ 'title' => title, 'url' => current_url + "?page=#{page}", 'is_link' => true }
end
def current_url
"/collections/frontpage"
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/shop_filter.rb | performance/shopify/shop_filter.rb | # frozen_string_literal: true
module ShopFilter
def asset_url(input)
"/files/1/[shop_id]/[shop_id]/assets/#{input}"
end
def global_asset_url(input)
"/global/#{input}"
end
def shopify_asset_url(input)
"/shopify/#{input}"
end
def script_tag(url)
%(<script src="#{url}" type="text/javascript"></script>)
end
def stylesheet_tag(url, media = "all")
%(<link href="#{url}" rel="stylesheet" type="text/css" media="#{media}" />)
end
def link_to(link, url, title = "")
%(<a href="#{url}" title="#{title}">#{link}</a>)
end
def img_tag(url, alt = "")
%(<img src="#{url}" alt="#{alt}" />)
end
def link_to_vendor(vendor)
if vendor
link_to(vendor, url_for_vendor(vendor), vendor)
else
'Unknown Vendor'
end
end
def link_to_type(type)
if type
link_to(type, url_for_type(type), type)
else
'Unknown Vendor'
end
end
def url_for_vendor(vendor_title)
"/collections/#{to_handle(vendor_title)}"
end
def url_for_type(type_title)
"/collections/#{to_handle(type_title)}"
end
def product_img_url(url, style = 'small')
unless url =~ %r{\Aproducts/([\w\-\_]+)\.(\w{2,4})}
raise ArgumentError, 'filter "size" can only be called on product images'
end
case style
when 'original'
'/files/shops/random_number/' + url
when 'grande', 'large', 'medium', 'compact', 'small', 'thumb', 'icon'
"/files/shops/random_number/products/#{Regexp.last_match(1)}_#{style}.#{Regexp.last_match(2)}"
else
raise ArgumentError, 'valid parameters for filter "size" are: original, grande, large, medium, compact, small, thumb and icon '
end
end
def default_pagination(paginate)
html = []
html << %(<span class="prev">#{link_to(paginate['previous']['title'], paginate['previous']['url'])}</span>) if paginate['previous']
paginate['parts'].each do |part|
html << if part['is_link']
%(<span class="page">#{link_to(part['title'], part['url'])}</span>)
elsif part['title'].to_i == paginate['current_page'].to_i
%(<span class="page current">#{part['title']}</span>)
else
%(<span class="deco">#{part['title']}</span>)
end
end
html << %(<span class="next">#{link_to(paginate['next']['title'], paginate['next']['url'])}</span>) if paginate['next']
html.join(' ')
end
# Accepts a number, and two words - one for singular, one for plural
# Returns the singular word if input equals 1, otherwise plural
def pluralize(input, singular, plural)
input == 1 ? singular : plural
end
private
def to_handle(str)
result = str.dup
result.downcase!
result.delete!("'\"()[]")
result.gsub!(/\W+/, '-')
result.gsub!(/-+\z/, '') if result[-1] == '-'
result.gsub!(/\A-+/, '') if result[0] == '-'
result
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/json_filter.rb | performance/shopify/json_filter.rb | # frozen_string_literal: true
require 'json'
module JsonFilter
def json(object)
JSON.dump(object.reject { |k, _v| k == "collections" })
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/tag_filter.rb | performance/shopify/tag_filter.rb | # frozen_string_literal: true
module TagFilter
def link_to_tag(label, tag)
"<a title=\"Show tag #{tag}\" href=\"/collections/#{@context['handle']}/#{tag}\">#{label}</a>"
end
def highlight_active_tag(tag, css_class = 'active')
if @context['current_tags'].include?(tag)
"<span class=\"#{css_class}\">#{tag}</span>"
else
tag
end
end
def link_to_add_tag(label, tag)
tags = (@context['current_tags'] + [tag]).uniq
"<a title=\"Show tag #{tag}\" href=\"/collections/#{@context['handle']}/#{tags.join('+')}\">#{label}</a>"
end
def link_to_remove_tag(label, tag)
tags = (@context['current_tags'] - [tag]).uniq
"<a title=\"Show tag #{tag}\" href=\"/collections/#{@context['handle']}/#{tags.join('+')}\">#{label}</a>"
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/money_filter.rb | performance/shopify/money_filter.rb | # frozen_string_literal: true
module MoneyFilter
def money_with_currency(money)
return '' if money.nil?
format("$ %.2f USD", money / 100.0)
end
def money(money)
return '' if money.nil?
format("$ %.2f", money / 100.0)
end
private
def currency
ShopDrop.new.currency
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/weight_filter.rb | performance/shopify/weight_filter.rb | # frozen_string_literal: true
module WeightFilter
def weight(grams)
format("%.2f", grams / 1000)
end
def weight_with_unit(grams)
"#{weight(grams)} kg"
end
end
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Shopify/liquid | https://github.com/Shopify/liquid/blob/a4a29f3e0836cfd04c1b55b52e92d36914424e7d/performance/shopify/liquid.rb | performance/shopify/liquid.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(__dir__ + '/../../lib')
require_relative '../../lib/liquid'
require_relative 'comment_form'
require_relative 'paginate'
require_relative 'json_filter'
require_relative 'money_filter'
require_relative 'shop_filter'
require_relative 'tag_filter'
require_relative 'weight_filter'
default_environment = Liquid::Environment.default
default_environment.register_tag('paginate', Paginate)
default_environment.register_tag('form', CommentForm)
default_environment.register_filter(JsonFilter)
default_environment.register_filter(MoneyFilter)
default_environment.register_filter(WeightFilter)
default_environment.register_filter(ShopFilter)
default_environment.register_filter(TagFilter)
| ruby | MIT | a4a29f3e0836cfd04c1b55b52e92d36914424e7d | 2026-01-04T15:37:46.392600Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.