Skip to content

Commit

Permalink
Fix remaining warnings (#991)
Browse files Browse the repository at this point in the history
* A bunch of warning fixes

* review fixes

* Forgot to remove this one
  • Loading branch information
helto4real authored Nov 4, 2023
1 parent 2ec5187 commit dae2bca
Show file tree
Hide file tree
Showing 42 changed files with 193 additions and 164 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
run: echo "::add-matcher::.github/matchers/dotnet.json"

- name: 🛠️ Build code
run: dotnet build --configuration Release
run: dotnet build --configuration Release -p:TreatWarningsAsErrors=true

- name: 👀 Unit Test
run: |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace LocalApps;


[NetDaemonApp]
public class SlowDisposableApp : IDisposable
public sealed class SlowDisposableApp : IDisposable
{
public SlowDisposableApp()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace LocalApps;

[NetDaemonApp]
public class MyAppLocalAppWithAsyncDispose : IAsyncDisposable, IDisposable
public sealed class MyAppLocalAppWithAsyncDispose : IAsyncDisposable, IDisposable
{
public bool AsyncDisposeIsCalled { get; private set; }
public bool DisposeIsCalled { get; private set; }
Expand All @@ -21,7 +21,7 @@ public void Dispose()
}

[NetDaemonApp]
public class MyAppLocalAppWithDispose : IDisposable
public sealed class MyAppLocalAppWithDispose : IDisposable
{
public bool DisposeIsCalled { get; private set; }

Expand All @@ -30,4 +30,4 @@ public void Dispose()
DisposeIsCalled = true;
GC.SuppressFinalize(this);
}
}
}
4 changes: 3 additions & 1 deletion src/Client/NetDaemon.HassClient.Tests/.editorconfig
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
[*.cs]
dotnet_diagnostic.xUnit1030.severity = none
dotnet_diagnostic.xUnit1030.severity = none
#Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly
dotnet_diagnostic.CA1861.severity = none
1 change: 0 additions & 1 deletion src/Client/NetDaemon.HassClient.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
global using NetDaemon.Client.Internal;
global using NetDaemon.Client.Internal.Helpers;
global using NetDaemon.Client.Internal.Net;
global using NetDaemon.Client.Exceptions;
global using NetDaemon.Client.Internal.Extensions;
global using NetDaemon.Client.Internal.HomeAssistant.Commands;
global using NetDaemon.Client.Settings;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace NetDaemon.HassClient.Tests.HelperTest;

public class ResultMessageHandlerTests
public class ResultMessageHandlerTests : IAsyncDisposable
{
private readonly Mock<ILogger<ResultMessageHandler>> _loggerMock = new();
private readonly ResultMessageHandler _resultMessageHandler;
Expand Down Expand Up @@ -84,4 +84,10 @@ private static async Task<HassMessage> SomeUnSuccessfulResultThrowsException()
await Task.Delay(400);
throw new InvalidOperationException("Ohh noooo!");
}

public async ValueTask DisposeAsync()
{
await _resultMessageHandler.DisposeAsync();
GC.SuppressFinalize(this);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using NetDaemon.Client.Exceptions;
using NetDaemon.HassClient.Tests.Net;

namespace NetDaemon.HassClient.Tests.HomeAssistantClientTest;
Expand Down Expand Up @@ -39,7 +40,7 @@ public async Task TestConnectWithHomeAShouldReturnConnection()

connection.Should().NotBeNull();
}

[Fact]
public async Task TestConnectWithOldVersionHomeAShouldReturnConnection()
{
Expand Down Expand Up @@ -111,7 +112,7 @@ private HomeAssistantClient GetDefaultAuthorizedHomeAssistantClient()
);
return GetDefaultHomeAssistantClient();
}

/// <summary>
/// Return a pre authenticated and running state
/// HomeAssistantClient
Expand Down Expand Up @@ -143,7 +144,7 @@ private HomeAssistantClient GetDefaultConnectOkHomeAssistantClient()
Success = true
} //{"id":1,"type":"result","success":true,"result":null}
);

// The add the fake config state that says running
_haConnectionMock.AddConfigResponseMessage(
new HassConfig
Expand All @@ -152,8 +153,8 @@ private HomeAssistantClient GetDefaultConnectOkHomeAssistantClient()
}
);
return GetDefaultHomeAssistantClient();
}
}

/// <summary>
/// Return a pre authenticated and running state
/// HomeAssistantClient with version less than 2023.9.x
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using NetDaemon.Client.Exceptions;
using NNetDaemon.HassClient.Tests.HomeAssistantRunnerTest;

namespace NetDaemon.HassClient.Tests.HomeAssistantRunnerTest;
Expand Down Expand Up @@ -33,7 +34,7 @@ public async Task TestSuccessfulShouldPostConnection()
DefaultRunner.CurrentConnection.Should().NotBeNull();
try
{
cancelSource.Cancel();
await cancelSource.CancelAsync();
await runnerTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
Expand Down Expand Up @@ -74,7 +75,7 @@ public async Task TestUnSuccessfulConnectionShouldPostCorrectDisconnectError()

try
{
cancelSource.Cancel();
await cancelSource.CancelAsync();
await runnerTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
Expand Down Expand Up @@ -114,7 +115,7 @@ public async Task TestNotReadyConnectionShouldPostCorrectDisconnectError()

try
{
cancelSource.Cancel();
await cancelSource.CancelAsync();
await runnerTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
Expand Down Expand Up @@ -154,7 +155,7 @@ public async Task TestNotAuthorizedConnectionShouldPostCorrectDisconnectError()

try
{
cancelSource.Cancel();
await cancelSource.CancelAsync();
await runnerTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
Expand All @@ -180,7 +181,7 @@ public async Task TestClientDisconnectShouldPostCorrectDisconnectError()
DefaultRunner.RunAsync("host", 0, false, "token", "wspath", TimeSpan.FromMilliseconds(100), cancelSource.Token);

// await DefaultRunner.DisposeAsync().ConfigureAwait(false);
cancelSource.Cancel();
await cancelSource.CancelAsync();
var reason = await disconnectionTask.ConfigureAwait(false);
DefaultRunner.CurrentConnection.Should().BeNull();
try
Expand Down Expand Up @@ -222,7 +223,7 @@ public async Task TestRemoteDisconnectShouldPostCorrectDisconnectError()
var reason = await disconnectionTask.ConfigureAwait(false);
try
{
cancelSource.Cancel();
await cancelSource.CancelAsync();
await runnerTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace NetDaemon.HassClient.Tests.Integration;
/// The Home Assistant Mock class implements a fake Home Assistant server by
/// exposing the websocket api and fakes responses to requests.
/// </summary>
public class HomeAssistantMock : IAsyncDisposable
public sealed class HomeAssistantMock : IAsyncDisposable
{
public const int RecieiveBufferSize = 1024 * 4;
public IHost HomeAssistantHost { get; }
Expand All @@ -30,7 +30,6 @@ public HomeAssistantMock()
public async ValueTask DisposeAsync()
{
await Stop().ConfigureAwait(false);
GC.SuppressFinalize(this);
}

/// <summary>
Expand Down Expand Up @@ -63,12 +62,13 @@ private async Task Stop()
await HomeAssistantHost.StopAsync().ConfigureAwait(false);
await HomeAssistantHost.WaitForShutdownAsync().ConfigureAwait(false);
}

}

/// <summary>
/// The class implementing the mock hass server
/// </summary>
public class HassMockStartup : IHostedService
public sealed class HassMockStartup : IHostedService, IDisposable
{
private readonly byte[] _authOkMessage =
File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Integration", "Testdata", "auth_ok.json"));
Expand All @@ -89,10 +89,9 @@ public Task StartAsync(CancellationToken cancellationToken)
return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
public async Task StopAsync(CancellationToken cancellationToken)
{
_cancelSource.Cancel();
return Task.CompletedTask;
await _cancelSource.CancelAsync();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment e)
Expand Down Expand Up @@ -430,4 +429,9 @@ private sealed class SendCommandMessage
[JsonPropertyName("type")] public string Type { get; set; } = string.Empty;
[JsonPropertyName("id")] public int Id { get; set; } = 0;
}

public void Dispose()
{
_cancelSource.Dispose();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace NetDaemon.HassClient.Tests.Integration;

public class IntegrationTestBase : IClassFixture<HomeAssistantServiceFixture>
{
protected readonly CancellationTokenSource TokenSource = new(TestSettings.DefaultTimeout);
protected CancellationTokenSource TokenSource { get; } = new(TestSettings.DefaultTimeout);

protected IntegrationTestBase(HomeAssistantServiceFixture fixture)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using NetDaemon.Client.Exceptions;

namespace NetDaemon.HassClient.Tests.Integration;

public class WebsocketIntegrationTests : IntegrationTestBase
Expand Down Expand Up @@ -337,7 +339,7 @@ public async Task TestMultipleSubscribeEventChangeAndGetEvent()
.Should()
.NotBeNull();

secondChangedEvent!.NewState!.Attributes!.FirstOrDefault(n => n.Key == "battery_level")!
secondChangedEvent.NewState!.Attributes!.FirstOrDefault(n => n.Key == "battery_level")!
.Should()
.NotBeNull();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Net;

namespace NetDaemon.Client.Internal.Exceptions;
namespace NetDaemon.Client.Exceptions;

[SuppressMessage("", "RCS1194")]
public class HomeAssistantApiCallException : Exception
Expand Down
1 change: 0 additions & 1 deletion src/Client/NetDaemon.HassClient/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
global using NetDaemon.Client.Internal.Helpers;
global using NetDaemon.Client.Internal.Json;
global using NetDaemon.Client.Internal.Net;
global using NetDaemon.Client.Exceptions;
global using NetDaemon.Client.Internal.Extensions;
global using NetDaemon.Client.Internal.HomeAssistant.Commands;
global using NetDaemon.Client.Internal.HomeAssistant.Messages;
Expand Down
9 changes: 2 additions & 7 deletions src/Client/NetDaemon.HassClient/Internal/Helpers/AsyncLazy.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
namespace NetDaemon.Client.Internal.Helpers;

public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Factory.StartNew(taskFactory).Unwrap())
{
}
}
public class AsyncLazy<T>(Func<Task<T>> taskFactory) : Lazy<Task<T>>(()
=> Task.Factory.StartNew(taskFactory).Unwrap());
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,11 @@

namespace NetDaemon.Client.Internal.Helpers;

internal class ResultMessageHandler : IAsyncDisposable
internal class ResultMessageHandler(ILogger logger) : IAsyncDisposable
{
internal int WaitForResultTimeout = 20000;
private readonly CancellationTokenSource _tokenSource = new();
private readonly ConcurrentDictionary<Task<HassMessage>, object?> _backgroundTasks = new();
private readonly ILogger _logger;

public ResultMessageHandler(ILogger logger)
{
_logger = logger;
}

public void HandleResult(Task<HassMessage> returnMessageTask, CommandMessage originalCommand)
{
Expand All @@ -33,7 +27,7 @@ async Task Wrap()
if (awaitedTask != task)
{
// We have a timeout
_logger.LogWarning(
logger.LogWarning(
"Command ({CommandType}) did not get response in timely fashion. Sent command is {CommandMessage}",
command.Type, command);
}
Expand All @@ -42,14 +36,14 @@ async Task Wrap()
var result = await task.ConfigureAwait(false);
if (!result.Success ?? false)
{
_logger.LogWarning(
logger.LogWarning(
"Failed command ({CommandType}) error: {ErrorResult}. Sent command is {CommandMessage}",
command.Type, result.Error, command);
}
}
catch (Exception e)
{
_logger.LogError(e, "Exception waiting for result message Sent command is {CommandMessage}", command);
logger.LogError(e, "Exception waiting for result message Sent command is {CommandMessage}", command);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using NetDaemon.Client.Internal.Exceptions;
using NetDaemon.Client.Exceptions;

namespace NetDaemon.Client.Internal;

Expand Down Expand Up @@ -82,4 +82,4 @@ private static string GetApiUrl(HomeAssistantSettings settings)
var httpScheme = settings.Ssl ? "https" : "http";
return $"{httpScheme}://{settings.Host}:{settings.Port}/api";
}
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using NetDaemon.Client.Exceptions;

namespace NetDaemon.Client.Internal;

internal class HomeAssistantClient(ILogger<IHomeAssistantClient> logger,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using NetDaemon.Client.Exceptions;

namespace NetDaemon.Client.Internal;

internal class HomeAssistantRunner(IHomeAssistantClient client,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace NetDaemon.Client.Internal.Net;

internal class WebSocketClientTransportPipeline : IWebSocketClientTransportPipeline
internal class WebSocketClientTransportPipeline(IWebSocketClient clientWebSocket) : IWebSocketClientTransportPipeline
{
/// <summary>
/// Default Json serialization options, Hass expects intended
Expand All @@ -13,12 +13,7 @@ internal class WebSocketClientTransportPipeline : IWebSocketClientTransportPipel

private readonly CancellationTokenSource _internalCancelSource = new();
private readonly Pipe _pipe = new();
private readonly IWebSocketClient _ws;

public WebSocketClientTransportPipeline(IWebSocketClient clientWebSocket)
{
_ws = clientWebSocket ?? throw new ArgumentNullException(nameof(clientWebSocket));
}
private readonly IWebSocketClient _ws = clientWebSocket ?? throw new ArgumentNullException(nameof(clientWebSocket));

private static int DefaultTimeOut => 5000;

Expand Down
Loading

0 comments on commit dae2bca

Please sign in to comment.