集成测试在上传图像端点上的魔术字节检查失败。

huangapple go评论86阅读模式
英文:

Integration tests fails on the Magic Bytes check on an upload-image endpoint

问题

我们有一个简单的REST API。其中一个端点是包含魔术字节验证,目前看起来是这样的:

private static bool HaveValidMagicBytes(IFormFile file)
{
    if (file == null || !MagicBytes.TryGetValue(file.ContentType, out byte[] magicBytes))
    {
        return false;
    }

    using (Stream stream = file.OpenReadStream())
    {
        var fileMagicBytes = new byte[magicBytes.Length];
        stream.Read(fileMagicBytes, 0, magicBytes.Length);
        bool haveValidMagicBytes = magicBytes.SequenceEqual(fileMagicBytes);
        return haveValidMagicBytes;
    }
}

我们已经为此编写了现有的集成测试,但似乎无法让它们与上面的代码一起工作。

我目前为“API端点的模拟图像”做准备:

private MultipartFormDataContent SetupFileImageTests(string fileName)
{
    var realFile = File.OpenRead(ImageHelper.GetImagePath()); //指向本地有效文件:TestData/test_image.PNG

    var mockedFile = new Mock<IFormFile>();
    var ms = new MemoryStream();
    var writer = new StreamWriter(ms);
    writer.Write(realFile);
    writer.Flush();
    ms.Position = 0;
    mockedFile.Setup(c => c.OpenReadStream()).Returns(ms);
    mockedFile.Setup(f => f.FileName).Returns(fileName).Verifiable();
    mockedFile.Setup(_ => _.CopyToAsync(It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
        .Returns((Stream stream, CancellationToken token) => ms.CopyToAsync(stream))
        .Verifiable();

    writer.Write(FileContent);
    writer.Flush();
    ms.Position = 0;

    mockedFile.Setup(f => f.OpenReadStream()).Returns(ms);
    mockedFile.Setup(f => f.Length).Returns(ms.Length);
    mockedFile.Setup(f => f.FileName).Returns(fileName);

    var fileContent = new StreamContent(mockedFile.Object.OpenReadStream())
    {
        Headers =
        {
            ContentLength = mockedFile.Object.Length,
            ContentType = new MediaTypeHeaderValue("image/jpeg")
        }
    };

    return new MultipartFormDataContent
    {
        {fileContent, "file", fileName}
    };
}

我尝试添加一个实际的真实图像,以便理论上应该成功通过检查,但仍然不行。我不太确定如何继续。

haveValidMagicBytes 仍然为false,因此导致整个过程崩溃。

英文:

We have a simple rest API. One of its endpoints is to include magicBytes validation, which currently looks like this

private static bool HaveValidMagicBytes(IFormFile file)
{
    if (file == null || !MagicBytes.TryGetValue(file.ContentType, out byte[] magicBytes))
    {
        return false;
    }

    using (Stream stream = file.OpenReadStream())
    {
        var fileMagicBytes = new byte[magicBytes.Length];
        stream.Read(fileMagicBytes, 0, magicBytes.Length);
        bool haveValidMagicBytes = magicBytes.SequenceEqual(fileMagicBytes);
        return haveValidMagicBytes;
    }
}

We have existing integration tests for this, but I can't seem to get them to work with the above piece of code.

I currently prep the 'mocked image for the api endpoint':

private MultipartFormDataContent SetupFileImageTests(string fileName)
{
    var realFile = File.OpenRead(ImageHelper.GetImagePath()); //points to a local, valid file: TestData/test_image.PNG

    var mockedFile = new Mock&lt;IFormFile&gt;();
    var ms = new MemoryStream();
    var writer = new StreamWriter(ms);
    writer.Write(realFile);
    writer.Flush();
    ms.Position = 0;
    mockedFile.Setup(c =&gt; c.OpenReadStream()).Returns(ms);
    mockedFile.Setup(f =&gt; f.FileName).Returns(fileName).Verifiable();
    mockedFile.Setup(_ =&gt; _.CopyToAsync(It.IsAny&lt;Stream&gt;(), It.IsAny&lt;CancellationToken&gt;()))
        .Returns((Stream stream, CancellationToken token) =&gt; ms.CopyToAsync(stream))
        .Verifiable();

    writer.Write(FileContent);
    writer.Flush();
    ms.Position = 0;

    mockedFile.Setup(f =&gt; f.OpenReadStream()).Returns(ms);
    mockedFile.Setup(f =&gt; f.Length).Returns(ms.Length);
    mockedFile.Setup(f =&gt; f.FileName).Returns(fileName);

    var fileContent = new StreamContent(mockedFile.Object.OpenReadStream())
    {
        Headers =
        {
            ContentLength = mockedFile.Object.Length,
            ContentType = new MediaTypeHeaderValue(&quot;image/jpeg&quot;)
        }
    };

    return new MultipartFormDataContent
    {
        {fileContent, &quot;file&quot;, fileName}
    };
}

I've tried adding an actual, real image, so that the check should succeed in theory, but it's still not. I'm not quite sure how to proceed.
haveValidMagicBytes is still false and thus causing the whole thing to crash.

答案1

得分: 1

我猜你使用了

new MediaTypeHeaderValue(&quot;image/jpeg&quot;)

但你的文件是

TestData/test_image.PNG

所以你应该使用image/png或者修改你的测试以忽略内容类型,而是与你接受的已知文件格式列表中的魔术字节进行比较。

英文:

My guess is that you use

new MediaTypeHeaderValue(&quot;image/jpeg&quot;)

but your file is

TestData/test_image.PNG

So you should either use image/png or change your test to ignore the content type, and instead compare the magic bytes with a list of known file formats you accept.

huangapple
  • 本文由 发表于 2023年7月24日 19:10:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定