Skip to content

Commit

Permalink
Tests getting love
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Dec 27, 2020
1 parent b35fa53 commit 848f823
Show file tree
Hide file tree
Showing 19 changed files with 232 additions and 92 deletions.
1 change: 1 addition & 0 deletions .linting/roslynator.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Just add ruleset file to a solution and open it.
<Rule Id="CA1308" Action="None" />
<Rule Id="CA1054" Action="None" />
<Rule Id="CA1716" Action="None" />
<Rule Id="CA2234" Action="None" />
<!-- Lots of catching rare null pointer exceptions in properties. Might refactor those in the future -->
<Rule Id="CA1065" Action="None" />

Expand Down
5 changes: 5 additions & 0 deletions src/App/NetDaemon.App/Common/NetDaemonAppBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,11 @@ public void ListenServiceCall(string domain, string service, Func<dynamic?, Task
/// <inheritdoc/>
public void Log(LogLevel level, string message, params object[] param)
{
if (Logger is null)
{
return;
}

if (param.Length > 0)
{
var result = param.Prepend(Id).ToArray();
Expand Down
2 changes: 1 addition & 1 deletion src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ public async Task Stop()
}

/// <inheritdoc/>
[SuppressMessage("", "1031")]
[SuppressMessage("", "CA1031")]
public async Task UnloadAllApps()
{
Logger.LogTrace("Unloading all apps ({instances}, {running})", InternalAllAppInstances.Count, InternalRunningAppInstances.Count);
Expand Down
11 changes: 3 additions & 8 deletions tests/NetDaemon.Daemon.Tests/Daemon/DataRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public async Task SavedDataShouldReturnSameDataUsingExpando()
data.Item = "Some data";

// ACT
await daemon.SaveDataAsync("data_exists", data);
await daemon.SaveDataAsync("data_exists", data).ConfigureAwait(false);
var collectedData = await daemon.GetDataAsync<ExpandoObject>("data_exists").ConfigureAwait(false);

// ASSERT
Expand Down Expand Up @@ -76,21 +76,16 @@ public async Task RepositoryLoadSavedDataUsingExpando()
dataBeingSaved.SomeDateTime = DateTime.Now;

// ACT
await dataRepository.Save<IDictionary<string, object>>("RepositoryLoadSavedData_id", dataBeingSaved);
await dataRepository.Save<IDictionary<string, object>>("RepositoryLoadSavedData_id", dataBeingSaved).ConfigureAwait(false);

var dataReturned = await dataRepository.Get<IDictionary<string, object>>("RepositoryLoadSavedData_id").ConfigureAwait(false);
var returnedFluentExpandoObject = new FluentExpandoObject();
returnedFluentExpandoObject.CopyFrom(dataReturned!);

dynamic dynamicDataReturned = returnedFluentExpandoObject;

if (dataBeingSaved.SomeString == dynamicDataReturned?.SomeString)
{
System.Console.WriteLine("hello");
}

// ASSERT
Assert.Equal(dataBeingSaved.SomeString, dynamicDataReturned?.SomeString);
Assert.Equal(dataBeingSaved.SomeString, dynamicDataReturned.SomeString);
Assert.Equal(dataBeingSaved.SomeInt, dynamicDataReturned!.SomeInt);
Assert.Equal(dataBeingSaved.SomeFloat, dynamicDataReturned!.SomeFloat);
// There is no way for json serializer to know this is a datetime
Expand Down
16 changes: 6 additions & 10 deletions tests/NetDaemon.Daemon.Tests/Daemon/HttpTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@ public class SerializedReturn

public class HttpTests : DaemonHostTestBase
{
public HttpTests() : base()
{
}

[Fact]
public async Task HttpClientShouldReturnCorrectContent()
{
Expand Down Expand Up @@ -84,7 +80,7 @@ public async Task HttpHandlerGetJsonShouldReturnCorrectContent()
// ARRANGE
const string? response = "{\"json_prop\": \"hello world\"}";

HttpClientFactoryMock factoryMock = new();
using HttpClientFactoryMock factoryMock = new();
factoryMock.SetResponse(response);

var httpHandler = new HttpHandler(factoryMock.Object);
Expand All @@ -102,7 +98,7 @@ public void HttpHandlerGetJsonBadFormatShouldReturnThrowException()
// ARRANGE
const string? response = "{\"json_prop\": \"hello world\"}";

HttpClientFactoryMock factoryMock = new();
using HttpClientFactoryMock factoryMock = new();
factoryMock.SetResponse(response);

var httpHandler = new HttpHandler(factoryMock.Object);
Expand All @@ -117,7 +113,7 @@ public async Task HttpHandlerPostJsonShouldReturnCorrectContent()
// ARRANGE
const string? response = "{\"json_prop\": \"hello world\"}";

HttpClientFactoryMock factoryMock = new();
using HttpClientFactoryMock factoryMock = new();
factoryMock.SetResponse(response);

var httpHandler = new HttpHandler(factoryMock.Object);
Expand All @@ -127,7 +123,7 @@ public async Task HttpHandlerPostJsonShouldReturnCorrectContent()
// ASSERT

Assert.Equal("hello world", result?.Property);
Assert.Equal("{\"posted\":\"some value\"}", factoryMock?.MessageHandler?.RequestContent);
Assert.Equal("{\"posted\":\"some value\"}", factoryMock.MessageHandler?.RequestContent);
}

[Fact]
Expand All @@ -136,7 +132,7 @@ public async Task HttpHandlerPostJsonNoReturnShouldReturnCorrectContent()
// ARRANGE
const string? response = "{\"json_prop\": \"hello world\"}";

HttpClientFactoryMock factoryMock = new();
using HttpClientFactoryMock factoryMock = new();
factoryMock.SetResponse(response);

var httpHandler = new HttpHandler(factoryMock.Object);
Expand All @@ -145,7 +141,7 @@ public async Task HttpHandlerPostJsonNoReturnShouldReturnCorrectContent()
await httpHandler.PostJson("http://fake.com", new { posted = "some value" }).ConfigureAwait(false);
// ASSERT

Assert.Equal("{\"posted\":\"some value\"}", factoryMock?.MessageHandler?.RequestContent);
Assert.Equal("{\"posted\":\"some value\"}", factoryMock.MessageHandler?.RequestContent);
}
}
}
6 changes: 4 additions & 2 deletions tests/NetDaemon.Daemon.Tests/Daemon/NetDaemonHostTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Xunit;
using NetDaemon.Daemon.Fakes;
using NetDaemon.Daemon.Tests.DaemonRunner.App;
using System.Diagnostics.CodeAnalysis;

namespace NetDaemon.Daemon.Tests.Daemon
{
Expand Down Expand Up @@ -157,7 +158,7 @@ public async Task SendEventShouldCallCorrectMethod()
var eventData = DaemonHostTestBase.GetDynamicDataObject();

// ACT
await DefaultDaemonHost.SendEvent("test_event", eventData);
await DefaultDaemonHost.SendEvent("test_event", eventData).ConfigureAwait(false);

await RunFakeDaemonUntilTimeout().ConfigureAwait(false);

Expand Down Expand Up @@ -372,6 +373,7 @@ public async Task CallServiceEventShouldCallCorrectFunction()
}

[Fact]
[SuppressMessage("", "CA1508")]
public async Task CallServiceEventOtherShouldNotCallFunction()
{
// ARRANGE
Expand All @@ -381,7 +383,7 @@ public async Task CallServiceEventOtherShouldNotCallFunction()
DefaultHassClientMock.AddCallServiceEvent("custom_domain", "other_service", dynObject);

var isCalled = false;
string? message = "";
string? message = null;

DefaultDaemonHost.ListenServiceCall("custom_domain", "any_service", data =>
{
Expand Down
79 changes: 67 additions & 12 deletions tests/NetDaemon.Daemon.Tests/DaemonRunner/Api/ApiTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Threading.Tasks;
using JoySoftware.HomeAssistant.Client;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand All @@ -11,35 +10,35 @@
using NetDaemon.Common;
using NetDaemon.Common.Reactive;
using NetDaemon.Daemon.Storage;
using NetDaemon.Daemon.Tests.Daemon;
using NetDaemon.Service.Api;
using Xunit;
using System.Threading;
using System.Text.Unicode;
using System.Text;
using System.Net.WebSockets;
using System.IO;
using System.Text.Json;
using System.Collections.Generic;
using System.Linq;
using NetDaemon.Common.Configuration;
using NetDaemon.Daemon.Fakes;
using NetDaemon.Common.Exceptions;
using System.Diagnostics.CodeAnalysis;

namespace NetDaemon.Daemon.Tests.DaemonRunner.Api
{
public class ApiFakeStartup
public class ApiFakeStartup : IAsyncLifetime, IDisposable
{
private readonly Mock<NetDaemonRxApp> _defaultMockedRxApp;
private readonly Common.NetDaemonApp _defaultDaemonApp;
private readonly Common.NetDaemonApp _defaultDaemonApp2;
private readonly BaseTestRxApp _defaultDaemonRxApp;
private readonly Mock<NetDaemonRxApp> _defaultMockedRxApp;
private readonly NetDaemonHost _defaultDaemonHost;
private readonly HttpHandlerMock _defaultHttpHandlerMock;
private readonly LoggerMock _loggerMock;

private readonly Mock<IDataRepository> _defaultDataRepositoryMock;
private readonly HassClientMock _defaultHassClientMock;
private readonly HttpHandlerMock _defaultHttpHandlerMock;
private bool disposedValue;

public IConfiguration Configuration { get; }

public ApiFakeStartup(IConfiguration configuration)
Expand Down Expand Up @@ -93,10 +92,10 @@ public void ConfigureServices(IServiceCollection services)
services.Configure<HomeAssistantSettings>(Configuration.GetSection("HomeAssistant"));
services.Configure<NetDaemonSettings>(Configuration.GetSection("NetDaemon"));

services.AddTransient<IHassClient>(_ => _defaultHassClientMock.Object);
services.AddTransient<IDataRepository>(_ => _defaultDataRepositoryMock.Object);
services.AddTransient<IHttpHandler, NetDaemon.Daemon.HttpHandler>();
services.AddSingleton<NetDaemonHost>(_ => _defaultDaemonHost);
services.AddTransient(_ => _defaultHassClientMock.Object);
services.AddTransient(_ => _defaultDataRepositoryMock.Object);
services.AddTransient<IHttpHandler, HttpHandler>();
services.AddSingleton(_ => _defaultDaemonHost);
services.AddHttpClient();
}

Expand All @@ -111,8 +110,42 @@ public static void Configure(IApplicationBuilder app, IWebHostEnvironment _)
app.UseWebSockets(webSocketOptions);
app.UseMiddleware<ApiWebsocketMiddleware>();
}

protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_defaultHttpHandlerMock.Dispose();
}

disposedValue = true;
}
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}

public Task InitializeAsync()
{
return Task.CompletedTask;
}

public async Task DisposeAsync()
{
await _defaultDaemonApp.DisposeAsync().ConfigureAwait(false);
await _defaultDaemonApp2.DisposeAsync().ConfigureAwait(false);
await _defaultDaemonRxApp.DisposeAsync().ConfigureAwait(false);
await _defaultDaemonHost.DisposeAsync().ConfigureAwait(false);
}
}
public class ApiTests : IAsyncLifetime

public class ApiTests : IAsyncLifetime, IDisposable
{
// protected readonly EventQueueManager EventQueueManager;
private readonly TestServer _server;
Expand All @@ -121,6 +154,7 @@ public class ApiTests : IAsyncLifetime
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
private bool disposedValue;

public ArraySegment<byte> Buffer { get; }

Expand All @@ -145,6 +179,7 @@ public Task InitializeAsync()
return Task.CompletedTask;
}

[SuppressMessage("", "CA2201")]
private static async Task<string> ReadString(WebSocket ws)
{
var buffer = new ArraySegment<byte>(new byte[8192]);
Expand Down Expand Up @@ -226,5 +261,25 @@ public async Task TestGetConfig()

Assert.NotNull(response?.DaemonSettings?.AppSource);
}

protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_server.Dispose();
}

disposedValue = true;
}
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
11 changes: 7 additions & 4 deletions tests/NetDaemon.Daemon.Tests/FakesTests/FakeTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
Expand Down Expand Up @@ -262,7 +263,7 @@ public async Task UsingEntitiesLambdaNewEventShouldCallFunction()
var called = false;

// ACT
DefaultDaemonRxApp.Entities(n => n.EntityId.StartsWith("binary_sensor.pir"))
DefaultDaemonRxApp.Entities(n => n.EntityId.StartsWith("binary_sensor.pir", true, CultureInfo.InvariantCulture))
.StateChanges
.Subscribe(_ => called = true);

Expand All @@ -283,7 +284,7 @@ public async Task CallbackObserverAttributeMissingShouldReturnNull()
string? missingString = "has initial value";

// ACT
DefaultDaemonRxApp.Entities(n => n.EntityId.StartsWith("binary_sensor.pir"))
DefaultDaemonRxApp.Entities(n => n.EntityId.StartsWith("binary_sensor.pir", true, CultureInfo.InvariantCulture))
.StateChanges
.Subscribe(s => missingString = s.New.Attribute?.missing_attribute);

Expand Down Expand Up @@ -411,7 +412,8 @@ public async Task GetDataShouldReturnCachedValue()
public async Task TestFakeAppTurnOnCorrectLight()
{
// Add the app to test
await AddAppInstance(new FakeApp()).ConfigureAwait(false);
await using var fakeApp = new FakeApp();
await AddAppInstance(fakeApp).ConfigureAwait(false);

// Init NetDaemon core runtime
await InitializeFakeDaemon().ConfigureAwait(false);
Expand All @@ -430,7 +432,8 @@ public async Task TestFakeAppTurnOnCorrectLight()
public async Task TestFakeAppCallNoteWhenBatteryLevelBelowValue()
{
// Add the app to test
await AddAppInstance(new FakeApp()).ConfigureAwait(false);
await using var fakeApp = new FakeApp();
await AddAppInstance(fakeApp).ConfigureAwait(false);

// Init NetDaemon core runtime
await InitializeFakeDaemon().ConfigureAwait(false);
Expand Down
Loading

0 comments on commit 848f823

Please sign in to comment.