Files
MeterVault/tests/Core.Tests/Analysis/FormulaParserTests.cs
T
Florian Schmidt 8940ef25c3
ci / build-test (push) Successful in 2m31s
Analysis: one selected period, one set of numbers, on every page
The dashboards told several stories at once. Overview asked for full
calendar years, meter detail for a fixed 12-month window that was really
13, Trends for 24 months with an Apply button, and the energy pages for
60. Each page derived "today" from UTC, so the first hours of a local day
belonged to yesterday. A missing tariff, a month nobody measured and a
genuine zero all rendered as 0. And a virtual meter -- the one thing the
spreadsheet leans on hardest -- was excluded from analysis outright:
MeterPeriodService returned null for it and the page offered a flow
diagram instead.

docs/DASHBOARD_ANALYSIS_CHANGE_BRIEF.md is the work order. Every choice it
left open is settled in docs/ANALYSIS_IMPLEMENTATION_NOTE.md as D-01..D-58
plus amendments A-01..A-30; code, tests and release notes cite those ids.

The analysis layer

Core/Analysis holds the pure rules: period presets resolved once in the
instance zone into a local date range and a half-open UTC range, bucket
plans, calendar-unit comparisons, coverage runs with a resolution class,
normalized quantities and units, the totals policy, the virtual formula
parser/validator/evaluator, and the cost calculator. "Now" comes from
TimeProvider; services never read the clock.

Normalization now writes, in the same transaction as consumption and by
diff, per-meter rollups by local day and month plus coverage runs and a
rollup state (AnalysisDataWriter). AnalysisReader answers a request from
those tables -- month rollups for month and year buckets, day rollups
otherwise, at most two partial edge days from consumption -- and
CostReader prices the result month by month. Pages, /api/v1 and the CSV
export read nothing else. The unused continuous aggregates are dropped.

The reader's statement count per request is constant whether it covers one
meter or a thousand. On a synthetic 1,000-meter, ten-year instance the
brief's target request (100 meters, ten years, monthly) takes 374 ms
against a two-second target, and the Overview went from 48,244 SQL
statements per load to 205.

Missing is not zero

Every bucket carries a status -- available, partial, missing, unresolved,
invalid, pending -- derived from coverage, never from the amount, with
provenance and a reason code beside it. A true zero is a number and a bar
on the baseline; an unknown bucket is a gap that says why; a month whose
data only exists monthly says so instead of inventing daily detail; a
scope with no tariff says "not priced" instead of 0. Rows whose interval
closes after now are reported separately rather than counted.

Virtual meters are analysis subjects

A virtual meter stores a canonical definition -- expression over m<id>
references, result kind, unit and cost rule -- validated on save and on
read for syntax, unknown or self references, loops and unit/kind rules.
It is evaluated on read from its sources' rollups over their joint
coverage: a missing source makes the bucket missing, an observed zero is
a valid input, a non-finite result is invalid with its dependency path,
and the page lists each source's contribution. Topology links are
topology only and never rewrite a saved calculation; expression-less
meters from older installs are converted once at startup. The editor has
Sum, Difference and Advanced modes with a live preview.

Totals and the bill

Per energy type the totals policy separates use, grid import, export,
generation and runtime, marks breakdown meters as breakdowns and virtual
meters as views, and never adds across units. The bill follows it: grid
import where there is one, separately priced subsections at their own
price, feed-in only on export meters, standing charges once per scope per
local day, manual costs once on their start day, categories as
non-overlapping covers whose composition reconciles to the bill. The
seeded demo's yearly totals now match the spreadsheet.

Pages and navigation

The period lives in the URL and every page reads the same contract, so a
link, a reload and the browser's Back button keep it. Shared components
carry it: page header with breadcrumbs, period toolbar, theme-aware chart
with an accessible table beside it, metric cards, comparison and
availability states, attention items that each link to the one action
that fixes them. Meter detail leads with an Analysis tab and resolves its
tabs by key; the energy page has Overview, History, Flow and Meters; the
old cost-only Trends page is a general Analysis page over portfolio, type,
category, meter or a meter comparison. Records tabs are paged server-side
instead of showing the latest 200. Everything is English and German,
light and dark, down to 360px.

Some figures change on purpose; docs/RELEASE_NOTES.md lists each one and
what the first start after the update does (it rebuilds all analysis data
before the web server listens). docs/SDD.md and CLAUDE.md describe the
system as it now is.

Tests: 1,733 Core and 746 integration, all green, plus an opt-in
performance suite with a synthetic 1,000-meter generator.
2026-09-20 10:29:13 +02:00

164 lines
6.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using MeterVault.Core.Analysis.Virtual;
namespace MeterVault.Core.Tests.Analysis;
/// <summary>
/// The formula grammar is user input evaluated on every read, so the parser is the safety boundary (D-26): it
/// accepts only numbers, <c>m&lt;id&gt;</c>, unary minus, <c>+ - * /</c> and parentheses, reports every rejection
/// with a position instead of throwing, and cannot be driven into a stack overflow. Ported from the old
/// ExpressionEvaluatorTests; the one deliberate change is that an unknown identifier is now an error, not 0.
/// </summary>
public sealed class FormulaParserTests
{
private static double Evaluate(string text) =>
Formula.Parse(text).Evaluate(id => id switch { 1 => 411, 2 => 416, _ => throw new KeyNotFoundException($"m{id}") });
[Theory]
[InlineData("1 + 2 * 3", 7)]
[InlineData("(1 + 2) * 3", 9)]
[InlineData("-5", -5)]
[InlineData("--5", 5)]
[InlineData("+5", 5)]
[InlineData("2 * -3", -6)]
[InlineData("-(1 + 2) * 3", -9)]
[InlineData("10 / 4", 2.5)]
[InlineData("2 - 3 - 4", -5)] // left-associative
[InlineData("8 / 4 / 2", 1)] // left-associative
[InlineData("0.5 * 4", 2)]
[InlineData(".5 + 5.", 5.5)]
[InlineData("m1 - m2", -5)] // Netz Einsparung Okt 2022: Haus 411 Netz 416
[InlineData("m1 + m2", 827)]
[InlineData("m1+m2", 827)]
[InlineData(" ( m1 ) - m2 ", -5)]
public void Evaluates_arithmetic_over_numbers_and_meter_references(string text, double expected)
{
Assert.Equal(expected, Evaluate(text), 9);
}
[Fact]
public void Numbers_are_invariant_decimals_whatever_the_current_culture()
{
var previous = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
Assert.Equal(0.25, Formula.Parse("0.25").Evaluate(_ => 0), 12);
Assert.Equal(FormulaErrorKind.UnexpectedCharacter, FormulaParser.Parse("0,25").Error!.Kind);
}
finally
{
Thread.CurrentThread.CurrentCulture = previous;
}
}
[Theory]
[InlineData("1 +", FormulaErrorKind.UnexpectedEnd, 3, null)]
[InlineData("(1 + 2", FormulaErrorKind.MissingClosingParenthesis, 0, "(")]
[InlineData("m1 + (m2 * (3 - 1)", FormulaErrorKind.MissingClosingParenthesis, 5, "(")]
[InlineData("1 2", FormulaErrorKind.UnexpectedToken, 2, "2")]
[InlineData("m1 m2", FormulaErrorKind.UnexpectedToken, 3, "m2")]
[InlineData(")", FormulaErrorKind.UnexpectedToken, 0, ")")]
[InlineData("(m1))", FormulaErrorKind.UnexpectedToken, 4, ")")]
[InlineData("m1 * * m2", FormulaErrorKind.UnexpectedToken, 5, "*")]
[InlineData("1 % 2", FormulaErrorKind.UnexpectedCharacter, 2, "%")]
[InlineData("1.2.3", FormulaErrorKind.InvalidNumber, 0, "1.2.3")]
[InlineData(".", FormulaErrorKind.InvalidNumber, 0, ".")]
[InlineData("1e3", FormulaErrorKind.UnexpectedToken, 1, "e3")]
[InlineData("2m1", FormulaErrorKind.UnexpectedToken, 1, "m1")]
[InlineData("m99999999999", FormulaErrorKind.MeterIdOutOfRange, 0, "m99999999999")]
public void Rejects_malformed_formulas_with_the_position_and_token(string text, FormulaErrorKind kind, int position, string? token)
{
var result = FormulaParser.Parse(text);
Assert.False(result.Success);
Assert.Equal(new FormulaError(kind, position, token), result.Error);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Empty_text_is_an_error_not_an_exception(string? text)
{
Assert.Equal(FormulaErrorKind.Empty, FormulaParser.Parse(text).Error!.Kind);
}
[Theory]
[InlineData("unknown + 1", "unknown", 0)] // the old evaluator read this as 1
[InlineData("m1 - n2", "n2", 5)]
[InlineData("M1 + m2", "M1", 0)]
[InlineData("m1a", "m1a", 0)]
[InlineData("m_1", "m_1", 0)]
[InlineData("m", "m", 0)]
[InlineData("sum(m1)", "sum", 0)]
[InlineData("m1 + Hausverbrauch", "Hausverbrauch", 5)]
public void Only_m_digits_identifiers_are_meter_references_and_anything_else_is_named(string text, string identifier, int position)
{
Assert.Equal(new FormulaError(FormulaErrorKind.UnknownIdentifier, position, identifier), FormulaParser.Parse(text).Error);
}
[Fact]
public void Nesting_64_parentheses_deep_is_accepted_and_65_is_rejected_at_the_65th()
{
static string Nested(int depth) => new string('(', depth) + "m1" + new string(')', depth);
Assert.True(FormulaParser.Parse(Nested(FormulaParser.MaxDepth)).Success);
var tooDeep = FormulaParser.Parse(Nested(FormulaParser.MaxDepth + 1));
Assert.Equal(new FormulaError(FormulaErrorKind.TooDeep, 64, "("), tooDeep.Error);
}
[Fact]
public void Two_thousand_characters_are_accepted_and_2001_rejected()
{
var chain = "m1" + string.Concat(Enumerable.Repeat(" + m1", 399)); // 1,997 characters
var exactly = chain + " ";
Assert.Equal(FormulaParser.MaxLength, exactly.Length);
var accepted = FormulaParser.Parse(exactly);
Assert.True(accepted.Success);
Assert.Equal(400 * 411, accepted.Formula.Evaluate(_ => 411), 6);
Assert.Equal(FormulaErrorKind.TooLong, FormulaParser.Parse(exactly + " ").Error!.Kind);
}
[Fact]
public void A_hundred_thousand_open_parentheses_are_rejected_without_overflowing_the_stack()
{
Assert.Equal(FormulaErrorKind.TooLong, FormulaParser.Parse(new string('(', 100_000)).Error!.Kind);
Assert.Equal(FormulaErrorKind.TooDeep, FormulaParser.Parse(new string('(', 1_999)).Error!.Kind);
}
[Fact]
public void Long_operator_chains_and_sign_runs_parse_and_evaluate_without_recursion()
{
var signs = FormulaParser.Parse(new string('-', 1_999) + "1");
Assert.True(signs.Success);
Assert.Equal(-1, signs.Formula.Evaluate(_ => 0));
var product = FormulaParser.Parse("1" + string.Concat(Enumerable.Repeat(" * 1", 499)));
Assert.True(product.Success);
Assert.Equal(1, product.Formula.Evaluate(_ => 0));
Assert.Equal(product.Formula, Formula.Parse(product.Formula.ToString()));
}
[Fact]
public void Scanning_finds_meter_tokens_even_in_text_that_does_not_parse()
{
Assert.Equal([2, 5, 12], FormulaParser.ScanMeterIds("m12 + (m5 * m2 +"));
Assert.Empty(FormulaParser.ScanMeterIds("1.5 + x2"));
Assert.Empty(FormulaParser.ScanMeterIds(null));
}
[Fact]
public void Rewriting_ids_in_text_keeps_the_users_spacing_and_even_a_syntax_error()
{
var map = new Dictionary<int, int> { [1] = 41, [2] = 42 };
Assert.Equal("m41 -( m42 )", FormulaParser.RewriteMeterIds("m1 -( m2 )", id => map[id]));
Assert.Equal("m41 + ", FormulaParser.RewriteMeterIds("m1 + ", id => map[id]));
Assert.Equal("0.1m99 + xm1", FormulaParser.RewriteMeterIds("0.1m2 + xm1", _ => 99)); // "xm1" names no meter
}
}