// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and WPF UI Contributors.
// All Rights Reserved.
using System.Threading;
using FlaUI.Core;
using FlaUI.Core.Conditions;
using FlaUI.Core.Input;
using FlaUI.Core.WindowsAPI;
namespace Wpf.Ui.Gallery.IntegrationTests.Fixtures;
///
/// Base class for UI tests implementing to manage lifecycle.
///
public abstract class UiTest : IAsyncLifetime
{
private readonly TestedApplication app = new();
///
/// Gets the wrapper for an application which should be automated.
///
internal Application? Application => app.Application;
///
/// Gets the main window of the applications process.
///
internal Window? MainWindow => app.MainWindow;
///
public ValueTask InitializeAsync() => app.InitializeAsync();
///
public ValueTask DisposeAsync() => app.DisposeAsync();
///
/// Finds the first descendant with the given automation id.
///
/// The automation id.
/// The found element or null if no element was found.
protected AutomationElement? FindFirst(string automationId) =>
app.MainWindow?.FindFirstDescendant(automationId);
/// Finds the first descendant with the condition.
/// The condition method.
/// The found element or null if no element was found.
protected AutomationElement? FindFirst(Func conditionFunc) =>
app.MainWindow?.FindFirstDescendant(conditionFunc);
///
/// Creates a Task that will complete after a time delay.
///
/// The time delay in seconds.
/// An optional cancellation token to cancel the delay.
/// A Task that represents the time delay.
///
/// After the specified time delay, the Task is completed in RanToCompletion state. If the
/// is cancelled, the returned task will be cancelled and an will be thrown.
///
protected Task Wait(int seconds, CancellationToken cancellationToken = default) =>
Task.Delay(TimeSpan.FromSeconds(seconds), cancellationToken);
///
/// Simulate typing in text. This is slower than setting but raises more events.
///
protected void Enter(string value)
{
if (string.IsNullOrEmpty(value))
{
return;
}
string[] source = value.Replace("\r\n", "\n").Split('\n');
Keyboard.Type(source[0]);
foreach (string text in ((IEnumerable)source).Skip(1))
{
Keyboard.Type(VirtualKeyShort.RETURN);
Keyboard.Type(text);
}
global::FlaUI.Core.Input.Wait.UntilInputIsProcessed();
}
///
/// Type the given key.
///
protected void Press(VirtualKeyShort virtualKey)
{
Keyboard.Type(virtualKey);
global::FlaUI.Core.Input.Wait.UntilInputIsProcessed();
}
}