Skip to content
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

Support assertions on System.Text.Json.JsonSerializerOptions based (de)serialization #2246

Draft
wants to merge 6 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -392,3 +392,5 @@ dotnet_diagnostic.MA0047.severity = none

# Use an overload of 'GetHashCode' that has a StringComparison parameter
dotnet_diagnostic.MA0074.severity = none

dotnet_diagnostic.VSSpell001.severity = suggestion # Correct spelling.
24 changes: 24 additions & 0 deletions Src/FluentAssertions/AssertionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
#if !NETSTANDARD2_0
using FluentAssertions.Events;
#endif
#if NET6_0_OR_GREATER
using System.Text.Json;
using FluentAssertions.Json;
#endif

namespace FluentAssertions;

Expand Down Expand Up @@ -467,6 +471,26 @@ public static NullableTimeOnlyAssertions Should(this TimeOnly? actualValue)
return new NullableTimeOnlyAssertions(actualValue);
}

/// <summary>
/// Returns an <see cref="JsonElementAssertions"/> object that can be used to assert the
/// current <see cref="JsonElement"/>.
/// </summary>
[Pure]
public static JsonElementAssertions Should(this JsonElement actualValue)
{
return new JsonElementAssertions(actualValue);
}

/// <summary>
/// Returns an <see cref="JsonSerializerOptionsAssertions"/> object that can be used to assert the
/// current <see cref="JsonSerializerOptions"/>.
/// </summary>
[Pure]
public static JsonSerializerOptionsAssertions Should(this JsonSerializerOptions actualValue)
{
return new JsonSerializerOptionsAssertions(actualValue);
}

#endif

/// <summary>
Expand Down
7 changes: 6 additions & 1 deletion Src/FluentAssertions/FluentAssertions.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<!-- To reduce build times, we only enable analyzers for the newest TFM -->
<PropertyGroup>
Expand Down Expand Up @@ -65,6 +65,7 @@
<When Condition="'$(TargetFramework)' == 'netcoreapp3.0'">
<ItemGroup>
<Compile Remove="Common/NullConfigurationStore.cs" />
<Compile Remove="Json/*.cs" />
<Compile Remove="SystemExtensions.cs" />
</ItemGroup>
<ItemGroup>
Expand All @@ -74,6 +75,7 @@
<When Condition="'$(TargetFramework)' == 'netcoreapp2.1'">
<ItemGroup>
<Compile Remove="Common/NullConfigurationStore.cs" />
<Compile Remove="Json/*.cs" />
<Compile Remove="SystemExtensions.cs" />
</ItemGroup>
<ItemGroup>
Expand All @@ -84,6 +86,7 @@
<ItemGroup>
<Compile Remove="Common/AppSettingsConfigurationStore.cs" />
<Compile Remove="Common/ConfigurationStoreExceptionInterceptor.cs" />
<Compile Remove="Json/*.cs" />
<Compile Remove="SystemExtensions.cs" />
</ItemGroup>
</When>
Expand All @@ -93,6 +96,7 @@
<Compile Remove="Common/ConfigurationStoreExceptionInterceptor.cs" />
<Compile Remove="Events/*.cs" />
<Compile Remove="EventRaisingExtensions.cs" />
<Compile Remove="Json/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.0" />
Expand All @@ -101,6 +105,7 @@
<When Condition="'$(TargetFramework)' == 'net47'">
<ItemGroup>
<Compile Remove="Common/NullConfigurationStore.cs" />
<Compile Remove="Json/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.0" />
Expand Down
150 changes: 150 additions & 0 deletions Src/FluentAssertions/Json/JsonElementAssertions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
using System.Diagnostics;
using System.Text.Json;
using FluentAssertions.Execution;

namespace FluentAssertions.Json;

/// <summary>
/// Contains a number of methods to assert that an <see cref="JsonElement" /> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class JsonElementAssertions
{
public JsonElement Subject { get; }

/// <summary>
/// Initializes a new instance of the <see cref="JsonElementAssertions" /> class.
/// </summary>
/// <param name="subject">The subject.</param>
public JsonElementAssertions(JsonElement subject)
{
Subject = subject;
}

/// <summary>
/// Asserts that the current <see cref="JsonElement"/> has the specified <see cref="JsonValueKind"/>.
/// </summary>
/// <param name="valueKind">The JSON string.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndConstraint<JsonElementAssertions> HaveValueKind(JsonValueKind valueKind, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.ValueKind == valueKind)
.FailWith("Expected {context:JSON} to have value kind {0}{reason}, but found {1}.", valueKind, Subject.ValueKind);

return new(this);

Check notice on line 42 in Src/FluentAssertions/Json/JsonElementAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Use preferred style of 'new' expression when created type is not evident

Missing type specification
}

/// <summary>
/// Asserts that the current <see cref="JsonElement"/> is the JSON null node.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndConstraint<JsonElementAssertions> BeNull(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.ValueKind == JsonValueKind.Null)
.FailWith("Expected {context:JSON} to be a JSON null{reason}, but found {0}.", Subject);

return new(this);

Check notice on line 62 in Src/FluentAssertions/Json/JsonElementAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Use preferred style of 'new' expression when created type is not evident

Missing type specification
}

/// <summary>
/// Asserts that the current <see cref="JsonElement"/> is the JSON string node.
/// </summary>
/// <param name="value">The value of the JSON string node.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndConstraint<JsonElementAssertions> BeString(string value, string because = "", params object[] becauseArgs)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use Be() in every case? The type info on the method name is redundant.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I considered that, and if we would only assert on simple nodes, that might would be sufficient.

However, if the JSON is a complex structure, you might want to assert against the JSON string it results in, what is different then the a JSON string node/element. Besides that, it also makes implicit that both the value and the element type are asserted.

In general, what the API should look like for JSON array, and JSON object results, is something I'm still thinking about. I think I personally would use this to assert on the full JSON result as a string:

options.Should().Serialize(myComplexModel)
    And.Shoud().Be("{ 'prop': 'Value', 'other': 12, children: [ ]}");

but others might opt for:

options.Should().Serialize(myComplexModel)
    And.Shoud().Be(new()
    {
        prop = "Value" ,
        other = 12,
        children = Array.Empty<object>()
     });

Where the anonymous object is used to represent the JsonElement. The latter is normally used for BeEquivalent(), but I'm wondering if that has meaning for this kind of assertions.

I'm also wondering if we want the opposite of BeString(), etc. Because, what does that say? That I except something not to be a string? Or a string, but with a different value?!

{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.ValueKind == JsonValueKind.String && Subject.GetString() == value)
.FailWith("Expected {context:JSON} to be a JSON string {0}{reason}, but found {1}.", value, Subject);

return new(this);

Check notice on line 83 in Src/FluentAssertions/Json/JsonElementAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Use preferred style of 'new' expression when created type is not evident

Missing type specification
}

/// <summary>
/// Asserts that the current <see cref="JsonElement"/> is the JSON number node.
/// </summary>
/// <param name="value">The value of the JSON number node.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndConstraint<JsonElementAssertions> BeNumber(decimal value, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.ValueKind == JsonValueKind.Number && Subject.GetDecimal() == value)
.FailWith("Expected {context:JSON} to be a JSON string {0}{reason}, but found {1}.", value, Subject);

return new(this);

Check notice on line 104 in Src/FluentAssertions/Json/JsonElementAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Use preferred style of 'new' expression when created type is not evident

Missing type specification
}

/// <inheritdoc cref="BeNumber(decimal, string, object[])"/>
public AndConstraint<JsonElementAssertions> BeNumber(long value, string because = "", params object[] becauseArgs)
=> BeNumber((decimal)value, because, becauseArgs);

/// <summary>
/// Asserts that the current <see cref="JsonElement"/> is the JSON true node.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndConstraint<JsonElementAssertions> BeTrue(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.ValueKind == JsonValueKind.True)
.FailWith("Expected {context:JSON} to be a JSON true{reason}, but found {0}.", Subject);

return new(this);

Check notice on line 128 in Src/FluentAssertions/Json/JsonElementAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Use preferred style of 'new' expression when created type is not evident

Missing type specification
}

/// <summary>
/// Asserts that the current <see cref="JsonElement"/> is the JSON false node.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndConstraint<JsonElementAssertions> BeFalse(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.ValueKind == JsonValueKind.False)
.FailWith("Expected {context:JSON} to be JSON false{reason}, but found {0}.", Subject);

return new(this);

Check notice on line 148 in Src/FluentAssertions/Json/JsonElementAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Use preferred style of 'new' expression when created type is not evident

Missing type specification
}
}
124 changes: 124 additions & 0 deletions Src/FluentAssertions/Json/JsonSerializerOptionsAssertions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using FluentAssertions.Common;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;

namespace FluentAssertions.Json;

/// <summary>
/// Contains a number of methods to assert that an <see cref="JsonSerializerOptions" /> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class JsonSerializerOptionsAssertions : ReferenceTypeAssertions<JsonSerializerOptions, JsonSerializerOptionsAssertions>
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializerOptionsAssertions" /> class.
/// </summary>
/// <param name="subject">The subject.</param>
public JsonSerializerOptionsAssertions(JsonSerializerOptions subject)
: base(subject)
{
}

protected override string Identifier => "options";

/// <summary>
/// Asserts that the current <see cref="JsonSerializerOptions"/> can be used to deserialize the specified JSON string.
/// </summary>
/// <typeparam name="T">The type to serialize to.</typeparam>
/// <param name="json">The JSON string.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="json"/> is <see langword="null"/>.</exception>
public AndWhichConstraint<JsonSerializerOptionsAssertions, T> Deserialize<T>(Stream json, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(json);

Execute.Assertion
.ForCondition(Subject is { })

Check notice on line 47 in Src/FluentAssertions/Json/JsonSerializerOptionsAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Arrange null checking pattern

Inconsistent null checking pattern style
.FailWith("Can not use {context} to deserialize from JSON as it is <null>.");

T deserialzed = TryDeserialize<T>(json, out Exception failure);

Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(failure is null)
.FailWith("Expected {context:the options} to deserialize {0}{reason}, but it failed: {1}.", json, failure?.Message);

return new AndWhichConstraint<JsonSerializerOptionsAssertions, T>(this, deserialzed);
}

/// <inheritdoc cref="Deserialize{T}(Stream, string, object[])"/>
public AndWhichConstraint<JsonSerializerOptionsAssertions, T> Deserialize<T>(string json, string because = "", params object[] becauseArgs)
{
Stream stream = json is null ? null : new MemoryStream(Encoding.UTF8.GetBytes(json));
return Deserialize<T>(stream, because, becauseArgs);
}

/// <summary>
/// Asserts that the current <see cref="JsonSerializerOptions"/> can be used to serialize the specified value.
/// </summary>
/// <typeparam name="T">The type to serialize to.</typeparam>
/// <param name="value">The value to serialize.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see paramref="because" />.
/// </param>
public AndWhichConstraint<JsonSerializerOptionsAssertions, JsonElement> Serialize<T>(T value, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(Subject is { })

Check notice on line 82 in Src/FluentAssertions/Json/JsonSerializerOptionsAssertions.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Arrange null checking pattern

Inconsistent null checking pattern style
.FailWith("Can not use {context} to serialize to JSON as it is <null>.");

JsonElement serialized = TrySerialize(value, out Exception failure);

Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(failure is null)
.FailWith("Expected {context:the options} to serialize {0}{reason}, but it failed: {1}.", value, failure?.Message);

return new AndWhichConstraint<JsonSerializerOptionsAssertions, JsonElement>(this, serialized);
}

private T TryDeserialize<T>(Stream json, out Exception failure)
{
try
{
failure = null;
return JsonSerializer.Deserialize<T>(json, Subject);
}
catch (Exception exception)
{
failure = exception;
return default;
}
}

private JsonElement TrySerialize<T>(T value, out Exception failure)
{
try
{
failure = null;
var bytes = JsonSerializer.SerializeToUtf8Bytes(value, Subject);
using var doc = JsonDocument.Parse(bytes);
return doc.RootElement.Clone();
}
catch (Exception exception)
{
failure = exception;
return default;
}
}
}
4 changes: 4 additions & 0 deletions Tests/FluentAssertions.Specs/FluentAssertions.Specs.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
<Compile Remove="Events\*.cs" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' != 'net6.0' ">
<Compile Remove="Json\*.cs" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net47'">
<!--
(SRCU = System.Runtime.CompilerServices.Unsafe)
Expand Down