summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorJean Boussier <jean.boussier@gmail.com>2021-05-19 16:07:24 +0200
committerJean Boussier <jean.boussier@gmail.com>2021-05-19 16:24:18 +0200
commit441958396f40d526a62e564761d2bad534465a5b (patch)
treed8fe066d81bafe293c34d600e9fe58a130505cae /test
parent3fabcb953f04b4c4927b419d6d91026f65e984af (diff)
downloadpsych-441958396f40d526a62e564761d2bad534465a5b.tar.gz
Implement YAML.safe_dump to make safe_load more usable.
In case where Psych is used as a two way serializers, e.g. to serialize some cache or config, it is preferable to have the same restrictions on both load and dump. Otherwise you might dump and persist some objects payloads that you later won't be able to read.
Diffstat (limited to 'test')
-rw-r--r--test/psych/test_psych.rb57
1 files changed, 57 insertions, 0 deletions
diff --git a/test/psych/test_psych.rb b/test/psych/test_psych.rb
index 256ed91..c9d39c5 100644
--- a/test/psych/test_psych.rb
+++ b/test/psych/test_psych.rb
@@ -381,4 +381,61 @@ hoge:
result = Psych.safe_load(yaml, symbolize_names: true)
assert_equal result, { foo: { bar: "baz", 1 => 2 }, hoge: [{ fuga: "piyo" }] }
end
+
+ def test_safe_dump_defaults
+ yaml = <<-eoyml
+---
+array:
+- 1
+float: 13.12
+booleans:
+- true
+- false
+eoyml
+
+ payload = YAML.safe_dump({
+ "array" => [1],
+ "float" => 13.12,
+ "booleans" => [true, false],
+ })
+ assert_equal yaml, payload
+ end
+
+ def test_safe_dump_unpermitted_class
+ error = assert_raises Psych::DisallowedClass do
+ YAML.safe_dump(Object.new)
+ end
+ assert_equal "Tried to dump unspecified class: Object", error.message
+
+ hash_subclass = Class.new(Hash)
+ error = assert_raises Psych::DisallowedClass do
+ YAML.safe_dump(hash_subclass.new)
+ end
+ assert_equal "Tried to dump unspecified class: #{hash_subclass.inspect}", error.message
+ end
+
+ def test_safe_dump_extra_permitted_classes
+ assert_equal "--- !ruby/object {}\n", YAML.safe_dump(Object.new, permitted_classes: [Object])
+ end
+
+ def test_safe_dump_symbols
+ error = assert_raises Psych::DisallowedClass do
+ YAML.safe_dump(:foo, permitted_classes: [Symbol])
+ end
+ assert_equal "Tried to dump unspecified class: Symbol(:foo)", error.message
+
+ assert_equal "--- :foo\n", YAML.safe_dump(:foo, permitted_classes: [Symbol], permitted_symbols: [:foo])
+ end
+
+ def test_safe_dump_aliases
+ x = []
+ x << x
+ error = assert_raises Psych::BadAlias do
+ YAML.safe_dump(x)
+ end
+ assert_equal "Tried to dump an aliased object", error.message
+
+ assert_equal "--- &1\n" + "- *1\n", YAML.safe_dump(x, aliases: true)
+ end
+
end