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

Services and extensions tests #61

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 0 additions & 10 deletions Doppler.ImageAnalyzer.Api/Controllers/DopplerControllerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,6 @@ protected DopplerControllerBase(IMediator mediator)
_mediator = mediator;
}

protected ActionResult HandleResponse(Response response, string logMessage)
{
if (!response.IsSuccessStatusCode)
{
return StatusCode((int)response.StatusCode, response.ValidationIssue);
}

return Ok();
}

protected ActionResult HandleResponse<T>(Response<T> response, string logMessage)
{
if (!response.IsSuccessStatusCode)
Expand Down
8 changes: 0 additions & 8 deletions Doppler.ImageAnalyzer.Api/Extensions/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,4 @@ public static Response<T> ToResponse<T>(this Exception exception, string? refere
: exception.ToString(); // Kept for backward compatibility.
return Response.GetResponseError<T>(statusCode: HttpStatusCode.InternalServerError, errorKey: UnexpectedErrorKey, errorDescription: description, exception: exception);
}

public static Response ToResponse(this Exception exception, string? referenceId = null)
{
var description = referenceId != null
? $"ReferenceId: {referenceId}"
: exception.ToString(); // Kept for backward compatibility.
return Response.GetResponseError(statusCode: HttpStatusCode.InternalServerError, errorKey: UnexpectedErrorKey, errorDescription: description, exception: exception);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,4 @@ public interface IRekognition
float? MinConfidence { get; set; }
int? MaxLabels { get; set; }
string? ProjectVersionArn { get; set; }
public bool? Customlabels { get; set; }

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,4 @@ public class Rekognition : IRekognition
public float? MinConfidence { get; set; }
public int? MaxLabels { get; set; }
public string? ProjectVersionArn { get; set; }
public bool? Customlabels { get; set; }

}
7 changes: 2 additions & 5 deletions Doppler.ImageAnalyzer.UnitTests/Api/Http/HttpTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;

namespace Doppler.ImageAnalyzer.UnitTests.Api.Http;
namespace Doppler.ImageAnalyzer.UnitTests.Api.Http;

public class HttpTests
{
Expand Down Expand Up @@ -93,4 +90,4 @@ public async Task POST_analyze_endpoint_with_invalid_should_return_401(string re

Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;

namespace Doppler.ImageAnalyzer.UnitTests.Api.Http;

class PlaygroundApplication : WebApplicationFactory<Program>
Expand Down
56 changes: 56 additions & 0 deletions Doppler.ImageAnalyzer.UnitTests/Api/Services/ExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
namespace Doppler.ImageAnalyzer.UnitTests.Api.Services;

public class ExtensionsTests
{
public ExtensionsTests()
{
}

[Fact]
public void LabelExtension_ToImageConfidence_WhenOk()
{
var label = new Label
{
Confidence = 90,
Name = "Name"
};

var result = label.ToImageConfidence();

Assert.True(result.Label == label.Name);
Assert.True(result.Confidence == label.Confidence);
Assert.False(result.IsModeration);
}

[Fact]
public void CustomLabelExtension_ToImageConfidence_WhenOk()
{
var customLabel = new CustomLabel
{
Confidence = 90,
Name = "Name"
};

var result = customLabel.ToImageConfidence();

Assert.True(result.Label == customLabel.Name);
Assert.True(result.Confidence == customLabel.Confidence);
Assert.False(result.IsModeration);
}

[Fact]
public void ModerationLabel_ToImageConfidence_WhenOk()
{
var moderationLabel = new ModerationLabel
{
Confidence = 90,
Name = "Name"
};

var result = moderationLabel.ToImageConfidence();

Assert.True(result.Label == moderationLabel.Name);
Assert.True(result.Confidence == moderationLabel.Confidence);
Assert.True(result.IsModeration);
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
namespace Doppler.ImageAnalyzer.UnitTests.Api.Services;

public class ImageProcessorTests
{
private readonly Mock<IImageDownloadClient> _imageDownloadClient;
private readonly Mock<IS3Client> _s3Client;
private readonly Mock<IRekognitionClient> _rekognitionClient;
private readonly Mock<IAppConfiguration> _appConfiguration;
private readonly IAppConfiguration _appConfiguration;

public ImageProcessorTests()
{
_imageDownloadClient = new Mock<IImageDownloadClient>();
_s3Client = new Mock<IS3Client>();
_rekognitionClient = new Mock<IRekognitionClient>();
_appConfiguration = new Mock<IAppConfiguration>();
_appConfiguration = new AppConfiguration();

var amazonS3Configuration = new AmazonS3Configuration
{
BucketName = "bucketName",
Path = "/",
};
var amazonRekognition = new AmazonRekognitionConfiguration
{
MinConfidence = 50,
MaxLabels = 10,
Customlabels = false
};
_appConfiguration.AmazonS3 = amazonS3Configuration;
_appConfiguration.AmazonRekognition = amazonRekognition;
}

[Fact]
Expand All @@ -21,10 +34,58 @@ public async Task ImageProcessor_GivenNullStream_ShouldReturnNull()
_imageDownloadClient.Setup(x => x.GetImageStream(It.IsAny<string>(), CancellationToken.None))
.ReturnsAsync((Stream)null);

var service = new ImageProcessor(_imageDownloadClient.Object, _s3Client.Object, _rekognitionClient.Object, _appConfiguration.Object);
var service = new ImageProcessor(_imageDownloadClient.Object, _s3Client.Object, _rekognitionClient.Object, _appConfiguration);

var result = await service.ProcessImage("http://filename.jpg", AnalysisType.AllLabels, CancellationToken.None);

Assert.True(result == null);
}

[Theory]
[InlineData(AnalysisType.ModerationContent, true, 1)]
[InlineData(AnalysisType.AllLabels, true, 2)]
[InlineData(AnalysisType.ModerationContent, false, 1)]
[InlineData(AnalysisType.AllLabels, false, 2)]
public async Task ImageProcessor_GivenValidStream_ShouldReturnConfidences(AnalysisType analysisType, bool customlabels, int confidenceCount)
{
_appConfiguration.AmazonRekognition.Customlabels = customlabels;
_imageDownloadClient.Setup(x => x.GetImageStream(It.IsAny<string>(), CancellationToken.None))
.ReturnsAsync(new MemoryStream(Encoding.UTF8.GetBytes("abc")));

_s3Client.Setup(x => x.UploadStreamAsync(It.IsAny<Stream>(), It.IsAny<IS3File>(), CancellationToken.None))
.Verifiable();

_rekognitionClient.Setup(x => x.DetectModerationLabelsAsync(It.IsAny<IS3File>(), It.IsAny<IRekognition>(), CancellationToken.None))
.ReturnsAsync(new List<ImageConfidence>
{
new ImageConfidence
{
FileName = "filename1",
Url = "http://filename2",
Label = "",
Confidence = 90,
IsModeration = true
}
});

_rekognitionClient.Setup(x => x.DetectLabelsAsync(It.IsAny<IS3File>(), It.IsAny<IRekognition>(), CancellationToken.None))
.ReturnsAsync(new List<ImageConfidence>
{
new ImageConfidence
{
FileName = "filename2",
Url = "http://filename1",
Label = "",
Confidence = 90,
IsModeration = true
}
});

var service = new ImageProcessor(_imageDownloadClient.Object, _s3Client.Object, _rekognitionClient.Object, _appConfiguration);

var result = await service.ProcessImage("http://filename.jpg", analysisType, CancellationToken.None);

Assert.False(result == null);
Assert.True(result.Count() == confidenceCount);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,4 @@ public void TestIsValidUrl()

Assert.False(extractor.IsValidUrl(invalidCharacterUrl));
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
namespace Doppler.ImageAnalyzer.UnitTests.Api.Services;

public class RekognitionClientTests
{
private readonly Mock<IAmazonRekognition> _amazonRekognition;
public RekognitionClientTests()
{
_amazonRekognition = new Mock<IAmazonRekognition>();
}

[Fact]
public async Task DetectModerationLabel_ReturnListOfConfidences_WhenOk()
{
_amazonRekognition.Setup(x => x.DetectModerationLabelsAsync(It.IsAny<DetectModerationLabelsRequest>(), CancellationToken.None))
.ReturnsAsync(new DetectModerationLabelsResponse());

var service = new RekognitionClient(_amazonRekognition.Object);

var (s3File, rekognition) = CreateamazonServiceParameters();

var result = await service.DetectModerationLabelsAsync(s3File, rekognition, CancellationToken.None);

Assert.True(result != null);
}

[Fact]
public async Task DetectLabels_ReturnListOfConfidences_WhenOk()
{
_amazonRekognition.Setup(x => x.DetectLabelsAsync(It.IsAny<DetectLabelsRequest>(), CancellationToken.None))
.ReturnsAsync(new DetectLabelsResponse());
var service = new RekognitionClient(_amazonRekognition.Object);

var (s3File, rekognition) = CreateamazonServiceParameters();

var result = await service.DetectLabelsAsync(s3File, rekognition, CancellationToken.None);

Assert.True(result != null);
}

[Fact]
public async Task DetectCustomLabelsAsync_ReturnListOfConfidences_WhenOk()
{
_amazonRekognition.Setup(x => x.DetectCustomLabelsAsync(It.IsAny<DetectCustomLabelsRequest>(), CancellationToken.None))
.ReturnsAsync(new DetectCustomLabelsResponse
{
CustomLabels = new List<CustomLabel> {
new CustomLabel {
Confidence = 90,
Name = "label1"
},
new CustomLabel {
Confidence = 90,
Name = "label2"
}
}
});

var service = new RekognitionClient(_amazonRekognition.Object);

var (s3File, rekognition) = CreateamazonServiceParameters();

var result = await service.DetectCustomLabelsAsync(s3File, rekognition, CancellationToken.None);

Assert.True(result != null);
}

private static (S3File, Rekognition) CreateamazonServiceParameters()
{
var s3file = new S3File
{
BucketName = "bucketName",
Path = "/",
FileName = "Filename.jpg"
};
var rekognition = new Rekognition
{
MinConfidence = 90,
MaxLabels = 10,
ProjectVersionArn = ""
};

return new(s3file, rekognition);
}
}
33 changes: 33 additions & 0 deletions Doppler.ImageAnalyzer.UnitTests/Api/Services/S3ClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace Doppler.ImageAnalyzer.UnitTests.Api.Services;

public class S3ClientTests
{
private readonly Mock<IAmazonS3> _amazonS3;

public S3ClientTests()
{
_amazonS3 = new Mock<IAmazonS3>();
}

[Fact]
public async Task UploadStreamAsync_VerifyMethodExecution_WhenOk()
{
_amazonS3.Setup(x => x.UploadObjectFromStreamAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Stream>(), null, CancellationToken.None))
.Verifiable();

var service = new S3Client(_amazonS3.Object);

var s3file = new S3File
{
BucketName = "bucketName",
Path = "/",
FileName = "Filename.jpg"
};

var stream = new MemoryStream(Encoding.UTF8.GetBytes("abc"));

await service.UploadStreamAsync(stream, s3file, CancellationToken.None);

_amazonS3.Verify(x => x.UploadObjectFromStreamAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Stream>(), null, CancellationToken.None), Times.Once());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,20 @@ public async Task AnalyzeImageList_GivenValidImages_ShouldReturnResponseWithAnal
Assert.True(response.Payload != null);
Assert.True(response.Payload.Count == 1);
}

[Fact]
public async Task AnalyzeImageList_GivenWrongAnalysisType_ShouldReturnEmptyAnalysisList()
{
_imageProcessor.Setup(x => x.ProcessImage(It.IsAny<string>(), It.IsAny<AnalysisType>(), CancellationToken.None))
.ReturnsAsync(new List<ImageConfidence> { new ImageConfidence { Confidence = (float?)0.99, FileName = "filename.jpg", IsModeration = true, Label = "Label" } });
var command = new AnalyzeImageListCommand.Command { ImageUrls = new List<string> { "http://filename.jpg" }, AnalysisType = "NonExisting" };
var handler = new AnalyzeImageListCommand.Handler(_imageUrlExtractor, _analysisOrchestrator);

var response = await handler.Handle(command, CancellationToken.None);

Assert.True(response.IsSuccessStatusCode);
Assert.True(response.StatusCode == HttpStatusCode.OK);
Assert.True(response.Payload != null);
Assert.True(response.Payload.Count == 0);
}
}
15 changes: 14 additions & 1 deletion Doppler.ImageAnalyzer.UnitTests/Utils/_Imports.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
global using Doppler.ImageAnalyzer.Api.Api;
global using Amazon.S3;
global using Amazon.Rekognition;
global using Amazon.Rekognition.Model;
global using Doppler.ImageAnalyzer.Api.Api;
global using Doppler.ImageAnalyzer.Api.Configurations;
global using Doppler.ImageAnalyzer.Api.Configurations.Amazon;
global using Doppler.ImageAnalyzer.Api.Configurations.Interfaces;
global using Doppler.ImageAnalyzer.Api.Controllers;
global using Doppler.ImageAnalyzer.Api.Features.Analysis.Commands.AnalyzeHtml;
global using Doppler.ImageAnalyzer.Api.Features.Analysis.Commands.AnalyzeImageList;
global using Doppler.ImageAnalyzer.Api.Features.Analysis.Requests;
global using Doppler.ImageAnalyzer.Api.Features.Analysis.Responses;
global using Doppler.ImageAnalyzer.Api.Services.AmazonRekognition;
global using Doppler.ImageAnalyzer.Api.Services.AmazonRekognition.Interfaces;
global using Doppler.ImageAnalyzer.Api.Services.AmazonRekognition.Extensions;
global using Doppler.ImageAnalyzer.Api.Services.AmazonS3;
global using Doppler.ImageAnalyzer.Api.Services.AmazonS3.Interfaces;
global using Doppler.ImageAnalyzer.Api.Services.ImageAnalysis;
global using Doppler.ImageAnalyzer.Api.Services.ImageAnalysis.Interfaces;
Expand All @@ -16,6 +24,11 @@
global using Doppler.ImageAnalyzer.Api.Services.ImageUrlExtractor;
global using Doppler.ImageAnalyzer.Api.Services.ImageUrlExtractor.Interfaces;
global using MediatR;
global using Microsoft.AspNetCore.Mvc.Testing;
global using Microsoft.Extensions.Hosting;
global using Moq;
global using System.Net;
global using System.Net.Http.Headers;
global using System.Net.Http.Json;
global using System.Text;
global using Xunit;