Compare commits

..
Author SHA1 Message Date
Guilherme Carreiro 0ae38bac69 Fix backward-compatibility issue with the 'sort' filter 2025-01-29 16:50:05 +01:00
14 changed files with 279 additions and 393 deletions
-15
View File
@@ -14,21 +14,8 @@ jobs:
- { ruby: 3.0, allowed-failure: false } # minimum supported
- { ruby: 3.2, allowed-failure: false }
- { ruby: 3.3, allowed-failure: false }
- { ruby: 3.3, allowed-failure: false }
- { ruby: 3.4, allowed-failure: false } # latest
- {
ruby: 3.4,
allowed-failure: false,
rubyopt: "--enable-frozen-string-literal",
}
- { ruby: 3.4, allowed-failure: false, rubyopt: "--yjit" }
- { ruby: ruby-head, allowed-failure: false }
- {
ruby: ruby-head,
allowed-failure: false,
rubyopt: "--enable-frozen-string-literal",
}
- { ruby: ruby-head, allowed-failure: false, rubyopt: "--yjit" }
name: Test Ruby ${{ matrix.entry.ruby }}
steps:
- uses: actions/checkout@v3
@@ -39,8 +26,6 @@ jobs:
bundler: latest
- run: bundle exec rake
continue-on-error: ${{ matrix.entry.allowed-failure }}
env:
RUBYOPT: ${{ matrix.entry.rubyopt }}
memory_profile:
runs-on: ubuntu-latest
+7 -19
View File
@@ -1,34 +1,22 @@
# Liquid Change Log
## 5.8.1 (unreleased)
## 5.8.0 (unreleased)
## 5.8.1
## 5.7.2 2025-01-30
* Fix `{% doc %}` tag to be visitable [Guilherme Carreiro]
## 5.8.0
* Introduce the new `{% doc %}` tag [Guilherme Carreiro]
## 5.7.3
* Raise Liquid::SyntaxError when parsing invalidly encoded strings [Chris AtLee]
## 5.7.2 2025-01-31
* Fix array filters to not support nested properties [Guilherme Carreiro]
- Fix the `sort` filter to handle nested properties gracefully when their types don't match
## 5.7.1 2025-01-24
* Fix the `find` and `find_index`filters to return `nil` when filtering empty arrays [Guilherme Carreiro]
* Fix the `has` filter to return `false` when filtering empty arrays [Guilherme Carreiro]
* Fix the `find` and `find_index`filters to return `nil` when filtering empty arrays
* Fix the `has` filter to return `false` when filtering empty arrays
## 5.7.0 2025-01-16
### Features
* Add `find`, `find_index`, `has`, and `reject` filters to arrays [Guilherme Carreiro]
* Compatibility with Ruby 3.4 [Ian Ker-Seymer]
* Add `find`, `find_index`, `has`, and `reject` filters to arrays
* Compatibility with Ruby 3.4
## 5.6.4 2025-01-14
-6
View File
@@ -161,12 +161,6 @@ module Liquid
end
# rubocop:enable Metrics/BlockNesting
output << EOS
rescue ::ArgumentError => e
if e.message == "invalid byte sequence in #{ss.string.encoding}"
raise SyntaxError, "Invalid byte sequence in #{ss.string.encoding}"
else
raise
end
end
def raise_syntax_error(start_pos, ss)
-2
View File
@@ -2,14 +2,12 @@
errors:
syntax:
tag_unexpected_args: "Syntax Error in '%{tag}' - Valid syntax: %{tag}"
block_tag_unexpected_args: "Syntax Error in '%{tag}' - Valid syntax: {% %{tag} %}{% end%{tag} %}"
assign: "Syntax Error in 'assign' - Valid syntax: assign [var] = [source]"
capture: "Syntax Error in 'capture' - Valid syntax: capture [var]"
case: "Syntax Error in 'case' - Valid syntax: case [condition]"
case_invalid_when: "Syntax Error in tag 'case' - Valid when condition: {% when [condition] [or condition2...] %}"
case_invalid_else: "Syntax Error in tag 'case' - Valid else condition: {% else %} (no parameters) "
cycle: "Syntax Error in 'cycle' - Valid syntax: cycle [name :] var [, var2, var3 ...]"
doc_invalid_nested: "Syntax Error in 'doc' - Nested doc tags are not allowed"
for: "Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]"
for_invalid_in: "For loops require an 'in' clause"
for_invalid_attribute: "Invalid attribute in for loop. Valid attributes are limit and offset"
+68 -31
View File
@@ -387,8 +387,23 @@ module Liquid
end
elsif ary.all? { |el| el.respond_to?(:[]) }
begin
property = Utils.to_s(property)
ary.sort { |a, b| nil_safe_compare(a[property], b[property]) }
ary.sort do |a, b|
a = fetch_property(a, property)
b = fetch_property(b, property)
##
# We handle nested properties gracefully to avoid breaking backward
# compatibility.
#
# However, we raise errors for incompatible types when no nested
# properties are used to maintain strict type checking in simple
# cases.
if has_nested_property?(property)
type_safe_compare(a, b) { |a, b| nil_safe_compare(a, b) }
else
nil_safe_compare(a, b)
end
end
rescue TypeError
raise_property_error(property)
end
@@ -417,8 +432,7 @@ module Liquid
end
elsif ary.all? { |el| el.respond_to?(:[]) }
begin
property = Utils.to_s(property)
ary.sort { |a, b| nil_safe_casecmp(a[property], b[property]) }
ary.sort { |a, b| nil_safe_casecmp(fetch_property(a, property), fetch_property(b, property)) }
rescue TypeError
raise_property_error(property)
end
@@ -458,7 +472,7 @@ module Liquid
# Tests if any item in an array has a specific property value.
# @liquid_description
# This requires you to provide both the property name and the associated value.
# @liquid_syntax array | has: string, string
# @liquid_syntax array | some: string, string
# @liquid_return [boolean]
def has(input, property, target_value = nil)
filter_array(input, property, target_value, false) { |ary, &block| ary.any?(&block) }
@@ -505,9 +519,8 @@ module Liquid
elsif ary.empty? # The next two cases assume a non-empty array.
[]
else
property = Utils.to_s(property)
ary.uniq do |item|
item[property]
fetch_property(item, property)
rescue TypeError
raise_property_error(property)
rescue NoMethodError
@@ -537,14 +550,13 @@ module Liquid
# @liquid_syntax array | map: string
# @liquid_return [array[untyped]]
def map(input, property)
property = Utils.to_s(property)
InputIterator.new(input, context).map do |e|
e = e.call if e.is_a?(Proc)
if property == "to_liquid"
e
elsif e.respond_to?(:[])
r = e[property]
r = fetch_property(e, property)
r.is_a?(Proc) ? r.call : r
end
end
@@ -567,9 +579,8 @@ module Liquid
elsif ary.empty? # The next two cases assume a non-empty array.
[]
else
property = Liquid::Utils.to_s(property)
ary.reject do |item|
item[property].nil?
fetch_property(item, property).nil?
rescue TypeError
raise_property_error(property)
rescue NoMethodError
@@ -717,16 +728,7 @@ module Liquid
input.gsub(/\r?\n/, "<br />\n")
end
# @liquid_public_docs
# @liquid_type filter
# @liquid_category date
# @liquid_summary
# Formats a date according to a specified format string.
# @liquid_description
# This filter formats a date using various format specifiers. If the format string is empty,
# the original input is returned. If the input cannot be converted to a date, the original input is returned.
#
# The following format specifiers can be used:
# Reformat a date using Ruby's core Time#strftime( string ) -> string
#
# %a - The abbreviated weekday name (``Sun'')
# %A - The full weekday name (``Sunday'')
@@ -755,8 +757,8 @@ module Liquid
# %Y - Year with century
# %Z - Time zone name
# %% - Literal ``%'' character
# @liquid_syntax date | date: string
# @liquid_return [string]
#
# See also: http://www.ruby-doc.org/core/Time.html#method-i-strftime
def date(input, format)
str_format = Utils.to_s(format)
return input if str_format.empty?
@@ -957,8 +959,6 @@ module Liquid
# @liquid_syntax array | sum
# @liquid_return [number]
def sum(input, property = nil)
property = property.nil? ? nil : Utils.to_s(property)
ary = InputIterator.new(input, context)
return 0 if ary.empty?
@@ -966,7 +966,7 @@ module Liquid
if property.nil?
item
elsif item.respond_to?(:[])
item[property]
fetch_property(item, property)
else
0
end
@@ -986,17 +986,15 @@ module Liquid
attr_reader :context
def filter_array(input, property, target_value, default_value = [], &block)
property = Liquid::Utils.to_s(property)
return default_value if property.empty?
ary = InputIterator.new(input, context)
return default_value if ary.empty?
block.call(ary) do |item|
if target_value.nil?
item[property]
fetch_property(item, property)
else
item[property] == target_value
fetch_property(item, property) == target_value
end
rescue TypeError
raise_property_error(property)
@@ -1006,6 +1004,35 @@ module Liquid
end
end
def fetch_property(drop, property_or_keys)
##
# This keeps backward compatibility by supporting properties containing
# dots. This is valid in Liquid syntax and used in some runtimes, such as
# Shopify with metafields.
#
# Using this approach, properties like 'price.value' can be accessed in
# both of the following examples:
#
# ```
# [
# { 'name' => 'Item 1', 'price.price' => 40000 },
# { 'name' => 'Item 2', 'price' => { 'value' => 39900 } }
# ]
# ```
value = drop[property_or_keys]
return value if !value.nil? || !has_nested_property?(property_or_keys)
keys = property_or_keys.split('.')
keys.reduce(drop) do |drop, key|
drop.respond_to?(:[]) ? drop[key] : drop
end
end
def has_nested_property?(property)
property.is_a?(String) && property.include?('.')
end
def raise_property_error(property)
raise Liquid::ArgumentError, "cannot select the property '#{property}'"
end
@@ -1029,6 +1056,16 @@ module Liquid
end
end
def type_safe_compare(a, b)
klass_a = a.class
klass_b = b.class
# Converting classes to string to have a deterministic comparison.
return nil_safe_casecmp(klass_a, klass_b) if klass_a != klass_b
yield(a, b)
end
def nil_safe_casecmp(a, b)
if !a.nil? && !b.nil?
a.to_s.casecmp(b.to_s)
-2
View File
@@ -19,7 +19,6 @@ require_relative "tags/comment"
require_relative "tags/raw"
require_relative "tags/render"
require_relative "tags/cycle"
require_relative "tags/doc"
module Liquid
module Tags
@@ -43,7 +42,6 @@ module Liquid
'if' => If,
'echo' => Echo,
'tablerow' => TableRow,
'doc' => Doc,
}.freeze
end
end
-78
View File
@@ -1,78 +0,0 @@
# frozen_string_literal: true
module Liquid
# @liquid_public_docs
# @liquid_type tag
# @liquid_category syntax
# @liquid_name doc
# @liquid_summary
# Documents template elements with annotations.
# @liquid_description
# The `doc` tag allows developers to include documentation within Liquid
# templates. Any content inside `doc` tags is not rendered or outputted.
# Liquid code inside will be parsed but not executed. This facilitates
# tooling support for features like code completion, linting, and inline
# documentation.
#
# For detailed documentation syntax and examples, see the
# [`LiquidDoc` reference](/docs/storefronts/themes/tools/liquid-doc).
#
# @liquid_syntax
# {% doc %}
# Renders a message.
#
# @param {string} foo - A string value.
# @param {string} [bar] - An optional string value.
#
# @example
# {% render 'message', foo: 'Hello', bar: 'World' %}
# {% enddoc %}
# {{ foo }}, {{ bar }}!
class Doc < Block
NO_UNEXPECTED_ARGS = /\A\s*\z/
def initialize(tag_name, markup, parse_context)
super
ensure_valid_markup(tag_name, markup, parse_context)
end
def parse(tokens)
while (token = tokens.shift)
tag_name = token =~ BlockBody::FullTokenPossiblyInvalid && Regexp.last_match(2)
raise_nested_doc_error if tag_name == @tag_name
if tag_name == block_delimiter
parse_context.trim_whitespace = (token[-3] == WhitespaceControl)
return
end
end
raise_tag_never_closed(block_name)
end
def render_to_output_buffer(_context, output)
output
end
def blank?
true
end
def nodelist
[]
end
private
def ensure_valid_markup(tag_name, markup, parse_context)
unless NO_UNEXPECTED_ARGS.match?(markup)
raise SyntaxError, parse_context.locale.t("errors.syntax.block_tag_unexpected_args", tag: tag_name)
end
end
def raise_nested_doc_error
raise SyntaxError, parse_context.locale.t("errors.syntax.doc_invalid_nested")
end
end
end
-6
View File
@@ -103,12 +103,6 @@ module Liquid
pos = @ss.pos -= 2
@source.byteslice(start, pos - start)
rescue ::ArgumentError => e
if e.message == "invalid byte sequence in #{@ss.string.encoding}"
raise SyntaxError, "Invalid byte sequence in #{@ss.string.encoding}"
else
raise
end
end
def next_variable_token
+1 -1
View File
@@ -2,5 +2,5 @@
# frozen_string_literal: true
module Liquid
VERSION = "5.8.2"
VERSION = "5.7.2"
end
+202 -21
View File
@@ -54,6 +54,30 @@ class TestEnumerable < Liquid::Drop
end
end
class TestDeepEnumerable < Liquid::Drop
include Enumerable
class Product < Liquid::Drop
attr_reader :title, :price, :premium
def initialize(title:, price:, premium: nil)
@title = { "content" => title, "language" => "en" }
@price = { "value" => price, "unit" => "USD" }
@premium = { "category" => premium } if premium
end
end
def each(&block)
[
Product.new(title: "Pro goggles", price: 1299),
Product.new(title: "Thermal gloves", price: 1299),
Product.new(title: "Alpine jacket", price: 3999, premium: 'Basic'),
Product.new(title: "Mountain boots", price: 3899, premium: 'Pro'),
Product.new(title: "Safety helmet", price: 1999)
].each(&block)
end
end
class NumberLikeThing < Liquid::Drop
def initialize(amount)
@amount = amount
@@ -414,6 +438,15 @@ class StandardFiltersTest < Minitest::Test
end
end
def test_sort_natural_with_deep_enumerables
template = <<~LIQUID
{{- products | sort_natural: 'title.content' | map: 'title.content' | join: ', ' -}}
LIQUID
expected_output = "Alpine jacket, Mountain boots, Pro goggles, Safety helmet, Thermal gloves"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_legacy_sort_hash
assert_equal([{ a: 1, b: 2 }], @filters.sort(a: 1, b: 2))
end
@@ -450,6 +483,15 @@ class StandardFiltersTest < Minitest::Test
end
end
def test_uniq_with_deep_enumerables
template = <<~LIQUID
{{- products | uniq: 'price.value' | map: "title.content" | join: ', ' -}}
LIQUID
expected_output = "Pro goggles, Alpine jacket, Mountain boots, Safety helmet"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_compact_empty_array
assert_equal([], @filters.compact([], "a"))
end
@@ -466,6 +508,15 @@ class StandardFiltersTest < Minitest::Test
end
end
def test_compact_with_deep_enumerables
template = <<~LIQUID
{{- products | compact: 'premium.category' | map: 'title.content' | join: ', ' -}}
LIQUID
expected_output = "Alpine jacket, Mountain boots"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_reverse
assert_equal([4, 3, 2, 1], @filters.reverse([1, 2, 3, 4]))
end
@@ -575,6 +626,15 @@ class StandardFiltersTest < Minitest::Test
assert_template_result("213", '{{ foo | sort: "bar" | map: "foo" }}', { "foo" => TestEnumerable.new })
end
def test_sort_with_deep_enumerables
template = <<~LIQUID
{{- products | sort: 'price.value' | map: 'title.content' | join: ', ' -}}
LIQUID
expected_output = "Pro goggles, Thermal gloves, Safety helmet, Mountain boots, Alpine jacket"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.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] })
@@ -891,6 +951,15 @@ class StandardFiltersTest < Minitest::Test
assert_template_result(expected_output, template, { "array" => array })
end
def test_reject_with_deep_enumerables
template = <<~LIQUID
{{- products | reject: 'title.content', 'Pro goggles' | map: 'price.value' | join: ', ' -}}
LIQUID
expected_output = "1299, 3999, 3899, 1999"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_has
array = [
{ "handle" => "alpha", "ok" => true },
@@ -959,6 +1028,16 @@ class StandardFiltersTest < Minitest::Test
assert_template_result(expected_output, template, { "array" => array })
end
def test_has_with_deep_enumerables
template = <<~LIQUID
{{- products | has: 'title.content', 'Pro goggles' -}},
{{- products | has: 'title.content', 'foo' -}}
LIQUID
expected_output = "true,false"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_find_with_value
products = [
{ "title" => "Pro goggles", "price" => 1299 },
@@ -977,6 +1056,16 @@ class StandardFiltersTest < Minitest::Test
assert_template_result(expected_output, template, { "products" => products })
end
def test_find_with_deep_enumerables
template = <<~LIQUID
{%- assign product = products | find: 'title.content', 'Pro goggles' -%}
{{- product.title.content -}}
LIQUID
expected_output = "Pro goggles"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_find_with_empty_arrays
template = <<~LIQUID
{%- assign product = products | find: 'title.content', 'Not found' -%}
@@ -1007,6 +1096,16 @@ class StandardFiltersTest < Minitest::Test
assert_template_result(expected_output, template, { "products" => products })
end
def test_find_index_with_deep_enumerables
template = <<~LIQUID
{%- assign index = products | find_index: 'title.content', 'Alpine jacket' -%}
{{- index -}}
LIQUID
expected_output = "2"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_find_index_with_empty_arrays
template = <<~LIQUID
{%- assign index = products | find_index: 'title.content', 'Not found' -%}
@@ -1061,19 +1160,6 @@ class StandardFiltersTest < Minitest::Test
assert_template_result(expected_output, template, { "array" => array })
end
def test_where_with_non_string_property
array = [
{ "handle" => "alpha", "{}" => true },
{ "handle" => "beta", "{}" => false },
{ "handle" => "gamma", "{}" => false },
{ "handle" => "delta", "{}" => true },
]
template = "{{ array | where: some_property, true | map: 'handle' | join: ' ' }}"
expected_output = "alpha delta"
assert_template_result(expected_output, template, { "array" => array, "some_property" => {} })
end
def test_where_string_keys
input = [
"alpha", "beta", "gamma", "delta"
@@ -1130,6 +1216,15 @@ class StandardFiltersTest < Minitest::Test
assert_nil(@filters.where([nil], "ok"))
end
def test_where_with_deep_enumerables
template = <<~LIQUID
{{- products | where: 'title.content', 'Pro goggles' | map: 'price.value' -}}
LIQUID
expected_output = "1299"
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_all_filters_never_raise_non_liquid_exception
test_drop = TestDrop.new(value: "test")
test_drop.context = Context.new
@@ -1281,15 +1376,101 @@ class StandardFiltersTest < Minitest::Test
assert_template_result("0", "{{ input | sum: 'subtotal' }}", { "input" => input })
end
def test_sum_with_non_string_property
input = [{ "true" => 1 }, { "1.0" => 0.2, "1" => -0.3 }, { "1..5" => 0.4 }]
def test_sum_with_deep_enumerables
template = <<~LIQUID
{{- products | sum: 'price.value' -}}
LIQUID
expected_output = "12495"
assert_equal(1, @filters.sum(input, true))
assert_equal(0.2, @filters.sum(input, 1.0))
assert_equal(-0.3, @filters.sum(input, 1))
assert_equal(0.4, @filters.sum(input, (1..5)))
assert_equal(0, @filters.sum(input, nil))
assert_equal(0, @filters.sum(input, ""))
assert_template_result(expected_output, template, { "products" => TestDeepEnumerable.new })
end
def test_sort_with_different_types
input = [
{ "price" => 1000 },
{ "price" => :none },
{ "price" => 3000 }
]
assert_raises(Liquid::ArgumentError) do
@filters.sort(input, "price")
end
end
def test_sort_with_nested_different_types
input = [
{ "price" => { "value" => 1000, "unit" => "BRL" } },
{ "price" => { "value" => 2000, "unit" => nil } },
{ "price" => { "value" => 3000, "unit" => :none } }
]
expected_output = "2000, 1000, 3000"
template = <<~LIQUID
{{- input | sort: 'price.unit' | map: 'price.value' | join: ', ' -}}
LIQUID
assert_template_result(expected_output, template, { "input" => input })
end
def test_sort_natural_with_nested_different_types
input = [
{ "price" => { "value" => 1000, "unit" => "brl" } },
{ "price" => { "value" => 2000, "unit" => "BRL" } },
{ "price" => { "value" => 3000, "unit" => nil } },
{ "price" => { "value" => 4000, "unit" => :brl } }
]
expected_output = "1000, 2000, 4000, 3000"
template = <<~LIQUID
{{- input | sort_natural: 'price.unit' | map: 'price.value' | join: ', ' -}}
LIQUID
assert_template_result(expected_output, template, { "input" => input })
end
def test_uniq_with_nested_different_types
input = [
{ "price" => { "value" => 1000, "unit" => "BRL" } },
{ "price" => { "value" => 2000, "unit" => "BRL" } },
{ "price" => { "value" => 3000, "unit" => :USD } },
{ "price" => { "value" => 4000, "unit" => :BRL } },
{ "price" => { "value" => 5000, "unit" => nil } }
]
expected_output = "BRL, USD, BRL, " # Uniq handles different types uniqueness
template = <<~LIQUID
{{- input | uniq: 'price.unit' | map: 'price.unit' | join: ', ' -}}
LIQUID
assert_template_result(expected_output, template, { "input" => input })
end
def test_map_with_nested_different_types
input = [
{ "price" => { "value" => 1000, "unit" => "brl" } },
{ "price" => { "value" => 2000, "unit" => "BRL" } },
{ "price" => { "value" => 3000, "unit" => nil } },
{ "price" => { "value" => 4000, "unit" => :brl } }
]
expected_output = "brl, BRL, , brl"
template = <<~LIQUID
{{- input | map: 'price.unit'| join: ', ' -}}
LIQUID
assert_template_result(expected_output, template, { "input" => input })
end
def test_sum_with_nested_different_types
input = [
{ "price" => { "value" => 1000 } },
{ "price" => { "value" => nil } },
{ "price" => { "value" => :none } },
{ "price" => { "value" => 3000 } }
]
expected_output = "4000"
template = <<~LIQUID
{{- input | sum: 'price.value' -}}
LIQUID
assert_template_result(expected_output, template, { "input" => input })
end
private
+1 -7
View File
@@ -47,18 +47,12 @@ class BlockUnitTest < Minitest::Test
)
end
def test_comment_tag_with_block
def test_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)
-10
View File
@@ -131,16 +131,6 @@ class LexerUnitTest < Minitest::Test
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)
-184
View File
@@ -1,184 +0,0 @@
# 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_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_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
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
-11
View File
@@ -35,15 +35,4 @@ class TemplateUnitTest < Minitest::Test
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