Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/winapp-CLI/WinApp.Cli.Tests/BaseCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,37 @@ protected async Task<int> ParseAndInvokeWithCaptureAsync(Command command, string
return await parseResult.InvokeAsync(parseResult.InvocationConfiguration, cancellationToken: cancellationToken);
}

/// <summary>
/// Invokes <paramref name="command"/> with the process-wide Spectre ambient console
/// (<see cref="AnsiConsole.Console"/>) temporarily redirected to a fresh <see cref="TestConsole"/>,
/// then always restores the previous ambient console — even on failure — so global console state
/// does not leak across tests. Use this to capture output written through the static ambient
/// console (e.g. Info/Warning log lines that do not route through the injected stderr writer).
/// </summary>
/// <remarks>
/// Callers must be <c>[DoNotParallelize]</c> because the ambient console is process-wide. The
/// command's own stdout/stderr are still captured via <see cref="ParseAndInvokeWithCaptureAsync(Command, string[])"/>
/// (into <see cref="TestAnsiConsole"/> / <see cref="ConsoleStdErr"/>); the returned string is the
/// text written to the swapped-in ambient console.
/// </remarks>
/// <returns>The command exit code and the text captured from the ambient console.</returns>
protected async Task<(int ExitCode, string AmbientOutput)> InvokeWithAmbientConsoleCaptureAsync(
Command command, string[] manifestArgs)
{
var previousAmbient = AnsiConsole.Console;
var ambient = new TestConsole();
AnsiConsole.Console = ambient;
try
{
int exitCode = await ParseAndInvokeWithCaptureAsync(command, manifestArgs);
return (exitCode, ambient.Output);
}
finally
{
AnsiConsole.Console = previousAmbient;
}
}

/// <summary>
/// Invokes <see cref="Program.Main"/> with captured stdout/stderr.
/// Writers are intentionally not disposed to avoid ObjectDisposedException from
Expand Down
99 changes: 99 additions & 0 deletions src/winapp-CLI/WinApp.Cli.Tests/PointerInputFrameTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -917,4 +917,103 @@ public void RunTouchGesture_NonError21_PropagatesImmediately_CalledExactlyOnce()
Assert.IsFalse(PointerInput.IsWin32ErrorNotReady(caught!),
"The propagated exception must not be recognised as a Win32 error 21");
}

// -------------------------------------------------------------------------
// Bucket 3 (issue #630) — coverage top-up for two residual InjectTouchStroke
// frame branches: (1) the best-effort finally lift that SUCCEEDS after a
// mid-stroke glide throw (complement to the ..._UpFailureSwallowed case), and
// (2) Interpolate's single-waypoint fast path, reached when one contact has a
// lone waypoint while another glides. Both use durationMs:0 so they run with
// no real-clock delays.
// -------------------------------------------------------------------------

[TestMethod]
public void InjectTouchStroke_GlideFrameThrows_BestEffortLiftSucceeds_OriginalExceptionPreserved()
{
// Complement to ..._UpFailureSwallowed: the mid-stroke glide throws, but the finally's
// best-effort UP lift SUCCEEDS. The original glide exception must still propagate unmasked,
// and a genuine UP frame must have been emitted during the unwind (best-effort cleanup).
var glideEx = new InvalidOperationException("glide frame failed");

int sendCount = 0;
bool glideAttempted = false;
bool upLiftSent = false;

PointerInput.TouchSender sender = contacts =>
{
sendCount++;
if (contacts.Any(c => c.pointerInfo.pointerFlags.HasFlag(POINTER_FLAGS.POINTER_FLAG_UP)))
{
upLiftSent = true; // best-effort lift in the finally succeeds (does NOT throw)
return;
}
if (contacts.Any(c => c.pointerInfo.pointerFlags.HasFlag(POINTER_FLAGS.POINTER_FLAG_UPDATE)))
{
glideAttempted = true;
throw glideEx;
}
};

// Single contact, two waypoints → exactly one immediate glide (UPDATE) frame, which throws
// and unwinds to the finally before the normal-path UP is reached.
var paths = new List<IReadOnlyList<PointerPoint>>
{
new List<PointerPoint> { new PointerPoint(0, 0), new PointerPoint(100, 0) }
};

InvalidOperationException? caught = null;
try
{
PointerInput.InjectTouchStroke(paths, holdMs: 0, durationMs: 0, sender);
Assert.Fail("Expected the glide exception to propagate");
}
catch (InvalidOperationException ex) { caught = ex; }

Assert.AreSame(glideEx, caught,
"The original glide exception must propagate even though the best-effort lift SUCCEEDED");
Assert.IsTrue(glideAttempted, "The glide (UPDATE) frame must have been attempted");
Assert.IsTrue(upLiftSent, "The finally must still emit a best-effort UP lift frame after the glide throw");
Assert.AreEqual(3, sendCount,
"Expected exactly three sends: DOWN, the throwing glide UPDATE, then the best-effort UP lift");
}

[TestMethod]
public void InjectTouchStroke_MixedWaypointCounts_SingleWaypointContactStaysPinned()
{
// One multi-waypoint contact drives the glide loop; a second, single-waypoint contact must
// stay pinned at its lone coordinate on every glide frame (Interpolate's Count==1 fast path),
// rather than drifting toward the moving contact.
var movingStart = new PointerPoint(0, 0);
var movingEnd = new PointerPoint(100, 0);
var pinned = new PointerPoint(500, 500);

var paths = new List<IReadOnlyList<PointerPoint>>
{
new List<PointerPoint> { movingStart, movingEnd }, // contact 0: two waypoints → glides
new List<PointerPoint> { pinned } // contact 1: one waypoint → pinned
};

var contact1Positions = new List<(int X, int Y)>();
var contact0Positions = new List<(int X, int Y)>();

PointerInput.TouchSender sender = contacts =>
{
if (contacts.Any(c => c.pointerInfo.pointerFlags.HasFlag(POINTER_FLAGS.POINTER_FLAG_UPDATE)))
{
var c0 = contacts[0];
var c1 = contacts[1];
contact0Positions.Add((c0.pointerInfo.ptPixelLocation.X, c0.pointerInfo.ptPixelLocation.Y));
contact1Positions.Add((c1.pointerInfo.ptPixelLocation.X, c1.pointerInfo.ptPixelLocation.Y));
}
};

PointerInput.InjectTouchStroke(paths, holdMs: 0, durationMs: 0, sender);

Assert.IsTrue(contact1Positions.Count > 1,
"A multi-waypoint contact must produce multiple glide (UPDATE) frames");
Assert.IsTrue(contact1Positions.All(p => p == (pinned.X, pinned.Y)),
"The single-waypoint contact must stay pinned at its lone coordinate across every glide frame");
Assert.IsTrue(contact0Positions.Any(p => p.X > movingStart.X && p.X <= movingEnd.X),
"The multi-waypoint contact must actually advance along its segment (sanity check the glide moved)");
}
}
47 changes: 47 additions & 0 deletions src/winapp-CLI/WinApp.Cli.Tests/PointerInputPressureTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) Microsoft Corporation and Contributors. All rights reserved.
// Licensed under the MIT License.

using WinApp.Cli.Helpers;

namespace WinApp.Cli.Tests;

/// <summary>
/// Unit tests for <see cref="PointerInput.MapPenPressure"/> — the pure float→Win32 (1..1024) pen
/// pressure mapping extracted from <see cref="PointerInput.Pen"/> so it is coverable without the
/// native synthetic-pointer device (issue #630). Verifies linear mapping, nearest-integer rounding,
/// clamping at both bounds, and the non-zero-pressure guarantee that in-contact pen frames require.
/// </summary>
[TestClass]
public class PointerInputPressureTests
{
[TestMethod]
[DataRow(0.0f, 1u, "0.0 maps to 0, then the in-contact guarantee bumps it up to 1")]
[DataRow(0.0004f, 1u, "A fraction that rounds to 0 (0.0004*1024 ≈ 0.41) is bumped up to 1")]
[DataRow(0.25f, 256u, "Interior value maps linearly: 0.25 * 1024 = 256")]
[DataRow(0.5f, 512u, "Interior value maps linearly: 0.5 * 1024 = 512")]
[DataRow(1.0f, 1024u, "Full pressure maps to the max: 1.0 * 1024 = 1024")]
[DataRow(2.0f, 1024u, "Above-range pressure clamps down to the 1024 upper bound")]
[DataRow(-1.0f, 1u, "Below-range pressure clamps to 0, then is bumped up to 1")]
public void MapPenPressure_MapsAndClampsToWin32Range(float pressure, uint expected, string because)
{
Assert.AreEqual(expected, PointerInput.MapPenPressure(pressure), because);
}

[TestMethod]
public void MapPenPressure_RoundsToNearestInteger_NotTruncates()
{
// 0.7 * 1024 = 716.8 -> must round to nearest (717), not truncate toward zero (716).
Assert.AreEqual(717u, PointerInput.MapPenPressure(0.7f),
"0.7 * 1024 = 716.8 must round to the nearest integer (717), not truncate to 716");
}

[TestMethod]
public void MapPenPressure_NeverReturnsZero_SoInContactFramesStayInContact()
{
// Windows drops an in-contact pen frame that reports zero pressure, so any tiny or
// non-positive input must still yield at least 1 (the ==0 -> 1 guard).
Assert.AreEqual(1u, PointerInput.MapPenPressure(0.0f), "zero must not stay zero");
Assert.AreEqual(1u, PointerInput.MapPenPressure(0.00001f), "a sub-half-unit fraction must not stay zero");
Assert.AreEqual(1u, PointerInput.MapPenPressure(-5.0f), "a negative pressure clamps to 0 then bumps to 1");
}
}
174 changes: 174 additions & 0 deletions src/winapp-CLI/WinApp.Cli.Tests/UiCommandTests.Pen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -436,4 +436,178 @@ public async Task Pen_LocalSession_NoDeliveryWarning()
Assert.IsFalse(result.TryGetProperty("warnings", out _),
"A local console session must not emit the remote-delivery warning");
}

// -------------------------------------------------------------------------
// Bucket 3 (issue #630) — coverage top-up: the remaining argument-validation
// branches, the selector-resolution failure guard, the non-JSON success/
// warning render path, and the COM / generic catch arms. Driven through the
// command handler with the existing fakes — no live injection.
// -------------------------------------------------------------------------

[TestMethod]
public void Pen_ShortDescription_NamesPenInput()
{
var description = GetRequiredService<UiPenCommand>().ShortDescription;
Assert.IsFalse(string.IsNullOrWhiteSpace(description));
StringAssert.Contains(description, "pen");
}

[TestMethod]
public async Task Pen_NegativeDuration_RejectedWithInvalidArguments()
{
// A negative --duration-ms is rejected by the lower-bound guard (distinct from the >Max guard).
var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command,
["-a", "TestApp", "--duration-ms", "-5", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "--duration-ms");
}

[TestMethod]
public async Task Pen_TiltOutOfRange_RejectedWithInvalidArguments()
{
// A parseable but out-of-range --tilt-x (>90) trips the handler's tilt range guard (distinct
// from the parse-time non-integer rejection already covered).
var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command,
["-a", "TestApp", "--at", "100,100", "--tilt-x", "200", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "tilt");
}

[TestMethod]
public async Task Pen_MalformedPath_RejectedWithInvalidArguments()
{
var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command,
["-a", "TestApp", "--path", "not-a-path", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "--path");
}

[TestMethod]
public async Task Pen_MalformedAtPoint_RejectedWithInvalidArguments()
{
var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command,
["-a", "TestApp", "--at", "nonsense", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "--at");
}

[TestMethod]
public async Task Pen_NoTarget_NoSelectorNoAtNoPath_RejectedWithInvalidArguments()
{
// Without a selector, --at, or --path there is no contact point to resolve.
var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command, ["-a", "TestApp", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "Provide a target");
}

[TestMethod]
public async Task Pen_MissingApp_NoAppNoWindow_ReturnsMissingApp()
{
// A valid selector but no --app/--window: the missing-app guard fires after all argument
// validation (so it yields missing_app, not invalid_arguments).
var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command, ["canvas-1", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "Target app required");
}

[TestMethod]
public async Task Pen_SelectorNotFound_ReturnsElementNotFound_NoInjection()
{
// A bare selector that resolves to no element: ResolvePointAsync reports element_not_found and
// returns not-Ok, so the command aborts before injection (covers the !target.Ok guard in the
// selector branch). FindSingleResult stays null by default.
_fakeSession.SessionResult.WindowHandle = 6100;

var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command, ["ghost-element", "-a", "TestApp", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "No element found");
}

[TestMethod]
[DoNotParallelize] // swaps the process-wide ambient AnsiConsole to capture non-error logger output
public async Task Pen_NonJson_LocalSession_LogsSuccessWithoutWarning()
{
// The non-JSON render path logs a human success line and, for a local session, no delivery
// warning. Info/Warning route through the static ambient console, so we swap it to capture.
_fakeSession.SessionResult.WindowHandle = 8400;
_fakeForeground.IsRemoteSessionResult = false;

var command = GetRequiredService<UiPenCommand>();
var (exitCode, ambientOutput) = await InvokeWithAmbientConsoleCaptureAsync(command, ["-a", "TestApp", "--at", "120,130"]);

Assert.AreEqual(0, exitCode);
Assert.AreEqual(1, _fakePointer.PenCalls.Count);
Assert.IsFalse(TestAnsiConsole.Output.Contains('{'), "Non-JSON path must not emit a JSON envelope");
StringAssert.Contains(ambientOutput, "pen", "Success line must name the pen action");
Assert.IsFalse(ambientOutput.Contains("remote", StringComparison.OrdinalIgnoreCase),
"A local session must not emit the remote-delivery warning");
}

[TestMethod]
[DoNotParallelize] // swaps the process-wide ambient AnsiConsole to capture non-error logger output
public async Task Pen_NonJson_RemoteSession_LogsSuccessAndDeliveryWarning()
{
_fakeSession.SessionResult.WindowHandle = 8401;
_fakeForeground.IsRemoteSessionResult = true;

var command = GetRequiredService<UiPenCommand>();
var (exitCode, ambientOutput) = await InvokeWithAmbientConsoleCaptureAsync(command, ["-a", "TestApp", "--at", "120,130"]);

Assert.AreEqual(0, exitCode, "The remote warning is advisory; injection still succeeds");
Assert.AreEqual(1, _fakePointer.PenCalls.Count);
StringAssert.Contains(ambientOutput, "remote", "Remote session must surface the delivery-uncertainty warning");
}

[TestMethod]
public async Task Pen_ComException_ReturnsStaleElement_NoInjection()
{
// A COMException surfacing during resolution is a stale-element signal; the command maps it to
// the stale envelope and never injects.
_fakeUia.FindSingleElementThrowException = new System.Runtime.InteropServices.COMException("UIA stale (test)");

var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command, ["canvas-1", "-a", "TestApp", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "no longer accessible");
AssertJsonErrorCode(UiJsonError.CodeStaleElement);
}

[TestMethod]
public async Task Pen_GenericException_ReturnsInternalError_NoInjection()
{
// A non-COM, non-app-not-found, non-IOE exception during session resolution falls through to
// the catch-all generic handler and is reported (not swallowed or crashed).
_fakeSession.ResolveThrow = new TimeoutException("boom (test)");

var command = GetRequiredService<UiPenCommand>();
var exitCode = await ParseAndInvokeWithCaptureAsync(command, ["canvas-1", "-a", "TestApp", "--json"]);

Assert.AreEqual(1, exitCode);
Assert.AreEqual(0, _fakePointer.PenCalls.Count);
StringAssert.Contains(ConsoleStdErr.ToString(), "boom (test)");
AssertJsonErrorCode(UiJsonError.CodeInternalError);
}
}
Loading
Loading