-
-
Notifications
You must be signed in to change notification settings - Fork 158
openapi: support validation attributes #1477
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
Merged
bkoelman
merged 27 commits into
json-api-dotnet:openapi
from
verdie-g:1055-openapi-model-validation
Jun 21, 2024
Merged
Changes from 5 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
e2a1ac4
openapi: support validation attributes
verdie-g 9dee70f
wip
verdie-g 07c9d7d
Improve NSwag tests
verdie-g 43bae11
Fix some warnings
verdie-g 0812983
Address some comments
verdie-g f04ec26
more stuff
verdie-g 2e28ac0
Discard unrelated changes
verdie-g 6c78d76
Discard more unrealted changes
verdie-g 90fd171
Add test for length attribute on collection
verdie-g 3dd960e
Address PR comments
verdie-g 0b7976b
stuff
verdie-g 10fe4ac
More stuff
verdie-g 0cfe1f7
Fix .NET 8 things
verdie-g 894c385
Fix coding style
verdie-g bd283c3
Set ConvertValueInInvariantCulture
verdie-g a7bc74a
Add Kiota tests
verdie-g 48541a7
Address some PR comments
verdie-g a9501ff
Add missing properties in happy test
verdie-g 15facbf
Fix CS
verdie-g 159a6c2
Convert DateTime to UTC server-side
verdie-g 225143b
Seal classes
verdie-g 8f0e849
Apply suggestions from code review
verdie-g f7ba49d
Address PR comments
verdie-g 2a9e773
Update test/OpenApiTests/ModelStateValidation/ModelStateValidationTes…
verdie-g bb22aca
Address comments
verdie-g 0238e72
Add back exclusive range
verdie-g 54fedf2
Address comment
verdie-g 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
358 changes: 358 additions & 0 deletions
358
test/OpenApiNSwagEndToEndTests/ModelStateValidation/ModelStateValidationTests.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,358 @@ | ||
using FluentAssertions; | ||
using FluentAssertions.Specialized; | ||
using JsonApiDotNetCore.OpenApi.Client.NSwag; | ||
using Newtonsoft.Json; | ||
using OpenApiNSwagEndToEndTests.ModelStateValidation.GeneratedCode; | ||
using OpenApiTests; | ||
using OpenApiTests.ModelStateValidation; | ||
using TestBuildingBlocks; | ||
using Xunit; | ||
using Xunit.Abstractions; | ||
|
||
namespace OpenApiNSwagEndToEndTests.ModelStateValidation; | ||
|
||
public sealed class ModelStateValidationTests : IClassFixture<IntegrationTestContext<OpenApiStartup<ModelStateValidationDbContext>, ModelStateValidationDbContext>> | ||
{ | ||
private readonly IntegrationTestContext<OpenApiStartup<ModelStateValidationDbContext>, ModelStateValidationDbContext> _testContext; | ||
private readonly XUnitLogHttpMessageHandler _logHttpMessageHandler; | ||
private readonly ModelStateValidationFakers _fakers = new(); | ||
|
||
public ModelStateValidationTests(IntegrationTestContext<OpenApiStartup<ModelStateValidationDbContext>, ModelStateValidationDbContext> testContext, ITestOutputHelper testOutputHelper) | ||
{ | ||
_testContext = testContext; | ||
_logHttpMessageHandler = new XUnitLogHttpMessageHandler(testOutputHelper); | ||
|
||
testContext.UseController<SocialMediaAccountsController>(); | ||
} | ||
|
||
[Fact] | ||
public async Task xxx() | ||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest() | ||
} | ||
}); | ||
|
||
// Assert | ||
ExceptionAssertions<JsonSerializationException> assertion = await action.Should().ThrowExactlyAsync<JsonSerializationException>(); | ||
assertion.Which.Message.Should().Be("Cannot write a null value for property 'lastName'. Property requires a value. Path 'data.attributes'."); | ||
} | ||
|
||
[Theory] | ||
[InlineData("ab")] | ||
[InlineData("abcdefghijklmnopqrs")] | ||
public async Task Cannot_exceed_length_constraint(string userName) | ||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
UserName = userName | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("The field UserName must be a string with a minimum length of 3 and a maximum length of 18."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/userName"); | ||
} | ||
|
||
[Fact] | ||
public async Task Cannot_violate_regular_expression_constraint() | ||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
UserName = "aB1" | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("Only letters are allowed."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/userName"); | ||
} | ||
|
||
[Fact] | ||
public async Task Cannot_use_invalid_credit_card() | ||
bkoelman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
CreditCard = "123-456" | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("The CreditCard field is not a valid credit card number."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/creditCard"); | ||
} | ||
|
||
[Fact] | ||
public async Task Cannot_use_invalid_email() | ||
bkoelman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
Email = "abc" | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("The Email field is not a valid e-mail address."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/email"); | ||
} | ||
|
||
[Theory] | ||
[InlineData(-1)] | ||
[InlineData(-0.56)] | ||
[InlineData(123.98)] | ||
[InlineData(124)] | ||
public async Task Cannot_use_double_outside_of_valid_range(int age) | ||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
Age = age | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("The field Age must be between 0 and 123."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/age"); | ||
} | ||
|
||
[Fact] | ||
public async Task Cannot_use_invalid_url() | ||
bkoelman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
BackgroundPicture = new Uri("/justapath", UriKind.Relative) | ||
bkoelman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("The BackgroundPicture field is not a valid fully-qualified http, https, or ftp URL."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/backgroundPicture"); | ||
} | ||
|
||
[Fact] | ||
public async Task Cannot_use_TimeSpan_outside_of_valid_range() | ||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
NextRevalidation = "00:00:01" | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Input validation failed."); | ||
errorObject.Detail.Should().Be("The field NextRevalidation must be between 01:00:00 and 05:00:00."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/nextRevalidation"); | ||
} | ||
|
||
[Fact] | ||
public async Task Cannot_use_invalid_TimeOnly() | ||
bkoelman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
LastName = socialMediaAccount.LastName, | ||
ValidatedAtTime = TimeSpan.FromSeconds(-1) | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
ErrorResponseDocument document = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which.Result; | ||
document.Errors.ShouldHaveCount(1); | ||
|
||
ErrorObject errorObject = document.Errors.First(); | ||
errorObject.Title.Should().Be("Failed to deserialize request body: Incompatible attribute value found."); | ||
errorObject.Detail.Should().Be("Failed to convert attribute 'validatedAtTime' with value '-00:00:01' of type 'String' to type 'Nullable<TimeOnly>'."); | ||
errorObject.Source.ShouldNotBeNull(); | ||
errorObject.Source.Pointer.Should().Be("/data/attributes/validatedAtTime"); | ||
} | ||
|
||
[Fact] | ||
public async Task Can_create_resource_with_valid_properties() | ||
{ | ||
// Arrange | ||
SocialMediaAccount socialMediaAccount = _fakers.SocialMediaAccount.Generate(); | ||
bkoelman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
using HttpClient httpClient = _testContext.Factory.CreateDefaultClient(_logHttpMessageHandler); | ||
ModelStateValidationClient apiClient = new(httpClient); | ||
|
||
// Act | ||
Func<Task<SocialMediaAccountPrimaryResponseDocument>> action = () => apiClient.PostSocialMediaAccountAsync(new SocialMediaAccountPostRequestDocument | ||
{ | ||
Data = new SocialMediaAccountDataInPostRequest | ||
{ | ||
Attributes = new SocialMediaAccountAttributesInPostRequest | ||
{ | ||
FirstName = socialMediaAccount.FirstName, | ||
GivenName = socialMediaAccount.GivenName, | ||
LastName = socialMediaAccount.LastName, | ||
UserName = socialMediaAccount.UserName, | ||
CreditCard = socialMediaAccount.CreditCard, | ||
Email = socialMediaAccount.Email, | ||
Phone = socialMediaAccount.Phone, | ||
Age = socialMediaAccount.Age, | ||
ProfilePicture = socialMediaAccount.ProfilePicture, | ||
BackgroundPicture = new Uri(socialMediaAccount.BackgroundPicture!), | ||
NextRevalidation = "02:00:00", | ||
ValidatedAt = socialMediaAccount.ValidatedAt!, | ||
ValidatedAtDate = new DateTimeOffset(socialMediaAccount.ValidatedAtDate!.Value.ToDateTime(new TimeOnly()).ToUniversalTime()), | ||
ValidatedAtTime = socialMediaAccount.ValidatedAtTime!.Value.ToTimeSpan() | ||
} | ||
} | ||
}); | ||
|
||
// Assert | ||
await action.Should().NotThrowAsync(); | ||
} | ||
} |
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
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.
Uh oh!
There was an error while loading. Please reload this page.