Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FOUNDATIONS: ShouldThrowDependencyValidationExceptionOnAddIfDbCurrencyErrorOccursAndLogItAsync->PASS #9

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions UsefulTime.Api/Brokers/DateTimes/DateTimeBroker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//=================================================
//Copyright (c) Coalition of Good-Hearted Engineers
//Free To Use To Find Comfort and Pease
//=================================================
namespace UsefulTime.Api.Brokers.DateTimes
{
public class DateTimeBroker:IDateTimeBroker
{
public DateTimeOffset GetCurrentDateTimeOffset() =>
DateTimeOffset.UtcNow;
}
}
11 changes: 11 additions & 0 deletions UsefulTime.Api/Brokers/DateTimes/IDateTimeBroker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//=================================================
//Copyright (c) Coalition of Good-Hearted Engineers
//Free To Use To Find Comfort and Pease
//=================================================
namespace UsefulTime.Api.Brokers.DateTimes
{
public interface IDateTimeBroker
{
DateTimeOffset GetCurrentDateTimeOffset();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//=================================================
//Copyright (c) Coalition of Good-Hearted Engineers
//Free To Use To Find Comfort and Pease
//=================================================
using Xeptions;

namespace UsefulTime.Api.Models.VideoMetadatas.Exceptions
{
public class LockedVideoMetadataException:Xeption
{
public LockedVideoMetadataException(string message, Exception exception)
:base(message,exception)
{ }
}
}
4 changes: 3 additions & 1 deletion UsefulTime.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//Copyright (c) Coalition of Good-Hearted Engineers
//Free To Use To Find Comfort and Pease
//=================================================
using UsefulTime.Api.Brokers.DateTimes;
using UsefulTime.Api.Brokers.Loggings;
using UsefulTime.Api.Brokers.Storages;
using UsefulTime.Api.Services.Foundations.VideoMetadatas;
Expand All @@ -18,8 +19,9 @@ private static void Main(string[] args)
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IStorageBroker, StorageBroker>();
builder.Services.AddTransient<ILoggingBroker, LoggingBroker>();
builder.Services.AddTransient<IDateTimeBroker, DateTimeBroker>();
builder.Services.AddTransient<IVideoMetadataService, VideoMetadataService>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//=================================================
using EFxceptions.Models.Exceptions;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using UsefulTime.Api.Models.VideoMetadatas;
using UsefulTime.Api.Models.VideoMetadatas.Exceptions;
using Xeptions;
Expand Down Expand Up @@ -43,6 +44,14 @@ private async ValueTask<VideoMetadata> TryCatch(ReturningVideoMetadataFunction r
innerException: duplicateKeyException);
throw CreateAndDependencyValidationException(alreadyExistVideoMetadataException);
}
catch (DbUpdateConcurrencyException dbUpdateConcurrencyException)
{
var lockedVideoMetadataException = new LockedVideoMetadataException(
"Video Metadata is locked, please try again.",
dbUpdateConcurrencyException);

throw CreateAndLogDependencyValidationException(lockedVideoMetadataException);
}
catch (Exception exception)
{
var failedVideoMetadataServiceException =
Expand All @@ -51,6 +60,17 @@ private async ValueTask<VideoMetadata> TryCatch(ReturningVideoMetadataFunction r
throw CreateAndLogServiseException(failedVideoMetadataServiceException);
}
}

private VideoMetadataDependencyException CreateAndLogDependencyException(Xeption exception)
{
var videoMetadataDependencyException = new VideoMetadataDependencyException(
message: "Failed video metadata error occured, cotact support",
innerException: exception);
this.loggingBroker.LogCritical(videoMetadataDependencyException);

return videoMetadataDependencyException;
}

private VideoMetadataServiceException CreateAndLogServiseException(Xeption exception)
{
var videoMetadataServiceException =
Expand Down Expand Up @@ -86,5 +106,15 @@ public VideoMetadataDependencyValidationException CreateAndDependencyValidationE
this.loggingBroker.LogError(videoMetadataDependencyValidationException);
return videoMetadataDependencyValidationException;
}
private VideoMetadataDependencyValidationException CreateAndLogDependencyValidationException(Xeption exception)
{
var videoMetadataDependencyValidationException = new VideoMetadataDependencyValidationException(
"Video Metadata dependency error occured, Fix errors and try again.",
exception);

this.loggingBroker.LogError(videoMetadataDependencyValidationException);

return videoMetadataDependencyValidationException;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,19 @@ private void ValidatevideoMetadataOnAdd(VideoMetadata videoMetadata)
ValidationVideoMetadataNotNull(videoMetadata);

Validate(
(Rule: IsInvalid(videoMetadata.Id), Parameter: nameof(videoMetadata.Id)),
(Rule: IsInvalid(videoMetadata.Title), Parameter: nameof(videoMetadata.Title)),
(Rule: IsInvalid(videoMetadata.BlobPath), Parameter: nameof(videoMetadata.BlobPath)),
(Rule: IsInvalid(videoMetadata.CreatedDate), Parameter: nameof(videoMetadata.CreatedDate)),
(Rule: IsInvalid(videoMetadata.UpdatedDate), Parameter: nameof(videoMetadata.UpdatedDate)));
(Rule: IsInvalid(videoMetadata.Id), Parameter: nameof(VideoMetadata.Id)),
(Rule: IsInvalid(videoMetadata.Title), Parameter: nameof(VideoMetadata.Title)),
(Rule: IsInvalid(videoMetadata.BlobPath), Parameter: nameof(VideoMetadata.BlobPath)),
(Rule: IsInvalid(videoMetadata.CreatedDate), Parameter: nameof(VideoMetadata.CreatedDate)),
(Rule: IsInvalid(videoMetadata.UpdatedDate), Parameter: nameof(VideoMetadata.UpdatedDate)),
(Rule: IsNotRecent(videoMetadata.CreatedDate), Parameter: nameof(VideoMetadata.CreatedDate)),

(Rule: IsNotSame(
firstDate: videoMetadata.CreatedDate,
secondDate: videoMetadata.UpdatedDate,
secondDateName: nameof(VideoMetadata.UpdatedDate)),
Parameter: nameof(VideoMetadata.CreatedDate))
);
}
private void ValidationVideoMetadataNotNull(VideoMetadata videoMetadata)
{
Expand All @@ -27,25 +35,50 @@ private void ValidationVideoMetadataNotNull(VideoMetadata videoMetadata)
throw new NullVideoMetadataException(message: "Video metadata is null");
}
}
private static dynamic IsInvalid(Guid id) => new
private static dynamic IsNotSame(
DateTimeOffset firstDate,
DateTimeOffset secondDate,
string secondDateName) => new
{
Condition = firstDate != secondDate,
Message = $"Date is not same as {secondDateName}"
};

private dynamic IsNotRecent(DateTimeOffset date) => new
{
Condition = id == Guid.Empty,
Message = "Id is required"
Condition = IsDateNotRecent(date),
Message = "Date is not recent"
};

private bool IsDateNotRecent(DateTimeOffset date)
{
DateTimeOffset currentDateTime = this.dateTimeBroker.GetCurrentDateTimeOffset();
TimeSpan timeDifference = currentDateTime.Subtract(date);

return timeDifference.TotalSeconds is > 60 or < 0;
}

private static dynamic IsInvalid(Guid Id) => new
{
Condition = Id == Guid.Empty,
Message = "Id is required."
};

private static dynamic IsInvalid(string text) => new
{
Condition = string.IsNullOrWhiteSpace(text),
Message = "Text is required"
Message = "Text is required."
};

private static dynamic IsInvalid(DateTimeOffset date) => new
{
Condition = date == default,
Message = "Data is required"
Condition = date == default(DateTimeOffset),
Message = "Date is required."
};

private static void Validate(params (dynamic Rule, string Parameter)[] validations)
{
var invalidVideoMetadataException =
new InvalidVideoMetadataException(message: "Video metadata is invalid");
var invalidVideoMetadataException = new InvalidVideoMetadataException(message: "Video Metadata is invalid.");

foreach ((dynamic rule, string parameter) in validations)
{
Expand All @@ -54,6 +87,7 @@ private static void Validate(params (dynamic Rule, string Parameter)[] validatio
invalidVideoMetadataException.UpsertDataList(parameter, rule.Message);
}
}

invalidVideoMetadataException.ThrowIfContainsErrors();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//Copyright (c) Coalition of Good-Hearted Engineers
//Free To Use To Find Comfort and Pease
//=================================================
using UsefulTime.Api.Brokers.DateTimes;
using UsefulTime.Api.Brokers.Loggings;
using UsefulTime.Api.Brokers.Storages;
using UsefulTime.Api.Models.VideoMetadatas;
Expand All @@ -12,11 +13,14 @@ public partial class VideoMetadataService : IVideoMetadataService
{
private readonly IStorageBroker storageBroker;
private readonly ILoggingBroker loggingBroker;
private readonly IDateTimeBroker dateTimeBroker;

public VideoMetadataService(IStorageBroker storageBroker, ILoggingBroker loggingBroker)
public VideoMetadataService(IStorageBroker storageBroker, ILoggingBroker loggingBroker,
IDateTimeBroker dateTimeBroker)
{
this.storageBroker = storageBroker;
this.loggingBroker = loggingBroker;
this.dateTimeBroker = dateTimeBroker;
}
public ValueTask<VideoMetadata> AddVideoMetadataAsync(VideoMetadata videoMetadata) =>
TryCatch(async () =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using EFxceptions.Models.Exceptions;
using FluentAssertions;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Moq;
using UsefulTime.Api.Models.VideoMetadatas;
using UsefulTime.Api.Models.VideoMetadatas.Exceptions;
Expand Down Expand Up @@ -103,5 +104,50 @@ public async Task ShouldThrowDependencyValidationOnAddIfDublicateKeyErrorOccursA
this.storageBrokerMock.VerifyNoOtherCalls();
this.loggingBrokerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task ShouldThrowDependencyValidationExceptionOnAddIfDbCurrencyErrorOccursAndLogItAsync()
{
//given
VideoMetadata someVideoMetadata = CreateRandomVideoMetadata();
var dbUpdateConcurrencyException = new DbUpdateConcurrencyException();

var lockedVideoMetadataException =
new LockedVideoMetadataException("Video Metadata is locked, please try again.",
dbUpdateConcurrencyException);

var expectedVideoMetadataDependencyValidationException =
new VideoMetadataDependencyValidationException(
"Video Metadata dependency error occured, Fix errors and try again.",
lockedVideoMetadataException);

this.dateTimeBrokerMock.Setup(broker =>
broker.GetCurrentDateTimeOffset())
.Throws(dbUpdateConcurrencyException);

//when
ValueTask<VideoMetadata> addVideoMetadataTask =
this.videoMetadataService.AddVideoMetadataAsync(someVideoMetadata);

var actualVideoMetadataDependencyValidationException =
await Assert.ThrowsAsync<VideoMetadataDependencyValidationException>(addVideoMetadataTask.AsTask);

//then
actualVideoMetadataDependencyValidationException.Should()
.BeEquivalentTo(expectedVideoMetadataDependencyValidationException);

this.dateTimeBrokerMock.Verify(broker =>
broker.GetCurrentDateTimeOffset(), Times.Once);

this.loggingBrokerMock.Verify(broker =>
broker.LogError(It.Is(SameExceptionAs(expectedVideoMetadataDependencyValidationException))),
Times.Once);

this.storageBrokerMock.Verify(broker =>
broker.InsertVideoMetadataAsync(someVideoMetadata), Times.Never);

this.dateTimeBrokerMock.VerifyNoOtherCalls();
this.storageBrokerMock.VerifyNoOtherCalls();
this.loggingBrokerMock.VerifyNoOtherCalls();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq.Expressions;
using System.Runtime.Serialization;
using Tynamix.ObjectFiller;
using UsefulTime.Api.Brokers.DateTimes;
using UsefulTime.Api.Brokers.Loggings;
using UsefulTime.Api.Brokers.Storages;
using UsefulTime.Api.Models.VideoMetadatas;
Expand All @@ -20,16 +21,19 @@
{
private readonly Mock<IStorageBroker> storageBrokerMock;
private readonly Mock<ILoggingBroker> loggingBrokerMock;
private readonly Mock<IDateTimeBroker> dateTimeBrokerMock;
private readonly IVideoMetadataService videoMetadataService;

public VideoMetadataServiceTest()
{
this.storageBrokerMock = new Mock<IStorageBroker>();
this.loggingBrokerMock = new Mock<ILoggingBroker>();
this.dateTimeBrokerMock= new Mock<IDateTimeBroker>();

this.videoMetadataService = new VideoMetadataService
(storageBroker: this.storageBrokerMock.Object,
loggingBroker: loggingBrokerMock.Object);
loggingBroker: this.loggingBrokerMock.Object,
dateTimeBroker: this.dateTimeBrokerMock.Object);
}

private Expression<Func<Xeption, bool>> SameExceptionAs(Xeption expectedException) =>
Expand All @@ -49,7 +53,7 @@
return filler;
}
private static SqlException GetSqlException()=>
(SqlException)FormatterServices.GetUninitializedObject(typeof(SqlException));

Check warning on line 56 in UsefulTime.Unit.Tests/Services/Foundations/VideoMetadatas/VideoMetadataServiceTest.cs

View workflow job for this annotation

GitHub Actions / build

'FormatterServices' is obsolete: 'Formatter-based serialization is obsolete and should not be used.' (https://aka.ms/dotnet-warnings/SYSLIB0050)
private static string GetRandomString()
{
return new MnemonicString().GetValue();
Expand Down
Loading