[AZ-365] Refactor C12: decompose RouteService.CreateRouteAsync

Extract RouteValidator (aggregating validator), RoutePointGraphBuilder
(point interpolation + sequence numbering), GeofenceGridCalculator
(NW/SE region centers), and RouteResponseMapper (entity -> DTO; also
used by GetRouteAsync, eliminating duplicate DTO assembly).

CreateRouteAsync shrinks 184 -> 52 LOC of orchestration. RouteService.cs
shrinks 295 -> 138 LOC overall. Validation aggregates all failures into
a single ArgumentException (AC-2); single-violation messages preserved
verbatim so existing RouteServiceTests pass unchanged. 28 new unit
tests for the four helpers (112/112 unit tests, smoke green).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Oleksandr Bezdieniezhnykh
2026-05-11 02:08:21 +03:00
parent d327000fb6
commit f7ad7aa5ab
11 changed files with 936 additions and 206 deletions
@@ -0,0 +1,85 @@
using FluentAssertions;
using SatelliteProvider.Common.DTO;
using SatelliteProvider.Services.RouteManagement;
namespace SatelliteProvider.Tests;
public class GeofenceGridCalculatorTests
{
[Fact]
public void GenerateRegions_SmallPolygon_ReturnsAtLeastOneCenter()
{
var sut = new GeofenceGridCalculator();
var nw = new GeoPoint(48.280, 37.370);
var se = new GeoPoint(48.265, 37.395);
var regions = sut.GenerateRegions(nw, se, regionSizeMeters: 300);
regions.Should().NotBeEmpty();
}
[Fact]
public void GenerateRegions_AllCentersInsidePolygon()
{
var sut = new GeofenceGridCalculator();
var nw = new GeoPoint(48.280, 37.370);
var se = new GeoPoint(48.265, 37.395);
var regions = sut.GenerateRegions(nw, se, regionSizeMeters: 300);
regions.Should().OnlyContain(p =>
p.Lat <= nw.Lat && p.Lat >= se.Lat &&
p.Lon >= nw.Lon && p.Lon <= se.Lon);
}
[Fact]
public void GenerateRegions_LargerRegionSize_ProducesFewerCenters()
{
var sut = new GeofenceGridCalculator();
var nw = new GeoPoint(48.280, 37.370);
var se = new GeoPoint(48.265, 37.395);
var fineGrid = sut.GenerateRegions(nw, se, regionSizeMeters: 200);
var coarseGrid = sut.GenerateRegions(nw, se, regionSizeMeters: 1000);
coarseGrid.Count.Should().BeLessThan(fineGrid.Count);
}
[Fact]
public void GenerateRegions_VeryLargeRegionSize_AlwaysReturnsAtLeastOneCenter()
{
var sut = new GeofenceGridCalculator();
var nw = new GeoPoint(48.280, 37.370);
var se = new GeoPoint(48.265, 37.395);
var regions = sut.GenerateRegions(nw, se, regionSizeMeters: 100_000);
regions.Should().HaveCount(1);
}
[Fact]
public void GenerateRegions_NonPositiveRegionSize_Throws()
{
var sut = new GeofenceGridCalculator();
var nw = new GeoPoint(48.280, 37.370);
var se = new GeoPoint(48.265, 37.395);
Action act = () => sut.GenerateRegions(nw, se, regionSizeMeters: 0);
act.Should().Throw<ArgumentOutOfRangeException>();
}
[Fact]
public void GenerateRegions_CountMatchesCeilingOfDiagonalSpan()
{
var sut = new GeofenceGridCalculator();
var nw = new GeoPoint(48.280, 37.370);
var se = new GeoPoint(48.265, 37.395);
var regions = sut.GenerateRegions(nw, se, regionSizeMeters: 300);
var distinctLats = regions.Select(r => r.Lat).Distinct().Count();
var distinctLons = regions.Select(r => r.Lon).Distinct().Count();
regions.Count.Should().Be(distinctLats * distinctLons);
}
}
@@ -0,0 +1,127 @@
using FluentAssertions;
using SatelliteProvider.Common.DTO;
using SatelliteProvider.Common.Utils;
using SatelliteProvider.Services.RouteManagement;
using SatelliteProvider.Tests.Fixtures;
namespace SatelliteProvider.Tests;
public class RoutePointGraphBuilderTests
{
private static List<RoutePoint> ToRoutePoints(IEnumerable<(double Lat, double Lon)> points) =>
points.Select(p => new RoutePoint { Latitude = p.Lat, Longitude = p.Lon }).ToList();
[Fact]
public void Build_TwoUserPoints_FirstIsStart_LastIsEnd_BetweenAreIntermediate()
{
var sut = new RoutePointGraphBuilder();
var input = ToRoutePoints(TestCoordinates.Route.Route01Points);
var graph = sut.Build(input);
graph.Points.First().PointType.Should().Be("start");
graph.Points.Last().PointType.Should().Be("end");
graph.Points.Skip(1).Take(graph.Points.Count - 2)
.Should().OnlyContain(p => p.PointType == "intermediate");
}
[Fact]
public void Build_ConsecutivePointsRespectMaxSpacing()
{
var sut = new RoutePointGraphBuilder();
var input = ToRoutePoints(TestCoordinates.Route.Route01Points);
var graph = sut.Build(input);
for (int i = 1; i < graph.Points.Count; i++)
{
var prev = graph.Points[i - 1];
var cur = graph.Points[i];
var distance = GeoUtils.CalculateDistance(
new GeoPoint(prev.Latitude, prev.Longitude),
new GeoPoint(cur.Latitude, cur.Longitude));
distance.Should().BeLessThanOrEqualTo(RoutePointGraphBuilder.MaxPointSpacingMeters + 0.5,
$"point {i - 1}→{i} must be ≤{RoutePointGraphBuilder.MaxPointSpacingMeters}m");
}
}
[Fact]
public void Build_TenPointRoute_HasOneStartOneEndAndEightAction()
{
var sut = new RoutePointGraphBuilder();
var input = ToRoutePoints(TestCoordinates.Route.Route04Points);
var graph = sut.Build(input);
graph.Points.Count(p => p.PointType == "start").Should().Be(1);
graph.Points.Count(p => p.PointType == "end").Should().Be(1);
graph.Points.Count(p => p.PointType == "action").Should().Be(8);
graph.Points.Should().Contain(p => p.PointType == "intermediate");
}
[Fact]
public void Build_TotalDistanceEqualsSumOfHaversineSegments()
{
var sut = new RoutePointGraphBuilder();
var input = ToRoutePoints(TestCoordinates.Route.Route01Points);
var graph = sut.Build(input);
var summed = 0.0;
for (int i = 1; i < graph.Points.Count; i++)
{
var prev = graph.Points[i - 1];
var cur = graph.Points[i];
summed += GeoUtils.CalculateDistance(
new GeoPoint(prev.Latitude, prev.Longitude),
new GeoPoint(cur.Latitude, cur.Longitude));
}
graph.TotalDistanceMeters.Should().BeApproximately(summed, 1.0);
}
[Fact]
public void Build_SequenceNumbersAreContiguousAndStartAtZero()
{
var sut = new RoutePointGraphBuilder();
var input = ToRoutePoints(TestCoordinates.Route.Route04Points);
var graph = sut.Build(input);
graph.Points.Select(p => p.SequenceNumber)
.Should().Equal(Enumerable.Range(0, graph.Points.Count));
}
[Fact]
public void Build_FirstPointHasNullDistanceFromPrevious()
{
var sut = new RoutePointGraphBuilder();
var input = ToRoutePoints(TestCoordinates.Route.Route01Points);
var graph = sut.Build(input);
graph.Points.First().DistanceFromPrevious.Should().BeNull();
graph.Points.Skip(1).Should().OnlyContain(p => p.DistanceFromPrevious.HasValue);
}
[Fact]
public void Build_FewerThanTwoPoints_Throws()
{
var sut = new RoutePointGraphBuilder();
var input = new List<RoutePoint> { new() { Latitude = 47.46, Longitude = 37.64 } };
Action act = () => sut.Build(input);
act.Should().Throw<ArgumentException>().WithMessage("*at least 2 points*");
}
[Fact]
public void Build_NullInput_Throws()
{
var sut = new RoutePointGraphBuilder();
Action act = () => sut.Build(null!);
act.Should().Throw<ArgumentNullException>();
}
}
@@ -0,0 +1,102 @@
using FluentAssertions;
using SatelliteProvider.Common.DTO;
using SatelliteProvider.DataAccess.Models;
using SatelliteProvider.Services.RouteManagement;
namespace SatelliteProvider.Tests;
public class RouteResponseMapperTests
{
private static RouteEntity BuildEntity(Guid id) => new()
{
Id = id,
Name = "demo route",
Description = "desc",
RegionSizeMeters = 500,
ZoomLevel = 18,
TotalDistanceMeters = 1234.56,
TotalPoints = 4,
RequestMaps = true,
MapsReady = false,
CsvFilePath = "/ready/route.csv",
SummaryFilePath = "/ready/route.txt",
StitchedImagePath = "/ready/route.jpg",
TilesZipPath = "/ready/route.zip",
CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc),
UpdatedAt = new DateTime(2026, 1, 1, 0, 5, 0, DateTimeKind.Utc),
};
[Fact]
public void Map_FromDtoPoints_CopiesAllEntityFields()
{
var id = Guid.NewGuid();
var entity = BuildEntity(id);
var dtos = new List<RoutePointDto>
{
new() { Latitude = 1, Longitude = 2, PointType = "start", SequenceNumber = 0, SegmentIndex = 0 },
new() { Latitude = 3, Longitude = 4, PointType = "end", SequenceNumber = 1, SegmentIndex = 1, DistanceFromPrevious = 100.0 },
};
var sut = new RouteResponseMapper();
var response = sut.Map(entity, dtos);
response.Id.Should().Be(id);
response.Name.Should().Be(entity.Name);
response.Description.Should().Be(entity.Description);
response.RegionSizeMeters.Should().Be(entity.RegionSizeMeters);
response.ZoomLevel.Should().Be(entity.ZoomLevel);
response.TotalDistanceMeters.Should().Be(entity.TotalDistanceMeters);
response.TotalPoints.Should().Be(entity.TotalPoints);
response.RequestMaps.Should().Be(entity.RequestMaps);
response.MapsReady.Should().Be(entity.MapsReady);
response.CsvFilePath.Should().Be(entity.CsvFilePath);
response.SummaryFilePath.Should().Be(entity.SummaryFilePath);
response.StitchedImagePath.Should().Be(entity.StitchedImagePath);
response.TilesZipPath.Should().Be(entity.TilesZipPath);
response.CreatedAt.Should().Be(entity.CreatedAt);
response.UpdatedAt.Should().Be(entity.UpdatedAt);
response.Points.Should().BeEquivalentTo(dtos);
}
[Fact]
public void Map_FromEntityPoints_ProjectsToDtosWithSameFields()
{
var id = Guid.NewGuid();
var entity = BuildEntity(id);
var pointEntities = new List<RoutePointEntity>
{
new() { Id = Guid.NewGuid(), RouteId = id, SequenceNumber = 0, Latitude = 1, Longitude = 2, PointType = "start", SegmentIndex = 0 },
new() { Id = Guid.NewGuid(), RouteId = id, SequenceNumber = 1, Latitude = 3, Longitude = 4, PointType = "end", SegmentIndex = 1, DistanceFromPrevious = 100.0 },
};
var sut = new RouteResponseMapper();
var response = sut.Map(entity, pointEntities);
response.Points.Should().HaveCount(2);
response.Points[0].PointType.Should().Be("start");
response.Points[0].Latitude.Should().Be(1);
response.Points[1].PointType.Should().Be("end");
response.Points[1].DistanceFromPrevious.Should().Be(100.0);
}
[Fact]
public void Map_NullEntity_Throws()
{
var sut = new RouteResponseMapper();
Action act = () => sut.Map(null!, new List<RoutePointDto>());
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void Map_NullPoints_Throws()
{
var sut = new RouteResponseMapper();
var entity = BuildEntity(Guid.NewGuid());
Action act = () => sut.Map(entity, (IEnumerable<RoutePointDto>)null!);
act.Should().Throw<ArgumentNullException>();
}
}
@@ -0,0 +1,184 @@
using FluentAssertions;
using SatelliteProvider.Common.DTO;
using SatelliteProvider.Services.RouteManagement;
using SatelliteProvider.Tests.Fixtures;
namespace SatelliteProvider.Tests;
public class RouteValidatorTests
{
private static CreateRouteRequest BuildValidRequest()
{
return new CreateRouteRequest
{
Id = Guid.NewGuid(),
Name = "valid-route",
Description = "test",
RegionSizeMeters = 500,
ZoomLevel = 18,
Points = TestCoordinates.Route.Route01Points
.Select(p => new RoutePoint { Latitude = p.Lat, Longitude = p.Lon })
.ToList(),
};
}
[Fact]
public void Validate_ValidRequest_DoesNotThrow_AZ365_AC2()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
Action act = () => sut.Validate(request);
act.Should().NotThrow();
}
[Fact]
public void Validate_FewerThanTwoPoints_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Points = new List<RoutePoint> { new() { Latitude = 47.46, Longitude = 37.64 } };
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>().WithMessage("*at least 2 points*");
}
[Fact]
public void Validate_RegionSizeOutOfRange_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.RegionSizeMeters = 50;
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>()
.WithMessage("*Region size must be between 100 and 10000*");
}
[Fact]
public void Validate_BlankName_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Name = " ";
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>().WithMessage("*Route name is required*");
}
[Fact]
public void Validate_GeofencePolygonZeroZero_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Geofences = new Geofences
{
Polygons = new List<GeofencePolygon>
{
new() { NorthWest = new GeoPoint(0, 0), SouthEast = new GeoPoint(0, 0) },
},
};
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>()
.WithMessage("*coordinates cannot be (0,0)*");
}
[Fact]
public void Validate_GeofenceInvertedLatitudes_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Geofences = new Geofences
{
Polygons = new List<GeofencePolygon>
{
new()
{
NorthWest = new GeoPoint(48.250, 37.370),
SouthEast = new GeoPoint(48.280, 37.395),
},
},
};
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>().WithMessage("*northWest latitude*");
}
[Fact]
public void Validate_NullPolygonCorner_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Geofences = new Geofences
{
Polygons = new List<GeofencePolygon>
{
new() { NorthWest = null, SouthEast = new GeoPoint(48.260, 37.390) },
},
};
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>()
.WithMessage("*polygon coordinates are required*");
}
[Fact]
public void Validate_OutOfRangeLatitude_Throws()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Geofences = new Geofences
{
Polygons = new List<GeofencePolygon>
{
new()
{
NorthWest = new GeoPoint(95, 37.370),
SouthEast = new GeoPoint(48.265, 37.395),
},
},
};
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>()
.WithMessage("*coordinates must be valid*");
}
[Fact]
public void Validate_MultipleErrors_AggregatesIntoSingleException_AZ365_AC2()
{
var sut = new RouteValidator();
var request = BuildValidRequest();
request.Name = "";
request.RegionSizeMeters = 50;
request.Points = new List<RoutePoint>();
Action act = () => sut.Validate(request);
act.Should().Throw<ArgumentException>()
.Where(ex =>
ex.Message.Contains("at least 2 points")
&& ex.Message.Contains("Region size must be between 100 and 10000")
&& ex.Message.Contains("Route name is required"),
"AZ-365 AC-2: validator aggregates all failures into a single ArgumentException");
}
[Fact]
public void Validate_NullRequest_Throws()
{
var sut = new RouteValidator();
Action act = () => sut.Validate(null!);
act.Should().Throw<ArgumentNullException>();
}
}