forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCustomConverterTests.cs
More file actions
222 lines (179 loc) · 8.41 KB
/
CustomConverterTests.cs
File metadata and controls
222 lines (179 loc) · 8.41 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.IO;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
[Fact]
public static void MultipleConvertersInObjectArray()
{
const string expectedJson = @"[""?"",{""TypeDiscriminator"":1,""CreditLimit"":100,""Name"":""C""},null]";
var options = new JsonSerializerOptions();
options.Converters.Add(new MyBoolEnumConverter());
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
Customer customer = new Customer();
customer.CreditLimit = 100;
customer.Name = "C";
MyBoolEnum myBoolEnum = MyBoolEnum.Unknown;
MyBoolEnum? myNullBoolEnum = null;
string json = JsonSerializer.Serialize(new object[] { myBoolEnum, customer, myNullBoolEnum }, options);
Assert.Equal(expectedJson, json);
JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json, options);
string jsonElementString = jsonElement.ToString();
Assert.Equal(expectedJson, jsonElementString);
}
[Fact]
public static void OptionsArePassedToCreateConverter()
{
TestFactory factory = new TestFactory();
JsonSerializerOptions options = new JsonSerializerOptions { Converters = { factory } };
string json = JsonSerializer.Serialize("Test", options);
Assert.Equal(@"""Test""", json);
Assert.Same(options, factory.Options);
}
public class TestFactory : JsonConverterFactory
{
public JsonSerializerOptions Options { get; private set; }
public override bool CanConvert(Type typeToConvert) => true;
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
Options = options;
return new SimpleConverter();
}
public class SimpleConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
=> writer.WriteStringValue(value);
}
}
private class ConverterReturningNull : JsonConverter<Customer>
{
public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Assert.Equal(JsonTokenType.StartObject, reader.TokenType);
bool rc = reader.Read();
Assert.True(rc);
Assert.Equal(JsonTokenType.EndObject, reader.TokenType);
return null;
}
public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
{
throw new NotSupportedException();
}
}
[Fact]
public static void VerifyConverterWithTrailingWhitespace()
{
string json = "{} ";
var options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
byte[] utf8 = Encoding.UTF8.GetBytes(json);
// The serializer will finish reading the whitespace and no exception will be thrown.
Customer c = JsonSerializer.Deserialize<Customer>(utf8, options);
Assert.Null(c);
}
[Fact]
public static void VerifyConverterWithTrailingComments()
{
string json = "{} //";
byte[] utf8 = Encoding.UTF8.GetBytes(json);
// Disallow comments
var options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Customer>(utf8, options));
// Skip comments
options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
options.ReadCommentHandling = JsonCommentHandling.Skip;
Customer c = JsonSerializer.Deserialize<Customer>(utf8, options);
Assert.Null(c);
}
public class ObjectBoolConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True)
{
return true;
}
if (reader.TokenType == JsonTokenType.False)
{
return false;
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
[Fact]
public static void VerifyObjectConverterWithPreservedReferences()
{
var json = "true";
byte[] utf8 = Encoding.UTF8.GetBytes(json);
var options = new JsonSerializerOptions()
{
ReferenceHandler = ReferenceHandler.Preserve,
};
options.Converters.Add(new ObjectBoolConverter());
object obj = (JsonSerializer.Deserialize<object>(utf8, options));
Assert.IsType<bool>(obj);
Assert.Equal(true, obj);
}
[Fact]
public static void GetConverterRootsBuiltInConverters()
{
JsonSerializerOptions options = new();
RunTest<DateTime>();
RunTest<Point_2D>();
void RunTest<TConverterReturn>()
{
JsonConverter converter = options.GetConverter(typeof(TConverterReturn));
Assert.NotNull(converter);
Assert.True(converter is JsonConverter<TConverterReturn>);
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/66232", TargetFrameworkMonikers.NetFramework)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/66371", typeof(PlatformDetection), nameof(PlatformDetection.IsMonoInterpreter))]
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void GetConverter_Poco_WriteThrowsNotSupportedException()
{
RemoteExecutor.Invoke(static () =>
{
JsonSerializerOptions options = new();
JsonConverter<Point_2D> converter = (JsonConverter<Point_2D>)options.GetConverter(typeof(Point_2D));
using var writer = new Utf8JsonWriter(new MemoryStream());
var value = new Point_2D(0, 0);
// Running the converter without priming the options instance
// for reflection-based serialization should throw NotSupportedException
// since it can't resolve reflection-based metadata.
Assert.Throws<NotSupportedException>(() => converter.Write(writer, value, options));
Debug.Assert(writer.BytesCommitted + writer.BytesPending == 0);
JsonSerializer.Serialize(42, options);
// Same operation should succeed when instance has been primed.
converter.Write(writer, value, options);
Debug.Assert(writer.BytesCommitted + writer.BytesPending > 0);
writer.Reset();
// State change should not leak into unrelated options instances.
var options2 = new JsonSerializerOptions();
options2.AddContext<JsonContext>();
Assert.Throws<NotSupportedException>(() => converter.Write(writer, value, options2));
Debug.Assert(writer.BytesCommitted + writer.BytesPending == 0);
}).Dispose();
}
[Fact]
public static void GetConverterTypeToConvertNull()
{
Assert.Throws<ArgumentNullException>(() => (new JsonSerializerOptions()).GetConverter(typeToConvert: null!));
}
}
}