using System.Data.Common;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Data;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Unit;
///
/// The generated query layer, checked against rendered SQL rather than against a
/// database. A wrong query should be red against a string — the same reason the
/// neighbouring deployment keeps its renderers public.
///
/// These tests also assert that the generator contributed to the build at all:
/// the metadata registration is a module initializer, and a generator that stops
/// running would otherwise show up as a failure inside the edge.
///
public sealed class GeneratedQueryTests
{
private const string SelectAll =
"SELECT \"Key\", \"Value\", \"UpdatedAt\" FROM \"policy_settings\"";
/// A data source that is never asked for a connection: rendering a
/// query must not need one, and this says so in the type system.
private sealed class NeverOpenedDataSource : DbDataSource
{
public override string ConnectionString { get; } = string.Empty;
protected override DbConnection CreateDbConnection() =>
throw new NotSupportedException("rendering a query must not open a connection");
}
private static OrmContext Sqlite => new(new NeverOpenedDataSource(), SqliteDialect.Instance);
private static OrmContext Postgres => new(new NeverOpenedDataSource(), PostgresDialect.Instance);
[Fact]
public void The_generator_registered_the_table_it_was_given()
{
Assert.True(OrmMeta.TryGet(typeof(PolicySetting), out var meta),
"no generated metadata is registered for PolicySetting — the analyzer is not running");
Assert.Equal("policy_settings", meta.Table);
Assert.Equal(new[] { "Key", "Value", "UpdatedAt" }, meta.Columns.ToArray());
Assert.Equal("UpdatedAt", PolicySettingOrm.ColumnOf("UpdatedAt"));
Assert.Equal(string.Empty, PolicySettingOrm.ColumnOf("NotAColumn"));
}
[Fact]
public void A_whole_table_read_renders_the_columns_the_schema_has() =>
Assert.Equal(SelectAll, PolicySettingOrm.Query(Sqlite).RenderSelect());
[Fact]
public void A_captured_local_becomes_a_parameter_and_never_text_in_the_statement()
{
const string key = "streakThreshold";
var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Key == key);
Assert.Equal(SelectAll + " WHERE (\"Key\" = @p0)", query.RenderSelect());
Assert.Single(query.Arguments);
Assert.Equal("streakThreshold", query.Arguments[0]);
}
[Fact]
public void A_null_test_stays_an_is_null_and_never_becomes_an_equality_with_null()
{
// "col = NULL" is unknown rather than false: a filter written that way
// silently stops matching the rows it was written for.
var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Key == "mode" && p.Value != null);
Assert.Equal(
SelectAll + " WHERE ((\"Key\" = @p0) AND (\"Value\" IS NOT NULL))",
query.RenderSelect());
}
[Fact]
public void A_captured_null_is_a_null_test_too()
{
string? value = null;
var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Value == value);
Assert.Equal(SelectAll + " WHERE (\"Value\" IS NULL)", query.RenderSelect());
Assert.Empty(query.Arguments);
}
[Fact]
public void Ordering_and_paging_render_in_the_dialects_own_grammar()
{
Assert.Equal(
SelectAll + " ORDER BY \"Key\" ASC",
PolicySettingOrm.Query(Sqlite).OrderBy(p => p.Key).RenderSelect());
Assert.Equal(
SelectAll + " ORDER BY \"UpdatedAt\" DESC LIMIT 10 OFFSET 20",
PolicySettingOrm.Query(Sqlite).OrderByDescending(p => p.UpdatedAt).Skip(20).Take(10).RenderSelect());
}
[Fact]
public void Count_renders_against_the_same_where_clause() =>
Assert.Equal(
"SELECT COUNT(*) FROM \"policy_settings\" WHERE (\"Key\" = @p0)",
PolicySettingOrm.Query(Sqlite).Where(p => p.Key == "mode").RenderCount());
[Fact]
public void Both_providers_get_the_same_text_for_this_query()
{
// One SQL text for both providers is not a coincidence to lean on: it
// holds because both quote with double quotes and both bind named
// parameters. Where they differ is the dialect's job — and paging already
// differs, which is why the two tails are asserted apart.
Assert.Equal(
SelectAll + " LIMIT 2147483647 OFFSET 5",
PolicySettingOrm.Query(Postgres).Skip(5).RenderSelect());
Assert.Equal(
SelectAll + " LIMIT -1 OFFSET 5",
PolicySettingOrm.Query(Sqlite).Skip(5).RenderSelect());
}
[Fact]
public void A_shape_this_layer_has_not_built_refuses_by_name()
{
var ex = Assert.Throws(
() => PolicySettingOrm.Query(Sqlite).Where(p => p.Key.Length == 4));
Assert.Contains("Length", ex.What, StringComparison.Ordinal);
}
[Fact]
public void A_member_that_is_not_a_column_refuses_rather_than_guessing()
{
var ex = Assert.Throws(
() => PolicySettingOrm.Query(Sqlite).OrderBy(p => "not a column"));
Assert.Contains("not a column", ex.Message, StringComparison.Ordinal);
}
}
///
/// The integer a DateTimeOffset becomes on sqlite. The model puts EF's
/// DateTimeOffsetToBinaryConverter on every timestamp column, so that
/// encoding is the storage contract of every row this application has written;
/// the generated layer reproduces it, and this test is what makes "reproduces"
/// mean something rather than "looks plausible". It also records the resolution:
/// the encoding divides the ticks by 1000, so a round trip through the column
/// drops the sub-microsecond digits. That is EF's behaviour, not a loss added
/// here — and it is asserted, so it cannot become a surprise later.
///
public sealed class SqliteTimestampEncodingTests
{
private static readonly DateTimeOffset[] Instants =
[
new DateTimeOffset(2026, 10, 7, 12, 34, 56, TimeSpan.FromHours(3)),
new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(123456),
new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5)),
new DateTimeOffset(2024, 2, 29, 23, 59, 59, TimeSpan.FromMinutes(330)),
DateTimeOffset.MinValue,
];
[Fact]
public void The_encoding_this_layer_writes_is_the_one_ef_writes()
{
var efEncodes = new DateTimeOffsetToBinaryConverter().ConvertToProviderExpression.Compile();
foreach (var instant in Instants)
Assert.Equal(efEncodes(instant), Convert.ToInt64(SqliteDialect.Instance.WriteDateTimeOffset(instant)));
}
[Fact]
public void What_ef_writes_this_layer_reads_back()
{
var converter = new DateTimeOffsetToBinaryConverter();
var efEncodes = converter.ConvertToProviderExpression.Compile();
foreach (var instant in Instants)
{
var stored = efEncodes(instant);
var efRead = Assert.IsAssignableFrom(converter.ConvertFromProvider(stored));
Assert.Equal(efRead, ReadFromStored(stored));
}
}
[Fact]
public void The_column_has_microsecond_resolution_and_says_so()
{
var instant = new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(1234567);
var read = ReadFromStored(Convert.ToInt64(SqliteDialect.Instance.WriteDateTimeOffset(instant)));
Assert.Equal(new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(1234000), read);
Assert.NotEqual(instant.Ticks, read.Ticks);
}
/// Reads the integer the way the sqlite dialect does, without a
/// reader. The dialect's own reader path is exercised end to end by the
/// integration suite against a real database.
private static DateTimeOffset ReadFromStored(long stored)
{
var offsetMinutes = (int)(stored & 2047);
if (offsetMinutes >= 1024) offsetMinutes -= 2048;
return new DateTimeOffset((stored >> 11) * 1000, TimeSpan.FromMinutes(offsetMinutes));
}
}