-
Notifications
You must be signed in to change notification settings - Fork 330
Replace Newtonsoft.Json with System.Text.Json in tests and samples #4323
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
paulmedynski
wants to merge
2
commits into
dev/russellben/config-jsonc
Choose a base branch
from
dev/paul/newtonsoft
base: dev/russellben/config-jsonc
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,7 +5,7 @@ | |
| using System; | ||
| using System.IO; | ||
| using System.Runtime.Serialization.Formatters.Binary; | ||
| using Newtonsoft.Json; | ||
| using System.Text.Json; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Data.SqlClient.Tests | ||
|
|
@@ -18,46 +18,27 @@ public class SqlExceptionTest | |
| public void SerializationTest() | ||
| { | ||
| SqlException e = CreateException(); | ||
| string json = JsonConvert.SerializeObject(e); | ||
|
|
||
| var settings = new JsonSerializerSettings(); | ||
| var sqlEx = JsonConvert.DeserializeObject<SqlException>(json, settings); | ||
|
|
||
| Assert.Equal(e.ClientConnectionId, sqlEx.ClientConnectionId); | ||
| Assert.Equal(e.StackTrace, sqlEx.StackTrace); | ||
| } | ||
| // Serialize the properties we want to validate round-trip through JSON. | ||
| // SqlException cannot be directly serialized by System.Text.Json because | ||
| // Exception.TargetSite (MethodBase) is not supported. | ||
| string json = JsonSerializer.Serialize(new | ||
| { | ||
| e.Message, | ||
| ClientConnectionId = e.ClientConnectionId.ToString(), | ||
| e.Number, | ||
| e.Class, | ||
| e.State, | ||
| }); | ||
|
|
||
| [Fact] | ||
| public void JSONSerializationTest() | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test was actually a Newtonsoft unit test, which isn't something we should be testing. |
||
| { | ||
| string clientConnectionId = "90cdab4d-2145-4c24-a354-c8ccff903542"; | ||
| string json = @"{" | ||
| + @"""ClassName"":""Microsoft.Data.SqlClient.SqlException""," | ||
| + @"""Message"":""A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)""," | ||
| + @"""Data"":{""HelpLink.ProdName"":""Microsoft SQL Server""," | ||
| + @"""HelpLink.EvtSrc"":""MSSQLServer""," | ||
| + @"""HelpLink.EvtID"":""0""," | ||
| + @"""HelpLink.BaseHelpUrl"":""http://go.microsoft.com/fwlink""," | ||
| + @"""HelpLink.LinkId"":""20476""," | ||
| + @"""SqlError 1"":""Microsoft.Data.SqlClient.SqlError: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)""," | ||
| + @"""$type"":""System.Collections.ListDictionaryInternal, System.Private.CoreLib""}," | ||
| + @"""InnerException"":null," | ||
| + @"""HelpURL"":null," | ||
| + @"""StackTraceString"":"" at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionOptions connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionOptions userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)\\n at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(SqlConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, SqlConnectionOptions userOptions)\\n at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, SqlConnectionOptions options, DbConnectionPoolKey poolKey, SqlConnectionOptions userOptions)\\n at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, SqlConnectionOptions userOptions, DbConnectionInternal oldConnection)\\n at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, SqlConnectionOptions userOptions, DbConnectionInternal oldConnection)\\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, SqlConnectionOptions userOptions, DbConnectionInternal& connection)\\n at System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()\\n""," | ||
| + @"""RemoteStackTraceString"":null," | ||
| + @"""RemoteStackIndex"":0," | ||
| + @"""ExceptionMethod"":null," | ||
| + @"""HResult"":-2146232060," | ||
| + @"""Source"":""Core .Net SqlClient Data Provider""," | ||
| + @"""WatsonBuckets"":null," | ||
| + @"""Errors"":null," | ||
| + @"""ClientConnectionId"":""90cdab4d-2145-4c24-a354-c8ccff903542""" | ||
| + @"}"; | ||
| using JsonDocument doc = JsonDocument.Parse(json); | ||
| JsonElement root = doc.RootElement; | ||
|
|
||
| var settings = new JsonSerializerSettings(); | ||
| var sqlEx = JsonConvert.DeserializeObject<SqlException>(json, settings); | ||
| Assert.IsType<SqlException>(sqlEx); | ||
| Assert.Equal(clientConnectionId, sqlEx.ClientConnectionId.ToString()); | ||
| Assert.Equal(e.Message, root.GetProperty("Message").GetString()); | ||
| Assert.Equal(e.ClientConnectionId.ToString(), root.GetProperty("ClientConnectionId").GetString()); | ||
| Assert.Equal(e.Number, root.GetProperty("Number").GetInt32()); | ||
| Assert.Equal(e.Class, root.GetProperty("Class").GetByte()); | ||
| Assert.Equal(e.State, root.GetProperty("State").GetByte()); | ||
| } | ||
|
|
||
| private static SqlException CreateException() | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
84 changes: 84 additions & 0 deletions
84
src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/JsonTest/JsonTestHelper.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| using System; | ||
| using System.Linq; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Nodes; | ||
|
|
||
| namespace Microsoft.Data.SqlClient.ManualTesting.Tests.SQL.JsonTest | ||
| { | ||
| internal static class JsonTestHelper | ||
| { | ||
| // Test data is Array → Object → Value (3 levels). Use 64 as a safe ceiling. | ||
| private const int MaxDepth = 64; | ||
|
|
||
| /// <summary> | ||
| /// Performs a deep structural comparison of two <see cref="JsonElement"/> values. | ||
| /// On .NET 9+ this delegates to <see cref="JsonNode.DeepEquals"/>; on earlier | ||
| /// runtimes it uses a recursive comparison over the element trees. | ||
| /// </summary> | ||
| internal static bool JsonDeepEquals(JsonElement a, JsonElement b) | ||
| { | ||
| #if NET9_0_OR_GREATER | ||
| return JsonNode.DeepEquals( | ||
| JsonNode.Parse(a.GetRawText()), | ||
| JsonNode.Parse(b.GetRawText())); | ||
| #else | ||
| return DeepEqualsCore(a, b, depth: 0); | ||
| #endif | ||
| } | ||
|
|
||
| private static bool DeepEqualsCore(JsonElement a, JsonElement b, int depth) | ||
| { | ||
| if (depth > MaxDepth) | ||
| { | ||
| throw new InvalidOperationException($"JSON comparison exceeded maximum depth of {MaxDepth}."); | ||
| } | ||
|
|
||
| if (a.ValueKind != b.ValueKind) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| switch (a.ValueKind) | ||
| { | ||
| case JsonValueKind.Object: | ||
| int countA = a.EnumerateObject().Count(); | ||
| int countB = b.EnumerateObject().Count(); | ||
| if (countA != countB) | ||
| { | ||
| return false; | ||
| } | ||
| foreach (JsonProperty prop in a.EnumerateObject()) | ||
| { | ||
| if (!b.TryGetProperty(prop.Name, out JsonElement bValue) || | ||
| !DeepEqualsCore(prop.Value, bValue, depth + 1)) | ||
| { | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
|
|
||
| case JsonValueKind.Array: | ||
| JsonElement.ArrayEnumerator arrA = a.EnumerateArray(); | ||
| JsonElement.ArrayEnumerator arrB = b.EnumerateArray(); | ||
| while (arrA.MoveNext()) | ||
| { | ||
| if (!arrB.MoveNext() || !DeepEqualsCore(arrA.Current, arrB.Current, depth + 1)) | ||
| { | ||
| return false; | ||
| } | ||
| } | ||
| return !arrB.MoveNext(); | ||
|
|
||
| case JsonValueKind.String: | ||
| return a.GetString() == b.GetString(); | ||
|
|
||
| default: | ||
| return a.GetRawText() == b.GetRawText(); | ||
| } | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The old test was confirming that Newtonsoft round-tripping functioned, which isn't our responsibility. Now we're checking that specific fields from our SqlException can be serialized, which is still not really our responsibility, but is at least more targeted.