Skip to content

Commit

Permalink
Fix more warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Evangelink committed Jun 15, 2022
1 parent 5353b4a commit f7cd809
Show file tree
Hide file tree
Showing 14 changed files with 100 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ private void AddExtensionAssemblies(BeforeTestRunStartPayload payload)
var datacollectorSearchPaths = new HashSet<string>();
foreach (var source in payload.Sources)
{
datacollectorSearchPaths.Add(Path.GetDirectoryName(source));
datacollectorSearchPaths.Add(Path.GetDirectoryName(source)!);
}

var customTestAdaptersPaths = RunSettingsUtilities.GetTestAdaptersPaths(payload.SettingsXml);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public ConnectedEventArgs(ICommunicationChannel channel)
Connected = true;
}

public ConnectedEventArgs(Exception faultException)
public ConnectedEventArgs(Exception? faultException)
{
Connected = false;
Fault = faultException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public interface ICommunicationEndPoint
/// </summary>
/// <param name="endPoint">Address to connect</param>
/// <returns>Address of the connected endPoint</returns>
string Start(string endPoint);
string? Start(string endPoint);

/// <summary>
/// Stops the endPoint and closes the underlying communication channel.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ public class JsonDataSerializer : IDataSerializer

private static readonly bool DisableFastJson = FeatureFlag.Instance.IsSet(FeatureFlag.DISABLE_FASTER_JSON_SERIALIZATION);

private static readonly JsonSerializer s_payloadSerializer; // payload serializer for version <= 1
private static readonly JsonSerializer s_payloadSerializer2; // payload serializer for version >= 2
private static readonly JsonSerializerSettings s_fastJsonSettings; // serializer settings for faster json
private static readonly JsonSerializerSettings s_jsonSettings; // serializer settings for serializer v1, which should use to deserialize message headers
private static readonly JsonSerializer s_serializer; // generic serializer
private static readonly JsonSerializer PayloadSerializerV1; // payload serializer for version <= 1
private static readonly JsonSerializer PayloadSerializerV2; // payload serializer for version >= 2
private static readonly JsonSerializerSettings FastJsonSettings; // serializer settings for faster json
private static readonly JsonSerializerSettings JsonSettings; // serializer settings for serializer v1, which should use to deserialize message headers
private static readonly JsonSerializer Serializer; // generic serializer

static JsonDataSerializer()
{
Expand All @@ -40,14 +40,14 @@ static JsonDataSerializer()
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};

s_jsonSettings = jsonSettings;
JsonSettings = jsonSettings;

s_serializer = JsonSerializer.Create();
s_payloadSerializer = JsonSerializer.Create(jsonSettings);
s_payloadSerializer2 = JsonSerializer.Create(jsonSettings);
Serializer = JsonSerializer.Create();
PayloadSerializerV1 = JsonSerializer.Create(jsonSettings);
PayloadSerializerV2 = JsonSerializer.Create(jsonSettings);

var contractResolver = new DefaultTestPlatformContractResolver();
s_fastJsonSettings = new JsonSerializerSettings
FastJsonSettings = new JsonSerializerSettings
{
DateFormatHandling = jsonSettings.DateFormatHandling,
DateParseHandling = jsonSettings.DateParseHandling,
Expand All @@ -61,8 +61,8 @@ static JsonDataSerializer()
ContractResolver = contractResolver,
};

s_payloadSerializer.ContractResolver = new TestPlatformContractResolver1();
s_payloadSerializer2.ContractResolver = contractResolver;
PayloadSerializerV1.ContractResolver = new TestPlatformContractResolver1();
PayloadSerializerV2.ContractResolver = contractResolver;

#if TRACE_JSON_SERIALIZATION
// MemoryTraceWriter can help diagnose serialization issues. Enable it for
Expand Down Expand Up @@ -105,7 +105,7 @@ public Message DeserializeMessage(string rawMessage)
{
// PERF: If the fast path fails, deserialize into header object that does not have any Payload. When the message type info
// is at the start of the message, this is also pretty fast. Again, this won't touch the payload.
MessageHeader header = JsonConvert.DeserializeObject<MessageHeader>(rawMessage, s_jsonSettings);
MessageHeader header = JsonConvert.DeserializeObject<MessageHeader>(rawMessage, JsonSettings);
version = header.Version;
messageType = header.MessageType;
}
Expand Down Expand Up @@ -155,11 +155,11 @@ public Message DeserializeMessage(string rawMessage)
var rawMessage = messageWithRawMessage.RawMessage;

// The deserialized message can still have a version (0 or 1), that should use the old deserializer
if (payloadSerializer == s_payloadSerializer2)
if (payloadSerializer == PayloadSerializerV2)
{
// PERF: Fast path is compatibile only with protocol versions that use serializer_2,
// and this is faster than deserializing via deserializer_2.
var messageWithPayload = JsonConvert.DeserializeObject<PayloadedMessage<T>>(rawMessage, s_fastJsonSettings);
var messageWithPayload = JsonConvert.DeserializeObject<PayloadedMessage<T>>(rawMessage, FastJsonSettings);
return messageWithPayload.Payload;
}
else
Expand Down Expand Up @@ -289,7 +289,7 @@ public T Deserialize<T>(string json, int version = 1)
/// <returns>Serialized message.</returns>
public string SerializeMessage(string? messageType)
{
return Serialize(s_serializer, new Message { MessageType = messageType });
return Serialize(Serializer, new Message { MessageType = messageType });
}

/// <summary>
Expand All @@ -313,19 +313,19 @@ public string SerializePayload(string? messageType, object? payload)
public string SerializePayload(string? messageType, object? payload, int version)
{
var payloadSerializer = GetPayloadSerializer(version);
// Fast json is only equivalent to the serialization that is used for protocol version 2 and upwards (or more precisely for the paths that use s_payloadSerializer2)
// Fast json is only equivalent to the serialization that is used for protocol version 2 and upwards (or more precisely for the paths that use PayloadSerializerV2)
// so when we resolved the old serializer we should use non-fast path.
if (DisableFastJson || payloadSerializer == s_payloadSerializer)
if (DisableFastJson || payloadSerializer == PayloadSerializerV1)
{
var serializedPayload = JToken.FromObject(payload, payloadSerializer);

return version > 1 ?
Serialize(s_serializer, new VersionedMessage { MessageType = messageType, Version = version, Payload = serializedPayload }) :
Serialize(s_serializer, new Message { MessageType = messageType, Payload = serializedPayload });
Serialize(Serializer, new VersionedMessage { MessageType = messageType, Version = version, Payload = serializedPayload }) :
Serialize(Serializer, new Message { MessageType = messageType, Payload = serializedPayload });
}
else
{
return JsonConvert.SerializeObject(new VersionedMessageForSerialization { MessageType = messageType, Version = version, Payload = payload }, s_fastJsonSettings);
return JsonConvert.SerializeObject(new VersionedMessageForSerialization { MessageType = messageType, Version = version, Payload = payload }, FastJsonSettings);
}
}

Expand Down Expand Up @@ -410,8 +410,8 @@ private static JsonSerializer GetPayloadSerializer(int? version)
// serializer v2, we downgrade to protocol 2 when 3 would be negotiated
// unless this is disabled by VSTEST_DISABLE_PROTOCOL_3_VERSION_DOWNGRADE
// env variable.
0 or 1 or 3 => s_payloadSerializer,
2 or 4 or 5 or 6 or 7 => s_payloadSerializer2,
0 or 1 or 3 => PayloadSerializerV1,
2 or 4 or 5 or 6 or 7 => PayloadSerializerV2,

_ => throw new NotSupportedException($"Protocol version {version} is not supported. "
+ "Ensure it is compatible with the latest serializer or add a new one."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Import Project="$(TestPlatformRoot)scripts/build/TestPlatform.Settings.targets" />
<PropertyGroup>
<AssemblyName>Microsoft.TestPlatform.CommunicationUtilities</AssemblyName>
<TargetFrameworks>netstandard2.0;netstandard1.3;net451</TargetFrameworks>
<TargetFrameworks>net6.0;netstandard2.0;netstandard1.3;net451</TargetFrameworks>
<TargetFrameworks Condition=" '$(DotNetBuildFromSource)' == 'true' ">net6.0</TargetFrameworks>
<IsTestProject>false</IsTestProject>
</PropertyGroup>
Expand Down
Empty file.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -29,55 +29,59 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
var data = JObject.Load(reader);
var properties = data["Properties"];

if (properties != null && properties.HasValues)
if (properties == null || !properties.HasValues)
{
// Every class that inherits from TestObject uses a properties store for <Property, Object>
// key value pairs.
foreach (var property in properties.Values<JToken>())
{
var testProperty = property["Key"].ToObject<TestProperty>(serializer);
return testCase;
}

// Let the null values be passed in as null data
var token = property["Value"];
string? propertyData = null;
if (token.Type != JTokenType.Null)
// Every class that inherits from TestObject uses a properties store for <Property, Object>
// key value pairs.
foreach (var property in properties.Values<JToken>())
{
var testProperty = property["Key"].ToObject<TestProperty>(serializer);

// Let the null values be passed in as null data
var token = property["Value"];
string? propertyData = null;
if (token.Type != JTokenType.Null)
{
// If the property is already a string. No need to convert again.
if (token.Type == JTokenType.String)
{
// If the property is already a string. No need to convert again.
if (token.Type == JTokenType.String)
{
propertyData = token.ToObject<string>(serializer);
}
else
{
// On deserialization, the value for each TestProperty is always a string. It is up
// to the consumer to deserialize it further as appropriate.
propertyData = token.ToString(Formatting.None).Trim('"');
}
propertyData = token.ToObject<string>(serializer);
}

switch (testProperty.Id)
else
{
case "TestCase.Id":
testCase.Id = Guid.Parse(propertyData); break;
case "TestCase.ExecutorUri":
testCase.ExecutorUri = new Uri(propertyData); break;
case "TestCase.FullyQualifiedName":
testCase.FullyQualifiedName = propertyData; break;
case "TestCase.DisplayName":
testCase.DisplayName = propertyData; break;
case "TestCase.Source":
testCase.Source = propertyData; break;
case "TestCase.CodeFilePath":
testCase.CodeFilePath = propertyData; break;
case "TestCase.LineNumber":
testCase.LineNumber = int.Parse(propertyData); break;
default:
// No need to register member properties as they get registered as part of TestCaseProperties class.
testProperty = TestProperty.Register(testProperty.Id, testProperty.Label, testProperty.GetValueType(), testProperty.Attributes, typeof(TestObject));
testCase.SetPropertyValue(testProperty, propertyData);
break;
// On deserialization, the value for each TestProperty is always a string. It is up
// to the consumer to deserialize it further as appropriate.
propertyData = token.ToString(Formatting.None).Trim('"');
}
}

TPDebug.Assert(propertyData is not null, "propertyData is null");

switch (testProperty.Id)
{
case "TestCase.Id":
testCase.Id = Guid.Parse(propertyData); break;
case "TestCase.ExecutorUri":
testCase.ExecutorUri = new Uri(propertyData); break;
case "TestCase.FullyQualifiedName":
testCase.FullyQualifiedName = propertyData; break;
case "TestCase.DisplayName":
testCase.DisplayName = propertyData; break;
case "TestCase.Source":
testCase.Source = propertyData; break;
case "TestCase.CodeFilePath":
testCase.CodeFilePath = propertyData; break;
case "TestCase.LineNumber":
testCase.LineNumber = int.Parse(propertyData); break;
default:
// No need to register member properties as they get registered as part of TestCaseProperties class.
testProperty = TestProperty.Register(testProperty.Id, testProperty.Label, testProperty.GetValueType(), testProperty.Attributes, typeof(TestObject));
testCase.SetPropertyValue(testProperty, propertyData);
break;
}
}

return testCase;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
}
}

TPDebug.Assert(propertyData is not null, "propertyData is null");
switch (testProperty.Id)
{
case "TestResult.DisplayName":
Expand Down
41 changes: 21 additions & 20 deletions src/Microsoft.TestPlatform.CommunicationUtilities/SocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,28 +76,29 @@ private void OnServerConnected(Task connectAsyncTask)
{
EqtTrace.Info("SocketClient.OnServerConnected: connected to server endpoint: {0}", _endPoint);

if (Connected != null)
if (Connected == null)
{
if (connectAsyncTask.IsFaulted)
{
Connected.SafeInvoke(this, new ConnectedEventArgs(connectAsyncTask.Exception), "SocketClient: Server Failed to Connect");
EqtTrace.Verbose("Unable to connect to server, Exception occurred: {0}", connectAsyncTask.Exception);
}
else
{
_channel = _channelFactory(_tcpClient.GetStream());
Connected.SafeInvoke(this, new ConnectedEventArgs(_channel), "SocketClient: ServerConnected");

EqtTrace.Verbose("Connected to server, and starting MessageLoopAsync");

// Start the message loop
Task.Run(() => _tcpClient.MessageLoopAsync(
_channel,
StopOnError,
_cancellation.Token))
.ConfigureAwait(false);
}
return;
}

if (connectAsyncTask.IsFaulted)
{
Connected.SafeInvoke(this, new ConnectedEventArgs(connectAsyncTask.Exception), "SocketClient: Server Failed to Connect");
EqtTrace.Verbose("Unable to connect to server, Exception occurred: {0}", connectAsyncTask.Exception);
return;
}

_channel = _channelFactory(_tcpClient.GetStream());
Connected.SafeInvoke(this, new ConnectedEventArgs(_channel), "SocketClient: ServerConnected");

EqtTrace.Verbose("Connected to server, and starting MessageLoopAsync");

// Start the message loop
Task.Run(() => _tcpClient.MessageLoopAsync(
_channel,
StopOnError,
_cancellation.Token))
.ConfigureAwait(false);
}

private void StopOnError(Exception? error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ protected SocketServer(Func<Stream, ICommunicationChannel> channelFactory)
/// <inheritdoc />
public event EventHandler<DisconnectedEventArgs>? Disconnected;

public string Start(string endPoint)
public string? Start(string endPoint)
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private void Dispose(bool disposing)
/// <returns>IPEndpoint from give string</returns>
private static IPEndPoint? GetIpEndPoint(string endpointAddress)
{
return Uri.TryCreate(string.Concat("tcp://", endpointAddress), UriKind.Absolute, out Uri uri)
return Uri.TryCreate(string.Concat("tcp://", endpointAddress), UriKind.Absolute, out Uri? uri)
? new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port)
: null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ internal static Task MessageLoopAsync(
/// </summary>
/// <param name="value">Input endpoint address</param>
/// <returns>IPEndpoint from give string, if its not a valid string. It will create endpoint with loop back address with port 0</returns>
internal static IPEndPoint GetIpEndPoint(this string value)
internal static IPEndPoint GetIpEndPoint(this string? value)
{
return Uri.TryCreate(string.Concat("tcp://", value), UriKind.Absolute, out Uri uri)
return Uri.TryCreate(string.Concat("tcp://", value), UriKind.Absolute, out Uri? uri)
? new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port)
: new IPEndPoint(IPAddress.Loopback, 0);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void SocketThroughput2()
serverConnected.Set();
};

var port = server.Start(IPAddress.Loopback.ToString() + ":0");
var port = server.Start(IPAddress.Loopback.ToString() + ":0")!;
client.Start(port);

clientConnected.Wait();
Expand Down

0 comments on commit f7cd809

Please sign in to comment.