Skip to content

Commit

Permalink
Code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineatrhea committed Oct 3, 2023
1 parent ec1b77e commit 95de256
Show file tree
Hide file tree
Showing 10 changed files with 366 additions and 4 deletions.
1 change: 1 addition & 0 deletions COMET.Web.Common.Test/COMET.Web.Common.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<ItemGroup>
<PackageReference Include="bunit.web" Version="1.14.4" />
<PackageReference Include="DevExpress.Blazor" Version="23.1.4" />
<PackageReference Include="Moq" Version="4.18.4" />
</ItemGroup>

<ItemGroup>
Expand Down
64 changes: 64 additions & 0 deletions COMET.Web.Common.Test/Helpers/MockedLoggerHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MockedLoggerHelper.cs" company="RHEA System S.A.">
// Copyright (c) 2023 RHEA System S.A.
//
// Authors: Sam Gerené, Alex Vorobiev, Alexander van Delft, Jaime Bernar, Théate Antoine
//
// This file is part of COMET WEB Community Edition
// The COMET WEB Community Edition is the RHEA Web Application implementation of ECSS-E-TM-10-25
// Annex A and Annex C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace COMET.Web.Common.Test.Helpers
{
using System.Linq.Expressions;

using Microsoft.Extensions.Logging;

using Moq;

/// <summary>
/// Helper class for any <see cref="Moq.Mock"/> for <seealso cref="ILogger{TCategoryName}"/>
/// </summary>
public static class MockedLoggerHelper
{
/// <summary>
/// Provides the matching expression to verify
/// </summary>
/// <typeparam name="T">The type for the <see cref="ILogger{TCategoryName}"/></typeparam>
/// <param name="level">The <see cref="LogLevel"/></param>
/// <param name="predicate">A predicate for the matching log message</param>
/// <returns>An <see cref="Expression"/></returns>
private static Expression<Action<ILogger<T>>> Verify<T>(LogLevel level, Func<object, bool> predicate)
{
return x => x.Log(level, 0, It.Is<It.IsAnyType>((o, t) => predicate(o)), It.IsAny<Exception>(), It.IsAny<Func<It.IsAnyType, Exception, string>>());
}

/// <summary>
/// Verifies that the <see cref="ILogger{TCategoryName}"/> has log message that matches the provided <paramref name="predicate"/>
/// </summary>
/// <typeparam name="T">The type for the <see cref="ILogger{TCategoryName}"/></typeparam>
/// <param name="mock">The <see cref="Mock"/> <see cref="ILogger{TCategoryName}"/></param>
/// <param name="level">The <see cref="LogLevel"/></param>
/// <param name="predicate">A predicate for the matching log message</param>
/// <param name="times">The <see cref="DevExpress.Pdf.Native.BouncyCastle.Utilities.Times"/> to verify</param>
public static void Verify<T>(this Mock<ILogger<T>> mock, LogLevel level, Func<object, bool> predicate, Times times)
{
mock.Verify(Verify<T>(level, predicate), times);
}
}
}
10 changes: 8 additions & 2 deletions COMET.Web.Common.Tests/COMET.Web.Common.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<ItemGroup>
<None Remove="Data\DefaultTextConfiguration.json" />
<None Remove="Resources\configuration\DefaultTextConfiguration.json" />
<None Remove="Resources\configuration\server_configuration.json" />
</ItemGroup>

<ItemGroup>
Expand All @@ -29,6 +30,11 @@
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="Resources\configuration\server_configuration.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>

<ItemGroup>
Expand All @@ -46,6 +52,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="RichardSzalay.MockHttp" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
Expand All @@ -54,8 +61,7 @@
</ItemGroup>

<ItemGroup>
<Folder Include="Server\Services\ConfigurationService\" />
<Folder Include="Server\Services\StringTableService\" />
<Folder Include="WebAssembly\Services\StringTableService\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ServiceCollectionExtensionsTestFixture.cs" company="RHEA System S.A.">
// Copyright (c) 2023 RHEA System S.A.
//
// Authors: Sam Gerené, Alex Vorobiev, Alexander van Delft, Jaime Bernar, Théate Antoine
//
// This file is part of COMET WEB Community Edition
// The COMET WEB Community Edition is the RHEA Web Application implementation of ECSS-E-TM-10-25
// Annex A and Annex C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace COMET.Web.Common.Tests.Extensions
{
using COMET.Web.Common.Extensions;

using Microsoft.Extensions.DependencyInjection;

using Moq;

using NUnit.Framework;

[TestFixture]
public class ServiceCollectionExtensionsTestFixture
{
[Test]
public void VerifyRegistration()
{
var serviceCollection = new Mock<IServiceCollection>();

Assert.Multiple(() =>
{
Assert.That(() => serviceCollection.Object.RegisterCommonLibrary(), Throws.Nothing);
Assert.That(() => serviceCollection.Object.RegisterCommonLibrary(false), Throws.Nothing);
Assert.That(() => serviceCollection.Object.RegisterCommonLibrary(false, options => { }), Throws.Nothing);
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ServiceProviderExtensionsTestFixture.cs" company="RHEA System S.A.">
// Copyright (c) 2023 RHEA System S.A.
//
// Authors: Sam Gerené, Alex Vorobiev, Alexander van Delft, Jaime Bernar, Théate Antoine
//
// This file is part of COMET WEB Community Edition
// The COMET WEB Community Edition is the RHEA Web Application implementation of ECSS-E-TM-10-25
// Annex A and Annex C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace COMET.Web.Common.Tests.Extensions
{
using COMET.Web.Common.Extensions;
using COMET.Web.Common.Services.ConfigurationService;
using COMET.Web.Common.Services.StringTableService;

using Moq;

using NUnit.Framework;

[TestFixture]
public class ServiceProviderExtensionsTestFixture
{
[Test]
public void VerifyServicesInitialization()
{
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(x => x.GetService(typeof(IStringTableService))).Returns(null);
serviceProvider.Setup(x => x.GetService(typeof(IConfigurationService))).Returns(null);

Assert.That( () => serviceProvider.Object.InitializeServices(), Throws.Exception);

serviceProvider.Setup(x => x.GetService(typeof(IStringTableService))).Returns(new Mock<IStringTableService>().Object);
serviceProvider.Setup(x => x.GetService(typeof(IConfigurationService))).Returns(new Mock<IConfigurationService>().Object);

Assert.That( () => serviceProvider.Object.InitializeServices(), Throws.Nothing);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"ServerAddress": ""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConfigurationServiceTestFixture.cs" company="RHEA System S.A.">
// Copyright (c) 2023 RHEA System S.A.
//
// Authors: Sam Gerené, Alex Vorobiev, Alexander van Delft, Jaime Bernar, Théate Antoine
//
// This file is part of COMET WEB Community Edition
// The COMET WEB Community Edition is the RHEA Web Application implementation of ECSS-E-TM-10-25
// Annex A and Annex C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace COMET.Web.Common.Tests.WebAssembly.Services.ConfigurationService
{
using System.Net;

using Castle.Core.Logging;

using COMET.Web.Common.Model;
using COMET.Web.Common.Utilities;
using COMET.Web.Common.WebAssembly.Services.ConfigurationService;
using COMET.Web.Common.Test.Helpers;

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;

using Moq;

using NUnit.Framework;

using RichardSzalay.MockHttp;

[TestFixture]
public class ConfigurationServiceTestFixture
{
private ConfigurationService configurationService;
private MockHttpMessageHandler mockHttpMessageHandler;
private Mock<IOptions<GlobalOptions>> options;
private GlobalOptions globalOptions;
private Mock<ILogger<ConfigurationService>> logger;

[SetUp]
public void Setup()
{
this.mockHttpMessageHandler = new MockHttpMessageHandler();
var httpClient = this.mockHttpMessageHandler.ToHttpClient();
httpClient.BaseAddress = new Uri("http://localhost/");
this.options = new Mock<IOptions<GlobalOptions>>();
this.globalOptions = new GlobalOptions();
this.options.Setup(x => x.Value).Returns(this.globalOptions);
this.logger = new Mock<ILogger<ConfigurationService>>();
this.configurationService = new ConfigurationService(this.options.Object, httpClient, this.logger.Object);
}

[Test]
public async Task VerifiyInitialization()
{
this.mockHttpMessageHandler.When(HttpMethod.Get, "/_content/CDP4.WEB.Common/server_configuration.json")
.Throw(new Exception());

await this.configurationService.InitializeService();
this.logger.Verify(LogLevel.Critical, o => o!.ToString()!.Contains("Exception has been raised"), Times.Once());

this.mockHttpMessageHandler.ResetBackendDefinitions();

var httpResponse = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.InternalServerError
};

this.mockHttpMessageHandler.When(HttpMethod.Get, "/_content/CDP4.WEB.Common/server_configuration.json")
.Respond(_ => httpResponse);

await this.configurationService.InitializeService();
this.logger.Verify(LogLevel.Error, o => o!.ToString()!.Contains("Error fetching server configuration. Status code:"), Times.Once());

httpResponse.StatusCode = HttpStatusCode.NotFound;

await this.configurationService.InitializeService();
this.logger.Verify(LogLevel.Error, o => o!.ToString()!.Contains("Server configuration file not found at "), Times.Once());

httpResponse.StatusCode = HttpStatusCode.OK;
httpResponse.Content = new StringContent("{\"ServerAddress\":\"http://localhost\"}");
await this.configurationService.InitializeService();
Assert.That(this.configurationService.ServerAddress, Is.EqualTo("http://localhost"));
}
}
}
Loading

0 comments on commit 95de256

Please sign in to comment.