Skip to content

Commit

Permalink
Enable nullable on ObjectModel (#3793)
Browse files Browse the repository at this point in the history
  • Loading branch information
Evangelink committed Jun 22, 2022
1 parent 69a84d7 commit b58c1ce
Show file tree
Hide file tree
Showing 368 changed files with 1,786 additions and 1,962 deletions.
32 changes: 16 additions & 16 deletions playground/TestPlatform.Playground/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ static void Main(string[] args)
var sourceSettings = $$$"""
<RunSettings>
<RunConfiguration>

<!-- <MaxCpuCount>1</MaxCpuCount> -->
<!-- <TargetPlatform>x86</TargetPlatform> -->
<!-- <TargetFrameworkVersion>net472</TargetFrameworkVersion> -->
Expand Down Expand Up @@ -135,23 +135,23 @@ public class PlaygroundTestDiscoveryHandler : ITestDiscoveryEventsHandler, ITest

public List<TestCase> TestCases { get; internal set; } = new List<TestCase>();

public void HandleDiscoveredTests(IEnumerable<TestCase> discoveredTestCases)
public void HandleDiscoveredTests(IEnumerable<TestCase>? discoveredTestCases)
{
Console.WriteLine($"[DISCOVERY.PROGRESS]");
Console.WriteLine(WriteTests(discoveredTestCases));
_testCasesCount += discoveredTestCases.Count();
if (discoveredTestCases != null) { TestCases.AddRange(discoveredTestCases); }
}

public void HandleDiscoveryComplete(long totalTests, IEnumerable<TestCase> lastChunk, bool isAborted)
public void HandleDiscoveryComplete(long totalTests, IEnumerable<TestCase>? lastChunk, bool isAborted)
{
Console.WriteLine($"[DISCOVERY.COMPLETE] aborted? {isAborted}, tests count: {totalTests}");
Console.WriteLine("Last chunk:");
Console.WriteLine(WriteTests(lastChunk));
if (lastChunk != null) { TestCases.AddRange(lastChunk); }
}

public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable<TestCase> lastChunk)
public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable<TestCase>? lastChunk)
{
Console.WriteLine($"[DISCOVERY.COMPLETE] aborted? {discoveryCompleteEventArgs.IsAborted}, tests count: {discoveryCompleteEventArgs.TotalCount}, discovered count: {_testCasesCount}");
Console.WriteLine("Last chunk:");
Expand All @@ -167,7 +167,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete
if (lastChunk != null) { TestCases.AddRange(lastChunk); }
}

public void HandleLogMessage(TestMessageLevel level, string message)
public void HandleLogMessage(TestMessageLevel level, string? message)
{
Console.WriteLine($"[DISCOVERY.{level.ToString().ToUpper()}] {message}");
}
Expand All @@ -177,12 +177,12 @@ public void HandleRawMessage(string rawMessage)
Console.WriteLine($"[DISCOVERY.MESSAGE] {rawMessage}");
}

private static string WriteTests(IEnumerable<TestCase> testCases)
private static string WriteTests(IEnumerable<TestCase>? testCases)
=> testCases?.Any() == true
? "\t" + string.Join("\n\t", testCases.Select(r => r.Source + " " + r.DisplayName))
? "\t" + string.Join("\n\t", testCases?.Select(r => r.Source + " " + r.DisplayName))
: "\t<empty>";

private static string WriteSources(IEnumerable<string> sources)
private static string WriteSources(IEnumerable<string>? sources)
=> sources?.Any() == true
? "\t" + string.Join("\n\t", sources)
: "\t<empty>";
Expand All @@ -195,7 +195,7 @@ public TestRunHandler()
{
}

public void HandleLogMessage(TestMessageLevel level, string message)
public void HandleLogMessage(TestMessageLevel level, string? message)
{
Console.WriteLine($"[{level.ToString().ToUpper()}]: {message}");
}
Expand All @@ -205,16 +205,16 @@ public void HandleRawMessage(string rawMessage)
Console.WriteLine($"[RUN.MESSAGE]: {rawMessage}");
}

public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection<AttachmentSet> runContextAttachments, ICollection<string> executorUris)
public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs? lastChunkArgs, ICollection<AttachmentSet>? runContextAttachments, ICollection<string>? executorUris)
{
Console.WriteLine($"[RUN.COMPLETE]: err: {testRunCompleteArgs.Error}, lastChunk:");
Console.WriteLine(WriteTests(lastChunkArgs?.NewTestResults));
}

public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs)
public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs)
{
Console.WriteLine($"[RUN.PROGRESS]");
Console.WriteLine(WriteTests(testRunChangedArgs.NewTestResults));
Console.WriteLine(WriteTests(testRunChangedArgs?.NewTestResults));
}

public int LaunchProcessWithDebuggerAttached(TestProcessStartInfo testProcessStartInfo)
Expand Down Expand Up @@ -261,7 +261,7 @@ internal class TestSessionHandler : ITestSessionEventsHandler
{
public TestSessionInfo? TestSessionInfo { get; private set; }

public void HandleLogMessage(TestMessageLevel level, string message)
public void HandleLogMessage(TestMessageLevel level, string? message)
{

}
Expand All @@ -271,12 +271,12 @@ public void HandleRawMessage(string rawMessage)

}

public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs eventArgs)
public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs? eventArgs)
{
TestSessionInfo = eventArgs.TestSessionInfo;
TestSessionInfo = eventArgs?.TestSessionInfo;
}

public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs eventArgs)
public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs? eventArgs)
{

}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead
M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead
M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead
M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead
M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead
M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ internal class EventLogContainer : IEventLogContainer
private readonly int _maxLogEntries;

private readonly DataCollectionLogger _dataCollectionLogger;

private readonly DataCollectionContext? _dataCollectionContext;
private readonly DataCollectionContext _dataCollectionContext;

/// <summary>
/// Keeps track of if we are disposed.
Expand Down Expand Up @@ -53,7 +52,7 @@ internal class EventLogContainer : IEventLogContainer
/// <param name="dataCollectionContext">
/// Data Collection Context
/// </param>
public EventLogContainer(string eventLogName, ISet<string>? eventSources, ISet<EventLogEntryType> entryTypes, int maxLogEntries, DataCollectionLogger dataCollectionLogger, DataCollectionContext? dataCollectionContext)
public EventLogContainer(string eventLogName, ISet<string>? eventSources, ISet<EventLogEntryType> entryTypes, int maxLogEntries, DataCollectionLogger dataCollectionLogger, DataCollectionContext dataCollectionContext)
{
EventLog = new EventLog(eventLogName);
EventLog.EnableRaisingEvents = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,13 @@ internal EventLogDataCollector(IFileHelper fileHelper)
/// Used by the data collector to send warnings, errors, or other messages
/// </param>
/// <param name="dataCollectionEnvironmentContext">Provides contextual information about the agent environment</param>
[MemberNotNull(nameof(_events), nameof(_dataSink), nameof(_logger))]
[MemberNotNull(nameof(_events), nameof(_dataSink), nameof(_logger), nameof(_dataCollectorContext))]
public override void Initialize(
XmlElement? configurationElement,
DataCollectionEvents events,
DataCollectionSink dataSink,
DataCollectionLogger logger,
DataCollectionEnvironmentContext dataCollectionEnvironmentContext)
DataCollectionEnvironmentContext? dataCollectionEnvironmentContext)
{
ValidateArg.NotNull(events, nameof(events));
ValidateArg.NotNull(dataSink, nameof(dataSink));
Expand All @@ -163,7 +163,7 @@ public override void Initialize(
_events = events;
_dataSink = dataSink;
_logger = logger;
_dataCollectorContext = dataCollectionEnvironmentContext.SessionDataCollectionContext;
_dataCollectorContext = dataCollectionEnvironmentContext!.SessionDataCollectionContext;

// Load the configuration
CollectorNameValueConfigurationManager nameValueSettings =
Expand All @@ -173,7 +173,7 @@ public override void Initialize(
ConfigureEventSources(nameValueSettings);
ConfigureEntryTypes(nameValueSettings);
ConfigureMaxEntries(nameValueSettings);
ConfigureEventLogNames(nameValueSettings);
ConfigureEventLogNames(nameValueSettings, _dataCollectorContext);

// Register for events
events.SessionStart += _sessionStartEventHandler;
Expand All @@ -183,6 +183,7 @@ public override void Initialize(
}

#endregion

/// <summary>
/// The write event logs.
/// </summary>
Expand Down Expand Up @@ -444,7 +445,7 @@ private void WriteCollectedEventLogEntries(
}

[MemberNotNull(nameof(EventLogNames))]
private void ConfigureEventLogNames(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)
private void ConfigureEventLogNames(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager, DataCollectionContext dataCollectorContext)
{
EventLogNames = new HashSet<string>();
string? eventLogs = collectorNameValueConfigurationManager[EventLogConstants.SettingEventLogs];
Expand Down Expand Up @@ -476,7 +477,7 @@ private void ConfigureEventLogNames(CollectorNameValueConfigurationManager colle
EntryTypes,
int.MaxValue,
_logger,
_dataCollectorContext);
dataCollectorContext);
_eventLogContainerMap.Add(eventLogName, eventLogContainer);
}

Expand All @@ -485,7 +486,7 @@ private void ConfigureEventLogNames(CollectorNameValueConfigurationManager colle
catch (Exception ex)
{
_logger.LogError(
_dataCollectorContext,
dataCollectorContext,
new EventLogCollectorException(string.Format(CultureInfo.CurrentCulture, Resource.ReadError, eventLogName, Environment.MachineName), ex));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector
Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.EventLogDataCollector() -> void
override Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.Dispose(bool disposing) -> void
override Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.Initialize(System.Xml.XmlElement? configurationElement, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEvents! events, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionSink! dataSink, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEnvironmentContext! dataCollectionEnvironmentContext) -> void
override Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.Initialize(System.Xml.XmlElement? configurationElement, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEvents! events, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionSink! dataSink, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEnvironmentContext? dataCollectionEnvironmentContext) -> void
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;

using Microsoft.TestPlatform.AdapterUtilities.Helpers;
Expand Down Expand Up @@ -116,7 +115,7 @@ private static int ParseMethodName(string managedMethodName, int start, out stri
// parse arity in the form `nn where nn is an integer value.
private static int ParseArity(string managedMethodName, int start, out int arity)
{
Debug.Assert(managedMethodName[start] == '`');
TPDebug.Assert(managedMethodName[start] == '`');

int i = start + 1; // skip initial '`' char
for (; i < managedMethodName.Length; i++)
Expand All @@ -137,7 +136,7 @@ private static int ParseParameterTypeList(string managedMethodName, int start, o
{
return start;
}
Debug.Assert(managedMethodName[start] == '(');
TPDebug.Assert(managedMethodName[start] == '(');

var types = new List<string>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,28 @@
<AdditionalFiles Condition=" '$(TargetFramework)' != 'netstandard1.0' AND '$(TargetFramework)' != 'uap10.0' " Include="PublicAPI\net\PublicAPI.Unshipped.txt" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\..\shared\NullableAttributes.cs" Link="NullableAttributes.cs" />
</ItemGroup>

<ItemGroup>
<None Update="NullableHelpers.tt">
<LastGenOutput>NullableHelpers.cs</LastGenOutput>
<Generator>TextTemplatingFileGenerator</Generator>
</None>
</ItemGroup>

<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>

<ItemGroup>
<Compile Update="NullableHelpers.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>NullableHelpers.tt</DependentUpon>
</Compile>
</ItemGroup>

<Import Project="$(TestPlatformRoot)scripts\build\TestPlatform.targets" />
</Project>
42 changes: 42 additions & 0 deletions src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// <auto-generated>
// This code is auto-generated. Changes to this file will be lost!
// This T4 file is copied in various projects because inclusion as link or through shared project
// doesn't allow to generate the C# file locally. If some modification is required, please update
// all instances.
// </auto-generated>

#nullable enable

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.TestPlatform.AdapterUtilities;

internal static class StringUtils
{
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")]
public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value)
=> string.IsNullOrEmpty(value);

/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")]
public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value)
=> string.IsNullOrWhiteSpace(value);
}

[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")]
internal static class TPDebug
{
/// <inheritdoc cref="Debug.Assert(bool)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b)
=> Debug.Assert(b);

/// <inheritdoc cref="Debug.Assert(bool, string)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b, string message)
=> Debug.Assert(b, message);
}
45 changes: 45 additions & 0 deletions src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.tt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// <auto-generated>
// This code is auto-generated. Changes to this file will be lost!
// This T4 file is copied in various projects because inclusion as link or through shared project
// doesn't allow to generate the C# file locally. If some modification is required, please update
// all instances.
// </auto-generated>

#nullable enable

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace <#= System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint") #>;

internal static class StringUtils
{
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")]
public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value)
=> string.IsNullOrEmpty(value);

/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")]
public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value)
=> string.IsNullOrWhiteSpace(value);
}

[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")]
internal static class TPDebug
{
/// <inheritdoc cref="Debug.Assert(bool)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b)
=> Debug.Assert(b);

/// <inheritdoc cref="Debug.Assert(bool, string)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b, string message)
=> Debug.Assert(b, message);
}
4 changes: 2 additions & 2 deletions src/Microsoft.TestPlatform.Build/BannedSymbols.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead
M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead
M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead
M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead
M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead
M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public TestRunAttachmentsProcessingEventsHandler(ICommunicationManager communica
}

/// <inheritdoc/>
public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable<AttachmentSet> lastChunk)
public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable<AttachmentSet>? lastChunk)
{
EqtTrace.Info("Test run attachments processing completed.");

Expand Down Expand Up @@ -60,7 +60,7 @@ public void HandleProcessedAttachmentsChunk(IEnumerable<AttachmentSet> attachmen
}

/// <inheritdoc/>
public void HandleLogMessage(TestMessageLevel level, string message)
public void HandleLogMessage(TestMessageLevel level, string? message)
{
var testMessagePayload = new TestMessagePayload { MessageLevel = level, Message = message };
_communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload);
Expand Down
Loading

0 comments on commit b58c1ce

Please sign in to comment.