-
-
Notifications
You must be signed in to change notification settings - Fork 540
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
Corniel
wants to merge
6
commits into
fluentassertions:develop
Choose a base branch
from
Corniel:feature/json-assertions
base: develop
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
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
Show all changes
6 commits
Select commit
Hold shift + click to select a range
07a4c85
Initial setup.
Corniel f3eb1f8
Update documentation, and test coverage.
Corniel 3184c12
Implemented: HaveValueKind.
Corniel 87d89f6
Add assertions on JSON nodes null, string, number, true, and false.
Corniel 0347e6a
Add documentation.
Corniel 7dd7080
Use `.Which`, instead of `.And.Value`.
Corniel File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains 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 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 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 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,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); | ||
} | ||
|
||
/// <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); | ||
} | ||
|
||
/// <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) | ||
{ | ||
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); | ||
} | ||
|
||
/// <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); | ||
} | ||
|
||
/// <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); | ||
} | ||
|
||
/// <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); | ||
} | ||
} |
124 changes: 124 additions & 0 deletions
124
Src/FluentAssertions/Json/JsonSerializerOptionsAssertions.cs
This file contains 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,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 { }) | ||
.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 { }) | ||
.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; | ||
} | ||
} | ||
} |
This file contains 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
Oops, something went wrong.
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.
Why not use
Be()
in every case? The type info on the method name is redundant.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.
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:
but others might opt for:
Where the anonymous object is used to represent the
JsonElement
. The latter is normally used forBeEquivalent()
, 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?!