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

@@ -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);