Skip to content

Commit

Permalink
Add Tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinGrote committed Nov 28, 2024
1 parent b8b3aa2 commit 47a2634
Showing 1 changed file with 111 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
Expand All @@ -11,13 +12,22 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Debug;
using OmniSharp.Extensions.DebugAdapter.Client;
using DapStackFrame = OmniSharp.Extensions.DebugAdapter.Protocol.Models.StackFrame;
using OmniSharp.Extensions.DebugAdapter.Protocol.Events;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
using OmniSharp.Extensions.JsonRpc.Server;
using Xunit;
using Xunit.Abstractions;

namespace PowerShellEditorServices.Test.E2E
{
public class XunitOutputTraceListener(ITestOutputHelper output) : TraceListener
{
public override void Write(string message) => output.WriteLine(message);
public override void WriteLine(string message) => output.WriteLine(message);
}

[Trait("Category", "DAP")]
public class DebugAdapterProtocolMessageTests : IAsyncLifetime, IDisposable
{
Expand All @@ -28,15 +38,28 @@ public class DebugAdapterProtocolMessageTests : IAsyncLifetime, IDisposable
private DebugAdapterClient PsesDebugAdapterClient;
private PsesStdioProcess _psesProcess;

/// <summary>
/// Completes when the debug adapter is started.
/// </summary>
public TaskCompletionSource<object> Started { get; } = new TaskCompletionSource<object>();

/// <summary>
/// Completes when the first breakpoint is reached.
/// </summary>
public TaskCompletionSource<StoppedEvent> Stopped { get; } = new TaskCompletionSource<StoppedEvent>();

/// <summary>
/// Constructor. The ITestOutputHelper is injected by xUnit and used to write diagnostic logs.
/// </summary>
/// <param name="output"></param>
public DebugAdapterProtocolMessageTests(ITestOutputHelper output) => _output = output;

public async Task InitializeAsync()
{
LoggerFactory debugLoggerFactory = new();
debugLoggerFactory.AddProvider(new DebugLoggerProvider());

// NOTE: To see debug logger output, add this line to your test

_psesProcess = new PsesStdioProcess(debugLoggerFactory, true);
await _psesProcess.Start();

Expand Down Expand Up @@ -65,6 +88,13 @@ public async Task InitializeAsync()
Started.SetResult(true);
return Task.CompletedTask;
})
// We use this to create a task we can await to test debugging after a breakpoint has been received.
.OnNotification<StoppedEvent>(null, (stoppedEvent, _) =>
{
Console.WriteLine("StoppedEvent received");
Stopped.SetResult(stoppedEvent);
return Task.CompletedTask;
})
// The OnInitialized delegate gets run when we first receive the _Initialize_ response:
// https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize
.OnInitialized((_, _, _, _) =>
Expand Down Expand Up @@ -263,6 +293,86 @@ public async Task CanSetBreakpointsAsync()
(i) => Assert.Equal("after breakpoint", i));
}

[SkippableFact]
public async Task FailsIfStacktraceRequestedWhenNotPaused()
{
Skip.If(PsesStdioProcess.RunningInConstrainedLanguageMode,
"Breakpoints can't be set in Constrained Language Mode.");
string filePath = NewTestFile(GenerateScriptFromLoggingStatements(
"labelTestBreakpoint"
));
// Set a breakpoint
await PsesDebugAdapterClient.SetBreakpoints(
new SetBreakpointsArguments
{
Source = new Source { Name = Path.GetFileName(filePath), Path = filePath },
Breakpoints = new SourceBreakpoint[] { new SourceBreakpoint { Line = 1 } },
SourceModified = false,
}
);

// Signal to start the script
await PsesDebugAdapterClient.RequestConfigurationDone(new ConfigurationDoneArguments());
await PsesDebugAdapterClient.LaunchScript(filePath, Started);


// Get the stacktrace for the breakpoint
await Assert.ThrowsAsync<JsonRpcException>(() => PsesDebugAdapterClient.RequestStackTrace(
new StackTraceArguments { }
));
}

[SkippableFact]
public async Task SendsInitialLabelBreakpointForPerformanceReasons(ITestOutputHelper output)
{
Skip.If(PsesStdioProcess.RunningInConstrainedLanguageMode,
"Breakpoints can't be set in Constrained Language Mode.");
string filePath = NewTestFile(GenerateScriptFromLoggingStatements(
"before breakpoint",
"at breakpoint",
"after breakpoint"
));

// Enables DAP messages to be written to the test output
Trace.Listeners.Add(new XunitOutputTraceListener(_output));

//TODO: This is technically wrong per the spec, configDone should be completed BEFORE launching, but this is how the vscode client does it today and we really need to fix that.
await PsesDebugAdapterClient.LaunchScript(filePath, Started);

// {"command":"setBreakpoints","arguments":{"source":{"name":"dfsdfg.ps1","path":"/Users/tyleonha/Code/PowerShell/Misc/foo/dfsdfg.ps1"},"lines":[2],"breakpoints":[{"line":2}],"sourceModified":false},"type":"request","seq":3}
SetBreakpointsResponse setBreakpointsResponse = await PsesDebugAdapterClient.SetBreakpoints(new SetBreakpointsArguments
{
Source = new Source { Name = Path.GetFileName(filePath), Path = filePath },
Breakpoints = new SourceBreakpoint[] { new SourceBreakpoint { Line = 2 } },
SourceModified = false,
});

Breakpoint breakpoint = setBreakpointsResponse.Breakpoints.First();
Assert.True(breakpoint.Verified);
Assert.Equal(filePath, breakpoint.Source.Path, ignoreCase: s_isWindows);
Assert.Equal(2, breakpoint.Line);

ConfigurationDoneResponse configDoneResponse = await PsesDebugAdapterClient.RequestConfigurationDone(new ConfigurationDoneArguments());

// FIXME: I think there is a race condition here. If you remove this, the following line Stack Trace fails because the breakpoint hasn't been hit yet. I think the whole getLog process just works long enough for ConfigurationDone to complete and for the breakpoint to be hit.

// I've tried to do this properly by waiting for a StoppedEvent, but that doesn't seem to work, I'm probably just not wiring it up right in the handler.
Assert.NotNull(configDoneResponse);
Assert.Collection(await GetLog(),
(i) => Assert.Equal("before breakpoint", i));
File.Delete(s_testOutputPath);

// Get the stacktrace for the breakpoint
StackTraceResponse stackTraceResponse = await PsesDebugAdapterClient.RequestStackTrace(
new StackTraceArguments { ThreadId = 1 }
);
DapStackFrame firstFrame = stackTraceResponse.StackFrames.First();
Assert.Equal(
firstFrame.PresentationHint,
StackFramePresentationHint.Label
);
}

// This is a regression test for a bug where user code causes a new synchronization context
// to be created, breaking the extension. It's most evident when debugging PowerShell
// scripts that use System.Windows.Forms. It required fixing both Editor Services and
Expand Down

0 comments on commit 47a2634

Please sign in to comment.