Files
MeterVault/tests/Integration.Tests/MeterPeriodServiceTests.cs
T
schmidt.florian 8fe5f4411b
ci / build-test (push) Successful in 1m16s
Fix defects found auditing the ingestion, import and connector changes
An audit of this session's commits found several real problems, three of which
lose or expose data. Ordered by severity.

Live recompute was not atomic. RecomputeMeterAsync clears a meter's series with
ExecuteDelete, which commits by itself when no transaction is ambient, and only
then adds the rebuilt rows. Between the two the meter had *no* consumption:
a dashboard read reported zero, and a crash or cancelled request made the loss
permanent, for data the SDD treats as the long-term source of truth (§5.5).
Import and the events API already wrapped their recomputes; live ingestion,
which I added this session, did not. Now shares one transaction, joining an
ambient one rather than nesting.

The MQTT backfill migration counted brokers without regard to is_enabled. One
live broker plus a disabled leftover counted two, declined to backfill, and left
those sources unbound — which under endpoint-scoped routing means silently and
permanently dead. The "two or more is ambiguous" reasoning did not hold there:
the worker only ever connected to enabled endpoints. Corrected by a follow-up
migration rather than an edit, since the original may already have run; it
touches only rows still NULL, so hand-made bindings are safe.

A mapping edited after a dry run committed the *old* staged rows under the
*new* mapping. Readings went to the previous meter while the batch recorded the
current mapping — wrong data, provenance contradicting it, no exception. The
earlier fix re-validated but did not detect staleness. Commit now compares the
mapping against the one the preview was staged under and refuses.

"Test connection" sent a stored token to whatever Base URL was in the dialog.
Encrypting secrets at rest means the UI can decrypt what the operator can no
longer read, so this turned the button into an exfiltration primitive: point it
at any host, the token arrives as a Bearer header. A stored token now only goes
to the origin it was saved for; testing elsewhere requires typing it again.

A source that cannot ingest looked identical to a healthy one. Endpoint-scoped
routing made unbound and mis-bound sources silently dead, while the Sources tab
showed no connector at all and the delete dialog still promised sources would be
"unlinked". Added a Connector column that names the fault, stopped offering
disabled connectors (both workers filter on IsEnabled), and made the delete
warning say ingestion stops.

Virtual meters rendered four zero tiles: they evaluate on read and only
materialize when a cost category references them (§14.1), so summing
consumption is a confident lie about a working meter. They now report nothing
and the page explains why.

Re-importing an overlapping file failed at the database with EF's "An error
occurred while saving the entity changes", naming neither meter nor date — the
diagnosis problem a3af483 set out to fix, via the path its guard could not see.
Checked up front now, bounded by each meter's staged range.

The LXC updater left the service stopped on any failure. set -e plus an
explicit stop means Restart=always does not apply, so an OOM-killed publish or
a brief Gitea outage took MeterVault down until someone noticed. An EXIT trap
restarts the previous build and says so.

Claude-Session: https://claude.ai/code/session_01V6joyergfvVLFEizH1hJLd
2026-07-18 19:52:48 +02:00

159 lines
5.9 KiB
C#

using MeterVault.Core.Domain;
using MeterVault.Infrastructure.Costing;
using MeterVault.Infrastructure.Dashboard;
using MeterVault.Infrastructure.Options;
using MeterVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace MeterVault.Integration.Tests;
/// <summary>
/// The meter-detail headline numbers: month/year totals bucketed in the instance timezone, and the
/// generation-vs-consumption split that decides which of the two a meter reports.
/// </summary>
[Collection("Timescale")]
public sealed class MeterPeriodServiceTests(TimescaleFixture fx)
{
[Fact]
public async Task Buckets_by_local_month_and_compares_with_the_previous_one()
{
await using var db = fx.CreateContext();
var meterId = await SetupAsync(db, MeterMode.CumulativeCounter);
var today = DateOnly.FromDateTime(DateTime.UtcNow);
var thisMonth = new DateOnly(today.Year, today.Month, 1);
var lastMonth = thisMonth.AddMonths(-1);
await AddConsumptionAsync(db, meterId, ConsumptionKind.Consumption, thisMonth.AddDays(1), 30);
await AddConsumptionAsync(db, meterId, ConsumptionKind.Consumption, lastMonth.AddDays(3), 100);
var view = await NewService().GetAsync(meterId);
Assert.NotNull(view);
Assert.Equal("Consumption", view!.Label);
Assert.Equal(30d, view.MonthToDate, 3);
Assert.Equal(100d, view.LastMonth, 3);
Assert.Equal(130d, view.YearToDate, 3);
// Projection scales the partial month up, so it must be at least what has already happened.
Assert.True(view.MonthProjected >= view.MonthToDate);
await CleanupAsync(db, meterId);
}
[Fact]
public async Task A_generation_counter_reports_generation_not_consumption()
{
// Regression: a PV meter showed "0 kWh consumption", which is true and useless.
await using var db = fx.CreateContext();
var meterId = await SetupAsync(db, MeterMode.GenerationCounter);
var today = DateOnly.FromDateTime(DateTime.UtcNow);
await AddConsumptionAsync(
db, meterId, ConsumptionKind.Generation, new DateOnly(today.Year, today.Month, 1).AddDays(1), 42);
var view = await NewService().GetAsync(meterId);
Assert.NotNull(view);
Assert.Equal("Generation", view!.Label);
Assert.Equal(42d, view.MonthToDate, 3);
await CleanupAsync(db, meterId);
}
[Fact]
public async Task A_meter_with_no_consumption_yields_an_empty_history_rather_than_a_flat_line()
{
await using var db = fx.CreateContext();
var meterId = await SetupAsync(db, MeterMode.CumulativeCounter);
var view = await NewService().GetAsync(meterId);
Assert.NotNull(view);
Assert.False(view!.HasHistory);
Assert.Empty(view.Last12Months);
Assert.Null(view.MonthChange); // no previous month to divide by
await CleanupAsync(db, meterId);
}
[Fact]
public async Task A_virtual_meter_reports_nothing_rather_than_a_confident_zero()
{
// Virtual meters evaluate on read and only materialize when a cost category references them
// (SDD §14.1). Summing `consumption` would render four zero tiles for a working meter.
await using var db = fx.CreateContext();
var meterId = await SetupAsync(db, MeterMode.Virtual);
Assert.Null(await NewService().GetAsync(meterId));
await CleanupAsync(db, meterId);
}
[Fact]
public async Task A_negative_previous_period_reports_no_basis_rather_than_an_inverted_percentage()
{
// Net export: -100 -> -150 is half again as much exported, but dividing by a negative
// baseline would render it "+50%", which reads as more consumption.
await using var db = fx.CreateContext();
var meterId = await SetupAsync(db, MeterMode.CumulativeCounter);
var today = DateOnly.FromDateTime(DateTime.UtcNow);
var thisMonth = new DateOnly(today.Year, today.Month, 1);
await AddConsumptionAsync(db, meterId, ConsumptionKind.Consumption, thisMonth.AddDays(1), -150);
await AddConsumptionAsync(db, meterId, ConsumptionKind.Consumption, thisMonth.AddMonths(-1).AddDays(3), -100);
var view = await NewService().GetAsync(meterId);
Assert.NotNull(view);
Assert.Null(view!.MonthChange);
await CleanupAsync(db, meterId);
}
private MeterPeriodService NewService()
{
var options = Microsoft.Extensions.Options.Options.Create(
new MeterVaultOptions { TimeZone = "Europe/Berlin", Currency = "EUR" });
return new MeterPeriodService(fx, new CostService(fx), options);
}
private static async Task<int> SetupAsync(MeterVaultDbContext db, MeterMode mode)
{
await DatabaseSeeder.SeedAsync(db);
var type = await db.EnergyTypes.FirstAsync(t => t.Key == "electricity");
var meter = new Meter
{
Name = $"period-{Guid.NewGuid():N}",
EnergyTypeId = type.Id,
Mode = mode,
Unit = "kWh",
};
db.Meters.Add(meter);
await db.SaveChangesAsync();
return meter.Id;
}
private static async Task AddConsumptionAsync(
MeterVaultDbContext db, int meterId, ConsumptionKind kind, DateOnly day, double amount)
{
db.Consumption.Add(new Consumption
{
MeterId = meterId,
// Midday local, so the row cannot drift into an adjacent month through the UTC offset.
Time = new DateTimeOffset(day.Year, day.Month, day.Day, 12, 0, 0, TimeSpan.Zero),
Kind = kind,
Amount = amount,
Quality = ReadingQuality.Measured,
});
await db.SaveChangesAsync();
}
private static async Task CleanupAsync(MeterVaultDbContext db, int meterId)
{
await db.Consumption.Where(c => c.MeterId == meterId).ExecuteDeleteAsync();
await db.Meters.Where(m => m.Id == meterId).ExecuteDeleteAsync();
}
}