File: template_test.rb

package info (click to toggle)
ruby-liquid 5.4.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,176 kB
  • sloc: ruby: 10,561; makefile: 6
file content (340 lines) | stat: -rw-r--r-- 11,768 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# 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
    t = Template.parse("{% assign foo = (x..y) %}{{ foo }}")
    result = t.render('x' => 1, 'y' => 5)
    assert_equal('1..5', result)

    t = Template.parse("{% assign nums = (x..y) %}{% for num in nums %}{{ num }}{% endfor %}")
    result = t.render('x' => 1, 'y' => 5)
    assert_equal('12345', result)
  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
end