Skip to content

Commit

Permalink
More and better tests
Browse files Browse the repository at this point in the history
  • Loading branch information
tiglate committed Oct 12, 2024
1 parent 6f01a3e commit e933cbc
Show file tree
Hide file tree
Showing 8 changed files with 213 additions and 0 deletions.
46 changes: 46 additions & 0 deletions Curupira.Tests/AppClient/Services/AutofacHelperTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Autofac;
using Curupira.AppClient.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Curupira.Tests.AppClient.Services
{
[TestClass]
public class AutofacHelperTests
{
private IContainer _container;
private AutofacHelper _autofacHelper;

[TestInitialize]
public void SetUp()
{
var builder = new ContainerBuilder();
// Register types here
builder.RegisterType<SomeImplementation>().As<ISomeInterface>().Named<ISomeInterface>("SomeName");
_container = builder.Build();

_autofacHelper = new AutofacHelper(_container);
}

[TestCleanup]
public void Cleanup()
{
_container.Dispose();
}

[TestMethod]
public void GetNamedImplementationsOfInterface_ShouldReturnCorrectImplementations()
{
// Act
var implementations = _autofacHelper.GetNamedImplementationsOfInterface<ISomeInterface>();

// Assert
Assert.AreEqual(1, implementations.Count);
Assert.AreEqual("SomeName", implementations[0].Name);
Assert.AreEqual(typeof(SomeImplementation), implementations[0].ImplementationType);
}

public interface ISomeInterface { }

public class SomeImplementation : ISomeInterface { }
}
}
3 changes: 3 additions & 0 deletions Curupira.Tests/Curupira.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@
<ItemGroup>
<Compile Include="AppClient\AppRunnerTests.cs" />
<Compile Include="AppClient\OptionsTests.cs" />
<Compile Include="AppClient\Services\AutofacHelperTests.cs" />
<Compile Include="AppClient\Services\PluginExecutorTests.cs" />
<Compile Include="Plugins\Backup\BackupPluginConfigParserTests.cs" />
<Compile Include="Plugins\Backup\BackupPluginTests.cs" />
Expand All @@ -178,9 +179,11 @@
<Compile Include="Plugins\FoldersCreator\FoldersCreatorPluginWithDelay.cs" />
<Compile Include="Plugins\Installer\InstallerPluginConfigParserTests.cs" />
<Compile Include="Plugins\Installer\InstallerPluginTests.cs" />
<Compile Include="Plugins\Installer\ProcessExecutorTests.cs" />
<Compile Include="Plugins\ServiceManager\ServiceManagerPluginConfigParserTests.cs" />
<Compile Include="Plugins\ServiceManager\ServiceManagerPluginTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WindowsService\ApiKeyValidationTests.cs" />
<Compile Include="WindowsService\AppRunnerTests.cs" />
<Compile Include="WindowsService\Controllers\BackupControllerTests.cs" />
<Compile Include="WindowsService\Controllers\EventLogsControllerTests.cs" />
Expand Down
6 changes: 6 additions & 0 deletions Curupira.Tests/Plugins/Installer/InstallerPluginTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ public void Setup()
_plugin.Init();
}

[TestCleanup]
public void Cleanup()
{
_plugin?.Dispose();
}

[TestMethod]
public async Task ExecuteAsync_ShouldExtractZipComponentSuccessfully_RealFileSystem()
{
Expand Down
48 changes: 48 additions & 0 deletions Curupira.Tests/Plugins/Installer/ProcessExecutorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Curupira.Plugins.Installer;

namespace Curupira.Tests.Plugins.Installer
{
[TestClass]
public class ProcessExecutorTests
{
private IProcessExecutor _processExecutor;

[TestInitialize]
public void SetUp()
{
_processExecutor = new ProcessExecutor();
}

[TestMethod]
public async Task ExecuteAsync_ShouldReturnZeroExitCode_WhenCommandSucceeds()
{
// Arrange
string fileName = "cmd.exe";
string arguments = "/c echo Hello, World!";
string workingDirectory = ".";

// Act
int exitCode = await _processExecutor.ExecuteAsync(fileName, arguments, workingDirectory);

// Assert
Assert.AreEqual(0, exitCode);
}

[TestMethod]
public async Task ExecuteAsync_ShouldReturnNonZeroExitCode_WhenCommandFails()
{
// Arrange
string fileName = "cmd.exe";
string arguments = "/c invalidcommand";
string workingDirectory = ".";

// Act
int exitCode = await _processExecutor.ExecuteAsync(fileName, arguments, workingDirectory);

// Assert
Assert.AreNotEqual(0, exitCode);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ public void Setup()
_serviceManagerPluginMock.Object.Init();
}

[TestCleanup]
public void Cleanup()
{
_serviceManagerPluginMock?.Object.Dispose();
}

[TestMethod]
public async Task Execute_ShouldLogError_WhenBundleIsMissing()
{
Expand Down
74 changes: 74 additions & 0 deletions Curupira.Tests/WindowsService/ApiKeyValidationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Curupira.WindowsService;
using Microsoft.Owin.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Curupira.Tests.WindowsService
{
[TestClass]
public class ApiKeyValidationTests
{
private TestServer _server;
private HttpClient _client;
private string _validApiKey;

[TestInitialize]
public void Setup()
{
_validApiKey = Guid.NewGuid().ToString();
Environment.SetEnvironmentVariable("API_KEY", _validApiKey);
_server = TestServer.Create<Startup>();
_client = _server.HttpClient;
}

[TestCleanup]
public void Cleanup()
{
_client.Dispose();
_server.Dispose();
}

[TestMethod]
public async Task GetSystemUsage_WithValidApiKey_ReturnsOk()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/system/usage");
request.Headers.Add("X-Api-Key", _validApiKey);

// Act
var response = await _client.SendAsync(request).ConfigureAwait(false);

// Assert
Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode);
}

[TestMethod]
public async Task GetSystemUsage_WithInvalidApiKey_ReturnsUnauthorized()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/system/usage");
request.Headers.Add("X-Api-Key", "invalidApiKey");

// Act
var response = await _client.SendAsync(request).ConfigureAwait(false);

// Assert
Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}

[TestMethod]
public async Task GetSystemUsage_WithNoApiKey_ReturnsUnauthorized()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/system/usage");

// Act
var response = await _client.SendAsync(request).ConfigureAwait(false);

// Assert
Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
21 changes: 21 additions & 0 deletions Curupira.Tests/WindowsService/StartupIntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Curupira.WindowsService;
using Curupira.WindowsService.Controllers;
using Microsoft.Owin.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
Expand Down Expand Up @@ -60,5 +61,25 @@ public void Startup_ThrowsException_WhenApiKeyNotDefined()
Assert.ThrowsException<InvalidOperationException>(() => server.HttpClient.GetAsync("/api/health").RunSynchronously());
}
}

[TestMethod]
public async Task Get_ThrowsUnhandledException_GlobalExceptionFilterHandlesIt()
{
// Arrange
HealthController.ShouldThrowException = true;
var requestUri = "/api/health"; // Reusing the existing health endpoint

// Act
var response = await _client.GetAsync(requestUri).ConfigureAwait(false);

// Assert
Assert.AreEqual(System.Net.HttpStatusCode.InternalServerError, response.StatusCode);

var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Assert.IsTrue(content.Contains("An error occurred. Please try again later."));

// Cleanup
HealthController.ShouldThrowException = false;
}
}
}
9 changes: 9 additions & 0 deletions Curupira.WindowsService/Controllers/HealthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ namespace Curupira.WindowsService.Controllers
{
public class HealthController : ApiController
{
public static bool ShouldThrowException { get; set; } = false;

[HttpGet]
[Route("api/health")]
public IHttpActionResult CheckHealth()
{
if (ShouldThrowException)
{
#pragma warning disable S112 // General or reserved exceptions should never be thrown
throw new Exception("This is an unhandled exception.");
#pragma warning restore S112 // General or reserved exceptions should never be thrown
}

return Ok(new { status = "Healthy", timestamp = DateTime.UtcNow });
}
}
Expand Down

0 comments on commit e933cbc

Please sign in to comment.