Browse Source

Merge branch 'feature/added_test_for_imports' of Neca/HRCenter into BE_dev

pull/153/head
safet.purkovic 3 years ago
parent
commit
7c240e6125

+ 17
- 17
Diligent.WebAPI.Business/Services/Emailer.cs View File

@@ -244,25 +244,25 @@ namespace Diligent.WebAPI.Business.Services
/// <exception cref="ArgumentException"></exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public async Task<bool> SendEmailWithDelayAsync(List<string> to, string subject, string body, bool isHtml = false, DateTime? dontSendBefore = null)
{
try
{
var email = CreateEmail(to, subject, body, isHtml, dontSendBefore);
//public async Task<bool> SendEmailWithDelayAsync(List<string> to, string subject, string body, bool isHtml = false, DateTime? dontSendBefore = null)
//{
// try
// {
// var email = CreateEmail(to, subject, body, isHtml, dontSendBefore);

//var result = await WriteEmailToDbAsync(email);
// //var result = await WriteEmailToDbAsync(email);

return true;
}
catch (ArgumentException)
{
throw;
}
catch (Exception e)
{
throw new Exception("Error while attempting to send an email with delay.", e);
}
}
// return true;
// }
// catch (ArgumentException)
// {
// throw;
// }
// catch (Exception e)
// {
// throw new Exception("Error while attempting to send an email with delay.", e);
// }
//}

/// <summary>
/// Creates a <see cref="DiligEmail"/> object with specified arguments.

+ 0
- 1
Diligent.WebAPI.Business/Services/Interfaces/IEmailer.cs View File

@@ -14,6 +14,5 @@ namespace Diligent.WebAPI.Business.Services.Interfaces
Task<bool> SendEmailAndWriteToDbAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null);
Task<bool> SendEmailAndWriteToDbAsync(string to, string subject, string body, bool isHtml = false, List<string> cc = null);
Task<bool> SendEmailAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null);
Task<bool> SendEmailWithDelayAsync(List<string> to, string subject, string body, bool isHtml = false, DateTime? dontSendBefore = null);
}
}

+ 10
- 5
Diligent.WebAPI.Business/Services/SaveImportedDataService.cs View File

@@ -6,12 +6,10 @@ namespace Diligent.WebAPI.Business.Services
public class SaveImportedDataService : ISaveImportedDataService
{
private readonly ILogger<SaveImportedDataService> _logger;
private readonly IApplicantService _applicantService;
private readonly IAdService _adService;

public SaveImportedDataService(IApplicantService applicantService, ILogger<SaveImportedDataService> logger, IAdService adService)
public SaveImportedDataService(ILogger<SaveImportedDataService> logger, IAdService adService)
{
_applicantService = applicantService;
_logger = logger;
_adService = adService;
}
@@ -20,14 +18,18 @@ namespace Diligent.WebAPI.Business.Services
List<ApplicantImportDto> applicants = new List<ApplicantImportDto>();
try
{
_logger.LogInformation("Unoirtubg data from file...");
var path = Path.Combine(Directory.GetCurrentDirectory(), "Files", "s.xlsx");
Spreadsheet document = new Spreadsheet();
document.LoadFromFile(path);
_logger.LogInformation("File is opened successfully");
var worksheetsNumber = document.Workbook.Worksheets.Count;
_logger.LogInformation($"File contains {worksheetsNumber} sheets");
for (int k = 0; k < worksheetsNumber; k++)
{
var worksheets = document.Workbook.Worksheets[k];
var position = worksheets.Name;
_logger.LogInformation($"Import data for Ad {position}");
var ad = await _adService.ImportAsync(new AdCreateDto
{
Title = position,
@@ -60,6 +62,7 @@ namespace Diligent.WebAPI.Business.Services
Ad = ad,
TypeOfEmployment = position.Contains("praksa") ? "Praksa" : "Posao"
};
_logger.LogInformation($"Loaded user {a.FirstName} {a.LastName}");
try
{
string str = worksheets.Cell(i, 3).ToString();
@@ -69,16 +72,18 @@ namespace Diligent.WebAPI.Business.Services
}
catch (Exception ex)
{
_logger.LogError("Incorect date time for this candidate");
}
applicants.Add(a);
_logger.LogInformation("Candidate added successfully in the list");
i++;
}
}
}
catch (Exception e)
{

_logger.LogError(e.Message);
throw new FileNotFoundException("File is not uploaded!");
}
return applicants;
}

+ 1
- 0
Diligent.WebAPI.Host/Attributes/AuthorizeAttribute.cs View File

@@ -1,5 +1,6 @@
namespace Diligent.WebAPI.Host.Attributes
{
[ExcludeFromCodeCoverage]
[AttributeUsage(AttributeTargets.Method)]
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{

+ 2
- 2
Diligent.WebAPI.Host/Middlewares/ExceptionMiddleware.cs View File

@@ -22,7 +22,7 @@ namespace Diligent.WebAPI.Host.Middlewares
public DiligBadRequestException(string message, Exception innerException) : base(message, innerException) { }
public DiligBadRequestException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[ExcludeFromCodeCoverage]
public class DiligExceptionMiddleware
{
private readonly RequestDelegate _next;
@@ -112,7 +112,7 @@ namespace Diligent.WebAPI.Host.Middlewares
return context.Response.WriteAsync(responseString);
}
}
[ExcludeFromCodeCoverage]
public static class DiligExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseDiligExceptionHandler(this IApplicationBuilder app)

+ 4
- 0
Diligent.WebAPI.Tests/Diligent.WebAPI.Tests.csproj View File

@@ -31,4 +31,8 @@
<ProjectReference Include="..\Diligent.WebAPI.Host\Diligent.WebAPI.Host.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="TestResults\" />
</ItemGroup>

</Project>

+ 127
- 0
Diligent.WebAPI.Tests/Services/EmailerTests.cs View File

@@ -0,0 +1,127 @@
using Diligent.WebAPI.Business.Services;
using Diligent.WebAPI.Business.Services.Interfaces;
using Diligent.WebAPI.Business.Settings;
using Diligent.WebAPI.Contracts.Exceptions;
using Diligent.WebAPI.Contracts.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute.ExceptionExtensions;
using System.Net.Mail;

namespace Diligent.WebAPI.Tests.Services
{
public class EmailerTests
{
private readonly IOptions<MailSettings> _settings;
private readonly ILogger<Emailer> _logger = Substitute.For<ILogger<Emailer>>();
private readonly DiligEmail _email;
private readonly MailMessage _message;
private readonly List<string> _emailAddresses;
private readonly List<string> _emailAddressesCC;
private readonly MailSettings _mailSettings;
public EmailerTests()
{
_emailAddresses = new List<string> { "dzenis@dilig.net", "meris@dilig.net" };
_emailAddressesCC = new List<string> { "ermin@dilig.net", "safet@dilig.net" };
_email = new DiligEmail
{
To = "dzenis@dilig.net;meris@dilig.net",
Subject = "Forget password",
Body = "Forget password"
};
_message = new MailMessage
{
Subject = "Forget password",
Body = "Forget password",
IsBodyHtml = false,
Sender = new MailAddress("htcenter@dilig.net", "hrcenter"),
From = new MailAddress("htcenter@dilig.net")
};
_message.To.Add(string.Join(",", _emailAddresses));
_message.CC.Add(string.Join(",", _emailAddressesCC));
_mailSettings = new MailSettings
{
SmtpFrom = "htcenter@dilig.net",
SmtpFromName = "hrcenter",
SmtpServer = "gmail",
SmtpPassword = "Password123?",
SmtpPort = 5000,
SmtpUsername = "hrcenter",
SmtpUseSSL = true
};
_settings = Options.Create<MailSettings>(_mailSettings);
}
[Fact]
public void CreateEmail_ShouldReturnDiligEmail_WhenArgumentsAreSent()
{
Emailer emailer = new Emailer(_settings, _logger);
var result = emailer.CreateEmail(new List<string>() { "dzenis@dilig.net","meris@dilig.net"},
"Forget password","Forget password");
result.Should().Be(_email);
}

[Fact]
public void CreateEmail_ShouldThrowArgumentException_WhenListOfReceiveresIsEmpty()
{
Emailer emailer = new Emailer(_settings, _logger);

Assert.Throws<ArgumentException>( () => emailer.CreateEmail(new List<string>(), "Forget password",
"Forget password"));
}
[Fact]
public void GetMailMessage_ShouldReturnMailMessage_WhenArgumentsAreSent()
{
Emailer emailer = new Emailer(_settings, _logger);
var result = emailer.GetMailMessage(_emailAddresses,
"Forget password","Forget password",false,_emailAddressesCC);
result.Subject.Should().Be(_message.Subject);
result.Body.Should().Be(_message.Body);
result.IsBodyHtml.Should().Be(_message.IsBodyHtml);
result.Sender.Should().Be(_message.Sender);
result.From.Should().Be(_message.From);
result.To.Should().HaveCount(_message.To.Count());
result.CC.Should().HaveCount(_message.CC.Count());
}

[Fact]
public void GetMailMessage_ShouldThrowArgumentException_WhenListOfReceiveresIsEmpty()
{
Emailer emailer = new Emailer(_settings, _logger);

Assert.Throws<ArgumentException>(() => emailer.GetMailMessage(new List<string>(), "Forget password",
"Forget password"));
}
[Fact]
public void GetSmtpClient_ShouldReturnGetSmtpClient_WhenSettingsArePresent()
{
Emailer emailer = new Emailer(_settings, _logger);
var result = emailer.GetSmtpClient();

result.EnableSsl.Should().Be(_mailSettings.SmtpUseSSL);
result.Port.Should().Be(_mailSettings.SmtpPort);
result.Host.Should().Be(_mailSettings.SmtpServer);
}
[Fact]
public void SendEmailAsync_ShouldThrowArgumentException_WhenListOfReceiveresIsEmpty()
{
Emailer emailer = new Emailer(_settings, _logger);

Assert.ThrowsAsync<ArgumentException>(async () => await emailer.SendEmailAsync(new List<string>(), "Forget password",
"Forget password"));
}
//[Fact]
//public async Task SendEmailAndWriteToDbAsync_ShouldReturnDiligEmail_WhenArgumentsAreSent()
//{
// Emailer emailer = new Emailer(_settings, _logger);

// emailer.When(x => x.SendEmailAsync(Arg.Any<List<string>>(),Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<List<string>>())).ReturnsForAll(true);

// var result = emailer.SendEmailAndWriteToDbAsync(new List<string>() { "dzenis@dilig.net", "meris@dilig.net" },
// "Forget password", "Forget password");

// result.Should().Be(_email);
//}
}
}

+ 44
- 0
Diligent.WebAPI.Tests/Services/ImportServiceTests.cs View File

@@ -0,0 +1,44 @@
using Diligent.WebAPI.Business.Services;
using Diligent.WebAPI.Contracts.DTOs.Applicant;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Diligent.WebAPI.Tests.Services
{
public class ImportServiceTests
{
private readonly List<ApplicantImportDto> _applicantImportDtos;
private readonly ILogger<ImportService> _logger = Substitute.For<ILogger<ImportService>>();
private readonly ISaveImportedDataService _service = Substitute.For<ISaveImportedDataService>();
private readonly IFormFile file = Substitute.For<IFormFile>();
public ImportServiceTests()
{
_applicantImportDtos = new List<ApplicantImportDto>
{
new ApplicantImportDto{ Email = "dzenis@dilig.net" },
new ApplicantImportDto{ Email = "meris@dilig.net" },
new ApplicantImportDto{ Email = "ermin@dilig.net" }
};
}

[Fact]
public async Task TesImport_ShouldHaveThreeItems_WhenISaveImportedDataServiceReturnsThreeItems()
{
ImportService importService = new ImportService(_logger, _service);
_service.Save().Returns(_applicantImportDtos);

var result = await importService.Import(file);

result.Should().HaveCount(3);
}

[Fact]
public async Task TesImport_ShouldThrowsException_WhenErrorIsPresent()
{
ImportService importService = new ImportService(_logger, _service);
_service.When(x => x.Save()).Do(x => { throw new Exception(); });

await Assert.ThrowsAsync<Exception>(async () => await importService.Import(file));
}
}
}

+ 21
- 0
Diligent.WebAPI.Tests/Services/SaveImportedDataServiceTests.cs View File

@@ -0,0 +1,21 @@
using Diligent.WebAPI.Business.Services;
using Microsoft.Extensions.Logging;

namespace Diligent.WebAPI.Tests.Services
{
public class SaveImportedDataServiceTests
{
private readonly ILogger<SaveImportedDataService> _logger = Substitute.For<ILogger<SaveImportedDataService>>();
private readonly IAdService _adService = Substitute.For<IAdService>();
[Fact]
public async Task Save_ShouldSaveApplicantsInArray_WhenFileExists()
{
SaveImportedDataService service = new SaveImportedDataService(_logger, _adService);

var result = await service.Save();

result.Should().HaveCount(560);
}
}
}

+ 5
- 0
Diligent.WebAPI.Tests/Services/SelectionLevelsServiceTests.cs View File

@@ -4,9 +4,14 @@ using Diligent.WebAPI.Business.Services;
using Diligent.WebAPI.Contracts.DTOs.Ad;
using Diligent.WebAPI.Contracts.DTOs.Applicant;
using Diligent.WebAPI.Contracts.DTOs.SelectionLevel;
using Diligent.WebAPI.Contracts.DTOs.SelectionProcess;
using Diligent.WebAPI.Contracts.Exceptions;
using Diligent.WebAPI.Data.Entities;
using FluentAssertions.Common;
using Microsoft.Extensions.Logging;
using NSubstitute.ExceptionExtensions;
using NSubstitute.Extensions;
using System.Reflection;

namespace Diligent.WebAPI.Tests.Services
{

+ 5551
- 1
Diligent.WebAPI.Tests/coverage.json
File diff suppressed because it is too large
View File


Loading…
Cancel
Save