Skip to content

Commit

Permalink
More love
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Dec 26, 2020
1 parent 6a85491 commit 84f36d6
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 25 deletions.
17 changes: 11 additions & 6 deletions src/Fakes/NetDaemon.Fakes/DaemonHostTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ namespace NetDaemon.Daemon.Fakes
public class DaemonHostTestBase : IAsyncLifetime
{
private Task? _fakeConnectedDaemon;
private CancellationTokenSource? _cancelSource;

/// <summary>
/// Default contructor
Expand Down Expand Up @@ -68,6 +69,7 @@ public DaemonHostTestBase()
/// </summary>
public Task DisposeAsync()
{
_cancelSource?.Dispose();
return Task.CompletedTask;
}

Expand Down Expand Up @@ -111,6 +113,8 @@ public virtual Task InitializeAsync()
/// <param name="state">The state to sett</param>
public void SetEntityState(HassState state)
{
_ = state ??
throw new NetDaemonArgumentNullException(nameof(state));
DefaultHassClientMock.FakeStates[state.EntityId] = state;
}

Expand All @@ -136,6 +140,8 @@ public void SetEntityState(string entityId, dynamic? state = null, string? area
/// <param name="app">The instance of the app to add</param>
public async Task AddAppInstance(INetDaemonAppBase app)
{
_ = app ??
throw new NetDaemonArgumentNullException(nameof(app));
if (string.IsNullOrEmpty(app.Id))
app.Id = Guid.NewGuid().ToString();
DefaultDaemonHost.InternalAllAppInstances[app.Id] = app;
Expand Down Expand Up @@ -241,7 +247,7 @@ public void VerifyEventSent(string ev, object? eventData)
/// <param name="data">Data sent by service</param>
/// <param name="waitForResponse">If service was waiting for response</param>
/// <param name="times">Number of times called</param>
public void VerifyCallService(string domain, string service, object? data = null, bool waitForResponse = false, Moq.Times? times = null)
public void VerifyCallService(string domain, string service, object? data = null, bool waitForResponse = false, Times? times = null)
{
DefaultHassClientMock.VerifyCallService(domain, service, data, waitForResponse, times);
}
Expand All @@ -255,7 +261,7 @@ public void VerifyCallService(string domain, string service, object? data = null
/// <param name="waitForResponse">If service was waiting for response</param>
/// <param name="times">Number of times called</param>
/// <param name="attributesTuples">Attributes to verify</param>
public void VerifyCallService(string domain, string service, string entityId, bool waitForResponse = false, Moq.Times? times = null,
public void VerifyCallService(string domain, string service, string entityId, bool waitForResponse = false, Times? times = null,
params (string attribute, object value)[] attributesTuples)
{
var serviceObject = new FluentExpandoObject
Expand Down Expand Up @@ -295,7 +301,6 @@ public void VerifyCallServiceTimes(string service, Times times)
/// Wait for task until canceled
/// </summary>
/// <param name="task">Task to wait for</param>
/// <returns></returns>
private static async Task WaitUntilCanceled(Task task)
{
try
Expand Down Expand Up @@ -375,14 +380,14 @@ protected async Task RunFakeDaemonUntilTimeout()
/// <param name="overrideDebugNotCancel">True to use timeout while debugging</param>
private async Task<Task> GetConnectedNetDaemonTask(short milliSeconds = 100, bool overrideDebugNotCancel = false)
{
var cancelSource = Debugger.IsAttached && !overrideDebugNotCancel
_cancelSource = Debugger.IsAttached && !overrideDebugNotCancel
? new CancellationTokenSource()
: new CancellationTokenSource(milliSeconds);

await InitApps().ConfigureAwait(false);

var daemonTask = DefaultDaemonHost.Run("host", 8123, false, "token", cancelSource.Token);
await WaitForDefaultDaemonToConnect(DefaultDaemonHost, cancelSource.Token).ConfigureAwait(false);
var daemonTask = DefaultDaemonHost.Run("host", 8123, false, "token", _cancelSource.Token);
await WaitForDefaultDaemonToConnect(DefaultDaemonHost, _cancelSource.Token).ConfigureAwait(false);
return daemonTask;
}

Expand Down
27 changes: 15 additions & 12 deletions src/Fakes/NetDaemon.Fakes/HassClientMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,27 @@ public class HassClientMock : Mock<IHassClient>
/// <summary>
/// Fake areas in HassClient
/// </summary>
/// <returns></returns>
public HassAreas Areas = new();
public HassAreas Areas { get; } = new();

/// <summary>
/// Fake devices in HassClient
/// </summary>
/// <returns></returns>
public HassDevices Devices = new();
public HassDevices Devices { get; } = new();

/// <summary>
/// Fake entities in HassClient
/// </summary>
public HassEntities Entities = new();
public HassEntities Entities { get; } = new();

/// <summary>
/// Fake events in HassClient
/// </summary>
public ConcurrentQueue<HassEvent> FakeEvents = new();
public ConcurrentQueue<HassEvent> FakeEvents { get; } = new();
/// <summary>
/// All current fake entities and it's states
/// </summary>
public ConcurrentDictionary<string, HassState> FakeStates = new();
public ConcurrentDictionary<string, HassState> FakeStates { get; } = new();

/// <summary>
/// Default constructor
Expand All @@ -58,7 +57,7 @@ public HassClientMock()
SetupGet(x => x.States).Returns(FakeStates);

Setup(x => x.GetAllStates(It.IsAny<CancellationToken>()))
.ReturnsAsync(() => (IEnumerable<HassState>)FakeStates.Values);
.ReturnsAsync(() => FakeStates.Values);

Setup(x => x.ReadEventAsync())
.ReturnsAsync(() => FakeEvents.TryDequeue(out var ev) ? ev : null);
Expand Down Expand Up @@ -257,6 +256,10 @@ public void AddCustomEvent(string eventType, dynamic? data)
/// <param name="entity">NetDaemon state instance</param>
public static void AssertEqual(HassState hassState, EntityState entity)
{
_ = hassState ??
throw new NetDaemonArgumentNullException(nameof(hassState));
_ = entity ??
throw new NetDaemonArgumentNullException(nameof(entity));
Assert.Equal(hassState.EntityId, entity.EntityId);
Assert.Equal(hassState.State, entity.State);
Assert.Equal(hassState.LastChanged, entity.LastChanged);
Expand All @@ -282,7 +285,7 @@ public static void AssertEqual(HassState hassState, EntityState entity)
/// <param name="milliSeconds"></param>
public static CancellationTokenSource GetSourceWithTimeout(int milliSeconds = 100)
{
return (Debugger.IsAttached)
return Debugger.IsAttached
? new CancellationTokenSource()
: new CancellationTokenSource(milliSeconds);
}
Expand All @@ -298,7 +301,7 @@ public static CancellationTokenSource GetSourceWithTimeout(int milliSeconds = 10
{
var attributes = new FluentExpandoObject();
foreach (var (attribute, value) in attributesTuples)
((IDictionary<string, object>)attributes)[attribute] = value;
attributes[attribute] = value;

Verify(n => n.CallService(domain, service, attributes, It.IsAny<bool>()), Times.AtLeastOnce);
}
Expand All @@ -311,7 +314,7 @@ public static CancellationTokenSource GetSourceWithTimeout(int milliSeconds = 10
/// <param name="data">Data sent by service</param>
/// <param name="waitForResponse">If service was waiting for response</param>
/// <param name="times">Number of times called</param>
public void VerifyCallService(string domain, string service, object? data = null, bool waitForResponse = false, Moq.Times? times = null)
public void VerifyCallService(string domain, string service, object? data = null, bool waitForResponse = false, Times? times = null)
{
if (times is not null)
Verify(n => n.CallService(domain, service, data!, waitForResponse), times.Value);
Expand All @@ -326,7 +329,7 @@ public void VerifyCallService(string domain, string service, object? data = null
/// <param name="service">Service to verify</param>
/// <param name="waitForResponse">If service was waiting for response</param>
/// <param name="times">Number of times called</param>
public void VerifyCallService(string domain, string service, bool waitForResponse = false, Moq.Times? times = null)
public void VerifyCallService(string domain, string service, bool waitForResponse = false, Times? times = null)
{
if (times is not null)
Verify(n => n.CallService(domain, service, It.IsAny<object>(), waitForResponse), times.Value);
Expand Down Expand Up @@ -355,7 +358,7 @@ public void VerifyCallServiceTimes(string service, Times times)
{
var attributes = new FluentExpandoObject();
foreach (var (attribute, value) in attributesTuples)
((IDictionary<string, object>)attributes)[attribute] = value;
attributes[attribute] = value;

Verify(n => n.SetState(entity, state, attributes), Times.AtLeastOnce);
}
Expand Down
49 changes: 47 additions & 2 deletions src/Fakes/NetDaemon.Fakes/HttpHandlerMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
using System.Threading;
using System.Threading.Tasks;
using NetDaemon.Common;
using System;

namespace NetDaemon.Daemon.Fakes
{
/// <summary>
/// HttpClient Mock
/// </summary>
public class HttpClientFactoryMock : Mock<IHttpClientFactory>
public class HttpClientFactoryMock : Mock<IHttpClientFactory>, IDisposable
{
private HttpClient? _httpClient;
private MockHttpMessageHandler? _handler;
Expand All @@ -38,12 +39,34 @@ public void SetResponse(string response, HttpStatusCode statusCode = HttpStatusC
_httpClient = new HttpClient(_handler);
Setup(x => x.CreateClient(It.IsAny<string>())).Returns(_httpClient!);
}

/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

/// <summary>
/// Disposes the object and cancel delay
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Make sure any subscriptions are canceled
_httpClient?.Dispose();
_handler?.Dispose();
}
}
}

/// <summary>
/// Mock of HttpHandler
/// </summary>
public class HttpHandlerMock : Mock<IHttpHandler>
public class HttpHandlerMock : Mock<IHttpHandler>, IDisposable
{
private HttpClient? _httpClient;
private MockHttpMessageHandler? _handler;
Expand Down Expand Up @@ -71,6 +94,28 @@ public void SetResponse(string response, HttpStatusCode statusCode = HttpStatusC
_httpClient = new HttpClient(_handler);
Setup(x => x.CreateHttpClient(It.IsAny<string>())).Returns(_httpClient!);
}

/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

/// <summary>
/// Disposes the object and cancel delay
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Make sure any subscriptions are canceled
_handler?.Dispose();
_httpClient?.Dispose();
}
}
}

/// <summary>
Expand Down
6 changes: 6 additions & 0 deletions src/Fakes/NetDaemon.Fakes/NetDaemon.Fakes.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,14 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Roslynator.Analyzers" Version="3.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<CodeAnalysisRuleSet>..\..\..\.linting\roslynator.ruleset</CodeAnalysisRuleSet>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
</PropertyGroup>
</Project>
1 change: 1 addition & 0 deletions src/Service/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ await Host.CreateDefaultBuilder(args)
catch (Exception e)
{
Console.WriteLine($"Failed to start host... {e}");
throw;
}
finally
{
Expand Down
6 changes: 6 additions & 0 deletions src/Service/Service.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Roslynator.Analyzers" Version="3.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand All @@ -26,5 +30,7 @@
</ItemGroup>
<PropertyGroup>
<CodeAnalysisRuleSet>..\..\.linting\roslynator.ruleset</CodeAnalysisRuleSet>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ namespace NetDaemon.Daemon.Tests.DaemonRunner.App
/// <summary>
/// Greets (or insults) people when coming home :)
/// </summary>
public class AssemblyDaemonApp : NetDaemon.Common.NetDaemonApp
public class AssemblyDaemonApp : Common.NetDaemonApp
{
#region -- Test config --

public string? StringConfig { get; set; } = null;
public int? IntConfig { get; set; } = null;
public IEnumerable<string>? EnumerableConfig { get; set; } = null;
public string? StringConfig { get; set; }
public int? IntConfig { get; set; }
public IEnumerable<string>? EnumerableConfig { get; set; }

#endregion -- Test config --

Expand All @@ -28,7 +28,7 @@ public class AssemblyDaemonApp : NetDaemon.Common.NetDaemonApp
#endregion -- Test secrets --

// For testing
public bool HandleServiceCallIsCalled { get; set; } = false;
public bool HandleServiceCallIsCalled { get; set; }

public override Task InitializeAsync()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
/// <summary>
/// Greets (or insults) people when coming home :)
/// </summary>
[SuppressMessage("", "CS1002")]
[SuppressMessage("", "CS1038")]
public class AssmeblyFaultyCompileErrorDaemonApp : NetDaemonApp
{
#region -- Test config --
Expand Down

0 comments on commit 84f36d6

Please sign in to comment.