Я пытаюсь написать тест, который проверяет, существует ли загруженный файл в AzureWebStorage. Я не могу издеваться над блобом, который содержит существующий файл. Я хочу попробовать издать ExistsAsyn c, чтобы он возвращал true, но получал ошибки компиляции. Тест, который я пытаюсь запустить, это GenerateFileNameIfFileExistForApprovals. Я пытаюсь издеваться над blob.ExistsAsyn c (); в c# классе
я пытаюсь установить для fileexist значение true. Я пытался ниже утверждений и получил сообщение _cloudBlob только для чтения и может быть установлен только в конструкторе. Я знаю, что он установлен только для чтения в конструкторе класса теста, но как еще мне его установить.
_cloudBlob = Substitute.For<CloudBlockBlob>().ExistsAsync().Result.Returns(true);
await _cloudBlobContainer.GetBlockBlobReference(null).ReturnsForAnyArgs(cloudBlob);
Тестовый компонент
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace Genistar.Identification.Functions.Tests
{
[Collection("Sequential")]
public class UploadIdentificationTests : HttpTestsBase
{
public UploadIdentificationTests()
{
var email = "test@gmail.com";
_request = HttpHelpers.HttpRequestSetupWithFile(new Dictionary<string, StringValues>(), "");
(_, _exceptionsHandler) = ArrangeForReturnCorrectOutput(email);
var uri = new Uri("http://myuri.com");
_cloudBlob = Substitute.For<CloudBlockBlob>(
new Uri("http://refract.tv/container/file.ext"),
new StorageCredentials("fakeaccoutn", Convert.ToBase64String(Encoding.Unicode.GetBytes("fakekeyval")),
"fakekeyname"));
_cloudBlobContainer = Substitute.For<CloudBlobContainer>(uri);
_cloudBlobContainer.GetBlockBlobReference(null).ReturnsForAnyArgs(_cloudBlob);
}
private readonly HttpRequest _request;
private readonly IFunctionService _exceptionsHandler;
private readonly CloudBlobContainer _cloudBlobContainer;
private readonly CloudBlockBlob _cloudBlob;
[Fact]
public void Run_ThrowsExceptionForLargeFile()
{
// Arrange
var request = HttpHelpers.HttpRequestSetupWithNoFile(new Dictionary<string, StringValues>(), "");
// Act
Func<Task> exception = async () => await UploadIdentification.Run(request, ImageUploadSections.Amra, "1", _cloudBlobContainer,
_exceptionsHandler);
// Assert
exception.Should().Throw<ArgumentException>();
}
[Fact]
public void Run_ThrowsExceptionForNoFile()
{
// Arrange
var request = HttpHelpers.HttpRequestSetupWithLargeFile(new Dictionary<string, StringValues>(), "");
// Act
Func<Task> exception = async () => await UploadIdentification.Run(request, ImageUploadSections.Iba, "1", _cloudBlobContainer,
_exceptionsHandler);
// Assert
exception.Should().Throw<ArgumentException>();
}
[Fact]
public async void Run_UploadsTextFileSuccessfullyForApprovals()
{
// Arrange
var request = HttpHelpers.HttpRequestSetupWithWordDocFile(new Dictionary<string, StringValues>(), "");
request.ContentType = MediaTypeNames.Text.Plain;
// Act
var result = (OkResult)await UploadIdentification.Run(request, ImageUploadSections.ApprovalsBankStatement, "1", _cloudBlobContainer,
_exceptionsHandler);
// Assert
Assert.Equal(200, result.StatusCode);
await _cloudBlob.Received(1).UploadFromStreamAsync(Arg.Any<Stream>());
}
[Fact]
public async void GenerateFileNameIfFileExistForApprovals()
{
// Arrange
var request = HttpHelpers.HttpRequestSetupWithWordDocFile(new Dictionary<string, StringValues>(), "");
request.ContentType = MediaTypeNames.Text.Plain;
// Act
var result = (OkResult)await UploadIdentification.Run(request, ImageUploadSections.ApprovalsBankStatement, "1", _cloudBlobContainer,
_exceptionsHandler);
// Assert
Assert.Equal(200, result.StatusCode);
await _cloudBlob.Received(1).UploadFromStreamAsync(Arg.Any<Stream>());
}
}
}
C# Класс
public static class UploadIdentification
{
private const int MaxFileSizeMb = 10;
[FunctionName("UploadIdentification")]
public static Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "identification/{section}/{userId}/UploadIdentification")] HttpRequest req,
string section,
string userId,
[Blob("identification", Connection = "AzureWebJobsStorage")] CloudBlobContainer idBlobContainer,
[Inject] IFunctionService handler
) => handler.HandleAsync(async () =>
{
Stream fileStream;
string fileExtension;
string contentType;
string securityPolicy;
bool isApproval = false;
section = WebUtility.UrlDecode(section);
switch (section)
{
case ImageUploadSections.Amra:
securityPolicy = SecurityPolicies.CompleteAmra;
break;
case ImageUploadSections.DcfAdditionalInfo:
securityPolicy = SecurityPolicies.CreateDataCaptureForm;
break;
case ImageUploadSections.Iba:
case ImageUploadSections.IbaAdditionalInfo:
securityPolicy = SecurityPolicies.UploadIbaIdentification;
break;
case ImageUploadSections.BankStatement:
securityPolicy = SecurityPolicies.CreateBankAccount;
break;
case ImageUploadSections.ApprovalsIba:
case ImageUploadSections.ApprovalsDcf:
case ImageUploadSections.ApprovalsBankStatement:
isApproval = true;
securityPolicy = SecurityPolicies.ViewNotes;
break;
default:
throw new ArgumentException($"Invalid section: {section}");
}
var (_, email, repId) = isApproval ? await handler.ValidateRequestAsync(req, securityPolicy) :
await handler.ValidateRequestAsync(req, securityPolicy,int.Parse(userId));
var userCode = isApproval ? userId : repId.GetRepCode();
var documentType = req.Headers["Document"][0];
var form = await req.ReadFormAsync();
if (!form.Files.Any())
throw new ArgumentException("No file submitted.");
var file = form.Files[0];
var fileName = documentType == string.Empty ? file.FileName : documentType;
fileName = Path.GetFileNameWithoutExtension(fileName);
if (file.Length > MaxFileSizeMb * 1024 * 1024)
throw new ArgumentException($"File is too large, maximum file size is {MaxFileSizeMb}MB.");
var inputFileExt = Path.GetExtension(file.FileName).Replace(".", "");
if (inputFileExt.Equals("pdf"))
{
fileStream = file.OpenReadStream();
fileExtension = ".pdf";
contentType = MediaTypeNames.Application.Pdf;
}
else if (ExtensionIsAnAllowedImage(inputFileExt) && !isApproval)
{
fileStream = ConvertImage(file);
fileExtension = ".jpg";
contentType = MediaTypeNames.Image.Jpeg;
}
else if (isApproval)
{
fileStream = file.OpenReadStream();
fileExtension = "." + inputFileExt;
contentType = req.ContentType;
}
else
{
throw new ArgumentException($"File extension is not supported {inputFileExt}");
}
await idBlobContainer.CreateIfNotExistsAsync();
var blob = idBlobContainer.GetBlockBlobReference($"{userCode}/{section}/{fileName}{fileExtension}");
bool fileExist = await blob.ExistsAsync();
if (fileExist)
{
if (isApproval)
{
string dateString = DateTime.Now.ToString("yyyyMMddhhmmssfff");
fileName = fileName + dateString;
}
var destBlob = idBlobContainer.GetBlockBlobReference($"{userCode}/{section}/archive/{fileName}{fileExtension}");
await destBlob.StartCopyAsync(blob);
}
blob.Properties.ContentType = contentType;
await blob.UploadFromStreamAsync(fileStream);
fileStream.Close();
return new OkResult();
});
private static MemoryStream ConvertImage(IFormFile file)
{
var fileByteArray = ConvertFile(file);
var memStream = new MemoryStream();
using (var image = new MagickImage(fileByteArray))
{
image.Format = MagickFormat.Jpg;
image.ScaleDownImageIfTooLarge(ImageConstraints.MaxHeight, ImageConstraints.MaxWidth);
image.Write(memStream);
memStream.Position = 0;
}
return memStream;
}
private static byte[] ConvertFile(IFormFile file)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
return ms.ToArray();
}
}
private static bool ExtensionIsAnAllowedImage(string ext)
{
return Enum.GetValues(typeof(MagickFormat)).Cast<MagickFormat>()
.Any(v => v.ToString().Equals(ext, StringComparison.InvariantCultureIgnoreCase));
}
}
}