1require 'psych/helper' 2 3module Psych 4 class TestString < TestCase 5 class X < String 6 end 7 8 class Y < String 9 attr_accessor :val 10 end 11 12 class Z < String 13 def initialize 14 force_encoding Encoding::US_ASCII 15 end 16 end 17 18 def test_another_subclass_with_attributes 19 y = Psych.load Psych.dump Y.new("foo").tap {|y| y.val = 1} 20 assert_equal "foo", y 21 assert_equal Y, y.class 22 assert_equal 1, y.val 23 end 24 25 def test_backwards_with_syck 26 x = Psych.load "--- !str:#{X.name} foo\n\n" 27 assert_equal X, x.class 28 assert_equal 'foo', x 29 end 30 31 def test_empty_subclass 32 assert_match "!ruby/string:#{X}", Psych.dump(X.new) 33 x = Psych.load Psych.dump X.new 34 assert_equal X, x.class 35 end 36 37 def test_empty_character_subclass 38 assert_match "!ruby/string:#{Z}", Psych.dump(Z.new) 39 x = Psych.load Psych.dump Z.new 40 assert_equal Z, x.class 41 end 42 43 def test_subclass_with_attributes 44 y = Psych.load Psych.dump Y.new.tap {|y| y.val = 1} 45 assert_equal Y, y.class 46 assert_equal 1, y.val 47 end 48 49 def test_string_with_base_60 50 yaml = Psych.dump '01:03:05' 51 assert_match "'01:03:05'", yaml 52 assert_equal '01:03:05', Psych.load(yaml) 53 end 54 55 def test_nonascii_string_as_binary 56 string = "hello \x80 world!" 57 string.force_encoding 'ascii-8bit' 58 yml = Psych.dump string 59 assert_match(/binary/, yml) 60 assert_equal string, Psych.load(yml) 61 end 62 63 def test_binary_string_null 64 string = "\x00" 65 yml = Psych.dump string 66 assert_match(/binary/, yml) 67 assert_equal string, Psych.load(yml) 68 end 69 70 def test_binary_string 71 string = binary_string 72 yml = Psych.dump string 73 assert_match(/binary/, yml) 74 assert_equal string, Psych.load(yml) 75 end 76 77 def test_non_binary_string 78 string = binary_string(0.29) 79 yml = Psych.dump string 80 refute_match(/binary/, yml) 81 assert_equal string, Psych.load(yml) 82 end 83 84 def test_ascii_only_8bit_string 85 string = "abc".encode(Encoding::ASCII_8BIT) 86 yml = Psych.dump string 87 refute_match(/binary/, yml) 88 assert_equal string, Psych.load(yml) 89 end 90 91 def test_string_with_ivars 92 food = "is delicious" 93 ivar = "on rock and roll" 94 food.instance_variable_set(:@we_built_this_city, ivar) 95 96 str = Psych.load Psych.dump food 97 assert_equal ivar, food.instance_variable_get(:@we_built_this_city) 98 end 99 100 def test_binary 101 string = [0, 123,22, 44, 9, 32, 34, 39].pack('C*') 102 assert_cycle string 103 end 104 105 def test_float_confusion 106 assert_cycle '1.' 107 end 108 109 def binary_string percentage = 0.31, length = 100 110 string = '' 111 (percentage * length).to_i.times do |i| 112 string << "\b" 113 end 114 string << 'a' * (length - string.length) 115 string 116 end 117 end 118end 119