Files
satellite-provider/SatelliteProvider.Tests/TileServiceTests.cs
T
Oleksandr Bezdieniezhnykh dea0b8b4c0 [AZ-286] [AZ-287] [AZ-288] Service-level unit tests (mocked deps)
Batch 2: 27 new tests, 31/31 total passing.

AZ-286 TileService (9 tests):
- BT-01 download stores tiles via repository
- BT-02 cache reuse passes existing tiles to downloader
- BT-02b stale-version cached tiles are NOT treated as still-valid
- BT-N02 GoogleMapsDownloaderV2 rejects zoom levels not in {15..19}
- GetTileAsync known/unknown id

AZ-287 RegionService (6 tests):
- AC-1 RequestRegionAsync inserts entity and queues request
- AC-2/AC-3 ProcessRegionAsync transitions queued→processing→completed
  and writes CSV + summary files
- AC-4 stitch path is set when stitchTiles=true
- ProcessRegionAsync handles RateLimitException by writing failed
  summary with the error message preserved
- GetRegionStatusAsync mapping
- Missing region id is logged and short-circuits without DB writes

AZ-288 RouteService (12 tests):
- AC-1 every consecutive pair is ≤200m apart on 2-point route
- AC-2 first/last user points keep their roles; middles are interpolated
- BT-10 10pt route → 1 start, 1 end, 8 action, plus intermediates
- BT-12 20pt route → 1 start, 1 end, 18 action
- AC-3 TotalDistanceMeters == Σ Haversine(point[i-1], point[i])
- BT-N03 < 2 points throws ArgumentException
- regionSize <100 / >10000 throws ArgumentException
- BT-N04 (0,0) corner throws
- BT-N05 inverted NW.lat <= SE.lat throws
- BT-11 valid geofence creates region requests + links them with
  isGeofence=true
- BT-07 GetRouteAsync returns route + points
- GetRouteAsync unknown id returns null

Code review: PASS_WITH_WARNINGS — 3 Low Spec-Gap findings:
  1. BT-N01 (invalid coords) deferred to AZ-289 integration tests
     (TileService doesn't validate coordinates — API-layer concern)
  2. Point-type label drift between blackbox-tests.md ("original")
     and code ("start"/"action"/"end")
  3. Region status drift: spec "pending" vs code "queued" — initial
     state on insert

Verification: docker dotnet test — 31/31 pass in 0.83s.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-10 05:02:00 +03:00

260 lines
9.5 KiB
C#

using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using SatelliteProvider.Common.Configs;
using SatelliteProvider.Common.DTO;
using SatelliteProvider.Common.Interfaces;
using SatelliteProvider.DataAccess.Models;
using SatelliteProvider.DataAccess.Repositories;
using SatelliteProvider.Services;
using SatelliteProvider.Tests.Fixtures;
namespace SatelliteProvider.Tests;
public class TileServiceTests
{
private static TileService BuildService(
Mock<ISatelliteDownloader> downloader,
Mock<ITileRepository> tileRepo)
{
return new TileService(downloader.Object, tileRepo.Object, NullLogger<TileService>.Instance);
}
private static DownloadedTileInfoV2 MakeDownloaded(int x, int y, int zoom, double lat, double lon, string filePath = "tiles/18/0/0/tile.jpg")
{
return new DownloadedTileInfoV2(x, y, zoom, lat, lon, filePath, 100.0);
}
[Fact]
public async Task DownloadAndStoreTilesAsync_NoExistingTiles_StoresAllDownloadedTiles_BT01()
{
// Arrange
var downloader = new Mock<ISatelliteDownloader>();
var tileRepo = new Mock<ITileRepository>();
tileRepo
.Setup(r => r.GetTilesByRegionAsync(
TestCoordinates.TileLat, TestCoordinates.TileLon, 200, TestCoordinates.DefaultZoom))
.ReturnsAsync(Array.Empty<TileEntity>());
var downloaded = new List<DownloadedTileInfoV2>
{
MakeDownloaded(123, 456, TestCoordinates.DefaultZoom, TestCoordinates.TileLat, TestCoordinates.TileLon),
};
downloader
.Setup(d => d.GetTilesWithMetadataAsync(
It.IsAny<GeoPoint>(),
It.IsAny<double>(),
TestCoordinates.DefaultZoom,
It.Is<IEnumerable<ExistingTileInfo>>(e => !e.Any()),
It.IsAny<CancellationToken>()))
.ReturnsAsync(downloaded);
var service = BuildService(downloader, tileRepo);
// Act
var result = await service.DownloadAndStoreTilesAsync(
TestCoordinates.TileLat, TestCoordinates.TileLon, 200, TestCoordinates.DefaultZoom);
// Assert
result.Should().HaveCount(1);
result[0].TileZoom.Should().Be(TestCoordinates.DefaultZoom);
result[0].TileSizePixels.Should().Be(256);
result[0].ImageType.Should().Be("jpg");
result[0].FilePath.Should().NotBeNullOrEmpty();
tileRepo.Verify(r => r.InsertAsync(It.IsAny<TileEntity>()), Times.Once);
}
[Fact]
public async Task DownloadAndStoreTilesAsync_HasCachedTiles_PassesThemToDownloader_BT02()
{
// Arrange
var downloader = new Mock<ISatelliteDownloader>();
var tileRepo = new Mock<ITileRepository>();
var existing = new List<TileEntity>
{
new()
{
Id = Guid.NewGuid(),
TileZoom = TestCoordinates.DefaultZoom,
Latitude = TestCoordinates.TileLat,
Longitude = TestCoordinates.TileLon,
Version = DateTime.UtcNow.Year,
FilePath = "tiles/18/0/0/cached.jpg",
TileSizePixels = 256,
ImageType = "jpg",
},
};
tileRepo
.Setup(r => r.GetTilesByRegionAsync(
TestCoordinates.TileLat, TestCoordinates.TileLon, 200, TestCoordinates.DefaultZoom))
.ReturnsAsync(existing);
IEnumerable<ExistingTileInfo>? capturedExisting = null;
downloader
.Setup(d => d.GetTilesWithMetadataAsync(
It.IsAny<GeoPoint>(),
It.IsAny<double>(),
TestCoordinates.DefaultZoom,
It.IsAny<IEnumerable<ExistingTileInfo>>(),
It.IsAny<CancellationToken>()))
.Callback<GeoPoint, double, int, IEnumerable<ExistingTileInfo>, CancellationToken>(
(_, _, _, e, _) => capturedExisting = e.ToList())
.ReturnsAsync(new List<DownloadedTileInfoV2>());
var service = BuildService(downloader, tileRepo);
// Act
var result = await service.DownloadAndStoreTilesAsync(
TestCoordinates.TileLat, TestCoordinates.TileLon, 200, TestCoordinates.DefaultZoom);
// Assert
result.Should().HaveCount(1);
result[0].Id.Should().Be(existing[0].Id);
capturedExisting.Should().NotBeNull();
capturedExisting!.Should().ContainSingle()
.Which.Should().BeEquivalentTo(new ExistingTileInfo(
TestCoordinates.TileLat, TestCoordinates.TileLon, TestCoordinates.DefaultZoom));
tileRepo.Verify(r => r.InsertAsync(It.IsAny<TileEntity>()), Times.Never,
"cached tile should not be re-inserted");
}
[Fact]
public async Task DownloadAndStoreTilesAsync_IgnoresStaleVersionCachedTiles_BT02b()
{
// Arrange
var downloader = new Mock<ISatelliteDownloader>();
var tileRepo = new Mock<ITileRepository>();
var stale = new List<TileEntity>
{
new()
{
Id = Guid.NewGuid(),
TileZoom = TestCoordinates.DefaultZoom,
Latitude = TestCoordinates.TileLat,
Longitude = TestCoordinates.TileLon,
Version = DateTime.UtcNow.Year - 1,
FilePath = "tiles/18/0/0/old.jpg",
},
};
tileRepo
.Setup(r => r.GetTilesByRegionAsync(
It.IsAny<double>(), It.IsAny<double>(), It.IsAny<double>(), It.IsAny<int>()))
.ReturnsAsync(stale);
IEnumerable<ExistingTileInfo>? capturedExisting = null;
downloader
.Setup(d => d.GetTilesWithMetadataAsync(
It.IsAny<GeoPoint>(),
It.IsAny<double>(),
It.IsAny<int>(),
It.IsAny<IEnumerable<ExistingTileInfo>>(),
It.IsAny<CancellationToken>()))
.Callback<GeoPoint, double, int, IEnumerable<ExistingTileInfo>, CancellationToken>(
(_, _, _, e, _) => capturedExisting = e.ToList())
.ReturnsAsync(new List<DownloadedTileInfoV2>
{
MakeDownloaded(123, 456, TestCoordinates.DefaultZoom, TestCoordinates.TileLat, TestCoordinates.TileLon),
});
var service = BuildService(downloader, tileRepo);
// Act
var result = await service.DownloadAndStoreTilesAsync(
TestCoordinates.TileLat, TestCoordinates.TileLon, 200, TestCoordinates.DefaultZoom);
// Assert
capturedExisting.Should().BeEmpty(
"stale-version tiles must not be passed to the downloader as 'already have it'");
result.Should().HaveCount(1, "only the freshly-downloaded tile is in the result");
tileRepo.Verify(r => r.InsertAsync(It.IsAny<TileEntity>()), Times.Once);
}
[Fact]
public async Task GetTileAsync_KnownId_ReturnsMappedMetadata()
{
// Arrange
var id = Guid.NewGuid();
var entity = new TileEntity
{
Id = id,
TileZoom = 18,
Latitude = TestCoordinates.TileLat,
Longitude = TestCoordinates.TileLon,
TileSizePixels = 256,
ImageType = "jpg",
FilePath = "tiles/18/0/0/x.jpg",
Version = 2026,
};
var tileRepo = new Mock<ITileRepository>();
tileRepo.Setup(r => r.GetByIdAsync(id)).ReturnsAsync(entity);
var service = BuildService(new Mock<ISatelliteDownloader>(), tileRepo);
// Act
var result = await service.GetTileAsync(id);
// Assert
result.Should().NotBeNull();
result!.Id.Should().Be(id);
result.FilePath.Should().Be("tiles/18/0/0/x.jpg");
}
[Fact]
public async Task GetTileAsync_UnknownId_ReturnsNull()
{
// Arrange
var tileRepo = new Mock<ITileRepository>();
tileRepo.Setup(r => r.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync((TileEntity?)null);
var service = BuildService(new Mock<ISatelliteDownloader>(), tileRepo);
// Act
var result = await service.GetTileAsync(Guid.NewGuid());
// Assert
result.Should().BeNull();
}
}
public class GoogleMapsDownloaderZoomValidationTests
{
private static GoogleMapsDownloaderV2 BuildDownloader()
{
var mapConfig = Options.Create(new MapConfig { Service = "googlemaps", ApiKey = "test-key" });
var storageConfig = Options.Create(new StorageConfig
{
TilesDirectory = Path.Combine(Path.GetTempPath(), "sp-tests-tiles"),
ReadyDirectory = Path.Combine(Path.GetTempPath(), "sp-tests-ready"),
});
var processingConfig = Options.Create(new ProcessingConfig());
var httpClientFactory = new Mock<IHttpClientFactory>().Object;
return new GoogleMapsDownloaderV2(
NullLogger<GoogleMapsDownloaderV2>.Instance,
mapConfig,
storageConfig,
processingConfig,
httpClientFactory);
}
[Theory]
[InlineData(25)]
[InlineData(14)]
[InlineData(0)]
[InlineData(-1)]
public async Task DownloadSingleTileAsync_RejectsZoomLevelOutsideAllowedRange_BTN02(int invalidZoom)
{
// Arrange
var downloader = BuildDownloader();
// Act
Func<Task> act = () => downloader.DownloadSingleTileAsync(TestCoordinates.TileLat, TestCoordinates.TileLon, invalidZoom);
// Assert
await act.Should().ThrowAsync<ArgumentException>()
.Where(ex => ex.ParamName == "zoomLevel" && ex.Message.Contains("not allowed"));
}
}