Skip to content

Commit 927f2ad

Browse files
EvangelinkCopilot
andauthored
Add readable ToString to JSON-RPC message records (#9570)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 53fe87e commit 927f2ad

2 files changed

Lines changed: 310 additions & 9 deletions

File tree

‎src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs‎

Lines changed: 166 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,38 @@ internal sealed record InitializeResponseArgs(int? ProcessId, ServerInfo ServerI
4242
internal record RequestArgsBase(Guid RunId, ICollection<TestNode>? TestNodes, string? GraphFilter);
4343

4444
internal sealed record DiscoverRequestArgs(Guid RunId, ICollection<TestNode>? TestNodes, string? GraphFilter) :
45-
RequestArgsBase(RunId, TestNodes, GraphFilter);
45+
RequestArgsBase(RunId, TestNodes, GraphFilter)
46+
{
47+
// The compiler-generated record ToString renders the TestNodes collection using its default
48+
// Object.ToString (e.g. 'System.Collections.Generic.List`1[...]'), which is unreadable in the
49+
// diagnostic logs. Render the members explicitly instead.
50+
public override string ToString()
51+
=> RpcMessageFormatting.FormatRequestArgs(nameof(DiscoverRequestArgs), RunId, TestNodes, GraphFilter);
52+
}
4653

4754
internal record ResponseArgsBase;
4855

4956
internal sealed record DiscoverResponseArgs : ResponseArgsBase;
5057

5158
internal sealed record RunRequestArgs(Guid RunId, ICollection<TestNode>? TestNodes, string? GraphFilter) :
52-
RequestArgsBase(RunId, TestNodes, GraphFilter);
53-
54-
internal sealed record RunResponseArgs(Artifact[] Artifacts) : ResponseArgsBase;
59+
RequestArgsBase(RunId, TestNodes, GraphFilter)
60+
{
61+
public override string ToString()
62+
=> RpcMessageFormatting.FormatRequestArgs(nameof(RunRequestArgs), RunId, TestNodes, GraphFilter);
63+
}
64+
65+
internal sealed record RunResponseArgs(Artifact[] Artifacts) : ResponseArgsBase
66+
{
67+
public override string ToString()
68+
{
69+
var builder = new StringBuilder();
70+
builder.Append(nameof(RunResponseArgs)).Append(" { ");
71+
builder.Append($"{nameof(Artifacts)} = ");
72+
RpcMessageFormatting.AppendItems(builder, Artifacts);
73+
builder.Append(" }");
74+
return builder.ToString();
75+
}
76+
}
5577

5678
internal sealed record Artifact(string Uri, string Producer, string Type, string DisplayName, string? Description = null);
5779

@@ -81,16 +103,151 @@ internal sealed record ServerTestingCapabilities(
81103
bool SupportsAttachments,
82104
bool MultiConnectionProvider);
83105

84-
internal sealed record TestNodeStateChangedEventArgs(Guid RunId, TestNodeUpdateMessage[]? Changes);
106+
internal sealed record TestNodeStateChangedEventArgs(Guid RunId, TestNodeUpdateMessage[]? Changes)
107+
{
108+
public override string ToString()
109+
{
110+
var builder = new StringBuilder();
111+
builder.Append(nameof(TestNodeStateChangedEventArgs)).Append(" { ");
112+
builder.Append($"{nameof(RunId)} = ").Append(RunId);
113+
builder.Append($", {nameof(Changes)} = ");
114+
RpcMessageFormatting.AppendItems(builder, Changes);
115+
builder.Append(" }");
116+
return builder.ToString();
117+
}
118+
}
85119

86120
internal sealed record LogEventArgs(ServerLogMessage LogMessage);
87121

88-
internal sealed record TelemetryEventArgs(string EventName, IDictionary<string, object> Metrics);
89-
90-
internal sealed record ProcessInfoArgs(string Program, string? Args, string? WorkingDirectory, IDictionary<string, string?>? EnvironmentVariables);
122+
internal sealed record TelemetryEventArgs(string EventName, IDictionary<string, object> Metrics)
123+
{
124+
public override string ToString()
125+
{
126+
var builder = new StringBuilder();
127+
builder.Append(nameof(TelemetryEventArgs)).Append(" { ");
128+
builder.Append($"{nameof(EventName)} = ").Append(EventName);
129+
builder.Append($", {nameof(Metrics)} = ");
130+
RpcMessageFormatting.AppendDictionary(builder, Metrics);
131+
builder.Append(" }");
132+
return builder.ToString();
133+
}
134+
}
135+
136+
internal sealed record ProcessInfoArgs(string Program, string? Args, string? WorkingDirectory, IDictionary<string, string?>? EnvironmentVariables)
137+
{
138+
public override string ToString()
139+
{
140+
var builder = new StringBuilder();
141+
builder.Append(nameof(ProcessInfoArgs)).Append(" { ");
142+
builder.Append($"{nameof(Program)} = ").Append(Program);
143+
builder.Append($", {nameof(Args)} = ");
144+
RpcMessageFormatting.AppendValue(builder, Args);
145+
builder.Append($", {nameof(WorkingDirectory)} = ");
146+
RpcMessageFormatting.AppendValue(builder, WorkingDirectory);
147+
builder.Append($", {nameof(EnvironmentVariables)} = ");
148+
RpcMessageFormatting.AppendDictionary(builder, EnvironmentVariables);
149+
builder.Append(" }");
150+
return builder.ToString();
151+
}
152+
}
91153

92154
internal sealed record AttachDebuggerInfoArgs(int ProcessId);
93155

94-
internal sealed record class TestsAttachments(RunTestAttachment[] Attachments);
156+
internal sealed record class TestsAttachments(RunTestAttachment[] Attachments)
157+
{
158+
public override string ToString()
159+
{
160+
var builder = new StringBuilder();
161+
builder.Append(nameof(TestsAttachments)).Append(" { ");
162+
builder.Append($"{nameof(Attachments)} = ");
163+
RpcMessageFormatting.AppendItems(builder, Attachments);
164+
builder.Append(" }");
165+
return builder.ToString();
166+
}
167+
}
95168

96169
internal sealed record class RunTestAttachment(string? Uri, string? Producer, string? Type, string? DisplayName, string? Description);
170+
171+
/// <summary>
172+
/// Helpers to render JSON-RPC message members that hold collections or dictionaries. The compiler-generated
173+
/// record <see cref="object.ToString"/> would otherwise print these members using the default
174+
/// <see cref="object.ToString"/> (e.g. <c>System.Collections.Generic.List`1[...]</c>), which is unreadable
175+
/// when the messages are dumped to the diagnostic logs.
176+
/// </summary>
177+
internal static class RpcMessageFormatting
178+
{
179+
public static string FormatRequestArgs(string typeName, Guid runId, ICollection<TestNode>? testNodes, string? graphFilter)
180+
{
181+
var builder = new StringBuilder();
182+
builder.Append(typeName).Append(" { ");
183+
builder.Append("RunId = ").Append(runId);
184+
builder.Append(", TestNodes = ");
185+
AppendItems(builder, testNodes);
186+
builder.Append(", GraphFilter = ");
187+
AppendValue(builder, graphFilter);
188+
builder.Append(" }");
189+
return builder.ToString();
190+
}
191+
192+
// Appends a value, rendering null explicitly as "<null>" so that a null value is not
193+
// confused with an empty string in the diagnostic logs.
194+
public static void AppendValue<T>(StringBuilder builder, T value)
195+
{
196+
if (value is null)
197+
{
198+
builder.Append("<null>");
199+
return;
200+
}
201+
202+
builder.Append(value);
203+
}
204+
205+
public static void AppendItems<T>(StringBuilder builder, IEnumerable<T>? items)
206+
{
207+
if (items is null)
208+
{
209+
builder.Append("<null>");
210+
return;
211+
}
212+
213+
builder.Append('[');
214+
bool first = true;
215+
foreach (T item in items)
216+
{
217+
if (!first)
218+
{
219+
builder.Append(", ");
220+
}
221+
222+
first = false;
223+
AppendValue(builder, item);
224+
}
225+
226+
builder.Append(']');
227+
}
228+
229+
public static void AppendDictionary<TValue>(StringBuilder builder, IDictionary<string, TValue>? dictionary)
230+
{
231+
if (dictionary is null)
232+
{
233+
builder.Append("<null>");
234+
return;
235+
}
236+
237+
builder.Append('[');
238+
bool first = true;
239+
foreach (KeyValuePair<string, TValue> pair in dictionary)
240+
{
241+
if (!first)
242+
{
243+
builder.Append(", ");
244+
}
245+
246+
first = false;
247+
builder.Append(pair.Key).Append(" = ");
248+
AppendValue(builder, pair.Value);
249+
}
250+
251+
builder.Append(']');
252+
}
253+
}
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using Microsoft.Testing.Platform.Extensions.Messages;
5+
using Microsoft.Testing.Platform.ServerMode;
6+
using Microsoft.Testing.Platform.TestHost;
7+
8+
namespace Microsoft.Testing.Platform.UnitTests;
9+
10+
[TestClass]
11+
public sealed class RpcMessagesTests
12+
{
13+
private static TestNode CreateTestNode(string uid, string displayName)
14+
=> new() { Uid = new TestNodeUid(uid), DisplayName = displayName };
15+
16+
[TestMethod]
17+
public void RunRequestArgs_ToString_RendersTestNodesReadably()
18+
{
19+
RunRequestArgs args = new(Guid.Empty, [CreateTestNode("uid1", "Test1"), CreateTestNode("uid2", "Test2")], GraphFilter: null);
20+
21+
string result = args.ToString();
22+
23+
Assert.StartsWith("RunRequestArgs {", result);
24+
AssertNoDefaultCollectionToString(result);
25+
Assert.Contains("Test1", result);
26+
Assert.Contains("Test2", result);
27+
}
28+
29+
[TestMethod]
30+
public void DiscoverRequestArgs_ToString_RendersTestNodesReadably()
31+
{
32+
DiscoverRequestArgs args = new(Guid.Empty, [CreateTestNode("uid1", "Test1")], GraphFilter: "filter");
33+
34+
string result = args.ToString();
35+
36+
Assert.StartsWith("DiscoverRequestArgs {", result);
37+
AssertNoDefaultCollectionToString(result);
38+
Assert.Contains("Test1", result);
39+
Assert.Contains("filter", result);
40+
}
41+
42+
[TestMethod]
43+
public void RequestArgs_ToString_WithNullTestNodes_RendersNull()
44+
{
45+
RunRequestArgs args = new(Guid.Empty, TestNodes: null, GraphFilter: null);
46+
47+
string result = args.ToString();
48+
49+
Assert.Contains("TestNodes = <null>", result);
50+
Assert.Contains("GraphFilter = <null>", result);
51+
AssertNoDefaultCollectionToString(result);
52+
}
53+
54+
[TestMethod]
55+
public void ProcessInfoArgs_ToString_WithNullMembers_RendersNull()
56+
{
57+
ProcessInfoArgs args = new("program.exe", Args: null, WorkingDirectory: null, EnvironmentVariables: null);
58+
59+
string result = args.ToString();
60+
61+
Assert.Contains("Args = <null>", result);
62+
Assert.Contains("WorkingDirectory = <null>", result);
63+
Assert.Contains("EnvironmentVariables = <null>", result);
64+
}
65+
66+
[TestMethod]
67+
public void ProcessInfoArgs_ToString_WithNullEnvironmentVariableValue_RendersNull()
68+
{
69+
ProcessInfoArgs args = new("program.exe", "--flag", "C:\\work", new Dictionary<string, string?> { ["VAR"] = null });
70+
71+
string result = args.ToString();
72+
73+
Assert.Contains("VAR = <null>", result);
74+
}
75+
76+
[TestMethod]
77+
public void RunResponseArgs_ToString_RendersArtifactsReadably()
78+
{
79+
RunResponseArgs args = new([new Artifact("uri", "producer", "type", "MyArtifact")]);
80+
81+
string result = args.ToString();
82+
83+
Assert.StartsWith("RunResponseArgs {", result);
84+
AssertNoDefaultCollectionToString(result);
85+
Assert.Contains("MyArtifact", result);
86+
}
87+
88+
[TestMethod]
89+
public void TestNodeStateChangedEventArgs_ToString_RendersChangesReadably()
90+
{
91+
TestNodeUpdateMessage change = new(new SessionUid("session"), CreateTestNode("uid1", "ChangedTest"));
92+
TestNodeStateChangedEventArgs args = new(Guid.Empty, [change]);
93+
94+
string result = args.ToString();
95+
96+
Assert.StartsWith("TestNodeStateChangedEventArgs {", result);
97+
AssertNoDefaultCollectionToString(result);
98+
Assert.Contains("ChangedTest", result);
99+
}
100+
101+
[TestMethod]
102+
public void TelemetryEventArgs_ToString_RendersMetricsReadably()
103+
{
104+
TelemetryEventArgs args = new("my-event", new Dictionary<string, object> { ["metric1"] = 42 });
105+
106+
string result = args.ToString();
107+
108+
Assert.StartsWith("TelemetryEventArgs {", result);
109+
AssertNoDefaultCollectionToString(result);
110+
Assert.Contains("my-event", result);
111+
Assert.Contains("metric1 = 42", result);
112+
}
113+
114+
[TestMethod]
115+
public void ProcessInfoArgs_ToString_RendersEnvironmentVariablesReadably()
116+
{
117+
ProcessInfoArgs args = new("program.exe", "--flag", "C:\\work", new Dictionary<string, string?> { ["VAR"] = "value" });
118+
119+
string result = args.ToString();
120+
121+
Assert.StartsWith("ProcessInfoArgs {", result);
122+
AssertNoDefaultCollectionToString(result);
123+
Assert.Contains("VAR = value", result);
124+
}
125+
126+
[TestMethod]
127+
public void TestsAttachments_ToString_RendersAttachmentsReadably()
128+
{
129+
TestsAttachments args = new([new RunTestAttachment("uri", "producer", "type", "MyAttachment", "desc")]);
130+
131+
string result = args.ToString();
132+
133+
Assert.StartsWith("TestsAttachments {", result);
134+
AssertNoDefaultCollectionToString(result);
135+
Assert.Contains("MyAttachment", result);
136+
}
137+
138+
private static void AssertNoDefaultCollectionToString(string value)
139+
{
140+
Assert.DoesNotContain("System.Collections", value);
141+
Assert.DoesNotContain("System.String[]", value);
142+
Assert.DoesNotContain("`1[", value);
143+
}
144+
}

0 commit comments

Comments
 (0)