forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonNetTests.cs
More file actions
261 lines (226 loc) · 8.35 KB
/
JsonNetTests.cs
File metadata and controls
261 lines (226 loc) · 8.35 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql.Tests;
using NpgsqlTypes;
using NUnit.Framework;
using System;
using System.Text;
using System.Threading.Tasks;
// ReSharper disable AccessToModifiedClosure
// ReSharper disable AccessToDisposedClosure
namespace Npgsql.PluginTests;
/// <summary>
/// Tests for the Npgsql.Json.NET mapping plugin
/// </summary>
[NonParallelizable]
[TestFixture(NpgsqlDbType.Jsonb)]
[TestFixture(NpgsqlDbType.Json)]
public class JsonNetTests : TestBase
{
[Test]
public Task Roundtrip_object()
=> AssertType(
JsonDataSource,
new Foo { Bar = 8 },
IsJsonb ? @"{""Bar"": 8}" : @"{""Bar"":8}",
_pgTypeName,
_npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3085")]
public Task Roundtrip_string()
=> AssertType(
JsonDataSource,
@"{""p"": 1}",
@"{""p"": 1}",
_pgTypeName,
_npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3085")]
public Task Roundtrip_char_array()
=> AssertType(
JsonDataSource,
@"{""p"": 1}".ToCharArray(),
@"{""p"": 1}",
_pgTypeName,
_npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3085")]
public Task Roundtrip_byte_array()
=> AssertType(
JsonDataSource,
Encoding.ASCII.GetBytes(@"{""p"": 1}"),
@"{""p"": 1}",
_pgTypeName,
_npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test]
public Task Roundtrip_JObject()
=> AssertType(
JsonDataSource,
new JObject { ["Bar"] = 8 },
IsJsonb ? @"{""Bar"": 8}" : @"{""Bar"":8}",
_pgTypeName,
_npgsqlDbType,
// By default we map JObject to jsonb
isDefaultForWriting: IsJsonb,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test]
public Task Roundtrip_JArray()
=> AssertType(
JsonDataSource,
new JArray(new[] { 1, 2, 3 }),
IsJsonb ? "[1, 2, 3]" : "[1,2,3]",
_pgTypeName,
_npgsqlDbType,
// By default we map JArray to jsonb
isDefaultForWriting: IsJsonb,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test]
public async Task Deserialize_failure()
{
await using var conn = await JsonDataSource.OpenConnectionAsync();
await using var cmd = new NpgsqlCommand($@"SELECT '[1, 2, 3]'::{_pgTypeName}", conn);
await using var reader = await cmd.ExecuteReaderAsync();
await reader.ReadAsync();
// Attempt to deserialize JSON array into object
Assert.That(() => reader.GetFieldValue<Foo>(0), Throws.TypeOf<JsonSerializationException>());
// State should still be OK to continue
var actual = reader.GetFieldValue<JArray>(0);
Assert.That((int)actual[0], Is.EqualTo(1));
}
[Test]
public async Task Clr_type_mapping()
{
var dataSourceBuilder = CreateDataSourceBuilder();
if (IsJsonb)
dataSourceBuilder.UseJsonNet(jsonbClrTypes: new[] { typeof(Foo) });
else
dataSourceBuilder.UseJsonNet(jsonClrTypes: new[] { typeof(Foo) });
await using var dataSource = dataSourceBuilder.Build();
await AssertType(
dataSource,
new Foo { Bar = 8 },
IsJsonb ? @"{""Bar"": 8}" : @"{""Bar"":8}",
_pgTypeName,
_npgsqlDbType,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
}
[Test]
public async Task Roundtrip_clr_array()
{
var dataSourceBuilder = CreateDataSourceBuilder();
if (IsJsonb)
dataSourceBuilder.UseJsonNet(jsonbClrTypes: new[] { typeof(int[]) });
else
dataSourceBuilder.UseJsonNet(jsonClrTypes: new[] { typeof(int[]) });
await using var dataSource = dataSourceBuilder.Build();
await AssertType(
dataSource,
new[] { 1, 2, 3 },
IsJsonb ? "[1, 2, 3]" : "[1,2,3]",
_pgTypeName,
_npgsqlDbType,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
}
class DateWrapper
{
public DateTime Date;
public override bool Equals(object? obj) => (obj as DateWrapper)?.Date == Date;
public override int GetHashCode() => Date.GetHashCode();
}
[Test]
public async Task Custom_serializer_settings()
{
var settings = new JsonSerializerSettings { DateFormatString = @"T\he d\t\h o\f MMMM, yyyy" };
var dataSourceBuilder = CreateDataSourceBuilder();
if (IsJsonb)
dataSourceBuilder.UseJsonNet(jsonbClrTypes: new[] { typeof(DateWrapper) }, settings: settings);
else
dataSourceBuilder.UseJsonNet(jsonClrTypes: new[] { typeof(DateWrapper) }, settings: settings);
await using var dataSource = dataSourceBuilder.Build();
await AssertType(
dataSource,
new DateWrapper { Date = new DateTime(2018, 04, 20) },
IsJsonb ? "{\"Date\": \"The 20th of April, 2018\"}" : "{\"Date\":\"The 20th of April, 2018\"}",
_pgTypeName,
_npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
}
[Test]
public async Task Bug3464()
{
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.UseJsonNet(jsonbClrTypes: new[] { typeof(Bug3464Class) });
await using var dataSource = dataSourceBuilder.Build();
var expected = new Bug3464Class { SomeString = new string('5', 8174) };
await using var conn = await dataSource.OpenConnectionAsync();
await using var cmd = new NpgsqlCommand(@"SELECT @p1, @p2", conn);
cmd.Parameters.AddWithValue("p1", expected).NpgsqlDbType = _npgsqlDbType;
cmd.Parameters.AddWithValue("p2", expected).NpgsqlDbType = _npgsqlDbType;
await using var reader = cmd.ExecuteReader();
}
public class Bug3464Class
{
public string? SomeString { get; set; }
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4537")]
public async Task Write_jobject_array_without_npgsqldbtype()
{
// By default we map JObject to jsonb
if (!IsJsonb)
return;
await using var conn = await JsonDataSource.OpenConnectionAsync();
var tableName = await TestUtil.CreateTempTable(conn, "key SERIAL PRIMARY KEY, ingredients json[]");
await using var cmd = new NpgsqlCommand { Connection = conn };
var jsonObject1 = new JObject
{
{ "name", "value1" },
{ "amount", 1 },
{ "unit", "ml" }
};
var jsonObject2 = new JObject
{
{ "name", "value2" },
{ "amount", 2 },
{ "unit", "g" }
};
cmd.CommandText = $"INSERT INTO {tableName} (ingredients) VALUES (@p)";
cmd.Parameters.Add(new("p", new[] { jsonObject1, jsonObject2 }));
await cmd.ExecuteNonQueryAsync();
}
class Foo
{
public int Bar { get; set; }
public override bool Equals(object? obj) => (obj as Foo)?.Bar == Bar;
public override int GetHashCode() => Bar.GetHashCode();
}
readonly NpgsqlDbType _npgsqlDbType;
readonly string _pgTypeName;
[OneTimeSetUp]
public void SetUp()
{
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.UseJsonNet();
JsonDataSource = dataSourceBuilder.Build();
}
[OneTimeTearDown]
public async Task Teardown()
=> await JsonDataSource.DisposeAsync();
public JsonNetTests(NpgsqlDbType npgsqlDbType)
{
_npgsqlDbType = npgsqlDbType;
_pgTypeName = npgsqlDbType.ToString().ToLower();
}
bool IsJsonb => _npgsqlDbType == NpgsqlDbType.Jsonb;
NpgsqlDataSource JsonDataSource = default!;
}