Compare commits

..
Author SHA1 Message Date
Pierre-Olivier Bédard 23cadd6240 Prototype: Dump yardoc to json 2022-01-19 22:03:28 -05:00
29 changed files with 36583 additions and 357 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ jobs:
matrix:
entry:
- { ruby: 2.5, allowed-failure: false } # minimum supported
- { ruby: 3.1, allowed-failure: false } # latest
- { ruby: 3.0, allowed-failure: false } # latest
- { ruby: ruby-head, allowed-failure: true }
name: test (${{ matrix.entry.ruby }})
steps:
-18
View File
@@ -1,23 +1,5 @@
# Liquid Change Log
## 5.3.0 (unreleased)
### Fixes
* StandardFilter: Fix missing @context on iterations (#1525) [Thierry Joyal]
### Deprecation
* Condition#evaluate to require mandatory context argument in Liquid 6.0.0 (#1527) [Thierry Joyal]
## 5.2.0 2022-03-01
### Features
* Add `remove_last`, and `replace_last` filters (#1422) [Anders Hagbard]
* Eagerly cache global filters (#1524) [Jean Boussier]
### Fixes
* Fix some internal errors in filters from invalid input (#1476) [Dylan Thacker-Smith]
* Allow dash in filter kwarg name for consistency with Liquid::C (#1518) [CP Clermont]
## 5.1.0 / 2021-09-09
### Features
+2 -2
View File
@@ -5,7 +5,7 @@
* [Contributing guidelines](CONTRIBUTING.md)
* [Version history](History.md)
* [Liquid documentation from Shopify](https://shopify.dev/api/liquid)
* [Liquid documentation from Shopify](http://docs.shopify.com/themes/liquid-basics)
* [Liquid Wiki at GitHub](https://github.com/Shopify/liquid/wiki)
* [Website](http://liquidmarkup.org/)
@@ -56,7 +56,7 @@ For standard use you can just pass it the content of a file and call render with
Setting the error mode of Liquid lets you specify how strictly you want your templates to be interpreted.
Normally the parser is very lax and will accept almost anything without error. Unfortunately this can make
it very hard to debug and can lead to unexpected behaviour.
it very hard to debug and can lead to unexpected behaviour.
Liquid also comes with a stricter parser that can be used when editing templates to give better error messages
when templates are invalid. You can enable this new parser like this:
+2 -2
View File
@@ -36,7 +36,7 @@ module Liquid
VariableIncompleteEnd = /\}\}?/
QuotedString = /"[^"]*"|'[^']*'/
QuotedFragment = /#{QuotedString}|(?:[^\s,\|'"]|#{QuotedString})+/o
TagAttributes = /(\w[\w-]*)\s*\:\s*(#{QuotedFragment})/o
TagAttributes = /(\w+)\s*\:\s*(#{QuotedFragment})/o
AnyStartingTag = /#{TagStart}|#{VariableStart}/o
PartialTemplateParser = /#{TagStart}.*?#{TagEnd}|#{VariableStart}.*?#{VariableIncompleteEnd}/om
TemplateParser = /(#{PartialTemplateParser}|#{AnyStartingTag})/om
@@ -59,8 +59,8 @@ require 'liquid/forloop_drop'
require 'liquid/extensions'
require 'liquid/errors'
require 'liquid/interrupts'
require 'liquid/strainer_template'
require 'liquid/strainer_factory'
require 'liquid/strainer_template'
require 'liquid/expression'
require 'liquid/context'
require 'liquid/parser_switching'
+2 -2
View File
@@ -231,8 +231,8 @@ module Liquid
end
def create_variable(token, parse_context)
if token =~ ContentOfVariable
markup = Regexp.last_match(1)
token.scan(ContentOfVariable) do |content|
markup = content.first
return Variable.new(markup, parse_context)
end
BlockBody.raise_missing_variable_terminator(token, parse_context)
+1 -7
View File
@@ -61,7 +61,7 @@ module Liquid
@child_condition = nil
end
def evaluate(context = deprecated_default_context)
def evaluate(context = Context.new)
condition = self
result = nil
loop do
@@ -150,12 +150,6 @@ module Liquid
end
end
def deprecated_default_context
warn("DEPRECATION WARNING: Condition#evaluate without a context argument is deprecated" \
" and will be removed from Liquid 6.0.0.")
Context.new
end
class ParseTreeVisitor < Liquid::ParseTreeVisitor
def children
[
+10 -11
View File
@@ -10,23 +10,21 @@ module Liquid
'empty' => ''
}.freeze
INTEGERS_REGEX = /\A(-?\d+)\z/
FLOATS_REGEX = /\A(-?\d[\d\.]+)\z/
SINGLE_QUOTED_STRING = /\A\s*'(.*)'\s*\z/m
DOUBLE_QUOTED_STRING = /\A\s*"(.*)"\s*\z/m
INTEGERS_REGEX = /\A\s*(-?\d+)\s*\z/
FLOATS_REGEX = /\A\s*(-?\d[\d\.]+)\s*\z/
# Use an atomic group (?>...) to avoid pathological backtracing from
# malicious input as described in https://github.com/Shopify/liquid/issues/1357
RANGES_REGEX = /\A\(\s*(?>(\S+)\s*\.\.)\s*(\S+)\s*\)\z/
RANGES_REGEX = /\A\s*\(\s*(?>(\S+)\s*\.\.)\s*(\S+)\s*\)\s*\z/
def self.parse(markup)
return nil unless markup
markup = markup.strip
if (markup.start_with?('"') && markup.end_with?('"')) ||
(markup.start_with?("'") && markup.end_with?("'"))
return markup[1..-2]
end
case markup
when nil
nil
when SINGLE_QUOTED_STRING, DOUBLE_QUOTED_STRING
Regexp.last_match(1)
when INTEGERS_REGEX
Regexp.last_match(1).to_i
when RANGES_REGEX
@@ -34,6 +32,7 @@ module Liquid
when FLOATS_REGEX
Regexp.last_match(1).to_f
else
markup = markup.strip
if LITERALS.key?(markup)
LITERALS[markup]
else
+18 -57
View File
@@ -213,23 +213,17 @@ module Liquid
if ary.empty?
[]
elsif target_value.nil?
ary.select do |item|
item[property]
elsif ary.first.respond_to?(:[]) && target_value.nil?
begin
ary.select { |item| item[property] }
rescue TypeError
raise_property_error(property)
rescue NoMethodError
return nil unless item.respond_to?(:[])
raise
end
else
ary.select do |item|
item[property] == target_value
elsif ary.first.respond_to?(:[])
begin
ary.select { |item| item[property] == target_value }
rescue TypeError
raise_property_error(property)
rescue NoMethodError
return nil unless item.respond_to?(:[])
raise
end
end
end
@@ -243,14 +237,11 @@ module Liquid
ary.uniq
elsif ary.empty? # The next two cases assume a non-empty array.
[]
else
ary.uniq do |item|
item[property]
elsif ary.first.respond_to?(:[])
begin
ary.uniq { |a| a[property] }
rescue TypeError
raise_property_error(property)
rescue NoMethodError
return nil unless item.respond_to?(:[])
raise
end
end
end
@@ -286,14 +277,11 @@ module Liquid
ary.compact
elsif ary.empty? # The next two cases assume a non-empty array.
[]
else
ary.reject do |item|
item[property].nil?
elsif ary.first.respond_to?(:[])
begin
ary.reject { |a| a[property].nil? }
rescue TypeError
raise_property_error(property)
rescue NoMethodError
return nil unless item.respond_to?(:[])
raise
end
end
end
@@ -308,34 +296,14 @@ module Liquid
input.to_s.sub(string.to_s, replacement.to_s)
end
# Replace the last occurrences of a string with another
def replace_last(input, string, replacement)
input = input.to_s
string = string.to_s
replacement = replacement.to_s
start_index = input.rindex(string)
return input unless start_index
output = input.dup
output[start_index, string.length] = replacement
output
end
# remove a substring
def remove(input, string)
replace(input, string, '')
input.to_s.gsub(string.to_s, '')
end
# remove the first occurrences of a substring
def remove_first(input, string)
replace_first(input, string, '')
end
# remove the last occurences of a substring
def remove_last(input, string)
replace_last(input, string, '')
input.to_s.sub(string.to_s, '')
end
# add one string to another
@@ -518,16 +486,10 @@ module Liquid
end
def nil_safe_compare(a, b)
result = a <=> b
if result
result
elsif a.nil?
1
elsif b.nil?
-1
if !a.nil? && !b.nil?
a <=> b
else
raise Liquid::ArgumentError, "cannot sort values of incompatible types"
a.nil? ? 1 : -1
end
end
@@ -582,9 +544,8 @@ module Liquid
def each
@input.each do |e|
e = e.respond_to?(:to_liquid) ? e.to_liquid : e
e.context = @context if e.respond_to?(:context=)
yield(e)
yield(e.respond_to?(:to_liquid) ? e.to_liquid : e)
end
end
end
+1 -5
View File
@@ -31,11 +31,7 @@ module Liquid
if @registers.key?(key)
@registers.fetch(key)
elsif default != UNDEFINED
if block_given?
@static.fetch(key, &block)
else
@static.fetch(key, default)
end
@static.fetch(key, default, &block)
else
@static.fetch(key, &block)
end
+10 -11
View File
@@ -7,26 +7,25 @@ module Liquid
def add_global_filter(filter)
strainer_class_cache.clear
GlobalCache.add_filter(filter)
global_filters << filter
end
def create(context, filters = [])
strainer_from_cache(filters).new(context)
end
GlobalCache = Class.new(StrainerTemplate)
private
def global_filters
@global_filters ||= []
end
def strainer_from_cache(filters)
if filters.empty?
GlobalCache
else
strainer_class_cache[filters] ||= begin
klass = Class.new(GlobalCache)
filters.each { |f| klass.add_filter(f) }
klass
end
strainer_class_cache[filters] ||= begin
klass = Class.new(StrainerTemplate)
global_filters.each { |f| klass.add_filter(f) }
filters.each { |f| klass.add_filter(f) }
klass
end
end
-5
View File
@@ -31,11 +31,6 @@ module Liquid
filter_methods.include?(method.to_s)
end
def inherited(subclass)
super
subclass.instance_variable_set(:@filter_methods, @filter_methods.dup)
end
private
def filter_methods
-11
View File
@@ -1,17 +1,6 @@
# frozen_string_literal: true
# @public_docs
module Liquid
# @public_docs
# @title Case
# @syntax The syntax
# @summary The summary
# @type tag
# @description
# Creates a switch statement to execute a particular block of code when a variable has a specified value.
# `case` initializes the switch statement, and `when` statements define the various conditions.
#
# An optional `else` statement at the end of the case provides code to execute if none of the conditions are met.
class Case < Block
Syntax = /(#{QuotedFragment})/o
WhenSyntax = /(#{QuotedFragment})(?:(?:\s+or\s+|\s*\,\s*)(#{QuotedFragment}.*))?/om
-11
View File
@@ -1,6 +1,5 @@
# frozen_string_literal: true
# @public_docs
module Liquid
# Cycle is usually used within a loop to alternate between values, like colors or DOM classes.
#
@@ -14,16 +13,6 @@ module Liquid
# <div class="red"> Item four </div>
# <div class="green"> Item five</div>
#
# @public_docs
# @title Cycle
# @syntax The syntax
# @summary Loops through a group of strings and prints them in the order that they were passed as arguments.
# @type tag
# @description
# Loops through a group of strings and prints them in the order that they were passed as arguments.
# Each time `cycle`` is called, the next string argument is printed.
#
# `cycle` must be used within a `for`` loop block.
class Cycle < Tag
SimpleSyntax = /\A#{QuotedFragment}+/o
NamedSyntax = /\A(#{QuotedFragment})\s*\:\s*(.*)/om
-7
View File
@@ -1,6 +1,5 @@
# frozen_string_literal: true
# @public_docs
module Liquid
# "For" iterates over an array or collection.
# Several useful variables are available to you within the loop.
@@ -46,12 +45,6 @@ module Liquid
# forloop.last:: Returns true if the item is the last item.
# forloop.parentloop:: Provides access to the parent loop, if present.
#
# @public_docs
# @title For
# @syntax The syntax
# @summary Repeatedly executes a block of code.
# @type tag
# @description The description
class For < Block
Syntax = /\A(#{VariableSegment}+)\s+in\s+(#{QuotedFragment}+)\s*(reversed)?/o
+6 -14
View File
@@ -1,24 +1,16 @@
# frozen_string_literal: true
# @public_docs
module Liquid
# If is the conditional block
#
# @public_docs
# @title If
# @syntax The syntax
# @summary Executes a block of code only if a certain condition is `true`.
# @type tag
# @description
# If is the conditional block
# {% if user.admin %}
# Admin user!
# {% else %}
# Not admin user
# {% endif %}
#
# {% if user.admin %}
# Admin user!
# {% else %}
# Not admin user
# {% endif %}
# There are {% if count < 5 %} less {% else %} more {% endif %} items than you need.
#
# There are {% if count < 5 %} less {% else %} more {% endif %} items than you need.
class If < Block
Syntax = /(#{QuotedFragment})\s*([=!<>a-z_]+)?\s*(#{QuotedFragment})?/o
ExpressionsAndOperators = /(?:\b(?:\s?and\s?|\s?or\s?)\b|(?:\s*(?!\b(?:\s?and\s?|\s?or\s?)\b)(?:#{QuotedFragment}|\S+)\s*)+)/o
-9
View File
@@ -1,15 +1,6 @@
# frozen_string_literal: true
# @public_docs
module Liquid
# @public_docs
# @title Tablerow
# @syntax The syntax
# @summary Generates an HTML table.
# @type tag
# @description
# Generates an HTML table. Must be wrapped in opening `<table>` and closing `</table>` HTML tags.
# For a full list of attributes available within a `tablerow` loop, see `tablerow` (object).
class TableRow < Block
Syntax = /(\w+)\s+in\s+(#{QuotedFragment}+)/o
+3 -9
View File
@@ -2,17 +2,11 @@
require_relative 'if'
# @public_docs
module Liquid
# @public_docs
# @title Unless
# @syntax The syntax
# @summary The opposite of `if`` executes a block of code only if a certain condition is not met.
# @type tag
# @description
# Unless is a conditional just like 'if' but works on the inverse logic.
# Unless is a conditional just like 'if' but works on the inverse logic.
#
# {% unless x < 0 %} x is greater than zero {% endunless %}
#
# {% unless x < 0 %} x is greater than zero {% endunless %}
class Unless < If
def render_to_output_buffer(context, output)
# First condition is interpreted backwards ( if not )
+1 -1
View File
@@ -2,5 +2,5 @@
# frozen_string_literal: true
module Liquid
VERSION = "5.3.0.alpha"
VERSION = "5.1.0"
end
+1
View File
@@ -31,4 +31,5 @@ Gem::Specification.new do |s|
s.add_development_dependency('rake', '~> 13.0')
s.add_development_dependency('minitest')
s.add_development_dependency('yard')
end
+36345
View File
File diff suppressed because it is too large Load Diff
+102
View File
@@ -0,0 +1,102 @@
require 'json'
# To run this: `yardoc --template-path templates --template content --format json --no-save`
def init
# I'm honestly not sure why we need to run this, but all other setup.rb files
# have that line. This is a prototype so 🤷‍♂️
objects = run_verifier(options.objects)
data = objects.map do |object|
serialize_object(object)
end
File.write(
"schema.json",
JSON.pretty_generate(data.compact)
)
end
def serialize_object(object)
# This diagram is really helpful
# https://github.com/lsegal/yard/blob/main/docs/CodeObjects.md
if object.class == YARD::CodeObjects::Proxy
# I'm not sure if we should *always* ignore proxy objects. In the case of liquid
# the only proxy objects come from instance mixins where they `include Enumerable`
return nil
end
# This is data provided by the "Base" class
# Every object contains at least these fields
# There's probably a bunch of stuff in here that we don't care about
data = {
"type" => object.class,
"name" => object.name,
"namespace_type" => object.namespace&.class,
"namespace_name" => object.namespace&.name,
"files" => object.files,
"source" => object.source,
"signature" => object.signature,
"docstring" => object.docstring,
"dynamic" => object.dynamic,
# This includes some "auto-generated" tags
# eg. `@return` on initialize methods
"tags" => object.tags.map {|tag| serialize_tag(tag)},
}
# ClassObject represents... classes that have methods. Duh.
# https://github.com/lsegal/yard/blob/main/lib/yard/code_objects/class_object.rb
if object.class == YARD::CodeObjects::ClassObject
# I decided to exclude children because I *think* it's very similar to method + mixins
# data["children"] = object.children.map {|child| serialize_object(child)}
# Do we care about this?
data["class_variables"] = object.cvars.map {|class_variable| serialize_object(class_variable)}
# This includes methods of all visibility.
# I don't know who decided to call this "meths"... but it was an interesting choice
data["methods"] = object.meths.map {|method| serialize_object(method)}
data["constants"] = object.constants.map {|constant| serialize_object(constant)}
data["instance_attributes"] = object.instance_attributes
data["class_attributes"] = object.class_attributes
# I don't know why we would care about these two things, so I'll
# exclude them from the output for now
# data["class_mixins"] = object.class_mixins.map {|mixin| serialize_object(mixin)}
# data["instance_mixins"] = object.instance_mixins.map {|mixin| serialize_object(mixin)}
end
# MethodObject represents methods on classes
# https://github.com/lsegal/yard/blob/main/lib/yard/code_objects/method_object.rb
if object.class == YARD::CodeObjects::MethodObject
data["visibility"] = object.visibility
data["scope"] = object.scope
data["explicit"] = object.explicit
data["parameters"] = object.parameters
data["aliases"] = object.aliases
end
# https://github.com/lsegal/yard/blob/main/lib/yard/code_objects/constant_object.rb
if object.class == YARD::CodeObjects::ConstantObject
data["value"] = object.value
end
return data
end
def serialize_tag(tag)
# Docs: https://github.com/lsegal/yard/blob/359006641260eef1fe6d28f5c43c7c98d40f257d/docs/Tags.md
# Class: https://github.com/lsegal/yard/blob/main/lib/yard/tags/tag.rb
{
"tag_name" => tag.tag_name,
"text" => tag.text,
"types" => tag.types,
"name" => tag.name
}
end
+14 -12
View File
@@ -24,7 +24,7 @@ class ContextSensitiveDrop < Liquid::Drop
end
end
class Category
class Category < Liquid::Drop
attr_accessor :name
def initialize(name)
@@ -36,9 +36,8 @@ class Category
end
end
class CategoryDrop < Liquid::Drop
class CategoryDrop
attr_accessor :category, :context
def initialize(category)
@category = category
end
@@ -406,42 +405,45 @@ class ContextTest < Minitest::Test
end
def test_lambda_is_called_once
@global = 0
@context['callcount'] = proc {
@global += 1
@global ||= 0
@global += 1
@global.to_s
}
assert_equal('1', @context['callcount'])
assert_equal('1', @context['callcount'])
assert_equal('1', @context['callcount'])
@global = nil
end
def test_nested_lambda_is_called_once
@global = 0
@context['callcount'] = { "lambda" => proc {
@global += 1
@global ||= 0
@global += 1
@global.to_s
} }
assert_equal('1', @context['callcount.lambda'])
assert_equal('1', @context['callcount.lambda'])
assert_equal('1', @context['callcount.lambda'])
@global = nil
end
def test_lambda_in_array_is_called_once
@global = 0
@context['callcount'] = [1, 2, proc {
@global += 1
@global ||= 0
@global += 1
@global.to_s
}, 4, 5]
assert_equal('1', @context['callcount[2]'])
assert_equal('1', @context['callcount[2]'])
assert_equal('1', @context['callcount[2]'])
@global = nil
end
def test_access_to_context_from_proc
-24
View File
@@ -1,24 +0,0 @@
# 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
+6 -33
View File
@@ -3,27 +3,6 @@
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
@@ -219,22 +198,16 @@ class ProfilerTest < Minitest::Test
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)
t.render!("collection" => ["one", "two"])
leaf = t.profiler[0].children[0]
assert_operator(leaf.self_time, :>, 0.0)
assert_operator(leaf.self_time, :>, 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)
t = Template.parse("{% if true %} {% increment test %} {{ test }} {% endif %}", profile: true)
t.render!
assert_operator(t.profiler[0].total_time, :>, 0.0)
assert_operator(t.profiler[0].total_time, :>, 0)
end
end
+32 -65
View File
@@ -3,6 +3,10 @@
require 'test_helper'
class Filters
include Liquid::StandardFilters
end
class TestThing
attr_reader :foo
@@ -25,24 +29,8 @@ class TestThing
end
class TestDrop < Liquid::Drop
def initialize(value:)
@value = value
end
attr_reader :value
def registers
@context.registers
end
end
class TestModel
def initialize(value:)
@value = value
end
def to_liquid
TestDrop.new(value: @value)
def test
"testfoo"
end
end
@@ -65,13 +53,10 @@ class NumberLikeThing < Liquid::Drop
end
class StandardFiltersTest < Minitest::Test
Filters = Class.new(Liquid::StrainerTemplate)
Filters.add_filter(Liquid::StandardFilters)
include Liquid
def setup
@filters = Filters.new(Context.new)
@filters = Filters.new
end
def test_size
@@ -274,8 +259,8 @@ class StandardFiltersTest < Minitest::Test
{ "price" => 1, "handle" => "gamma" },
{ "price" => 2, "handle" => "epsilon" },
{ "price" => 4, "handle" => "alpha" },
{ "handle" => "beta" },
{ "handle" => "delta" },
{ "handle" => "beta" },
]
assert_equal(expectation, @filters.sort(input, "price"))
end
@@ -378,9 +363,8 @@ class StandardFiltersTest < Minitest::Test
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'))
testdrop = TestDrop.new
assert_equal([testdrop], @filters.uniq([testdrop, TestDrop.new], 'test'))
end
def test_uniq_empty_array
@@ -439,16 +423,6 @@ class StandardFiltersTest < Minitest::Test
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 }] })
@@ -467,9 +441,9 @@ class StandardFiltersTest < Minitest::Test
end
def test_map_over_proc
drop = TestDrop.new(value: "testfoo")
drop = TestDrop.new
p = proc { drop }
templ = '{{ procs | map: "value" }}'
templ = '{{ procs | map: "test" }}'
assert_template_result("testfoo", templ, "procs" => [p])
end
@@ -565,31 +539,19 @@ class StandardFiltersTest < Minitest::Test
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('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('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 }}")
assert_equal(' ', @filters.remove("1 1 1 1", 1))
assert_equal('a a a', @filters.remove_first("a a a a", 'a '))
assert_equal(' 1 1 1', @filters.remove_first("1 1 1 1", 1))
assert_template_result('a a a', "{{ 'a a a a' | remove_first: 'a ' }}")
end
def test_pipes_in_string_arguments
@@ -865,7 +827,7 @@ class StandardFiltersTest < Minitest::Test
end
def test_all_filters_never_raise_non_liquid_exception
test_drop = TestDrop.new(value: "test")
test_drop = TestDrop.new
test_drop.context = Context.new
test_enum = TestEnumerable.new
test_enum.context = Context.new
@@ -890,14 +852,19 @@ class StandardFiltersTest < Minitest::Test
{ 1 => "bar" },
["foo", 123, nil, true, false, Drop, ["foo"], { foo: "bar" }],
]
StandardFilters.public_instance_methods(false).each do |method|
arg_count = @filters.method(method).arity
arg_count *= -1 if arg_count < 0
test_types.repeated_permutation(arg_count) do |args|
@filters.send(method, *args)
rescue Liquid::Error
nil
test_types.each do |first|
test_types.each do |other|
(@filters.methods - Object.methods).each do |method|
arg_count = @filters.method(method).arity
arg_count *= -1 if arg_count < 0
inputs = [first]
inputs << ([other] * (arg_count - 1)) if arg_count > 1
begin
@filters.send(method, *inputs)
rescue Liquid::ArgumentError, Liquid::ZeroDivisionError
nil
end
end
end
end
end
+10 -10
View File
@@ -72,21 +72,21 @@ module Minitest
end
def with_global_filter(*globals)
original_global_cache = Liquid::StrainerFactory::GlobalCache
Liquid::StrainerFactory.send(:remove_const, :GlobalCache)
Liquid::StrainerFactory.const_set(:GlobalCache, Class.new(Liquid::StrainerTemplate))
original_global_filters = Liquid::StrainerFactory.instance_variable_get(:@global_filters)
Liquid::StrainerFactory.instance_variable_set(:@global_filters, [])
globals.each do |global|
Liquid::StrainerFactory.add_global_filter(global)
end
Liquid::StrainerFactory.send(:strainer_class_cache).clear
globals.each do |global|
Liquid::Template.register_filter(global)
end
yield
ensure
Liquid::StrainerFactory.send(:strainer_class_cache).clear
begin
yield
ensure
Liquid::StrainerFactory.send(:remove_const, :GlobalCache)
Liquid::StrainerFactory.const_set(:GlobalCache, original_global_cache)
Liquid::StrainerFactory.send(:strainer_class_cache).clear
end
Liquid::StrainerFactory.instance_variable_set(:@global_filters, original_global_filters)
end
def with_error_mode(mode)
+14 -27
View File
@@ -10,8 +10,8 @@ class ConditionUnitTest < Minitest::Test
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))
assert_equal(false, Condition.new(1, '==', 2).evaluate)
assert_equal(true, Condition.new(1, '==', 1).evaluate)
end
def test_default_operators_evalute_true
@@ -67,11 +67,11 @@ class ConditionUnitTest < Minitest::Test
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))
assert_nil(Condition.new({}, '>', 2).evaluate)
assert_nil(Condition.new(2, '>', {}).evaluate)
assert_equal(false, Condition.new({}, '==', 2).evaluate)
assert_equal(true, Condition.new({ 'a' => 1 }, '==', 'a' => 1).evaluate)
assert_equal(true, Condition.new({ 'a' => 2 }, 'contains', 'a').evaluate)
end
def test_contains_works_on_arrays
@@ -106,29 +106,30 @@ class ConditionUnitTest < Minitest::Test
def test_or_condition
condition = Condition.new(1, '==', 2)
assert_equal(false, condition.evaluate(Context.new))
assert_equal(false, condition.evaluate)
condition.or(Condition.new(2, '==', 1))
assert_equal(false, condition.evaluate(Context.new))
assert_equal(false, condition.evaluate)
condition.or(Condition.new(1, '==', 1))
assert_equal(true, condition.evaluate(Context.new))
assert_equal(true, condition.evaluate)
end
def test_and_condition
condition = Condition.new(1, '==', 1)
assert_equal(true, condition.evaluate(Context.new))
assert_equal(true, condition.evaluate)
condition.and(Condition.new(2, '==', 2))
assert_equal(true, condition.evaluate(Context.new))
assert_equal(true, condition.evaluate)
condition.and(Condition.new(2, '==', 1))
assert_equal(false, condition.evaluate(Context.new))
assert_equal(false, condition.evaluate)
end
def test_should_allow_custom_proc_operator
@@ -147,20 +148,6 @@ class ConditionUnitTest < Minitest::Test
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
private
def assert_evaluates_true(left, op, right)
+1 -2
View File
@@ -52,8 +52,7 @@ class StrainerFactoryUnitTest < Minitest::Test
/\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.map(&:to_s), exception.backtrace[0].split(':')[0..1])
assert_equal(exception.backtrace[0].split(':')[0], __FILE__)
end
def test_strainer_only_invokes_public_filter_methods
+1 -1
View File
@@ -57,8 +57,8 @@ class StrainerTemplateUnitTest < Minitest::Test
end
def test_add_filter_does_not_raise_when_module_overrides_previously_registered_method
strainer = Context.new.strainer
with_global_filter do
strainer = Context.new.strainer
strainer.class.add_filter(PublicMethodOverrideFilter)
assert(strainer.class.send(:filter_methods).include?('public_filter'))
end