-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathJsonNumberHandlingTests.cs
More file actions
84 lines (76 loc) · 2.84 KB
/
JsonNumberHandlingTests.cs
File metadata and controls
84 lines (76 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.Text.Json;
using System.Text.Json.Protobuf.Tests;
using System.Text.Json.Serialization;
using Protobuf.System.Text.Json.Tests.Utils;
using Xunit;
namespace Protobuf.System.Text.Json.Tests;
public class JsonNumberHandlingTests
{
[Fact]
public void Should_deserialize_numbers_as_strings_when_NumberHandling_set_to_AllowReadingFromString()
{
// Arrange
var json =
"""
{
"doubleProperty" : "0.12",
"floatProperty" : "7.89",
"int32Property" : "123",
"int64Property" : "456",
"uint32Property" : "789",
"uint64Property" : "101112",
"sint32Property" : "1314",
"sint64Property" : "151617",
"fixed32Property" : "1819",
"fixed64Property" : "202122",
"sfixed32Property" : "2324",
"sfixed64Property" : "252627"
}
""";
var options = TestHelper.CreateJsonSerializerOptions();
options.NumberHandling = JsonNumberHandling.AllowReadingFromString;
// Act
var deserialized = JsonSerializer.Deserialize<SimpleMessage>(json, options);
// Assert
Assert.NotNull(deserialized);
Assert.Equal(0.12d, deserialized.DoubleProperty);
Assert.Equal(7.89f, deserialized.FloatProperty);
Assert.Equal(123, deserialized.Int32Property);
Assert.Equal(456L, deserialized.Int64Property);
Assert.Equal(789u, deserialized.Uint32Property);
Assert.Equal(101112ul, deserialized.Uint64Property);
Assert.Equal(1314, deserialized.Sint32Property);
Assert.Equal(151617L, deserialized.Sint64Property);
Assert.Equal(1819u, deserialized.Fixed32Property);
Assert.Equal(202122ul, deserialized.Fixed64Property);
Assert.Equal(2324, deserialized.Sfixed32Property);
Assert.Equal(252627L, deserialized.Sfixed64Property);
}
[Fact]
public void Should_fail_deserializing_numbers_as_strings_when_NumberHandling_not_set_to_AllowReadingFromString()
{
// Arrange
var json =
"""
{
"doubleProperty" : "0.12",
"floatProperty" : "7.89",
"int32Property" : "123",
"int64Property" : "456",
"uint32Property" : "789",
"uint64Property" : "101112",
"sint32Property" : "1314",
"sint64Property" : "151617",
"fixed32Property" : "1819",
"fixed64Property" : "202122",
"sfixed32Property" : "2324",
"sfixed64Property" : "252627"
}
""";
var options = TestHelper.CreateJsonSerializerOptions();
// Explicitly disable reading numbers from strings
options.NumberHandling = JsonNumberHandling.Strict;
// Act & Assert
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<SimpleMessage>(json, options));
}
}