Skip to content

Commit

Permalink
test: RenderTargetBitmaps
Browse files Browse the repository at this point in the history
  • Loading branch information
workgroupengineering committed Jan 28, 2022
1 parent 80478f9 commit 0f4e849
Show file tree
Hide file tree
Showing 6 changed files with 239 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/SamplesApp/SamplesApp.UITests/SamplesApp.UITests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

<ItemGroup>
<Folder Include="MessageDialogTests\" />
<Folder Include="Windows_UI_Xaml_Media_Imaging\RenderTargetBitmap_Tests_EpectedResults\" />
<Folder Include="Windows_UI_Xaml_Shapes\Basics_Shapes_Tests_EpectedResults\" />
</ItemGroup>

Expand All @@ -42,4 +43,10 @@
</None>
</ItemGroup>

<ItemGroup>
<None Update="Windows_UI_Xaml_Media_Imaging\RenderTargetBitmap_Tests_EpectedResults\Border.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System;
using System.IO;
using NUnit.Framework;
using SamplesApp.UITests.Extensions;
using SamplesApp.UITests.TestFramework;
using Uno.UITest.Helpers.Queries;

namespace SamplesApp.UITests.Windows_UI_Xaml_Media_Imaging
{
public partial class RenderTargetBitmap_Tests : SampleControlUITestBase
{
private const int TestTimeout = 7 * 60 * 1000;
[Test]
[AutoRetry]
[Timeout(TestTimeout)]
public void When_Border()
=> Validate("Border");

public void Validate(string controlName, PixelTolerance? tolerance = null)
{
Run("UITests.Windows_UI_Xaml_Media_Imaging.RenderTargetBitmaps", skipInitialScreenshot: true);

var ctrl = new QueryEx(q => q.Marked("_renderTargetTestRoot"));
;
var expectedDirectory = Path.Combine(
TestContext.CurrentContext.TestDirectory,
nameof(Windows_UI_Xaml_Media_Imaging) + "/RenderTargetBitmap_Tests_EpectedResults");
var actualDirectory = Path.Combine(
TestContext.CurrentContext.WorkDirectory,
nameof(Windows_UI_Xaml_Media_Imaging),
nameof(RenderTargetBitmap_Tests),
controlName);

tolerance = tolerance ?? (new PixelTolerance()
.WithColor(132) // We are almost only trying to detect edges
.WithOffset(3, 3, LocationToleranceKind.PerPixel)
.Discrete(2));

ctrl.SetDependencyPropertyValue("RunTest", controlName);
_app.WaitFor(() => !string.IsNullOrWhiteSpace(ctrl.GetDependencyPropertyValue<string>("TestResult"))
, timeout: TimeSpan.FromMinutes(1));

var testResultsRaw = ctrl.GetDependencyPropertyValue<string>("TestResult");

var testResults = testResultsRaw.Split(';');
Assert.That(testResults.Length, Is.EqualTo(2));

var isSuccess = testResults[0] == "SUCCESS";
var data = Convert.FromBase64String(testResults[1]);

var target = Path
.Combine(actualDirectory, controlName + (isSuccess ? ".png" : ".txt"))
.GetNormalizedLongPath();
var targetFile = new FileInfo(target);

targetFile.Directory.Create();
File.WriteAllBytes(target, data);
SetOptions(targetFile, new ScreenshotOptions { IgnoreInSnapshotCompare = true });
TestContext.AddTestAttachment(target, controlName);

if (!isSuccess)
{
Assert.Fail($"No test result for {controlName}.");
}

var expected = new FileInfo(Path.Combine(expectedDirectory, $"{controlName}.png"));
if (!expected.Exists)
{
Assert.Fail($"Expected screenshot does not exists ({expected.FullName})");
}

var scale = _app.GetDisplayScreenScaling();
ImageAssert.AreEqual(expected, ImageAssert.FirstQuadrant,
targetFile, ImageAssert.FirstQuadrant,
scale, tolerance.Value);
}
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions src/SamplesApp/UITests.Shared/UITests.Shared.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -4129,6 +4129,10 @@
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="$(MSBuildThisFileDirectory)Windows_UI_Xaml_Media_Imaging\RenderTargetBitmaps.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="$(MSBuildThisFileDirectory)Windows_UI_Xaml_Shapes\Basic_Shapes.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
Expand Down Expand Up @@ -6946,6 +6950,9 @@
<Compile Include="$(MSBuildThisFileDirectory)Windows_UI_Xaml_Media_Animation\SetTargetProperty.xaml.cs">
<DependentUpon>SetTargetProperty.xaml</DependentUpon>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)Windows_UI_Xaml_Media_Imaging\RenderTargetBitmaps.xaml.cs">
<DependentUpon>RenderTargetBitmaps.xaml</DependentUpon>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)Windows_UI_Xaml_Shapes\Basic_Shapes.xaml.cs">
<DependentUpon>Basic_Shapes.xaml</DependentUpon>
</Compile>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Page
x:Class="UITests.Windows_UI_Xaml_Media_Imaging.RenderTargetBitmaps"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UITests.Windows_UI_Xaml_Media_Imaging"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
x:Name="_renderTargetTestRoot"
>
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Width="100" Height="100" Background="Blue" BorderThickness="2" BorderBrush="Red"
x:Name="border"/>
<Button Content="Save As"
Click="SaveAs"
Grid.Row="1"/>
</Grid>

</Page>
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using System;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Uno.UI.Samples.Controls;

#if __IOS__
using UIKit;
#endif

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace UITests.Windows_UI_Xaml_Media_Imaging
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Sample("Imaging", IgnoreInSnapshotTests = true)]
public sealed partial class RenderTargetBitmaps : Page
{
public static DependencyProperty RunTestProperty { get; } =
DependencyProperty.Register(nameof(RunTest),
typeof(string),
typeof(RenderTargetBitmaps),
new PropertyMetadata(default(string)
, propertyChangedCallback: (s, e) =>
{
if (!string.IsNullOrEmpty((string)e.NewValue))
((RenderTargetBitmaps)s).RenderBoder();
}));

public string RunTest
{
get => (string)GetValue(RunTestProperty);
set => SetValue(RunTestProperty, value);
}
public static DependencyProperty TestResultProperty { get; } = DependencyProperty.Register(nameof(TestResult)
, typeof(string)
, typeof(RenderTargetBitmaps)
, new PropertyMetadata(default(string)));

public string TestResult
{
get { return (string)GetValue(TestResultProperty); }
set { SetValue(TestResultProperty, value); }
}
public RenderTargetBitmaps()
{
this.InitializeComponent();
}

private async void SaveAs(object sender, RoutedEventArgs e)
{
#if __SKIA__
// Workaround to avoid issue #7829
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, GenerateScreenshots);
#else
await GenerateScreenshots();
#endif
}

private async
#if __SKIA__
void
#else
System.Threading.Tasks.Task
#endif
GenerateScreenshots()
{
#if WINDOWS_UWP || __SKIA__

var folder = await new FolderPicker { FileTypeFilter = { "*" } }.PickSingleFolderAsync();
if (folder == null)
{
return;
}

var fileName = "BorderRender.png";
var renderer = new RenderTargetBitmap();
await renderer.RenderAsync(this.border);

var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var output = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, output);
encoder.SetSoftwareBitmap(SoftwareBitmap.CreateCopyFromBuffer(await renderer.GetPixelsAsync(), BitmapPixelFormat.Bgra8, renderer.PixelWidth, renderer.PixelHeight));
await encoder.FlushAsync();
await output.FlushAsync();
}
#endif
}

private async void RenderBoder()
{
var result = new System.Text.StringBuilder();
try
{
var renderer = new RenderTargetBitmap();
await renderer.RenderAsync(this.border); ;
var testResult = await renderer.GetPixelsAsync();

result.Append("SUCCESS;");
result.Append(Convert.ToBase64String(testResult.ToArray()));

}
catch (Exception e)
{
result.Append("ERROR;");
result.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(e.ToString())));

}
TestResult = result.ToString();
}
}
}

0 comments on commit 0f4e849

Please sign in to comment.