using AtomUI.Controls;
using Shouldly;
using Xunit;
namespace AtomUI.Controls.Shared.Tests.ImageLoading;
public class ImageContentValidatorTests
{
[Fact]
public void Valid_Png_Uses_Magic_Bytes_And_Reports_Dimensions()
{
var validator = new ImageContentValidator(ImageLoadingTestSupport.CreateOptions());
var probe = validator.Validate(
ImageLoadingTestSupport.CreateContent(ImageLoadingTestSupport.CreatePngHeader(32, 24)),
new BytesImageSource(new byte[] { 1 }, "png"),
TestContext.Current.CancellationToken);
probe.Format.ShouldBe(ImageContentFormat.Png);
probe.MediaType.ShouldBe("image/png");
probe.PixelWidth.ShouldBe(32);
probe.PixelHeight.ShouldBe(24);
}
[Fact]
public void Declared_Media_Type_Must_Match_Detected_Content()
{
AssertFailure(
ImageLoadErrorCode.ContentTypeMismatch,
ImageLoadingTestSupport.CreateContent(
ImageLoadingTestSupport.CreatePngHeader(),
"image/jpeg"),
new BytesImageSource(new byte[] { 1 }, "png"));
}
[Fact]
public void Remote_Svg_Is_Allowed_After_Static_Content_Validation()
{
var validator = new ImageContentValidator(ImageLoadingTestSupport.CreateOptions());
var probe = validator.Validate(
ImageLoadingTestSupport.CreateContent(
""u8.ToArray(),
"image/svg+xml"),
ImageSource.Parse("https://example.com/image.svg"),
TestContext.Current.CancellationToken);
probe.Format.ShouldBe(ImageContentFormat.Svg);
probe.SvgMetadata.ShouldNotBeNull();
}
[Fact]
public void Trusted_Avalonia_Asset_Svg_Is_Allowed()
{
var validator = new ImageContentValidator(ImageLoadingTestSupport.CreateOptions());
var content = ImageLoadingTestSupport.CreateContent(
""u8.ToArray(), "text/html"));
AssertFailure(
ImageLoadErrorCode.UnsupportedFormat,
ImageLoadingTestSupport.CreateContent([1, 2, 3, 4], null));
}
private static void AssertFailure(
ImageLoadErrorCode expected,
ImageEncodedContent content,
ImageSource? source = null,
ImageLoadingOptions? options = null)
{
var validator = new ImageContentValidator(options ?? ImageLoadingTestSupport.CreateOptions());
var exception = Should.Throw(() => validator.Validate(
content,
source ?? new BytesImageSource(new byte[] { 1 }, "content")));
exception.Error.Code.ShouldBe(expected);
}
}