Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2506,6 +2506,51 @@ public void StringsThatMatchKeywordsAreQuoted(string input)
Assert.Equal($"text: \"{input}\"{Environment.NewLine}", yaml);
}

[Theory]
[InlineData("~")]
[InlineData("null")]
[InlineData("Null")]
[InlineData("NULL")]
public void StringsThatResolveToNullAreQuotedByDefault(string input)
{
// Without quoting these round-trip back to null even for a string target (#493).
var yaml = Serializer.Serialize(input);
Assert.Equal($"\"{input}\"{Environment.NewLine}", yaml);
Assert.Equal(input, Deserializer.Deserialize<string>(yaml));
}

[Theory]
[InlineData("nUll")]
[InlineData("nul")]
[InlineData("nullish")]
[InlineData("hello")]
public void StringsThatOnlyResembleNullAreNotQuoted(string input)
{
var yaml = Serializer.Serialize(input);
Assert.Equal($"{input}{Environment.NewLine}", yaml);
Assert.Equal(input, Deserializer.Deserialize<string>(yaml));
}

[Fact]
public void ActualNullStillSerializesAsBareNull()
{
string value = null;
var yaml = Serializer.Serialize(value);
Assert.Null(Deserializer.Deserialize<string>(yaml));
}

[Theory]
[InlineData("~")]
[InlineData("null")]
[InlineData("Null")]
[InlineData("NULL")]
public void NullTokenDictionaryValuesRoundtripAsStrings(string input)
{
var data = new Dictionary<string, string> { { "k", input } };
var result = DoRoundtripFromObjectTo<Dictionary<string, string>>(data);
Assert.Equal(input, result["k"]);
}

public static IEnumerable<object[]> Yaml1_1SpecialStringsData = new[]
{
"-.inf", "-.Inf", "-.INF", "-0", "-0100_200", "-0b101", "-0x30", "-190:20:30", "-23", "-3.14",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
{
suggestedStyle = ScalarStyle.DoubleQuoted;
}
else if (ResolvesToNull(eventInfo.RenderedValue))
{
// A plain null token would deserialize back to null, losing the string (#493).
suggestedStyle = ScalarStyle.DoubleQuoted;
}
else
{
suggestedStyle = defaultScalarStyle;
Expand Down Expand Up @@ -242,5 +247,9 @@ private bool IsSpecialStringValue(string value)

return isSpecialStringValue_Regex?.IsMatch(value) ?? false;
}

// Mirrors the plain tokens NullNodeDeserializer resolves to null (empty is already quoted).
private static bool ResolvesToNull(string value)
=> value == "~" || value == "null" || value == "Null" || value == "NULL";
}
}