Adds editorconfig and refactors to the established rules

This commit is contained in:
BinaryAlley committed 2024-09-23 16:48:48 +03:00
1 parent 712a0f2b27
commit cd44f11d9e
138 files changed
+1799 -1629

No files matched your search

@@ -16,8 +16,8 @@ public class RepositoryFactoryTests
public void RepositoryFactoryImplementsRepositoryFactoryInterface_InterfaceIsImplemented_ReturnsTrue()
{
// Arrange
var repositoryFactory = new RepositoryFactory(null!);
RepositoryFactory repositoryFactory = new(null!);
// Assert
Assert.True(repositoryFactory is IRepositoryFactory);
}
@@ -20,10 +20,10 @@ public class UnitOfWorkTests
public void UnitOfWorkImplementsUnitOfWorkInterface_InterfaceIsImplemented_ReturnsTrue()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Assert
Assert.True(unitOfWork is IUnitOfWork);
@@ -34,36 +34,36 @@ public class BookJsonConverter : JsonConverter<Book>
{
JsonElement root = doc.RootElement;
var id = root.GetProperty("id").GetProperty("value").GetGuid();
var created = root.GetProperty("created").GetDateTime();
var metadata = DeserializeMetadata(root.GetProperty("metadata"));
Guid id = root.GetProperty("id").GetProperty("value").GetGuid();
DateTime created = root.GetProperty("created").GetDateTime();
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
BookFormat? format = null;
if (root.TryGetProperty("format", out var formatElement))
if (root.TryGetProperty("format", out JsonElement formatElement))
{
if (formatElement.ValueKind == JsonValueKind.String)
{
var formatString = formatElement.GetString()!;
string formatString = formatElement.GetString()!;
if (Enum.TryParse(formatString, out BookFormat parsedFormat))
format = parsedFormat;
}
}
var edition = root.GetProperty("edition").GetString();
var volumeNumber = root.GetProperty("volumeNumber").GetInt32();
var series = DeserializeBookSeries(root.GetProperty("series"));
var asin = root.GetProperty("asin").GetString();
var goodreadsId = root.GetProperty("goodreadsId").GetString();
var lccn = root.GetProperty("lccn").GetString();
var oclcNumber = root.GetProperty("oclcNumber").GetString();
var openLibraryId = root.GetProperty("openLibraryId").GetString();
var libraryThingId = root.GetProperty("libraryThingId").GetString();
var googleBooksId = root.GetProperty("googleBooksId").GetString();
var barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString();
var appleBooksId = root.GetProperty("appleBooksId").GetString();
var isbns = DeserializeIsbns(root.GetProperty("isbNs"));
var contributorIds = DeserializeContributorIds(root.GetProperty("contributors"));
var ratings = DeserializeRatings(root.GetProperty("ratings"));
string? edition = root.GetProperty("edition").GetString();
int volumeNumber = root.GetProperty("volumeNumber").GetInt32();
BookSeries series = DeserializeBookSeries(root.GetProperty("series"));
string? asin = root.GetProperty("asin").GetString();
string? goodreadsId = root.GetProperty("goodreadsId").GetString();
string? lccn = root.GetProperty("lccn").GetString();
string? oclcNumber = root.GetProperty("oclcNumber").GetString();
string? openLibraryId = root.GetProperty("openLibraryId").GetString();
string? libraryThingId = root.GetProperty("libraryThingId").GetString();
string? googleBooksId = root.GetProperty("googleBooksId").GetString();
string? barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString();
string? appleBooksId = root.GetProperty("appleBooksId").GetString();
List<Isbn> isbns = DeserializeIsbns(root.GetProperty("isbNs"));
List<MediaContributorId> contributorIds = DeserializeContributorIds(root.GetProperty("contributors"));
List<BookRating> ratings = DeserializeRatings(root.GetProperty("ratings"));
var createBookResult = Book.Create(
ErrorOr.ErrorOr<Book> createBookResult = Book.Create(
BookId.Create(id),
metadata,
Optional<BookFormat>.FromNullable(format),
@@ -85,9 +85,9 @@ public class BookJsonConverter : JsonConverter<Book>
contributorIds,
ratings: ratings
);
if (createBookResult.IsError)
throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}");
return createBookResult.Value;
return createBookResult.IsError
? throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}")
: createBookResult.Value;
}
}
@@ -109,20 +109,20 @@ public class BookJsonConverter : JsonConverter<Book>
/// <returns>The deserialized <see cref="WrittenContentMetadata"/>.</returns>
private WrittenContentMetadata DeserializeMetadata(JsonElement element)
{
var title = element.GetProperty("title").GetString();
var originalTitle = element.GetProperty("originalTitle").GetString();
var description = element.GetProperty("description").GetString();
var releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo"));
var genres = DeserializeGenres(element.GetProperty("genres"));
var tags = DeserializeTags(element.GetProperty("tags"));
var language = DeserializeLanguageInfo(element.GetProperty("language"));
var originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage"));
var publisher = element.GetProperty("publisher").GetString();
string? title = element.GetProperty("title").GetString();
string? originalTitle = element.GetProperty("originalTitle").GetString();
string? description = element.GetProperty("description").GetString();
ReleaseInfo releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo"));
List<Genre> genres = DeserializeGenres(element.GetProperty("genres"));
List<Tag> tags = DeserializeTags(element.GetProperty("tags"));
LanguageInfo? language = DeserializeLanguageInfo(element.GetProperty("language"));
LanguageInfo? originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage"));
string? publisher = element.GetProperty("publisher").GetString();
int? pageCount = null;
if (element.TryGetProperty("pageCount", out var pageCountElement))
if (element.TryGetProperty("pageCount", out JsonElement pageCountElement))
if (pageCountElement.ValueKind != JsonValueKind.Null)
pageCount = pageCountElement.GetInt32();
var metadataResult = WrittenContentMetadata.Create(
ErrorOr.ErrorOr<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
title!,
Optional<string>.FromNullable(originalTitle),
Optional<string>.FromNullable(description),
@@ -135,10 +135,9 @@ public class BookJsonConverter : JsonConverter<Book>
Optional<int>.FromNullable(pageCount)
);
if (metadataResult.IsError)
throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}");
return metadataResult.Value;
return metadataResult.IsError
? throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}")
: metadataResult.Value;
}
/// <summary>
@@ -148,20 +147,20 @@ public class BookJsonConverter : JsonConverter<Book>
/// <returns>The deserialized <see cref="ReleaseInfo"/>.</returns>
private ReleaseInfo DeserializeReleaseInfo(JsonElement element)
{
var originalReleaseDate = element.TryGetProperty("originalReleaseDate", out var ordElement) ?
DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) ?
DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null;
var originalReleaseYear = element.TryGetProperty("originalReleaseYear", out var oryElement) && oryElement.ValueKind == JsonValueKind.Number
int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number
? oryElement.GetInt32() : (int?)null;
var reReleaseDate = element.TryGetProperty("reReleaseDate", out var rrdElement) && rrdElement.ValueKind == JsonValueKind.String ?
DateOnly? reReleaseDate = element.TryGetProperty("reReleaseDate", out JsonElement rrdElement) && rrdElement.ValueKind == JsonValueKind.String ?
DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null;
var reReleaseYear = element.TryGetProperty("reReleaseYear", out var rryElement) && rryElement.ValueKind == JsonValueKind.Number
int? reReleaseYear = element.TryGetProperty("reReleaseYear", out JsonElement rryElement) && rryElement.ValueKind == JsonValueKind.Number
? rryElement.GetInt32() : (int?)null;
var releaseCountry = element.TryGetProperty("releaseCountry", out var rcElement) ?
string? releaseCountry = element.TryGetProperty("releaseCountry", out JsonElement rcElement) ?
rcElement.GetString() : null;
var releaseVersion = element.TryGetProperty("releaseVersion", out var rvElement) ?
string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ?
rvElement.GetString() : null;
var releaseInfoResult = ReleaseInfo.Create(
ErrorOr.ErrorOr<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(originalReleaseDate),
Optional<int>.FromNullable(originalReleaseYear),
Optional<DateOnly>.FromNullable(reReleaseDate),
@@ -170,9 +169,9 @@ public class BookJsonConverter : JsonConverter<Book>
Optional<string>.FromNullable(releaseVersion)
);
if (releaseInfoResult.IsError)
throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}");
return releaseInfoResult.Value;
return releaseInfoResult.IsError
? throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}")
: releaseInfoResult.Value;
}
/// <summary>
@@ -208,20 +207,19 @@ public class BookJsonConverter : JsonConverter<Book>
{
if (element.ValueKind != JsonValueKind.Null)
{
var languageCode = element.GetProperty("languageCode").GetString();
var languageName = element.GetProperty("languageName").GetString();
var nativeName = element.TryGetProperty("nativeName", out var nnElement) ? nnElement.GetString() : null;
string? languageCode = element.GetProperty("languageCode").GetString();
string? languageName = element.GetProperty("languageName").GetString();
string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null;
var languageInfoResult = LanguageInfo.Create(
ErrorOr.ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(
languageCode!,
languageName!,
Optional<string>.FromNullable(nativeName)
);
if (languageInfoResult.IsError)
throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}");
return languageInfoResult.Value;
return languageInfoResult.IsError
? throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}")
: languageInfoResult.Value;
}
else
return null;
@@ -259,7 +257,7 @@ public class BookJsonConverter : JsonConverter<Book>
private List<MediaContributorId> DeserializeContributorIds(JsonElement element)
{
// TODO: implement when contributors are implemented
return new List<MediaContributorId>();
return [];
}
/// <summary>
@@ -32,8 +32,8 @@ public static class BogusExtensions
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end)
{
var startDateTime = start.ToDateTime(TimeOnly.MinValue);
var endDateTime = end.ToDateTime(TimeOnly.MinValue);
DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue);
DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue);
return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime));
}
#endregion
@@ -21,9 +21,7 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly))
return DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
}
#endregion
}
@@ -42,18 +42,15 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
{
builder.ConfigureServices(services =>
{
var descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
if (descriptor is not null)
services.Remove(descriptor);
services.AddDbContext<LuminaDbContext>(options =>
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite(_connection));
ServiceProvider servicePreovider = services.BuildServiceProvider();
using (IServiceScope scope = servicePreovider.CreateScope())
{
options.UseSqlite(_connection);
});
var servicePreovider = services.BuildServiceProvider();
using (var scope = servicePreovider.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
IServiceProvider scopedServices = scope.ServiceProvider;
LuminaDbContext dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
dbContext.Database.EnsureCreated();
}
});
@@ -21,9 +21,7 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly?))
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
}
#endregion
}
@@ -48,10 +48,10 @@ public class AddBookRequestFixture
/// <returns>The created request to add a book.</returns>
public AddBookRequest CreateRequestBook()
{
var releaseYear = _random.Next(2000, 2010);
var reReleaseYear = _random.Next(2010, 2020);
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
var releaseInfo = new Faker<ReleaseInfoModel>()
ReleaseInfoModel releaseInfo = new Faker<ReleaseInfoModel>()
.CustomInstantiator(f => new ReleaseInfoModel(
default,
default,
@@ -68,19 +68,19 @@ public class AddBookRequestFixture
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
.Generate();
var genre = new Faker<GenreModel>()
Faker<GenreModel> genre = new Faker<GenreModel>()
.CustomInstantiator(f => new GenreModel(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
var tag = new Faker<TagModel>()
Faker<TagModel> tag = new Faker<TagModel>()
.CustomInstantiator(f => new TagModel(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
var mediaContributorRole = new Faker<MediaContributorRoleModel>()
Faker<MediaContributorRoleModel> mediaContributorRole = new Faker<MediaContributorRoleModel>()
.CustomInstantiator(f => new MediaContributorRoleModel(
default!,
default!
@@ -88,7 +88,7 @@ public class AddBookRequestFixture
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50)));
var mediaContributorName = new Faker<MediaContributorNameModel>()
Faker<MediaContributorNameModel> mediaContributorName = new Faker<MediaContributorNameModel>()
.CustomInstantiator(f => new MediaContributorNameModel(
default!,
default!
@@ -96,7 +96,7 @@ public class AddBookRequestFixture
.RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50)));
var mediaContributor = new Faker<MediaContributorModel>()
Faker<MediaContributorModel> mediaContributor = new Faker<MediaContributorModel>()
.CustomInstantiator(f => new MediaContributorModel(
default!,
default!
@@ -104,7 +104,7 @@ public class AddBookRequestFixture
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
var rating = new Faker<BookRatingModel>()
Faker<BookRatingModel> rating = new Faker<BookRatingModel>()
.CustomInstantiator(f => new BookRatingModel(
default,
default,
@@ -116,7 +116,7 @@ public class AddBookRequestFixture
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
var language = new Faker<LanguageInfoModel>()
Faker<LanguageInfoModel> language = new Faker<LanguageInfoModel>()
.CustomInstantiator(f => new LanguageInfoModel(
default!,
default!,
@@ -126,7 +126,7 @@ public class AddBookRequestFixture
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
var originalLanguage = new Faker<LanguageInfoModel>()
Faker<LanguageInfoModel> originalLanguage = new Faker<LanguageInfoModel>()
.CustomInstantiator(f => new LanguageInfoModel(
default!,
default!,
@@ -136,7 +136,7 @@ public class AddBookRequestFixture
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
var metadata = new Faker<WrittenContentMetadataModel>()
Faker<WrittenContentMetadataModel> metadata = new Faker<WrittenContentMetadataModel>()
.CustomInstantiator(f => new WrittenContentMetadataModel(
default!,
default,
@@ -160,30 +160,30 @@ public class AddBookRequestFixture
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300));
var isbn = new Faker<IsbnModel>()
Faker<IsbnModel> isbn = new Faker<IsbnModel>()
.CustomInstantiator(f => new IsbnModel(
default!,
default
))
.RuleFor(i => i.Value, f =>
{
var isIsbn13 = f.Random.Bool();
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
var prefix = f.Random.Bool() ? "978" : "979";
var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}";
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - (sum % 10)) % 10;
return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}";
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
var digits = new int[9];
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
@@ -224,16 +224,16 @@ public class AddBookRequestFixture
.RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString())
.RuleFor(x => x.LCCN, f =>
{
var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3))
string letters = new(Enumerable.Range(0, f.Random.Number(0, 3))
.Select(_ => f.Random.Char('a', 'z'))
.ToArray());
var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
return letters + digits;
})
.RuleFor(x => x.OCLCNumber, f =>
{
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
var prefix = f.Random.ArrayElement(prefixes);
string prefix = f.Random.ArrayElement(prefixes);
string number;
switch (prefix)
{
@@ -257,9 +257,9 @@ public class AddBookRequestFixture
})
.RuleFor(x => x.OpenLibraryId, f =>
{
var firstDigit = f.Random.Number(1, 9);
var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
int firstDigit = f.Random.Number(1, 9);
string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
return $"OL{firstDigit}{remainingDigits}{suffix}";
})
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
@@ -280,8 +280,8 @@ public class AddBookRequestFixture
private void ConfigureCustomRequestTypes()
{
var releaseYear = _random.Next(2000, 2010);
var reReleaseYear = _random.Next(2010, 2020);
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
_fixture.Register(() => new ReleaseInfoModel(
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
@@ -32,8 +32,8 @@ public static class BogusExtensions
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end)
{
var startDateTime = start.ToDateTime(TimeOnly.MinValue);
var endDateTime = end.ToDateTime(TimeOnly.MinValue);
DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue);
DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue);
return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime));
}
#endregion
@@ -21,9 +21,7 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly))
return DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
}
#endregion
}
@@ -21,9 +21,7 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly?))
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
}
#endregion
}
@@ -64,15 +64,15 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
var bookModel = _fixture.Create<BookModel>();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
BookModel bookModel = _fixture.Create<BookModel>();
_mockMapper.Map<BookModel>(Arg.Any<Book>()).Returns(bookModel);
_mockBookRepository.InsertAsync(Arg.Any<BookModel>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
@@ -85,11 +85,11 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenBookCreationFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with { Metadata = bookCommand.Metadata with { Title = null } };
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -102,15 +102,15 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenRepositoryInsertFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
var bookModel = _fixture.Create<BookModel>();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
BookModel bookModel = _fixture.Create<BookModel>();
_mockMapper.Map<BookModel>(Arg.Any<Book>()).Returns(bookModel);
_mockBookRepository.InsertAsync(Arg.Any<BookModel>(), Arg.Any<CancellationToken>())
.Returns(Errors.WrittenContent.BookAlreadyExists);
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -123,11 +123,11 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenCalledWithInvalidISBN_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with { ISBNs = [new IsbnModel("invalid", IsbnFormat.Isbn13)] };
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -140,11 +140,11 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenCalledWithInvalidRating_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with { Ratings = [new BookRatingModel(-1, 5, null, null)] };
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -157,7 +157,7 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenGenreCreationFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata with
@@ -167,7 +167,7 @@ public class AddBookCommandHandlerTests
};
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -180,7 +180,7 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenTagCreationFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata with
@@ -190,7 +190,7 @@ public class AddBookCommandHandlerTests
};
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -203,7 +203,7 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenReleaseInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata with
@@ -220,7 +220,7 @@ public class AddBookCommandHandlerTests
};
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -233,7 +233,7 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata with
@@ -243,7 +243,7 @@ public class AddBookCommandHandlerTests
};
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -256,7 +256,7 @@ public class AddBookCommandHandlerTests
public async Task Handle_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
var bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata with
@@ -266,7 +266,7 @@ public class AddBookCommandHandlerTests
};
// Act
var result = await _sut.Handle(bookCommand, CancellationToken.None);
ErrorOr<Book> result = await _sut.Handle(bookCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -48,10 +48,10 @@ public class AddBookCommandFixture
/// <returns>The created command to add a book.</returns>
public AddBookCommand CreateCommandBook()
{
var releaseYear = _random.Next(2000, 2010);
var reReleaseYear = _random.Next(2010, 2020);
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
var releaseInfo = new Faker<ReleaseInfoModel>()
ReleaseInfoModel releaseInfo = new Faker<ReleaseInfoModel>()
.CustomInstantiator(f => new ReleaseInfoModel(
default,
default,
@@ -68,33 +68,33 @@ public class AddBookCommandFixture
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
.Generate();
var genre = new Faker<GenreModel>()
Faker<GenreModel> genre = new Faker<GenreModel>()
.CustomInstantiator(f => new GenreModel(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
var tag = new Faker<TagModel>()
Faker<TagModel> tag = new Faker<TagModel>()
.CustomInstantiator(f => new TagModel(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
var mediaContributorRole = new Faker<MediaContributorRoleModel>()
Faker<MediaContributorRoleModel> mediaContributorRole = new Faker<MediaContributorRoleModel>()
.CustomInstantiator(f => new MediaContributorRoleModel(
default!,
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50)));
var mediaContributorName = new Faker<MediaContributorNameModel>()
Faker<MediaContributorNameModel> mediaContributorName = new Faker<MediaContributorNameModel>()
.CustomInstantiator(f => new MediaContributorNameModel(
default!,
default!
))
.RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50)));
var mediaContributor = new Faker<MediaContributorModel>()
Faker<MediaContributorModel> mediaContributor = new Faker<MediaContributorModel>()
.CustomInstantiator(f => new MediaContributorModel(
default!,
default!
@@ -102,7 +102,7 @@ public class AddBookCommandFixture
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
var rating = new Faker<BookRatingModel>()
Faker<BookRatingModel> rating = new Faker<BookRatingModel>()
.CustomInstantiator(f => new BookRatingModel(
default,
default,
@@ -114,7 +114,7 @@ public class AddBookCommandFixture
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
var language = new Faker<LanguageInfoModel>()
Faker<LanguageInfoModel> language = new Faker<LanguageInfoModel>()
.CustomInstantiator(f => new LanguageInfoModel(
default!,
default!,
@@ -124,7 +124,7 @@ public class AddBookCommandFixture
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
var originalLanguage = new Faker<LanguageInfoModel>()
Faker<LanguageInfoModel> originalLanguage = new Faker<LanguageInfoModel>()
.CustomInstantiator(f => new LanguageInfoModel(
default!,
default!,
@@ -134,7 +134,7 @@ public class AddBookCommandFixture
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
var metadata = new Faker<WrittenContentMetadataModel>()
Faker<WrittenContentMetadataModel> metadata = new Faker<WrittenContentMetadataModel>()
.CustomInstantiator(f => new WrittenContentMetadataModel(
default!,
default,
@@ -158,30 +158,30 @@ public class AddBookCommandFixture
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300));
var isbn = new Faker<IsbnModel>()
Faker<IsbnModel> isbn = new Faker<IsbnModel>()
.CustomInstantiator(f => new IsbnModel(
default!,
default
))
.RuleFor(i => i.Value, f =>
{
var isIsbn13 = f.Random.Bool();
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
var prefix = f.Random.Bool() ? "978" : "979";
var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}";
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - (sum % 10)) % 10;
return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}";
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
var digits = new int[9];
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
@@ -222,16 +222,16 @@ public class AddBookCommandFixture
.RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString())
.RuleFor(x => x.LCCN, f =>
{
var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3))
string letters = new(Enumerable.Range(0, f.Random.Number(0, 3))
.Select(_ => f.Random.Char('a', 'z'))
.ToArray());
var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
return letters + digits;
})
.RuleFor(x => x.OCLCNumber, f =>
{
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
var prefix = f.Random.ArrayElement(prefixes);
string prefix = f.Random.ArrayElement(prefixes);
string number;
switch (prefix)
{
@@ -255,9 +255,9 @@ public class AddBookCommandFixture
})
.RuleFor(x => x.OpenLibraryId, f =>
{
var firstDigit = f.Random.Number(1, 9);
var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
int firstDigit = f.Random.Number(1, 9);
string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
return $"OL{firstDigit}{remainingDigits}{suffix}";
})
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
@@ -278,8 +278,8 @@ public class AddBookCommandFixture
private void ConfigureCustomRequestTypes()
{
var releaseYear = _random.Next(2000, 2010);
var reReleaseYear = _random.Next(2010, 2020);
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
_fixture.Register(() => new ReleaseInfoModel(
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
@@ -42,8 +42,8 @@ public class DataAccessLayerServicesTests
public void AddDataAccessLayerServices_WhenBasePathExists_ShouldAddServices()
{
// Arrange
var services = new ServiceCollection();
var basePath = Path.GetTempPath(); // use a real existing path
ServiceCollection services = new();
string basePath = Path.GetTempPath(); // use a real existing path
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
@@ -59,16 +59,16 @@ public class DataAccessLayerServicesTests
public void AddDataAccessLayerServices_ShouldRegisterDbContextWithCorrectConnectionString()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
// Assert
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
ServiceDescriptor? descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
descriptor.Should().NotBeNull();
var serviceProvider = services.BuildServiceProvider();
var context = serviceProvider.GetService<LuminaDbContext>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
LuminaDbContext? context = serviceProvider.GetService<LuminaDbContext>();
context.Should().NotBeNull();
context!.Database.GetDbConnection().ConnectionString.Should().Contain("Lumina.db");
@@ -78,14 +78,14 @@ public class DataAccessLayerServicesTests
public void AddDataAccessLayerServices_WhenCalled_ShouldRegisterRepositories()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
var repository = serviceProvider.GetService<IBookRepository>();
IBookRepository? repository = serviceProvider.GetService<IBookRepository>();
repository.Should().NotBeNull();
}
#endregion
@@ -32,8 +32,8 @@ public static class BogusExtensions
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end)
{
var startDateTime = start.ToDateTime(TimeOnly.MinValue);
var endDateTime = end.ToDateTime(TimeOnly.MinValue);
DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue);
DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue);
return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime));
}
#endregion
@@ -21,9 +21,7 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly))
return DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
}
#endregion
}
@@ -21,9 +21,7 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly?))
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
}
#endregion
}
@@ -48,17 +48,17 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated()
{
// Arrange
var bookModel = _bookModelFixture.CreateBookModel();
BookModel bookModel = _bookModelFixture.CreateBookModel();
// Act
var result = await _sut.InsertAsync(bookModel, CancellationToken.None);
ErrorOr<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Created);
// Check if the book was added to the context's ChangeTracker
var addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
addedBook.Should().NotBeNull();
}
@@ -67,13 +67,13 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError()
{
// Arrange
var bookModel = _bookModelFixture.CreateBookModel();
BookModel bookModel = _bookModelFixture.CreateBookModel();
_mockContext.Books.Add(bookModel);
await _mockContext.SaveChangesAsync();
// Act
var result = await _sut.InsertAsync(bookModel, CancellationToken.None);
ErrorOr<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
@@ -85,24 +85,24 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes()
{
// Arrange
var existingTag = new TagModel("Existing");
TagModel existingTag = new("Existing");
_mockContext.Set<TagModel>().Add(existingTag);
await _mockContext.SaveChangesAsync();
var bookModel = _bookModelFixture.CreateBookModel();
BookModel bookModel = _bookModelFixture.CreateBookModel();
bookModel.Tags = [new("Existing"), new("New")];
// Act
var result = await _sut.InsertAsync(bookModel, CancellationToken.None);
ErrorOr<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Created);
var addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
addedBook.Should().NotBeNull();
var addedBookEntity = addedBook!.Entity;
BookModel addedBookEntity = addedBook!.Entity;
addedBookEntity.Tags.Should().HaveCount(2);
addedBookEntity.Tags.Should().Contain(t => t.Name == "Existing" && t == existingTag);
addedBookEntity.Tags.Should().Contain(t => t.Name == "New" && t != existingTag);
@@ -112,24 +112,24 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes()
{
// Arrange
var existingGenre = new GenreModel("Existing");
GenreModel existingGenre = new("Existing");
_mockContext.Set<GenreModel>().Add(existingGenre);
await _mockContext.SaveChangesAsync();
var bookModel = _bookModelFixture.CreateBookModel();
BookModel bookModel = _bookModelFixture.CreateBookModel();
bookModel.Genres = [new("Existing"), new("New")];
// Act
var result = await _sut.InsertAsync(bookModel, CancellationToken.None);
ErrorOr<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Created);
var addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
addedBook.Should().NotBeNull();
var addedBookEntity = addedBook!.Entity;
BookModel addedBookEntity = addedBook!.Entity;
addedBookEntity.Genres.Should().HaveCount(2);
addedBookEntity.Genres.Should().Contain(g => g.Name == "Existing" && g == existingGenre);
addedBookEntity.Genres.Should().Contain(g => g.Name == "New" && g != existingGenre);
@@ -139,17 +139,17 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks()
{
// Arrange
var books = new List<BookModel>
{
List<BookModel> books =
[
_bookModelFixture.CreateBookModel(),
_bookModelFixture.CreateBookModel(),
_bookModelFixture.CreateBookModel()
};
];
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
// Act
var result = await _sut.GetAllAsync(CancellationToken.None);
ErrorOr<IEnumerable<BookModel>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
@@ -162,7 +162,7 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList()
{
// Act
var result = await _sut.GetAllAsync(CancellationToken.None);
ErrorOr<IEnumerable<BookModel>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
@@ -174,7 +174,7 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities()
{
// Arrange
var book = _bookModelFixture.CreateBookModel();
BookModel book = _bookModelFixture.CreateBookModel();
book.Tags = [new TagModel("Tag1"), new TagModel("Tag2")];
book.Genres = [new GenreModel("Genre1"), new GenreModel("Genre2")];
book.ISBNs = [new IsbnModel("1234567890", IsbnFormat.Isbn10), new IsbnModel("1234567890123", IsbnFormat.Isbn13)];
@@ -182,13 +182,13 @@ public class BookRepositoryTests
await _mockContext.SaveChangesAsync();
// Act
var result = await _sut.GetAllAsync(CancellationToken.None);
ErrorOr<IEnumerable<BookModel>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Should().HaveCount(1);
var retrievedBook = result.Value.First();
BookModel retrievedBook = result.Value.First();
retrievedBook.Tags.Should().HaveCount(2);
retrievedBook.Genres.Should().HaveCount(2);
retrievedBook.ISBNs.Should().HaveCount(2);
@@ -46,8 +46,8 @@ public class BookModelFixture
/// <returns>The created BookModel.</returns>
public BookModel CreateBookModel()
{
var releaseYear = _random.Next(2000, 2010);
var reReleaseYear = _random.Next(2010, 2020);
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
return new Faker<BookModel>()
.RuleFor(x => x.Id, f => f.Random.Guid())
@@ -105,17 +105,17 @@ public class BookModelFixture
private string CreateLCCN(Faker f)
{
var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3))
string letters = new(Enumerable.Range(0, f.Random.Number(0, 3))
.Select(_ => f.Random.Char('a', 'z'))
.ToArray());
var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
return letters + digits;
}
private string CreateOCLCNumber(Faker f)
{
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
var prefix = f.Random.ArrayElement(prefixes);
string prefix = f.Random.ArrayElement(prefixes);
string number = prefix switch
{
"ocm" => f.Random.String2(8, "0123456789"),
@@ -129,9 +129,9 @@ public class BookModelFixture
private string CreateOpenLibraryId(Faker f)
{
var firstDigit = f.Random.Number(1, 9);
var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
int firstDigit = f.Random.Number(1, 9);
string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
return $"OL{firstDigit}{remainingDigits}{suffix}";
}
@@ -152,23 +152,23 @@ public class BookModelFixture
private string CreateIsbn(Faker f)
{
var isIsbn13 = f.Random.Bool();
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
var prefix = f.Random.Bool() ? "978" : "979";
var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}";
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - (sum % 10)) % 10;
return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}";
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
var digits = new int[9];
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
@@ -36,8 +36,8 @@ public class RepositoryDictionaryTests
public void Add_WhenValidRepositoryItemIsAdded_ShouldIncreaseCount()
{
// Arrange
var bookRepository = _fixture.Create<BookRepository>();
var repositoryDictionary = new RepositoryDictionary();
BookRepository bookRepository = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
// Act
repositoryDictionary.Add<IBookRepository>(bookRepository);
@@ -50,8 +50,8 @@ public class RepositoryDictionaryTests
public void Clear_WhenCalled_ShouldRemoveAllItems()
{
// Arrange
var bookRepository = _fixture.Create<BookRepository>();
var repositoryDictionary = new RepositoryDictionary();
BookRepository bookRepository = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
repositoryDictionary.Add<IBookRepository>(bookRepository);
// Act
@@ -65,12 +65,12 @@ public class RepositoryDictionaryTests
public void Get_WhenRepositoryExists_ShouldReturnCorrectRepository()
{
// Arrange
var expected = _fixture.Create<BookRepository>();
var repositoryDictionary = new RepositoryDictionary();
BookRepository expected = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
repositoryDictionary.Add<IBookRepository>(expected);
// Act
var actual = repositoryDictionary.Get<IBookRepository>(typeof(BookRepository));
IBookRepository actual = repositoryDictionary.Get<IBookRepository>(typeof(BookRepository));
// Assert
actual.Should().BeSameAs(expected);
@@ -80,7 +80,7 @@ public class RepositoryDictionaryTests
public void Add_WhenNullValueIsProvided_ShouldThrowArgumentException()
{
// Arrange
var repositoryDictionary = new RepositoryDictionary();
RepositoryDictionary repositoryDictionary = new();
// Act & Assert
Action act = () => repositoryDictionary.Add<IBookRepository>(null!);
@@ -91,8 +91,8 @@ public class RepositoryDictionaryTests
public void Add_WhenDuplicateValueIsAdded_ShouldThrowArgumentException()
{
// Arrange
var bookRepository = _fixture.Create<BookRepository>();
var repositoryDictionary = new RepositoryDictionary();
BookRepository bookRepository = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
repositoryDictionary.Add<IBookRepository>(bookRepository);
// Act & Assert
@@ -104,8 +104,8 @@ public class RepositoryDictionaryTests
public void Add_WhenNonRepositoryValueIsAdded_ShouldThrowArgumentException()
{
// Arrange
var nonRepository = new object();
var repositoryDictionary = new RepositoryDictionary();
object nonRepository = new();
RepositoryDictionary repositoryDictionary = new();
// Act & Assert
Action act = () => repositoryDictionary.Add(nonRepository);
@@ -21,13 +21,13 @@ public class RepositoryFactoryTests
public void CreateRepository_WhenCalled_ShouldReturnCorrectRepository()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var repositoryFactory = new RepositoryFactory(serviceProvider);
ServiceProvider serviceProvider = services.BuildServiceProvider();
RepositoryFactory repositoryFactory = new(serviceProvider);
// Act
var result = repositoryFactory.CreateRepository<IBookRepository>();
IBookRepository result = repositoryFactory.CreateRepository<IBookRepository>();
// Assert
result.Should().NotBeNull();
@@ -38,10 +38,10 @@ public class RepositoryFactoryTests
public void CreateRepository_WhenUnregisteredTypeRequested_ShouldThrowException()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var repositoryFactory = new RepositoryFactory(serviceProvider);
ServiceProvider serviceProvider = services.BuildServiceProvider();
RepositoryFactory repositoryFactory = new(serviceProvider);
// Act & Assert
Action act = () => repositoryFactory.CreateRepository<IUnregisteredRepository>();
@@ -35,8 +35,9 @@ public class UnitOfWorkTests
public UnitOfWorkTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_fixture.Customize<LuminaDbContext>(composer => composer.FromFactory(() => {
var options = new DbContextOptionsBuilder<LuminaDbContext>()
_fixture.Customize<LuminaDbContext>(composer => composer.FromFactory(() =>
{
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
return Substitute.ForPartsOf<LuminaDbContext>(options);
@@ -49,10 +50,10 @@ public class UnitOfWorkTests
public void ResetRepositories_WhenCalled_ShouldClearAllRepositories()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Act
unitOfWork.ResetRepositories();
@@ -65,10 +66,10 @@ public class UnitOfWorkTests
public void AddRepositories_WhenCalled_ShouldAddRepositories()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
int initialCount = unitOfWork.Repositories.Count;
// Act
@@ -84,11 +85,11 @@ public class UnitOfWorkTests
public void Constructor_WhenCalled_ShouldAddRepositories()
{
// Arrange
var repositoryFactory = _fixture.Create<IRepositoryFactory>();
var dbContext = _fixture.Create<LuminaDbContext>();
IRepositoryFactory repositoryFactory = _fixture.Create<IRepositoryFactory>();
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
// Act
var unitOfWork = new UnitOfWork(repositoryFactory, dbContext);
UnitOfWork unitOfWork = new(repositoryFactory, dbContext);
// Assert
unitOfWork.Repositories.Count.Should().BeGreaterThan(0);
@@ -98,14 +99,14 @@ public class UnitOfWorkTests
public void GetRepository_WhenRepositoryNotAdded_ShouldReturnNull()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
unitOfWork.ResetRepositories();
// Act
var result = unitOfWork.GetRepository<IBookRepository>();
IBookRepository result = unitOfWork.GetRepository<IBookRepository>();
// Assert
result.Should().BeNull();
@@ -115,10 +116,10 @@ public class UnitOfWorkTests
public void GetRepository_WhenRepositoriesAdded_ShouldReturnRepositories()
{
// Arrange
var services = new ServiceCollection();
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider();
var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Act & Assert
unitOfWork.GetRepository<IBookRepository>().Should().NotBeNull();
@@ -128,10 +129,10 @@ public class UnitOfWorkTests
public async Task SaveChangesAsync_WhenCalled_ShouldCallDbContextSaveChangesAsync()
{
// Arrange
var repositoryFactory = _fixture.Create<IRepositoryFactory>();
var dbContext = _fixture.Create<LuminaDbContext>();
var unitOfWork = new UnitOfWork(repositoryFactory, dbContext);
var cancellationToken = new CancellationToken();
IRepositoryFactory repositoryFactory = _fixture.Create<IRepositoryFactory>();
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
UnitOfWork unitOfWork = new(repositoryFactory, dbContext);
CancellationToken cancellationToken = new();
// Act
await unitOfWork.SaveChangesAsync(cancellationToken);
@@ -41,12 +41,12 @@ public class OptionsBuilderFluentValidationUtilitiesTests
public void ValidateFluently_WhenCalled_ShouldRegisterFluentValidationOptions()
{
// Arrange
var services = Substitute.For<IServiceCollection>();
var name = _fixture.Create<string>();
var optionsBuilder = new OptionsBuilder<OptionsBuilderFluentValidationUtilitiesFixture>(services, name);
IServiceCollection services = Substitute.For<IServiceCollection>();
string name = _fixture.Create<string>();
OptionsBuilder<OptionsBuilderFluentValidationUtilitiesFixture> optionsBuilder = new(services, name);
// Act
var result = optionsBuilder.ValidateFluently();
OptionsBuilder<OptionsBuilderFluentValidationUtilitiesFixture> result = optionsBuilder.ValidateFluently();
// Assert
result.Should().BeSameAs(optionsBuilder);
@@ -60,30 +60,30 @@ public class OptionsBuilderFluentValidationUtilitiesTests
public void ValidateFluently_WhenCalled_ShouldUseCorrectName()
{
// Arrange
var services = new ServiceCollection();
var name = _fixture.Create<string>();
var optionsBuilder = new OptionsBuilder<OptionsBuilderFluentValidationUtilitiesFixture>(services, name);
ServiceCollection services = new();
string name = _fixture.Create<string>();
OptionsBuilder<OptionsBuilderFluentValidationUtilitiesFixture> optionsBuilder = new(services, name);
// Act
optionsBuilder.ValidateFluently();
// Assert
var serviceDescriptor = services.FirstOrDefault(sd =>
ServiceDescriptor? serviceDescriptor = services.FirstOrDefault(sd =>
sd.ServiceType == typeof(IValidateOptions<OptionsBuilderFluentValidationUtilitiesFixture>) &&
sd.Lifetime == ServiceLifetime.Singleton &&
sd.ImplementationFactory != null);
serviceDescriptor.Should().NotBeNull();
var implementationFactory = serviceDescriptor!.ImplementationFactory;
Func<IServiceProvider, object>? implementationFactory = serviceDescriptor!.ImplementationFactory;
implementationFactory.Should().NotBeNull();
var serviceProvider = Substitute.For<IServiceProvider>();
var mockValidator = Substitute.For<IValidator<OptionsBuilderFluentValidationUtilitiesFixture>>();
IServiceProvider serviceProvider = Substitute.For<IServiceProvider>();
IValidator<OptionsBuilderFluentValidationUtilitiesFixture> mockValidator = Substitute.For<IValidator<OptionsBuilderFluentValidationUtilitiesFixture>>();
serviceProvider.GetService(typeof(IValidator<OptionsBuilderFluentValidationUtilitiesFixture>))
.Returns(mockValidator);
var fluentValidationOptions = implementationFactory!(serviceProvider) as FluentValidationOptions<OptionsBuilderFluentValidationUtilitiesFixture>;
FluentValidationOptions<OptionsBuilderFluentValidationUtilitiesFixture>? fluentValidationOptions = implementationFactory!(serviceProvider) as FluentValidationOptions<OptionsBuilderFluentValidationUtilitiesFixture>;
fluentValidationOptions.Should().NotBeNull();
fluentValidationOptions!.Name.Should().Be(name);
}
@@ -40,14 +40,14 @@ public class FluentValidationOptionsTests
public void Validate_WhenMatchingName_ShouldValidateOptions()
{
// Arrange
var name = _fixture.Create<string>();
var options = _fixture.Create<FluentValidationOptionsFixture>();
var validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
string name = _fixture.Create<string>();
FluentValidationOptionsFixture options = _fixture.Create<FluentValidationOptionsFixture>();
IValidator<FluentValidationOptionsFixture> validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
validator.Validate(options).Returns(new ValidationResult());
var sut = new FluentValidationOptions<FluentValidationOptionsFixture>(name, validator);
FluentValidationOptions<FluentValidationOptionsFixture> sut = new(name, validator);
// Act
var result = sut.Validate(name, options);
ValidateOptionsResult result = sut.Validate(name, options);
// Assert
result.Should().BeOfType<ValidateOptionsResult>();
@@ -59,14 +59,14 @@ public class FluentValidationOptionsTests
public void Validate_WhenNonMatchingName_ShouldSkipValidation()
{
// Arrange
var name = _fixture.Create<string>();
var differentName = _fixture.Create<string>();
var options = _fixture.Create<FluentValidationOptionsFixture>();
var validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
var sut = new FluentValidationOptions<FluentValidationOptionsFixture>(name, validator);
string name = _fixture.Create<string>();
string differentName = _fixture.Create<string>();
FluentValidationOptionsFixture options = _fixture.Create<FluentValidationOptionsFixture>();
IValidator<FluentValidationOptionsFixture> validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
FluentValidationOptions<FluentValidationOptionsFixture> sut = new(name, validator);
// Act
var result = sut.Validate(differentName, options);
ValidateOptionsResult result = sut.Validate(differentName, options);
// Assert
result.Should().Be(ValidateOptionsResult.Skip);
@@ -77,13 +77,13 @@ public class FluentValidationOptionsTests
public void Validate_WhenNullName_ShouldValidateOptions()
{
// Arrange
var options = _fixture.Create<FluentValidationOptionsFixture>();
var validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
FluentValidationOptionsFixture options = _fixture.Create<FluentValidationOptionsFixture>();
IValidator<FluentValidationOptionsFixture> validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
validator.Validate(options).Returns(new ValidationResult());
var sut = new FluentValidationOptions<FluentValidationOptionsFixture>(null, validator);
FluentValidationOptions<FluentValidationOptionsFixture> sut = new(null, validator);
// Act
var result = sut.Validate(_fixture.Create<string>(), options);
ValidateOptionsResult result = sut.Validate(_fixture.Create<string>(), options);
// Assert
result.Should().BeOfType<ValidateOptionsResult>();
@@ -95,9 +95,9 @@ public class FluentValidationOptionsTests
public void Validate_WhenNullOptions_ShouldThrowArgumentNullException()
{
// Arrange
var name = _fixture.Create<string>();
var validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
var sut = new FluentValidationOptions<FluentValidationOptionsFixture>(name, validator);
string name = _fixture.Create<string>();
IValidator<FluentValidationOptionsFixture> validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
FluentValidationOptions<FluentValidationOptionsFixture> sut = new(name, validator);
// Act
Action act = () => sut.Validate(name, null!);
@@ -110,18 +110,18 @@ public class FluentValidationOptionsTests
public void Validate_WhenInvalidOptions_ShouldReturnFailureResult()
{
// Arrange
var name = _fixture.Create<string>();
var options = _fixture.Create<FluentValidationOptionsFixture>();
var validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
var validationFailures = new List<ValidationFailure>
{
string name = _fixture.Create<string>();
FluentValidationOptionsFixture options = _fixture.Create<FluentValidationOptionsFixture>();
IValidator<FluentValidationOptionsFixture> validator = Substitute.For<IValidator<FluentValidationOptionsFixture>>();
List<ValidationFailure> validationFailures =
[
new("PropertyName", "Error Message")
};
];
validator.Validate(options).Returns(new ValidationResult(validationFailures));
var sut = new FluentValidationOptions<FluentValidationOptionsFixture>(name, validator);
FluentValidationOptions<FluentValidationOptionsFixture> sut = new(name, validator);
// Act
var result = sut.Validate(name, options);
ValidateOptionsResult result = sut.Validate(name, options);
// Assert
result.Should().BeOfType<ValidateOptionsResult>();
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using FluentAssertions;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
@@ -38,12 +38,12 @@ public class CommonSettingsModelValidatorTests
public void CommonSettingsModelValidator_WhenThemeProvided_ShouldNotHaveValidationError()
{
// Arrange
var model = _fixture.Build<CommonSettingsModel>()
CommonSettingsModel model = _fixture.Build<CommonSettingsModel>()
.With(x => x.Theme, "Dark")
.Create();
// Act
var result = _validator.Validate(model);
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
// Assert
result.IsValid.Should().BeTrue();
@@ -54,12 +54,12 @@ public class CommonSettingsModelValidatorTests
public void CommonSettingsModelValidator_WhenThemeNotProvided_ShouldNotHaveValidationError()
{
// Arrange
var model = _fixture.Build<CommonSettingsModel>()
CommonSettingsModel model = _fixture.Build<CommonSettingsModel>()
.With(x => x.Theme, string.Empty)
.Create();
// Act
var result = _validator.Validate(model);
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
// Assert
result.IsValid.Should().BeFalse();
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using FluentAssertions;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
@@ -37,12 +37,12 @@ public class DatabaseSettingsModelValidatorTests
public void DatabaseSettingsModelValidator_WhenDefaultConnectionProvided_ShouldNotHaveValidationError()
{
// Arrange
var model = _fixture.Build<DatabaseSettingsModel>()
DatabaseSettingsModel model = _fixture.Build<DatabaseSettingsModel>()
.With(x => x.DefaultConnection, "dummy-connection-string")
.Create();
// Act
var result = _validator.Validate(model);
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
// Assert
result.IsValid.Should().BeTrue();
@@ -53,12 +53,12 @@ public class DatabaseSettingsModelValidatorTests
public void DatabaseSettingsModelValidator_WhenDefaultConnectionNotProvided_ShouldHaveValidationError()
{
// Arrange
var model = _fixture.Build<DatabaseSettingsModel>()
DatabaseSettingsModel model = _fixture.Build<DatabaseSettingsModel>()
.With(x => x.DefaultConnection, string.Empty)
.Create();
// Act
var result = _validator.Validate(model);
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
// Assert
result.IsValid.Should().BeFalse();