-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathDebugAdapterProtocolMessageTests.cs
232 lines (198 loc) · 9.84 KB
/
DebugAdapterProtocolMessageTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OmniSharp.Extensions.DebugAdapter.Client;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
using Xunit;
using Xunit.Abstractions;
namespace PowerShellEditorServices.Test.E2E
{
public class DebugAdapterProtocolMessageTests : IAsyncLifetime
{
private const string TestOutputFileName = "__dapTestOutputFile.txt";
private readonly static bool s_isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
private readonly static string s_binDir =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private readonly static string s_testOutputPath = Path.Combine(s_binDir, TestOutputFileName);
private readonly ITestOutputHelper _output;
private DebugAdapterClient PsesDebugAdapterClient;
private PsesStdioProcess _psesProcess;
public TaskCompletionSource<object> Started { get; } = new TaskCompletionSource<object>();
public DebugAdapterProtocolMessageTests(ITestOutputHelper output)
{
_output = output;
}
public async Task InitializeAsync()
{
var factory = new LoggerFactory();
_psesProcess = new PsesStdioProcess(factory, true);
await _psesProcess.Start().ConfigureAwait(false);
var initialized = new TaskCompletionSource<bool>();
PsesDebugAdapterClient = DebugAdapterClient.Create(options =>
{
options
.WithInput(_psesProcess.OutputStream)
.WithOutput(_psesProcess.InputStream)
// The OnStarted delegate gets run when we receive the _Initialized_ event from the server:
// https://microsoft.github.io/debug-adapter-protocol/specification#Events_Initialized
.OnStarted((client, token) => {
Started.SetResult(true);
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((client, request, response, token) => {
initialized.SetResult(true);
return Task.CompletedTask;
});
});
// PSES follows the following flow:
// Receive a Initialize request
// Run Initialize handler and send response back
// Receive a Launch/Attach request
// Run Launch/Attach handler and send response back
// PSES sends the initialized event at the end of the Launch/Attach handler
// The way that the Omnisharp client works is that this Initialize method doesn't return until
// after OnStarted is run... which only happens when Initialized is received from the server.
// so if we would await this task, it would deadlock.
// To get around this, we run the Initialize() without await but use a `TaskCompletionSource<bool>`
// that gets completed when we receive the response to Initialize
// This tells us that we are ready to send messages to PSES... but are not stuck waiting for
// Initialized.
PsesDebugAdapterClient.Initialize(CancellationToken.None).ConfigureAwait(false);
await initialized.Task.ConfigureAwait(false);
}
public async Task DisposeAsync()
{
try
{
await PsesDebugAdapterClient.RequestDisconnect(new DisconnectArguments
{
Restart = false,
TerminateDebuggee = true
}).ConfigureAwait(false);
await _psesProcess.Stop().ConfigureAwait(false);
PsesDebugAdapterClient?.Dispose();
}
catch (ObjectDisposedException)
{
// Language client has a disposal bug in it
}
}
private static string NewTestFile(string script, bool isPester = false)
{
string fileExt = isPester ? ".Tests.ps1" : ".ps1";
string filePath = Path.Combine(s_binDir, Path.GetRandomFileName() + fileExt);
File.WriteAllText(filePath, script);
return filePath;
}
private string GenerateScriptFromLoggingStatements(params string[] logStatements)
{
if (logStatements.Length == 0)
{
throw new ArgumentNullException("Expected at least one argument.");
}
// Have script create/overwrite file first with `>`.
StringBuilder builder = new StringBuilder().Append('\'').Append(logStatements[0]).Append("' > '").Append(s_testOutputPath).AppendLine("'");
for (int i = 1; i < logStatements.Length; i++)
{
// Then append to that script with `>>`.
builder.Append('\'').Append(logStatements[i]).Append("' >> '").Append(s_testOutputPath).AppendLine("'");
}
_output.WriteLine("Script is:");
_output.WriteLine(builder.ToString());
return builder.ToString();
}
private static string[] GetLog()
{
return File.ReadLines(s_testOutputPath).ToArray();
}
[Trait("Category", "DAP")]
[Fact]
public void CanInitializeWithCorrectServerSettings()
{
Assert.True(PsesDebugAdapterClient.ServerSettings.SupportsConditionalBreakpoints);
Assert.True(PsesDebugAdapterClient.ServerSettings.SupportsConfigurationDoneRequest);
Assert.True(PsesDebugAdapterClient.ServerSettings.SupportsFunctionBreakpoints);
Assert.True(PsesDebugAdapterClient.ServerSettings.SupportsHitConditionalBreakpoints);
Assert.True(PsesDebugAdapterClient.ServerSettings.SupportsLogPoints);
Assert.True(PsesDebugAdapterClient.ServerSettings.SupportsSetVariable);
}
[Trait("Category", "DAP")]
[Fact]
public async Task CanLaunchScriptWithNoBreakpointsAsync()
{
string filePath = NewTestFile(GenerateScriptFromLoggingStatements("works"));
await PsesDebugAdapterClient.LaunchScript(filePath, Started).ConfigureAwait(false);
ConfigurationDoneResponse configDoneResponse = await PsesDebugAdapterClient.RequestConfigurationDone(new ConfigurationDoneArguments()).ConfigureAwait(false);
Assert.NotNull(configDoneResponse);
// At this point the script should be running so lets give it time
await Task.Delay(2000).ConfigureAwait(false);
string[] log = GetLog();
Assert.Equal("works", log[0]);
}
[Trait("Category", "DAP")]
[SkippableFact]
public async Task CanSetBreakpointsAsync()
{
Skip.If(
PsesStdioProcess.RunningInConstainedLanguageMode,
"You can't set breakpoints in ConstrainedLanguage mode.");
string filePath = NewTestFile(GenerateScriptFromLoggingStatements(
"before breakpoint",
"at breakpoint",
"after breakpoint"
));
await PsesDebugAdapterClient.LaunchScript(filePath, Started).ConfigureAwait(false);
// {"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
},
Lines = new long[] { 2 },
Breakpoints = new SourceBreakpoint[]
{
new SourceBreakpoint
{
Line = 2,
}
},
SourceModified = false,
}).ConfigureAwait(false);
var 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()).ConfigureAwait(false);
Assert.NotNull(configDoneResponse);
// At this point the script should be running so lets give it time
await Task.Delay(2000).ConfigureAwait(false);
string[] log = GetLog();
Assert.Single(log, (i) => i == "before breakpoint");
ContinueResponse continueResponse = await PsesDebugAdapterClient.RequestContinue(new ContinueArguments
{
ThreadId = 1,
}).ConfigureAwait(true);
Assert.NotNull(continueResponse);
// At this point the script should be running so lets give it time
await Task.Delay(2000).ConfigureAwait(false);
log = GetLog();
Assert.Collection(log,
(i) => Assert.Equal("before breakpoint", i),
(i) => Assert.Equal("at breakpoint", i),
(i) => Assert.Equal("after breakpoint", i));
}
}
}