mirror of
https://github.com/volodymyrsmirnov/MalwareMultiScan.git
synced 2025-08-24 05:22:22 +00:00
unit tests for API (99% coverage)
This commit is contained in:
parent
7f2528eb1d
commit
b2902c128a
@ -6,14 +6,15 @@ namespace MalwareMultiScan.Api.Attributes
|
||||
/// <summary>
|
||||
/// Validate URI to be an absolute http(s) URL.
|
||||
/// </summary>
|
||||
internal class IsHttpUrlAttribute : ValidationAttribute
|
||||
public class IsHttpUrlAttribute : ValidationAttribute
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
|
||||
{
|
||||
if (!Uri.TryCreate((string)value, UriKind.Absolute, out var uri)
|
||||
|| !uri.IsAbsoluteUri
|
||||
|| uri.Scheme != "http" && uri.Scheme != "https")
|
||||
|| uri.Scheme.ToLowerInvariant() != "http"
|
||||
&& uri.Scheme.ToLowerInvariant() != "https")
|
||||
return new ValidationResult("Only absolute http(s) URLs are supported");
|
||||
|
||||
return ValidationResult.Success;
|
||||
|
@ -1,5 +1,5 @@
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Services;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@ -10,9 +10,9 @@ namespace MalwareMultiScan.Api.Controllers
|
||||
[Produces("application/octet-stream")]
|
||||
public class DownloadController : Controller
|
||||
{
|
||||
private readonly ScanResultService _scanResultService;
|
||||
private readonly IScanResultService _scanResultService;
|
||||
|
||||
public DownloadController(ScanResultService scanResultService)
|
||||
public DownloadController(IScanResultService scanResultService)
|
||||
{
|
||||
_scanResultService = scanResultService;
|
||||
}
|
||||
|
@ -2,7 +2,7 @@ using System.ComponentModel.DataAnnotations;
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Attributes;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@ -13,9 +13,9 @@ namespace MalwareMultiScan.Api.Controllers
|
||||
[Produces("application/json")]
|
||||
public class QueueController : Controller
|
||||
{
|
||||
private readonly ScanResultService _scanResultService;
|
||||
private readonly IScanResultService _scanResultService;
|
||||
|
||||
public QueueController(ScanResultService scanResultService)
|
||||
public QueueController(IScanResultService scanResultService)
|
||||
{
|
||||
_scanResultService = scanResultService;
|
||||
}
|
||||
@ -31,10 +31,10 @@ namespace MalwareMultiScan.Api.Controllers
|
||||
string storedFileId;
|
||||
|
||||
await using (var uploadFileStream = file.OpenReadStream())
|
||||
storedFileId = await _scanResultService.StoreFile(file.Name, uploadFileStream);
|
||||
storedFileId = await _scanResultService.StoreFile(file.FileName, uploadFileStream);
|
||||
|
||||
await _scanResultService.QueueUrlScan(result, Url.Action("Index", "Download", new {id = storedFileId},
|
||||
Request.Scheme, Request.Host.Value));
|
||||
Request?.Scheme, Request?.Host.Value));
|
||||
|
||||
return CreatedAtAction("Index", "ScanResults", new {id = result.Id}, result);
|
||||
}
|
||||
|
@ -1,6 +1,8 @@
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services;
|
||||
using MalwareMultiScan.Api.Services.Implementations;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@ -11,9 +13,9 @@ namespace MalwareMultiScan.Api.Controllers
|
||||
[Produces("application/json")]
|
||||
public class ScanResultsController : Controller
|
||||
{
|
||||
private readonly ScanResultService _scanResultService;
|
||||
private readonly IScanResultService _scanResultService;
|
||||
|
||||
public ScanResultsController(ScanResultService scanResultService)
|
||||
public ScanResultsController(IScanResultService scanResultService)
|
||||
{
|
||||
_scanResultService = scanResultService;
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using EasyNetQ;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
@ -5,30 +6,30 @@ using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MongoDB.Driver;
|
||||
using MongoDB.Driver.GridFS;
|
||||
|
||||
namespace MalwareMultiScan.Api.Extensions
|
||||
{
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal static class ServiceCollectionExtensions
|
||||
{
|
||||
public static void AddMongoDb(this IServiceCollection services, IConfiguration configuration)
|
||||
internal static void AddMongoDb(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddSingleton(
|
||||
serviceProvider =>
|
||||
{
|
||||
var db = new MongoClient(configuration.GetConnectionString("Mongo"));
|
||||
var client = new MongoClient(configuration.GetConnectionString("Mongo"));
|
||||
var db = client.GetDatabase(configuration.GetValue<string>("DatabaseName"));
|
||||
|
||||
return db.GetDatabase(
|
||||
configuration.GetValue<string>("DatabaseName"));
|
||||
});
|
||||
services.AddSingleton(client);
|
||||
services.AddSingleton(db);
|
||||
services.AddSingleton<IGridFSBucket>(new GridFSBucket(db));
|
||||
}
|
||||
|
||||
public static void AddRabbitMq(this IServiceCollection services, IConfiguration configuration)
|
||||
internal static void AddRabbitMq(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddSingleton(x =>
|
||||
RabbitHutch.CreateBus(configuration.GetConnectionString("RabbitMQ")));
|
||||
}
|
||||
|
||||
public static void AddDockerForwardedHeadersOptions(this IServiceCollection services)
|
||||
internal static void AddDockerForwardedHeadersOptions(this IServiceCollection services)
|
||||
{
|
||||
services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
|
@ -1,8 +1,10 @@
|
||||
using EasyNetQ.LightInject;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace MalwareMultiScan.Api
|
||||
{
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
|
@ -1,31 +1,21 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EasyNetQ;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using MalwareMultiScan.Backends.Messages;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MalwareMultiScan.Api.Services
|
||||
namespace MalwareMultiScan.Api.Services.Implementations
|
||||
{
|
||||
/// <summary>
|
||||
/// Receiver hosted service.
|
||||
/// </summary>
|
||||
public class ReceiverHostedService : IHostedService
|
||||
public class ReceiverHostedService : IReceiverHostedService
|
||||
{
|
||||
private readonly IBus _bus;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<ReceiverHostedService> _logger;
|
||||
private readonly ScanResultService _scanResultService;
|
||||
|
||||
/// <summary>
|
||||
/// Create receiver hosted service.
|
||||
/// </summary>
|
||||
/// <param name="bus">Service bus.</param>
|
||||
/// <param name="configuration">Configuration.</param>
|
||||
/// <param name="scanResultService">Scan result service.</param>
|
||||
/// <param name="logger">Logger.</param>
|
||||
public ReceiverHostedService(IBus bus, IConfiguration configuration, ScanResultService scanResultService,
|
||||
private readonly IScanResultService _scanResultService;
|
||||
|
||||
public ReceiverHostedService(IBus bus, IConfiguration configuration, IScanResultService scanResultService,
|
||||
ILogger<ReceiverHostedService> logger)
|
||||
{
|
||||
_bus = bus;
|
||||
@ -33,8 +23,7 @@ namespace MalwareMultiScan.Api.Services
|
||||
_scanResultService = scanResultService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_bus.Receive<ScanResultMessage>(_configuration.GetValue<string>("ResultsSubscriptionId"), async message =>
|
||||
@ -55,12 +44,10 @@ namespace MalwareMultiScan.Api.Services
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_bus.Dispose();
|
||||
_bus?.Dispose();
|
||||
|
||||
_logger.LogInformation(
|
||||
"Stopped hosted service for receiving scan results");
|
@ -4,29 +4,20 @@ using System.Threading.Tasks;
|
||||
using EasyNetQ;
|
||||
using MalwareMultiScan.Api.Data.Configuration;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using MalwareMultiScan.Backends.Messages;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
|
||||
namespace MalwareMultiScan.Api.Services
|
||||
namespace MalwareMultiScan.Api.Services.Implementations
|
||||
{
|
||||
/// <summary>
|
||||
/// Scan backends service.
|
||||
/// </summary>
|
||||
public class ScanBackendService
|
||||
public class ScanBackendService : IScanBackendService
|
||||
{
|
||||
private readonly IBus _bus;
|
||||
private readonly ILogger<ScanBackendService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Create scan backend service.
|
||||
/// </summary>
|
||||
/// <param name="configuration">Configuration.</param>
|
||||
/// <param name="bus">Service bus.</param>
|
||||
/// <param name="logger">Logger.</param>
|
||||
/// <exception cref="FileNotFoundException">Missing BackendsConfiguration YAML file.</exception>
|
||||
public ScanBackendService(IConfiguration configuration, IBus bus, ILogger<ScanBackendService> logger)
|
||||
{
|
||||
_bus = bus;
|
||||
@ -45,18 +36,9 @@ namespace MalwareMultiScan.Api.Services
|
||||
|
||||
List = deserializer.Deserialize<ScanBackend[]>(configurationContent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// List of available scan backends.
|
||||
/// </summary>
|
||||
|
||||
public ScanBackend[] List { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Queue URL scan.
|
||||
/// </summary>
|
||||
/// <param name="result">Scan result instance.</param>
|
||||
/// <param name="backend">Scan backend.</param>
|
||||
/// <param name="fileUrl">File download URL.</param>
|
||||
|
||||
public async Task QueueUrlScan(ScanResult result, ScanBackend backend, string fileUrl)
|
||||
{
|
||||
_logger.LogInformation(
|
@ -2,40 +2,29 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Driver;
|
||||
using MongoDB.Driver.GridFS;
|
||||
|
||||
namespace MalwareMultiScan.Api.Services
|
||||
namespace MalwareMultiScan.Api.Services.Implementations
|
||||
{
|
||||
/// <summary>
|
||||
/// Scan results service.
|
||||
/// </summary>
|
||||
public class ScanResultService
|
||||
public class ScanResultService : IScanResultService
|
||||
{
|
||||
private const string CollectionName = "ScanResults";
|
||||
|
||||
private readonly GridFSBucket _bucket;
|
||||
private readonly IGridFSBucket _bucket;
|
||||
private readonly IMongoCollection<ScanResult> _collection;
|
||||
private readonly ScanBackendService _scanBackendService;
|
||||
|
||||
/// <summary>
|
||||
/// Create scan result service.
|
||||
/// </summary>
|
||||
/// <param name="db">Mongo database.</param>
|
||||
/// <param name="scanBackendService">Scan backend service.</param>
|
||||
public ScanResultService(IMongoDatabase db, ScanBackendService scanBackendService)
|
||||
private readonly IScanBackendService _scanBackendService;
|
||||
|
||||
public ScanResultService(IMongoDatabase db, IGridFSBucket bucket, IScanBackendService scanBackendService)
|
||||
{
|
||||
_bucket = bucket;
|
||||
_scanBackendService = scanBackendService;
|
||||
|
||||
_bucket = new GridFSBucket(db);
|
||||
|
||||
_collection = db.GetCollection<ScanResult>(CollectionName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create scan result.
|
||||
/// </summary>
|
||||
/// <returns>Scan result.</returns>
|
||||
|
||||
public async Task<ScanResult> CreateScanResult()
|
||||
{
|
||||
var scanResult = new ScanResult
|
||||
@ -49,12 +38,7 @@ namespace MalwareMultiScan.Api.Services
|
||||
|
||||
return scanResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get scan result.
|
||||
/// </summary>
|
||||
/// <param name="id">Scan result id.</param>
|
||||
/// <returns>Scan result.</returns>
|
||||
|
||||
public async Task<ScanResult> GetScanResult(string id)
|
||||
{
|
||||
var result = await _collection.FindAsync(
|
||||
@ -62,16 +46,7 @@ namespace MalwareMultiScan.Api.Services
|
||||
|
||||
return await result.FirstOrDefaultAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update scan status for the backend.
|
||||
/// </summary>
|
||||
/// <param name="resultId">Result id.</param>
|
||||
/// <param name="backendId">Backend id.</param>
|
||||
/// <param name="duration">Duration of scan.</param>
|
||||
/// <param name="completed">If the scan has been completed.</param>
|
||||
/// <param name="succeeded">If the scan has been succeeded.</param>
|
||||
/// <param name="threats">List of found threats.</param>
|
||||
|
||||
public async Task UpdateScanResultForBackend(string resultId, string backendId, long duration,
|
||||
bool completed = false, bool succeeded = false, string[] threats = null)
|
||||
{
|
||||
@ -85,24 +60,13 @@ namespace MalwareMultiScan.Api.Services
|
||||
Threats = threats ?? new string[] { }
|
||||
}));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue URL scan.
|
||||
/// </summary>
|
||||
/// <param name="result">Scan result instance.</param>
|
||||
/// <param name="fileUrl">File URL.</param>
|
||||
|
||||
public async Task QueueUrlScan(ScanResult result, string fileUrl)
|
||||
{
|
||||
foreach (var backend in _scanBackendService.List.Where(b => b.Enabled))
|
||||
await _scanBackendService.QueueUrlScan(result, backend, fileUrl);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Store file.
|
||||
/// </summary>
|
||||
/// <param name="fileName">File name.</param>
|
||||
/// <param name="fileStream">File stream.</param>
|
||||
/// <returns>Stored file id.</returns>
|
||||
|
||||
public async Task<string> StoreFile(string fileName, Stream fileStream)
|
||||
{
|
||||
var objectId = await _bucket.UploadFromStreamAsync(
|
||||
@ -110,21 +74,23 @@ namespace MalwareMultiScan.Api.Services
|
||||
|
||||
return objectId.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Obtain stored file stream.
|
||||
/// </summary>
|
||||
/// <param name="id">File id.</param>
|
||||
/// <returns>File seekable stream.</returns>
|
||||
|
||||
public async Task<Stream> ObtainFile(string id)
|
||||
{
|
||||
if (!ObjectId.TryParse(id, out var objectId))
|
||||
return null;
|
||||
|
||||
return await _bucket.OpenDownloadStreamAsync(objectId, new GridFSDownloadOptions
|
||||
try
|
||||
{
|
||||
Seekable = true
|
||||
});
|
||||
return await _bucket.OpenDownloadStreamAsync(objectId, new GridFSDownloadOptions
|
||||
{
|
||||
Seekable = true
|
||||
});
|
||||
}
|
||||
catch (GridFSFileNotFoundException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace MalwareMultiScan.Api.Services.Interfaces
|
||||
{
|
||||
public interface IReceiverHostedService : IHostedService
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Data.Configuration;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
|
||||
namespace MalwareMultiScan.Api.Services.Interfaces
|
||||
{
|
||||
public interface IScanBackendService
|
||||
{
|
||||
ScanBackend[] List { get; }
|
||||
|
||||
Task QueueUrlScan(ScanResult result, ScanBackend backend, string fileUrl);
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
|
||||
namespace MalwareMultiScan.Api.Services.Interfaces
|
||||
{
|
||||
public interface IScanResultService
|
||||
{
|
||||
Task<ScanResult> CreateScanResult();
|
||||
|
||||
Task<ScanResult> GetScanResult(string id);
|
||||
|
||||
Task UpdateScanResultForBackend(string resultId, string backendId, long duration,
|
||||
bool completed = false, bool succeeded = false, string[] threats = null);
|
||||
|
||||
Task QueueUrlScan(ScanResult result, string fileUrl);
|
||||
|
||||
Task<string> StoreFile(string fileName, Stream fileStream);
|
||||
|
||||
Task<Stream> ObtainFile(string id);
|
||||
}
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using MalwareMultiScan.Api.Extensions;
|
||||
using MalwareMultiScan.Api.Services;
|
||||
using MalwareMultiScan.Api.Services.Implementations;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@ -7,7 +9,8 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace MalwareMultiScan.Api
|
||||
{
|
||||
public class Startup
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal class Startup
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
@ -28,8 +31,8 @@ namespace MalwareMultiScan.Api
|
||||
services.AddMongoDb(_configuration);
|
||||
services.AddRabbitMq(_configuration);
|
||||
|
||||
services.AddSingleton<ScanBackendService>();
|
||||
services.AddSingleton<ScanResultService>();
|
||||
services.AddSingleton<IScanBackendService, ScanBackendService>();
|
||||
services.AddSingleton<IScanResultService, ScanResultService>();
|
||||
|
||||
services.AddControllers();
|
||||
|
||||
|
57
MalwareMultiScan.Tests/AttributesTests.cs
Normal file
57
MalwareMultiScan.Tests/AttributesTests.cs
Normal file
@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MalwareMultiScan.Api.Attributes;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Configuration.Memory;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MalwareMultiScan.Tests
|
||||
{
|
||||
public class AttributesTests
|
||||
{
|
||||
[Test]
|
||||
public void TestIsHttpUrlAttribute()
|
||||
{
|
||||
var attribute = new IsHttpUrlAttribute();
|
||||
|
||||
Assert.True(attribute.IsValid("http://test.com/file.zip"));
|
||||
Assert.True(attribute.IsValid("https://test.com/file.zip"));
|
||||
Assert.True(attribute.IsValid("HTTPS://test.com"));
|
||||
Assert.False(attribute.IsValid(null));
|
||||
Assert.False(attribute.IsValid(string.Empty));
|
||||
Assert.False(attribute.IsValid("test"));
|
||||
Assert.False(attribute.IsValid("ftp://test.com"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestMaxFileSizeAttribute()
|
||||
{
|
||||
var attribute = new MaxFileSizeAttribute();
|
||||
|
||||
var configuration = new ConfigurationRoot(new List<IConfigurationProvider>
|
||||
{
|
||||
new MemoryConfigurationProvider(new MemoryConfigurationSource())
|
||||
})
|
||||
{
|
||||
["MaxFileSize"] = "100"
|
||||
};
|
||||
|
||||
var context = new ValidationContext(
|
||||
string.Empty, Mock.Of<IServiceProvider>(x =>
|
||||
x.GetService(typeof(IConfiguration)) == configuration
|
||||
), null);
|
||||
|
||||
Assert.True(attribute.GetValidationResult(
|
||||
Mock.Of<IFormFile>(x => x.Length == 10), context) == ValidationResult.Success);
|
||||
|
||||
Assert.True(attribute.GetValidationResult(
|
||||
Mock.Of<IFormFile>(x => x.Length == 100), context) == ValidationResult.Success);
|
||||
|
||||
Assert.False(attribute.GetValidationResult(
|
||||
Mock.Of<IFormFile>(x => x.Length == 101), context) == ValidationResult.Success);
|
||||
}
|
||||
}
|
||||
}
|
103
MalwareMultiScan.Tests/ControllersTests.cs
Normal file
103
MalwareMultiScan.Tests/ControllersTests.cs
Normal file
@ -0,0 +1,103 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Controllers;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MalwareMultiScan.Tests
|
||||
{
|
||||
public class ControllersTests
|
||||
{
|
||||
private DownloadController _downloadController;
|
||||
private QueueController _queueController;
|
||||
private ScanResultsController _scanResultsController;
|
||||
private Mock<IScanResultService> _scanResultServiceMock;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_scanResultServiceMock = new Mock<IScanResultService>();
|
||||
|
||||
_scanResultServiceMock
|
||||
.Setup(x => x.ObtainFile("existing"))
|
||||
.Returns(Task.FromResult(new MemoryStream() as Stream));
|
||||
|
||||
_scanResultServiceMock
|
||||
.Setup(x => x.ObtainFile("non-existing"))
|
||||
.Returns(Task.FromResult((Stream) null));
|
||||
|
||||
_scanResultServiceMock
|
||||
.Setup(x => x.GetScanResult("existing"))
|
||||
.Returns(Task.FromResult(new ScanResult
|
||||
{
|
||||
Id = "existing"
|
||||
}));
|
||||
|
||||
_scanResultServiceMock
|
||||
.Setup(x => x.GetScanResult("non-existing"))
|
||||
.Returns(Task.FromResult((ScanResult) null));
|
||||
|
||||
_scanResultServiceMock
|
||||
.Setup(x => x.ObtainFile("non-existing"))
|
||||
.Returns(Task.FromResult((Stream) null));
|
||||
|
||||
_scanResultServiceMock
|
||||
.Setup(x => x.CreateScanResult())
|
||||
.Returns(Task.FromResult(new ScanResult()));
|
||||
|
||||
_downloadController = new DownloadController(_scanResultServiceMock.Object);
|
||||
_scanResultsController = new ScanResultsController(_scanResultServiceMock.Object);
|
||||
|
||||
_queueController = new QueueController(_scanResultServiceMock.Object)
|
||||
{
|
||||
Url = Mock.Of<IUrlHelper>()
|
||||
};
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestFileDownload()
|
||||
{
|
||||
Assert.True(await _downloadController.Index("existing") is FileStreamResult);
|
||||
Assert.True(await _downloadController.Index("non-existing") is NotFoundResult);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestScanResults()
|
||||
{
|
||||
Assert.True(
|
||||
await _scanResultsController.Index("existing") is OkObjectResult okObjectResult &&
|
||||
okObjectResult.Value is ScanResult scanResult && scanResult.Id == "existing");
|
||||
|
||||
Assert.True(await _scanResultsController.Index("non-existing") is NotFoundResult);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestFileQueue()
|
||||
{
|
||||
Assert.True(await _queueController.ScanFile(
|
||||
Mock.Of<IFormFile>(x =>
|
||||
x.FileName == "test.exe" &&
|
||||
x.OpenReadStream() == new MemoryStream())
|
||||
) is CreatedAtActionResult);
|
||||
|
||||
_scanResultServiceMock.Verify(
|
||||
x => x.StoreFile("test.exe", It.IsAny<Stream>()), Times.Once);
|
||||
|
||||
_scanResultServiceMock.Verify(
|
||||
x => x.QueueUrlScan(It.IsAny<ScanResult>(), It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestUrlQueue()
|
||||
{
|
||||
Assert.True(await _queueController.ScanUrl("http://test.com") is CreatedAtActionResult);
|
||||
|
||||
_scanResultServiceMock.Verify(
|
||||
x => x.QueueUrlScan(It.IsAny<ScanResult>(), "http://test.com"), Times.Once);
|
||||
}
|
||||
}
|
||||
}
|
22
MalwareMultiScan.Tests/MalwareMultiScan.Tests.csproj
Normal file
22
MalwareMultiScan.Tests/MalwareMultiScan.Tests.csproj
Normal file
@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="3.1.9" />
|
||||
<PackageReference Include="Mongo2Go" Version="2.2.14" />
|
||||
<PackageReference Include="Moq" Version="4.14.7" />
|
||||
<PackageReference Include="nunit" Version="3.12.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MalwareMultiScan.Api\MalwareMultiScan.Api.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
77
MalwareMultiScan.Tests/ReceiverHostedServiceTests.cs
Normal file
77
MalwareMultiScan.Tests/ReceiverHostedServiceTests.cs
Normal file
@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using EasyNetQ;
|
||||
using MalwareMultiScan.Api.Services.Implementations;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using MalwareMultiScan.Backends.Messages;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Configuration.Memory;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MalwareMultiScan.Tests
|
||||
{
|
||||
public class ReceiverHostedServiceTests
|
||||
{
|
||||
private IReceiverHostedService _receiverHostedService;
|
||||
private Mock<IBus> _busMock;
|
||||
private Mock<IScanResultService> _scanResultServiceMock;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_busMock = new Mock<IBus>();
|
||||
|
||||
_busMock
|
||||
.Setup(x => x.Receive("mms.results", It.IsAny<Func<ScanResultMessage, Task>>()))
|
||||
.Callback<string, Func<ScanResultMessage, Task>>((s, func) =>
|
||||
{
|
||||
var task = func.Invoke(new ScanResultMessage
|
||||
{
|
||||
Id = "test",
|
||||
Backend = "dummy",
|
||||
Duration = 100,
|
||||
Succeeded = true,
|
||||
Threats = new[] {"Test"}
|
||||
});
|
||||
|
||||
task.Wait();
|
||||
});
|
||||
|
||||
_scanResultServiceMock = new Mock<IScanResultService>();
|
||||
|
||||
var configuration = new ConfigurationRoot(new List<IConfigurationProvider>
|
||||
{
|
||||
new MemoryConfigurationProvider(new MemoryConfigurationSource())
|
||||
})
|
||||
{
|
||||
["ResultsSubscriptionId"] = "mms.results"
|
||||
};
|
||||
|
||||
_receiverHostedService = new ReceiverHostedService(
|
||||
_busMock.Object,
|
||||
configuration,
|
||||
_scanResultServiceMock.Object,
|
||||
Mock.Of<ILogger<ReceiverHostedService>>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestBusReceiveScanResultMessage()
|
||||
{
|
||||
await _receiverHostedService.StartAsync(default);
|
||||
|
||||
_scanResultServiceMock.Verify(x => x.UpdateScanResultForBackend(
|
||||
"test", "dummy", 100, true, true, new[] {"Test"}), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestBusIsDisposedOnStop()
|
||||
{
|
||||
await _receiverHostedService.StopAsync(default);
|
||||
|
||||
_busMock.Verify(x => x.Dispose(), Times.Once);
|
||||
}
|
||||
}
|
||||
}
|
63
MalwareMultiScan.Tests/ScanBackendServiceTests.cs
Normal file
63
MalwareMultiScan.Tests/ScanBackendServiceTests.cs
Normal file
@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using EasyNetQ;
|
||||
using MalwareMultiScan.Api.Data.Configuration;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services.Implementations;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using MalwareMultiScan.Backends.Messages;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Configuration.Memory;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MalwareMultiScan.Tests
|
||||
{
|
||||
public class ScanBackendServiceTests
|
||||
{
|
||||
private IScanBackendService _scanBackendService;
|
||||
private Mock<IBus> _busMock;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
var configuration = new ConfigurationRoot(new List<IConfigurationProvider>
|
||||
{
|
||||
new MemoryConfigurationProvider(new MemoryConfigurationSource())
|
||||
})
|
||||
{
|
||||
["BackendsConfiguration"] = "backends.yaml"
|
||||
};
|
||||
|
||||
_busMock = new Mock<IBus>();
|
||||
|
||||
_scanBackendService = new ScanBackendService(
|
||||
configuration,
|
||||
_busMock.Object,
|
||||
Mock.Of<ILogger<ScanBackendService>>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestBackendsAreNotEmpty()
|
||||
{
|
||||
Assert.IsNotEmpty(_scanBackendService.List);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestQueueUrlScan()
|
||||
{
|
||||
await _scanBackendService.QueueUrlScan(
|
||||
new ScanResult { Id = "test"},
|
||||
new ScanBackend { Id = "dummy"},
|
||||
"http://test.com"
|
||||
);
|
||||
|
||||
_busMock.Verify(x => x.SendAsync(
|
||||
"dummy", It.Is<ScanRequestMessage>(r =>
|
||||
r.Id == "test" &&
|
||||
r.Uri == new Uri("http://test.com"))), Times.Once);
|
||||
}
|
||||
}
|
||||
}
|
119
MalwareMultiScan.Tests/ScanResultServiceTests.cs
Normal file
119
MalwareMultiScan.Tests/ScanResultServiceTests.cs
Normal file
@ -0,0 +1,119 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MalwareMultiScan.Api.Data.Configuration;
|
||||
using MalwareMultiScan.Api.Data.Models;
|
||||
using MalwareMultiScan.Api.Services.Implementations;
|
||||
using MalwareMultiScan.Api.Services.Interfaces;
|
||||
using Mongo2Go;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Driver;
|
||||
using MongoDB.Driver.GridFS;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MalwareMultiScan.Tests
|
||||
{
|
||||
public class ScanResultServiceTest
|
||||
{
|
||||
private IScanResultService _resultService;
|
||||
private MongoDbRunner _mongoDbRunner;
|
||||
private Mock<IScanBackendService> _scanBackendService;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_mongoDbRunner = MongoDbRunner.Start();
|
||||
|
||||
var connection = new MongoClient(_mongoDbRunner.ConnectionString);
|
||||
var database = connection.GetDatabase("Test");
|
||||
var gridFsBucket = new GridFSBucket(database);
|
||||
|
||||
_scanBackendService = new Mock<IScanBackendService>();
|
||||
|
||||
_scanBackendService
|
||||
.SetupGet(x => x.List)
|
||||
.Returns(() => new[]
|
||||
{
|
||||
new ScanBackend {Id = "dummy", Enabled = true},
|
||||
new ScanBackend {Id = "clamav", Enabled = true},
|
||||
new ScanBackend {Id = "disabled", Enabled = false},
|
||||
});
|
||||
|
||||
_resultService = new ScanResultService(
|
||||
database, gridFsBucket, _scanBackendService.Object);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
_mongoDbRunner.Dispose();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestFileStorageStoreObtain()
|
||||
{
|
||||
var originalData = new byte[] {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
|
||||
string fileId;
|
||||
|
||||
await using (var dataStream = new MemoryStream(originalData))
|
||||
fileId = await _resultService.StoreFile("test.txt", dataStream);
|
||||
|
||||
Assert.NotNull(fileId);
|
||||
|
||||
Assert.IsNull(await _resultService.ObtainFile("wrong-id"));
|
||||
Assert.IsNull(await _resultService.ObtainFile(ObjectId.GenerateNewId().ToString()));
|
||||
|
||||
await using var fileSteam = await _resultService.ObtainFile(fileId);
|
||||
|
||||
var readData = new[]
|
||||
{
|
||||
(byte)fileSteam.ReadByte(),
|
||||
(byte)fileSteam.ReadByte(),
|
||||
(byte)fileSteam.ReadByte(),
|
||||
(byte)fileSteam.ReadByte()
|
||||
};
|
||||
|
||||
Assert.That(readData, Is.EquivalentTo(originalData));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestScanResultCreateGet()
|
||||
{
|
||||
var result = await _resultService.CreateScanResult();
|
||||
|
||||
Assert.NotNull(result.Id);
|
||||
Assert.That(result.Results, Contains.Key("dummy"));
|
||||
|
||||
await _resultService.UpdateScanResultForBackend(
|
||||
result.Id, "dummy", 100, true, true, new[] {"Test"});
|
||||
|
||||
result = await _resultService.GetScanResult(result.Id);
|
||||
|
||||
Assert.NotNull(result.Id);
|
||||
Assert.That(result.Results, Contains.Key("dummy"));
|
||||
|
||||
var dummyResult = result.Results["dummy"];
|
||||
|
||||
Assert.IsTrue(dummyResult.Completed);
|
||||
Assert.IsTrue(dummyResult.Succeeded);
|
||||
Assert.AreEqual(dummyResult.Duration, 100);
|
||||
Assert.IsNotEmpty(dummyResult.Threats);
|
||||
Assert.That(dummyResult.Threats, Is.EquivalentTo(new[] {"Test"}));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestQueueUrlScan()
|
||||
{
|
||||
var result = await _resultService.CreateScanResult();
|
||||
|
||||
await _resultService.QueueUrlScan(
|
||||
result, "http://url.com");
|
||||
|
||||
_scanBackendService.Verify(x => x.QueueUrlScan(
|
||||
It.IsAny<ScanResult>(),
|
||||
It.IsAny<ScanBackend>(),
|
||||
"http://url.com"), Times.Exactly(2));
|
||||
}
|
||||
}
|
||||
}
|
@ -13,6 +13,8 @@ ProjectSection(SolutionItems) = preProject
|
||||
docker-compose.yaml = docker-compose.yaml
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MalwareMultiScan.Tests", "MalwareMultiScan.Tests\MalwareMultiScan.Tests.csproj", "{9896162D-8FC7-4911-933F-A78C94128923}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@ -31,5 +33,9 @@ Global
|
||||
{8A16A3C4-2AE3-4F63-8280-635FF7878080}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8A16A3C4-2AE3-4F63-8280-635FF7878080}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8A16A3C4-2AE3-4F63-8280-635FF7878080}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9896162D-8FC7-4911-933F-A78C94128923}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9896162D-8FC7-4911-933F-A78C94128923}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9896162D-8FC7-4911-933F-A78C94128923}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9896162D-8FC7-4911-933F-A78C94128923}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
Loading…
x
Reference in New Issue
Block a user