|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "abstract_unit" |
| 4 | + |
| 5 | +module SharedBufferTests |
| 6 | + def self.included(test_case) |
| 7 | + test_case.test "#<< maintains HTML safety" do |
| 8 | + @buffer << "<script>alert('pwned!')</script>" |
| 9 | + assert_predicate @buffer, :html_safe? |
| 10 | + assert_predicate output, :html_safe? |
| 11 | + assert_equal "<script>alert('pwned!')</script>", output |
| 12 | + end |
| 13 | + |
| 14 | + test_case.test "#safe_append= bypasses HTML safety" do |
| 15 | + @buffer.safe_append = "<p>This is fine</p>" |
| 16 | + assert_predicate @buffer, :html_safe? |
| 17 | + assert_predicate output, :html_safe? |
| 18 | + assert_equal "<p>This is fine</p>", output |
| 19 | + end |
| 20 | + |
| 21 | + test_case.test "#raw allow to bypass HTML escaping" do |
| 22 | + raw_buffer = @buffer.raw |
| 23 | + raw_buffer << "<script>alert('pwned!')</script>" |
| 24 | + assert_predicate @buffer, :html_safe? |
| 25 | + assert_predicate output, :html_safe? |
| 26 | + assert_equal "<script>alert('pwned!')</script>", output |
| 27 | + end |
| 28 | + |
| 29 | + test_case.test "#capture allow to intercept writes" do |
| 30 | + @buffer << "Hello" |
| 31 | + result = @buffer.capture do |
| 32 | + @buffer << "George!" |
| 33 | + end |
| 34 | + assert_equal "George!", result |
| 35 | + assert_predicate result, :html_safe? |
| 36 | + |
| 37 | + @buffer << " World!" |
| 38 | + assert_equal "Hello World!", output |
| 39 | + end |
| 40 | + |
| 41 | + test_case.test "#raw respects #capture" do |
| 42 | + @buffer << "Hello" |
| 43 | + raw_buffer = @buffer.raw |
| 44 | + result = @buffer.capture do |
| 45 | + raw_buffer << "George!" |
| 46 | + end |
| 47 | + assert_equal "George!", result |
| 48 | + assert_predicate result, :html_safe? |
| 49 | + |
| 50 | + @buffer << " World!" |
| 51 | + assert_equal "Hello World!", output |
| 52 | + end |
| 53 | + end |
| 54 | +end |
| 55 | + |
| 56 | +class TestOutputBuffer < ActiveSupport::TestCase |
| 57 | + include SharedBufferTests |
| 58 | + |
| 59 | + setup do |
| 60 | + @buffer = ActionView::OutputBuffer.new |
| 61 | + end |
| 62 | + |
| 63 | + test "can be duped" do |
| 64 | + @buffer << "Hello" |
| 65 | + copy = @buffer.dup |
| 66 | + copy << " World!" |
| 67 | + assert_equal "Hello World!", copy.to_s |
| 68 | + assert_equal "Hello", output |
| 69 | + end |
| 70 | + |
| 71 | + private |
| 72 | + def output |
| 73 | + @buffer.to_s |
| 74 | + end |
| 75 | +end |
| 76 | + |
| 77 | +class TestStreamingBuffer < ActiveSupport::TestCase |
| 78 | + include SharedBufferTests |
| 79 | + |
| 80 | + setup do |
| 81 | + @raw_buffer = +"" |
| 82 | + @buffer = ActionView::StreamingBuffer.new(@raw_buffer.method(:<<)) |
| 83 | + end |
| 84 | + |
| 85 | + private |
| 86 | + def output |
| 87 | + @raw_buffer.html_safe |
| 88 | + end |
| 89 | +end |
0 commit comments