summaryrefslogtreecommitdiff
path: root/lib/eex/test/eex_test.exs
blob: dea891e489474f1a5dab1bedb99400c9df9b9d47 (plain)
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
Code.require_file("test_helper.exs", __DIR__)

require EEx

defmodule EExTest.Compiled do
  def before_compile do
    {__ENV__.line, hd(tl(get_stacktrace()))}
  end

  EEx.function_from_string(:def, :string_sample, "<%= a + b %>", [:a, :b])

  filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
  EEx.function_from_file(:defp, :private_file_sample, filename, [:bar])

  filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
  EEx.function_from_file(:def, :public_file_sample, filename, [:bar])

  def file_sample(arg), do: private_file_sample(arg)

  def after_compile do
    {__ENV__.line, hd(tl(get_stacktrace()))}
  end

  @file "unknown"
  def unknown do
    {__ENV__.line, hd(tl(get_stacktrace()))}
  end

  defp get_stacktrace do
    try do
      :erlang.error("failed")
    rescue
      _ -> __STACKTRACE__
    end
  end
end

defmodule Clause do
  defmacro defclause(expr, block) do
    quote do
      def unquote(expr), unquote(block)
    end
  end
end

defmodule EExTest do
  use ExUnit.Case, async: true

  doctest EEx
  doctest EEx.Engine
  doctest EEx.SmartEngine

  describe "evaluates" do
    test "simple string" do
      assert_eval("foo bar", "foo bar")
    end

    test "Unicode" do
      template = """
        • <%= "•" %> •
        <%= "Jößé Vâlìm" %> Jößé Vâlìm
      """

      assert_eval("  • • •\n  Jößé Vâlìm Jößé Vâlìm\n", template)
    end

    test "no spaces" do
      string = """
      <%=cond do%>
      <%false ->%>
        this
      <%true ->%>
        that
      <%end%>
      """

      expected = "\n  that\n\n"
      assert_eval(expected, string, [])
    end

    test "trim mode" do
      string = "<%= 123 %> \n  \n  <%= 789 %>"
      expected = "123\n789"
      assert_eval(expected, string, [], trim: true)

      string = "<%= 123 %> \n456\n  <%= 789 %>"
      expected = "123\n456\n789"
      assert_eval(expected, string, [], trim: true)

      string = "<%= 123 %> \n\n456\n\n  <%= 789 %>"
      expected = "123\n456\n789"
      assert_eval(expected, string, [], trim: true)

      string = "<%= 123 %> \n  \n456\n  \n  <%= 789 %>"
      expected = "123\n456\n789"
      assert_eval(expected, string, [], trim: true)

      string = "\n  <%= 123 %> \n  <%= 456 %>  \n  <%= 789 %>  \n"
      expected = "123\n456\n789"
      assert_eval(expected, string, [], trim: true)

      string = "\r\n  <%= 123 %> \r\n  <%= 456 %>  \r\n  <%= 789 %>  \r\n"
      expected = "123\n456\n789"
      assert_eval(expected, string, [], trim: true)
    end

    test "trim mode with middle expression" do
      string = """
      <%= cond do %>
      <% false -> %>
        this
      <% true -> %>
        that
      <% end %>
      """

      expected = "\n  that\n"
      assert_eval(expected, string, [], trim: true)
    end

    test "trim mode with multiple lines" do
      string = """
      <%= "First line" %>
      <%= "Second line" %>
      <%= "Third line" %>
      <%= "Fourth line" %>
      """

      expected = "First line\nSecond line\nThird line\nFourth line"
      assert_eval(expected, string, [], trim: true)
    end

    test "trim mode with no spaces" do
      string = """
      <%=if true do%>
        this
      <%else%>
        that
      <%end%>
      """

      expected = "\n  this\n"
      assert_eval(expected, string, [], trim: true)

      string = """
      <%=cond do%>
      <%false ->%>
        this
      <%true ->%>
        that
      <%end%>
      """

      expected = "\n  that\n"
      assert_eval(expected, string, [], trim: true)
    end

    test "embedded code" do
      assert_eval("foo bar", "foo <%= :bar %>")
    end

    test "embedded code with binding" do
      assert EEx.eval_string("foo <%= bar %>", bar: 1) == "foo 1"
    end

    test "embedded code with do end when true" do
      assert_eval("foo bar", "foo <%= if true do %>bar<% end %>")
    end

    test "embedded code with do end when false" do
      assert_eval("foo ", "foo <%= if false do %>bar<% end %>")
    end

    test "embedded code with do preceded by bracket" do
      assert_eval("foo bar", "foo <%= if {true}do %>bar<% end %>")
      assert_eval("foo bar", "foo <%= if (true)do %>bar<% end %>")
      assert_eval("foo bar", "foo <%= if [true]do %>bar<% end %>")
    end

    test "embedded code with do end and expression" do
      assert_eval("foo bar", "foo <%= if true do %><%= :bar %><% end %>")
    end

    test "embedded code with do end and multiple expressions" do
      assert_eval(
        "foo bar baz",
        "foo <%= if true do %>bar <% Process.put(:eex_text, 1) %><%= :baz %><% end %>"
      )

      assert Process.get(:eex_text) == 1
    end

    test "embedded code with middle expression" do
      assert_eval("foo bar", "foo <%= if true do %>bar<% else %>baz<% end %>")
    end

    test "embedded code with evaluated middle expression" do
      assert_eval("foo baz", "foo <%= if false do %>bar<% else %>baz<% end %>")
    end

    test "embedded code with comments in do end" do
      assert_eval("foo bar", "foo <%= case true do %><%# comment %><% true -> %>bar<% end %>")

      assert_eval(
        "foo\n\nbar\n",
        "foo\n<%= case true do %>\n<%# comment %>\n<% true -> %>\nbar\n<% end %>"
      )
    end

    test "embedded code with multi-line comments in do end" do
      assert_eval("foo bar", "foo <%= case true do %><%!-- comment --%><% true -> %>bar<% end %>")

      assert_eval(
        "foo\n\nbar\n",
        "foo\n<%= case true do %>\n<%!-- comment --%>\n<% true -> %>\nbar\n<% end %>"
      )
    end

    test "embedded code with nested do end" do
      assert_eval("foo bar", "foo <%= if true do %><%= if true do %>bar<% end %><% end %>")
    end

    test "embedded code with nested do end with middle expression" do
      assert_eval(
        "foo baz",
        "foo <%= if true do %><%= if false do %>bar<% else %>baz<% end %><% end %>"
      )
    end

    test "embedded code with end followed by bracket" do
      assert_eval(
        " 101  102  103 ",
        "<%= Enum.map([1, 2, 3], fn x -> %> <%= 100 + x %> <% end) %>"
      )

      assert_eval(
        " 101  102  103 ",
        "<%= Enum.map([1, 2, 3], fn x ->\n%> <%= 100 + x %> <% end) %>"
      )

      assert_eval(
        " 101  102  103 ",
        "<%= apply Enum, :map, [[1, 2, 3], fn x -> %> <%= 100 + x %> <% end] %>"
      )

      assert_eval(
        " 101  102  103 ",
        "<%= #{__MODULE__}.tuple_map {[1, 2, 3], fn x -> %> <%= 100 + x %> <% end} %>"
      )

      assert_eval(
        " 101  102  103 ",
        "<%= apply(Enum, :map, [[1, 2, 3], fn x -> %> <%= 100 + x %> <% end]) %>"
      )

      assert_eval(
        " 101  102  103 ",
        "<%= Enum.map([1, 2, 3], (fn x -> %> <%= 100 + x %> <% end) ) %>"
      )
    end

    test "embedded code with variable definition" do
      assert_eval("foo 1", "foo <% bar = 1 %><%= bar %>")
    end

    test "embedded code with require" do
      assert_eval("foo 1,2,3", "foo <% require Enum, as: E %><%= E.join [1, 2, 3], \",\" %>")
    end

    test "with end of token" do
      assert_eval("foo bar %>", "foo bar %>")
    end
  end

  describe "raises syntax errors" do
    test "when the token is invalid" do
      assert_raise EEx.SyntaxError, "nofile:1:12: missing token '%>'", fn ->
        EEx.compile_string("foo <%= bar")
      end
    end

    test "when middle expression is found without a start expression" do
      assert_raise EEx.SyntaxError,
                   "nofile:1:18: unexpected middle of expression <% else %>",
                   fn ->
                     EEx.compile_string("<%= if true %>foo<% else %>bar<% end %>")
                   end
    end

    test "when end expression is found without a start expression" do
      assert_raise EEx.SyntaxError, "nofile:1:5: unexpected end of expression <% end %>", fn ->
        EEx.compile_string("foo <% end %>")
      end
    end

    test "when start expression is found without an end expression" do
      msg = "nofile:2:18: unexpected end of string, expected a closing '<% end %>'"

      assert_raise EEx.SyntaxError, msg, fn ->
        EEx.compile_string("foo\n<%= if true do %>")
      end
    end

    test "when nested end expression is found without a start expression" do
      assert_raise EEx.SyntaxError, "nofile:1:31: unexpected end of expression <% end %>", fn ->
        EEx.compile_string("foo <%= if true do %><% end %><% end %>")
      end
    end

    test "when middle expression has a modifier" do
      assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
               EEx.compile_string("foo <%= if true do %>true<%= else %>false<% end %>")
             end) =~ ~s[unexpected beginning of EEx tag \"<%=\" on \"<%= else %>\"]
    end

    test "when end expression has a modifier" do
      assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
               EEx.compile_string("foo <%= if true do %>true<% else %>false<%= end %>")
             end) =~
               ~s[unexpected beginning of EEx tag \"<%=\" on \"<%= end %>\"]
    end

    test "when trying to use marker '/' without implementation" do
      msg =
        ~r/unsupported EEx syntax <%\/ %> \(the syntax is valid but not supported by the current EEx engine\)/

      assert_raise EEx.SyntaxError, msg, fn ->
        EEx.compile_string("<%/ true %>")
      end
    end

    test "when trying to use marker '|' without implementation" do
      msg =
        ~r/unsupported EEx syntax <%| %> \(the syntax is valid but not supported by the current EEx engine\)/

      assert_raise EEx.SyntaxError, msg, fn ->
        EEx.compile_string("<%| true %>")
      end
    end
  end

  describe "error messages" do
    test "honor line numbers" do
      assert_raise EEx.SyntaxError, "nofile:99:12: missing token '%>'", fn ->
        EEx.compile_string("foo <%= bar", line: 99)
      end
    end

    test "honor file names" do
      assert_raise EEx.SyntaxError, "my_file.eex:1:12: missing token '%>'", fn ->
        EEx.compile_string("foo <%= bar", file: "my_file.eex")
      end
    end
  end

  describe "environment" do
    test "respects line numbers" do
      expected = """
      foo
      2
      """

      string = """
      foo
      <%= __ENV__.line %>
      """

      assert_eval(expected, string)
    end

    test "respects line numbers inside nested expressions" do
      expected = """
      foo

      3

      5
      """

      string = """
      foo
      <%= if true do %>
      <%= __ENV__.line %>
      <% end %>
      <%= __ENV__.line %>
      """

      assert_eval(expected, string)
    end

    test "respects line numbers inside start expression" do
      expected = """
      foo

      true

      5
      """

      string = """
      foo
      <%= if __ENV__.line == 2 do %>
      <%= true %>
      <% end %>
      <%= __ENV__.line %>
      """

      assert_eval(expected, string)
    end

    test "respects line numbers inside middle expression with ->" do
      expected = """
      foo

      true

      7
      """

      string = """
      foo
      <%= cond do %>
      <% false -> %> false
      <% __ENV__.line == 4 -> %>
      <%= true %>
      <% end %>
      <%= __ENV__.line %>
      """

      assert_eval(expected, string)
    end

    test "respects line number inside middle expressions with keywords" do
      expected = """
      foo

      5

      7
      """

      string = """
      foo
      <%= if false do %>
      <%= __ENV__.line %>
      <% else %>
      <%= __ENV__.line %>
      <% end %>
      <%= __ENV__.line %>
      """

      assert_eval(expected, string)
    end

    test "respects files" do
      assert_eval("sample.ex", "<%= __ENV__.file %>", [], file: "sample.ex")
    end
  end

  describe "clauses" do
    test "inside functions" do
      expected = """

      Number 1

      Number 2

      Number 3

      """

      string = """
      <%= Enum.map [1, 2, 3], fn x -> %>
      Number <%= x %>
      <% end %>
      """

      assert_eval(expected, string)
    end

    test "inside multiple functions" do
      expected = """

      A 1

      B 2

      A 3

      """

      string = """
      <%= #{__MODULE__}.switching_map [1, 2, 3], fn x -> %>
      A <%= x %>
      <% end, fn x -> %>
      B <%= x %>
      <% end %>
      """

      assert_eval(expected, string)
    end

    test "inside callback and do block" do
      expected = """


      A 1

      B 2

      A 3

      """

      string = """
      <% require #{__MODULE__} %>
      <%= #{__MODULE__}.switching_macro [1, 2, 3], fn x -> %>
      A <%= x %>
      <% end do %>
      B <%= x %>
      <% end %>
      """

      assert_eval(expected, string)
    end

    test "inside cond" do
      expected = """
      foo

      true

      """

      string = """
      foo
      <%= cond do %>
      <% false -> %> false
      <% fn -> 1 end -> %>
      <%= true %>
      <% end %>
      """

      assert_eval(expected, string)
    end

    test "inside cond with do end" do
      string = """
      <% y = ["a", "b", "c"] %>
      <%= cond do %>
       <% "a" in y -> %>
        Good
       <% true -> %>
        <%= if true do %>true<% else %>false<% end %>
        Bad
      <% end %>
      """

      assert_eval("\n\n  Good\n \n", string)
    end

    test "line and column meta" do
      parser_options = Code.get_compiler_option(:parser_options)
      Code.put_compiler_option(:parser_options, columns: true)

      try do
        indentation = 12

        ast =
          EEx.compile_string(
            """
            <%= f() %> <% f() %>
              <%= f fn -> %>
                <%= f() %>
              <% end %>
            """,
            indentation: indentation
          )

        {_, calls} =
          Macro.prewalk(ast, [], fn
            {:f, meta, _args} = expr, acc -> {expr, [meta | acc]}
            other, acc -> {other, acc}
          end)

        assert Enum.reverse(calls) == [
                 [line: 1, column: indentation + 5],
                 [line: 1, column: indentation + 15],
                 [line: 2, column: indentation + 7],
                 [line: 3, column: indentation + 9]
               ]
      after
        Code.put_compiler_option(:parser_options, parser_options)
      end
    end
  end

  describe "buffers" do
    test "inside comprehensions" do
      string = """
      <%= for _name <- packages || [] do %>
      <% end %>
      <%= all || :done %>
      """

      assert_eval("\ndone\n", string, packages: nil, all: nil)
    end
  end

  describe "from file" do
    test "evaluates the source" do
      filename = Path.join(__DIR__, "fixtures/eex_template.eex")
      result = EEx.eval_file(filename)
      assert_normalized_newline_equal("foo bar.\n", result)
    end

    test "evaluates the source with bindings" do
      filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
      result = EEx.eval_file(filename, bar: 1)
      assert_normalized_newline_equal("foo 1\n", result)
    end

    test "raises an Exception when file is missing" do
      msg = "could not read file \"non-existent.eex\": no such file or directory"

      assert_raise File.Error, msg, fn ->
        filename = "non-existent.eex"
        EEx.compile_file(filename)
      end
    end

    test "sets external resource attribute" do
      assert EExTest.Compiled.__info__(:attributes)[:external_resource] ==
               [Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")]
    end

    test "supports t:Path.t() paths" do
      filename = to_charlist(Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex"))
      result = EEx.eval_file(filename, bar: 1)
      assert_normalized_newline_equal("foo 1\n", result)
    end

    assert_raise EEx.SyntaxError, "my_file.eex:1:12: missing token '%>'", fn ->
      EEx.compile_string("foo <%= bar", file: "my_file.eex")
    end

    test "supports overriding file and line through options" do
      filename = Path.join(__DIR__, "fixtures/eex_template_with_syntax_error.eex")

      assert_raise EEx.SyntaxError, "my_file.eex:11:1: missing token '%>'", fn ->
        EEx.eval_file(filename, _bindings = [], file: "my_file.eex", line: 10)
      end
    end
  end

  describe "precompiled" do
    test "from string" do
      assert EExTest.Compiled.string_sample(1, 2) == "3"
    end

    test "from file" do
      assert_normalized_newline_equal("foo 1\n", EExTest.Compiled.file_sample(1))
      assert_normalized_newline_equal("foo 1\n", EExTest.Compiled.public_file_sample(1))
    end

    test "from file does not affect backtrace" do
      file = to_charlist(Path.relative_to_cwd(__ENV__.file))

      assert EExTest.Compiled.before_compile() ==
               {7, {EExTest.Compiled, :before_compile, 0, [file: file, line: 7]}}

      assert EExTest.Compiled.after_compile() ==
               {21, {EExTest.Compiled, :after_compile, 0, [file: file, line: 21]}}

      assert EExTest.Compiled.unknown() ==
               {26, {EExTest.Compiled, :unknown, 0, [file: 'unknown', line: 26]}}
    end
  end

  defmodule TestEngine do
    @behaviour EEx.Engine

    def init(_opts) do
      "INIT"
    end

    def handle_body(body) do
      "BODY(#{body})"
    end

    def handle_begin(_) do
      "BEGIN"
    end

    def handle_end(buffer) do
      buffer <> ":END"
    end

    def handle_text(buffer, meta, text) do
      buffer <> ":TEXT-#{meta[:line]}-#{meta[:column]}(#{String.trim(text)})"
    end

    def handle_expr(buffer, "/", expr) do
      buffer <> ":DIV(#{Macro.to_string(expr)})"
    end

    def handle_expr(buffer, "=", expr) do
      buffer <> ":EQUAL(#{Macro.to_string(expr)})"
    end

    def handle_expr(buffer, mark, expr) do
      EEx.Engine.handle_expr(buffer, mark, expr)
    end
  end

  describe "custom engines" do
    test "text" do
      assert_eval("BODY(INIT:TEXT-1-1(foo))", "foo", [], engine: TestEngine)
    end

    test "custom marker" do
      assert_eval("BODY(INIT:TEXT-1-1(foo):DIV(:bar))", "foo <%/ :bar %>", [], engine: TestEngine)
    end

    test "begin/end" do
      assert_eval(
        ~s[BODY(INIT:TEXT-1-1(foo):EQUAL(if do\n  "BEGIN:TEXT-1-17(this):END"\nelse\n  "BEGIN:TEXT-1-31(that):END"\nend))],
        "foo <%= if do %>this<% else %>that<% end %>",
        [],
        engine: TestEngine
      )
    end

    test "not implemented custom marker" do
      msg =
        ~r/unsupported EEx syntax <%| %> \(the syntax is valid but not supported by the current EEx engine\)/

      assert_raise EEx.SyntaxError, msg, fn ->
        assert_eval({:wrapped, "foo baz"}, "foo <%| :bar %>", [], engine: TestEngine)
      end
    end
  end

  describe "parser options" do
    test "customizes parsed code" do
      atoms_encoder = fn "not_jose", _ -> {:ok, :jose} end

      assert_eval("valid", "<%= not_jose %>", [jose: "valid"],
        parser_options: [static_atoms_encoder: atoms_encoder]
      )
    end
  end

  defp assert_eval(expected, actual, binding \\ [], opts \\ []) do
    opts = Keyword.merge([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
    result = EEx.eval_string(actual, binding, opts)
    assert result == expected
  end

  defp assert_normalized_newline_equal(expected, actual) do
    assert String.replace(expected, "\r\n", "\n") == String.replace(actual, "\r\n", "\n")
  end

  def tuple_map({list, callback}) do
    Enum.map(list, callback)
  end

  def switching_map(list, a, b) do
    list
    |> Enum.with_index()
    |> Enum.map(fn
      {element, index} when rem(index, 2) == 0 -> a.(element)
      {element, index} when rem(index, 2) == 1 -> b.(element)
    end)
  end

  defmacro switching_macro(list, a, do: block) do
    quote do
      b = fn var!(x) ->
        unquote(block)
      end

      unquote(__MODULE__).switching_map(unquote(list), unquote(a), b)
    end
  end
end