Correctness/data: - Fix demo cost double-count: reference importer no longer imports the Kosten Strom/Wasser columns for categories that are metered (only Heizung), so Wasser rollup is 70€ not 140€. - Spurious-decrease guard: only a reset/swap in the window (prevReading, thisReading] explains a decrease — an old historical reset no longer permanently disables the guard. - Gate swap auto-detection on MappingProfile.DetectCumulativeSwaps (flag was ignored). - Prorate basePrice by bucket length (day/month/year); guard virtual expressions against NaN/Inf. Concurrency/infra: - Blazor: register a DbContextFactory; CostService/DashboardService and the read pages now use short-lived per-operation contexts (no shared circuit DbContext); guard Trends re-entrancy. - /events: wrap event insert + consumption recompute in one transaction (atomic); 404 (not 500) on unknown meter. - MQTT worker: subscribe to newly-added topics on each tick; move client cleanup into finally. - Migrations: CREATE MATERIALIZED VIEW IF NOT EXISTS + if_not_exists on CAgg/compression/ hypertable calls (re-run-safe after a mid-migration crash). - HA worker: prune stale poll-schedule entries; export: null dangling ImportBatchIds on restore. API/security: - API fail-closed by default: with no keys and AllowAnonymousApi off, /api/v1 returns 401 (protects /export and /import). New MeterVault:AllowAnonymousApi opt-in. - Cap /readings batch at 5000; report ignored (unknown-meter) count; enums as strings in JSON. +4 regression tests (guard window, API closed, /events 404, no demo double-count). 98 tests green; Docker deploy re-verified healthy with the API fail-closed. Claude-Session: https://claude.ai/code/session_01WujdMtMJPbxDpDnMeK22rr
This commit is contained in:
@@ -52,6 +52,37 @@ public sealed class ApiTests(TimescaleFixture fx)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record EventPush(int MeterId, DateTimeOffset Time, string Type,
|
||||
double? Amount, double? PrevValue, double? NewValue, string? Unit, string? Notes);
|
||||
|
||||
[Fact]
|
||||
public async Task Api_is_closed_when_no_keys_are_configured()
|
||||
{
|
||||
using var factory = new MeterVaultAppFactory(fx.ConnectionString, configureApiKey: false);
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/readings",
|
||||
new[] { new ReadingPush(1, DateTimeOffset.UtcNow, 1) });
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Events_for_a_missing_meter_return_404_not_500()
|
||||
{
|
||||
using var factory = new MeterVaultAppFactory(fx.ConnectionString);
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/events")
|
||||
{
|
||||
Content = JsonContent.Create(new EventPush(999999, DateTimeOffset.UtcNow, "Delivery", 100, null, null, "L", null)),
|
||||
};
|
||||
request.Headers.Add("X-Api-Key", MeterVaultAppFactory.ApiKey);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Meters_endpoint_and_swagger_are_available()
|
||||
{
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed class CostReconciliationTests(TimescaleFixture fx)
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var costs = await new CostService(db).GetMeterCostsAsync(meterId, From, To);
|
||||
var costs = await new CostService(fx).GetMeterCostsAsync(meterId, From, To);
|
||||
var computed = costs.ToDictionary(c => c.Period, c => c.Cost);
|
||||
var oracle = OracleByMonth(ReadRows(Water), dateColumn: 0, valueColumn: 4, firstDataRow: 1); // Kosten
|
||||
|
||||
@@ -64,7 +64,7 @@ public sealed class CostReconciliationTests(TimescaleFixture fx)
|
||||
db.CostCategoryMembers.Add(new CostCategoryMember { CategoryId = wasserCategory.Id, MeterId = meterId });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var rollup = await new CostService(db).GetCategoryCostsAsync(wasserCategory.Id, From, To);
|
||||
var rollup = await new CostService(fx).GetCategoryCostsAsync(wasserCategory.Id, From, To);
|
||||
var dec2022 = rollup.Single(r => r.Period == new DateOnly(2022, 12, 1));
|
||||
|
||||
Assert.Equal(70d, dec2022.Cost, 2); // Dez 2022: 14 m³ × 5,00 €
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using MeterVault.Infrastructure.Costing;
|
||||
using MeterVault.Infrastructure.Import;
|
||||
using MeterVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -31,6 +32,15 @@ public sealed class DashboardRenderTests(TimescaleFixture fx)
|
||||
Assert.Contains(await db.Meters.Select(m => m.Name).ToListAsync(), n => n == "Zähler Haus");
|
||||
Assert.True(await db.Meters.CountAsync() >= 8);
|
||||
Assert.True(await db.Consumption.AnyAsync());
|
||||
|
||||
// Regression (audit): Wasser is metered (water tariff), the Kosten Wasser column is
|
||||
// NOT imported, so the category is not double-counted — Dez 2022 = 14 m³ × 5 € = 70 €.
|
||||
var wasser = await db.CostCategories.FirstAsync(c => c.Name == "Wasser");
|
||||
var rollup = await new CostService(fx).GetCategoryCostsAsync(
|
||||
wasser.Id,
|
||||
new DateTimeOffset(2022, 12, 1, 0, 0, 0, TimeSpan.Zero),
|
||||
new DateTimeOffset(2023, 1, 1, 0, 0, 0, TimeSpan.Zero));
|
||||
Assert.Equal(70d, rollup.Sum(r => r.Cost), 1);
|
||||
}
|
||||
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
@@ -49,6 +49,28 @@ public sealed class IngestionServiceTests(TimescaleFixture fx)
|
||||
await CleanupAsync(db, meterId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Old_reset_does_not_permanently_disable_the_decrease_guard()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var (meterId, sourceId) = await SetupAsync(db, MeterMode.CumulativeCounter);
|
||||
var service = new IngestionService(db);
|
||||
|
||||
// A reset early on explains an early decrease...
|
||||
await service.IngestAsync(sourceId, T0, 100);
|
||||
db.MeterEvents.Add(new MeterEvent { MeterId = meterId, Time = T0.AddMinutes(10), EventType = MeterEventType.CounterReset, NewValue = 0 });
|
||||
await db.SaveChangesAsync();
|
||||
Assert.Equal(IngestionOutcome.Written, await service.IngestAsync(sourceId, T0.AddMinutes(20), 30));
|
||||
await service.IngestAsync(sourceId, T0.AddHours(1), 200);
|
||||
|
||||
// ...but a later spurious decrease with NO event in its window must still be rejected.
|
||||
var outcome = await service.IngestAsync(sourceId, T0.AddHours(2), 150);
|
||||
|
||||
Assert.Equal(IngestionOutcome.RejectedDecrease, outcome);
|
||||
|
||||
await CleanupAsync(db, meterId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Allows_decrease_when_a_swap_event_explains_it()
|
||||
{
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace MeterVault.Integration.Tests;
|
||||
/// Boots the real ASP.NET Core app in-memory against the shared Timescale container.
|
||||
/// Migrations are already applied by <see cref="TimescaleFixture"/>, so startup migration is off.
|
||||
/// </summary>
|
||||
public sealed class MeterVaultAppFactory(string connectionString) : WebApplicationFactory<Program>
|
||||
public sealed class MeterVaultAppFactory(string connectionString, bool configureApiKey = true) : WebApplicationFactory<Program>
|
||||
{
|
||||
public const string ApiKey = "test-api-key";
|
||||
|
||||
@@ -17,6 +17,9 @@ public sealed class MeterVaultAppFactory(string connectionString) : WebApplicati
|
||||
builder.UseSetting("ConnectionStrings:Default", connectionString);
|
||||
builder.UseSetting("MeterVault:RunMigrationsAtStartup", "false");
|
||||
builder.UseSetting("MeterVault:EnableLiveIngestion", "false");
|
||||
builder.UseSetting("MeterVault:ApiKeys:0", ApiKey);
|
||||
if (configureApiKey)
|
||||
{
|
||||
builder.UseSetting("MeterVault:ApiKeys:0", ApiKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ namespace MeterVault.Integration.Tests;
|
||||
/// The image tag is pinned: the compression DDL (add_compression_policy) was renamed toward
|
||||
/// add_columnstore_policy in newer Timescale, so a floating tag would risk breaking migrations.
|
||||
/// </summary>
|
||||
public sealed class TimescaleFixture : IAsyncLifetime
|
||||
public sealed class TimescaleFixture : IAsyncLifetime, IDbContextFactory<MeterVaultDbContext>
|
||||
{
|
||||
private readonly PostgreSqlContainer _db = new PostgreSqlBuilder("timescale/timescaledb:2.17.2-pg16")
|
||||
.WithDatabase("metervault")
|
||||
@@ -30,6 +30,9 @@ public sealed class TimescaleFixture : IAsyncLifetime
|
||||
return new MeterVaultDbContext(options);
|
||||
}
|
||||
|
||||
/// <summary>Lets tests construct services that take an <see cref="IDbContextFactory{TContext}"/>.</summary>
|
||||
public MeterVaultDbContext CreateDbContext() => CreateContext();
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await _db.StartAsync();
|
||||
|
||||
Reference in New Issue
Block a user