Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add simple tests for RobotModelController #2009

Merged
merged 6 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions backend/api.test/Controllers/RobotModelControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Api.Controllers.Models;
using Api.Database.Models;
using Api.Services;
using Api.Test.Database;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.PostgreSql;
using Xunit;

namespace Api.Test.Controllers;

public class RobotModelControllerTests : IAsyncLifetime
{
public required DatabaseUtilities DatabaseUtilities;
public required PostgreSqlContainer Container;
public required HttpClient Client;
public required JsonSerializerOptions SerializerOptions;

public required IRobotModelService RobotModelService;

public async Task InitializeAsync()
{
(Container, var connectionString, var connection) =
await TestSetupHelpers.ConfigurePostgreSqlDatabase();
var factory = TestSetupHelpers.ConfigureWebApplicationFactory(
postgreSqlConnectionString: connectionString
);
var serviceProvider = TestSetupHelpers.ConfigureServiceProvider(factory);

Client = TestSetupHelpers.ConfigureHttpClient(factory);
SerializerOptions = TestSetupHelpers.ConfigureJsonSerializerOptions();

DatabaseUtilities = new DatabaseUtilities(
TestSetupHelpers.ConfigurePostgreSqlContext(connectionString)
);

RobotModelService = serviceProvider.GetRequiredService<IRobotModelService>();
}

public Task DisposeAsync() => Task.CompletedTask;

[Fact]
public async Task CheckThatListAllRobotModelsReturnsSuccess()
{
var response = await Client.GetAsync("/robot-models");
var robotModels = await response.Content.ReadFromJsonAsync<List<RobotModel>>(
SerializerOptions
);

// Seven models are added by default to the database
// This number must be changed if new robots are introduced
Assert.Equal(7, robotModels!.Count);
andchiind marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
public async Task CheckThatLookupRobotModelByRobotTypeReturnsSuccess()
{
const RobotType RobotType = RobotType.Robot;

var response = await Client.GetAsync("/robot-models/type/" + RobotType);
var robotModel = await response.Content.ReadFromJsonAsync<RobotModel>(SerializerOptions);

Assert.Equal(RobotType, robotModel!.Type);
}

[Fact]
public async Task CheckThatLookupRobotModelByIdReturnsSuccess()
{
var robotModel = await RobotModelService.ReadByRobotType(RobotType.Robot);

var response = await Client.GetAsync("/robot-models/" + robotModel!.Id);
var robotModelFromResponse = await response.Content.ReadFromJsonAsync<RobotModel>(
SerializerOptions
);

Assert.Equal(robotModel.Id, robotModelFromResponse!.Id);
Assert.Equal(robotModel.Type, robotModelFromResponse!.Type);
}

[Fact]
public async Task CheckThatCreateRobotModelReturnsSuccess()
{
// Arrange
var modelBefore = await RobotModelService.ReadByRobotType(RobotType.Robot);
_ = await RobotModelService.Delete(modelBefore!.Id);

var query = new CreateRobotModelQuery { RobotType = RobotType.Robot };
var content = new StringContent(JsonSerializer.Serialize(query), null, "application/json");

// Act
var response = await Client.PostAsync("/robot-models", content);

// Assert
var modelAfter = await RobotModelService.ReadByRobotType(RobotType.Robot);

Assert.True(response.IsSuccessStatusCode);
Assert.NotEqual(modelBefore!.Id, modelAfter!.Id);
}

[Theory]
[InlineData(10, 90, 10, 50, true)]
[InlineData(-1, -10, 10, 50, false)]
[InlineData(110, 1000, 10, 900, false)]
[InlineData(0, 9000, 0, 100, true)]
public async Task CheckThatUpdatingRobotBasedOnIdIsSuccessful(
int batteryWarningThreshold,
int upperPressureWarningThreshold,
int lowerPressureWarningThreshold,
int batteryMissionStartThreshold,
bool valuesShouldHaveBeenChanged
)
{
// Arrange
var modelBefore = await RobotModelService.ReadByRobotType(RobotType.Robot);

var query = new UpdateRobotModelQuery
{
BatteryWarningThreshold = batteryWarningThreshold,
UpperPressureWarningThreshold = upperPressureWarningThreshold,
LowerPressureWarningThreshold = lowerPressureWarningThreshold,
BatteryMissionStartThreshold = batteryMissionStartThreshold,
};
var content = new StringContent(JsonSerializer.Serialize(query), null, "application/json");

// Act
_ = await Client.PutAsync("/robot-models/" + modelBefore!.Id, content);

// Assert
var modelAfter = await RobotModelService.ReadByRobotType(RobotType.Robot);
if (valuesShouldHaveBeenChanged)
{
Assert.Equal(modelAfter!.BatteryWarningThreshold, batteryWarningThreshold);
Assert.Equal(modelAfter!.UpperPressureWarningThreshold, upperPressureWarningThreshold);
Assert.Equal(modelAfter!.LowerPressureWarningThreshold, lowerPressureWarningThreshold);
Assert.Equal(modelAfter!.BatteryMissionStartThreshold, batteryMissionStartThreshold);
}
else
{
Assert.Equal(modelAfter!.BatteryWarningThreshold, modelBefore!.BatteryWarningThreshold);
Assert.Equal(
modelAfter!.UpperPressureWarningThreshold,
modelBefore!.UpperPressureWarningThreshold
);
Assert.Equal(
modelAfter!.LowerPressureWarningThreshold,
modelBefore!.LowerPressureWarningThreshold
);
Assert.Equal(
modelAfter!.BatteryMissionStartThreshold,
modelBefore!.BatteryMissionStartThreshold
);
}
}
}
8 changes: 7 additions & 1 deletion backend/api/Controllers/Models/UpdateRobotModelQuery.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
namespace Api.Controllers.Models
using System.ComponentModel.DataAnnotations;

namespace Api.Controllers.Models
{
public struct UpdateRobotModelQuery
{
/// <summary>
/// Lower battery warning threshold in percentage
/// </summary>
[Range(0, 100, ErrorMessage = "Value must be between 0 and 100")]
public float? BatteryWarningThreshold { get; set; }

/// <summary>
/// Upper pressure warning threshold in Bar
/// </summary>
[Range(0, float.MaxValue, ErrorMessage = "Value must be a non-negative number")]
public float? UpperPressureWarningThreshold { get; set; }

/// <summary>
/// Lower pressure warning threshold in Bar
/// </summary>
[Range(0, float.MaxValue, ErrorMessage = "Value must be a non-negative number")]
public float? LowerPressureWarningThreshold { get; set; }

/// <summary>
/// Lower battery threshold at which to allow missions to be scheduled, in percentage
/// </summary>
[Range(0, 100, ErrorMessage = "Value must be between 0 and 100")]
public float? BatteryMissionStartThreshold { get; set; }
}
}
19 changes: 0 additions & 19 deletions backend/api/Controllers/RobotModelController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,25 +188,6 @@ [FromBody] UpdateRobotModelQuery robotModelQuery
return await UpdateModel(robotModel, robotModelQuery);
}

/// <summary>
/// Deletes the robot model with the specified id from the database.
/// </summary>
[HttpDelete]
[Authorize(Roles = Role.Admin)]
[Route("{id}")]
[ProducesResponseType(typeof(RobotModel), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<RobotModel>> DeleteRobotModel([FromRoute] string id)
{
var robotModel = await robotModelService.Delete(id);
if (robotModel is null)
return NotFound($"Area with id {id} not found");
return Ok(robotModel);
}

private async Task<ActionResult<Robot>> UpdateModel(
RobotModel robotModel,
UpdateRobotModelQuery robotModelQuery
Expand Down