# frozen_string_literal: true
require_relative "abstract_unit"
require "active_support/core_ext/string/inflections"
require "yaml"
class SafeBufferTest < ActiveSupport::TestCase
def setup
@buffer = ActiveSupport::SafeBuffer.new
end
def test_titleize
assert_equal "Foo", "foo".html_safe.titleize
end
test "Should look like a string" do
assert @buffer.is_a?(String)
assert_equal "", @buffer
end
test "Should escape a raw string which is passed to them" do
@buffer << "')
# calling gsub! makes the dirty flag true
assert_not x.html_safe?, "should not be safe"
# getting a slice of it
y = x[0..-1]
# should still be unsafe
assert_not y.html_safe?, "should not be safe"
end
test "Should continue safe on slice" do
x = "
foo
".html_safe
assert_predicate x, :html_safe?
# getting a slice of it
y = x[0..-1]
# should still be safe
assert_predicate y, :html_safe?
end
test "Should work with interpolation (array argument)" do
x = "foo %s bar".html_safe % ["qux"]
assert_equal "foo qux bar", x
end
test "Should work with interpolation (hash argument)" do
x = "foo %{x} bar".html_safe % { x: "qux" }
assert_equal "foo qux bar", x
end
test "Should escape unsafe interpolated args" do
x = "foo %{x} bar".html_safe % { x: "
" }
assert_equal "foo <br/> bar", x
end
test "Should not escape safe interpolated args" do
x = "foo %{x} bar".html_safe % { x: "
".html_safe }
assert_equal "foo
bar", x
end
test "Should interpolate to a safe string" do
x = "foo %{x} bar".html_safe % { x: "qux" }
assert x.html_safe?, "should be safe"
end
test "Should not affect frozen objects when accessing characters" do
x = "Hello".html_safe
assert_nil x[/a/, 1]
end
test "Should set back references" do
a = "foo123".html_safe
a2 = a.sub(/([a-z]+)([0-9]+)/) { $2 + $1 }
assert_equal "123foo", a2
assert_not_predicate a2, :html_safe?
a.sub!(/([a-z]+)([0-9]+)/) { $2 + $1 }
assert_equal "123foo", a
assert_not_predicate a, :html_safe?
b = "foo123 bar456".html_safe
b2 = b.gsub(/([a-z]+)([0-9]+)/) { $2 + $1 }
assert_equal "123foo 456bar", b2
assert_not_predicate b2, :html_safe?
b.gsub!(/([a-z]+)([0-9]+)/) { $2 + $1 }
assert_equal "123foo 456bar", b
assert_not_predicate b, :html_safe?
end
test "Should support Enumerator" do
a = "aaa".html_safe.gsub!(/a/).with_index { |m, i| i }
assert_equal "012", a
end
end