Path: redb/redb.Tests.Integration/Tests/Base/CollectionGroupKeyTestsBase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Tests/Base/CollectionGroupKeyTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// GroupBy over a whole collection field groups by the same folded key that OrderBy and DistinctBy read: the elements /// in index order, a dictionary's values in key order. Equal lists are one group; the same elements in another order /// are another group. A dictionary entry, Codes["k"], is not an ordering or DistinctBy key: it is refused with a /// message that names what can be one. /// public abstract class CollectionGroupKeyTestsBase : IAsyncLifetime { private readonly IServiceProvider _services; private string _clearSql = ""; protected CollectionGroupKeyTestsBase(IServiceProvider services) => _services = services; // The two schemes are this class's own: every object in them is removed before and after each test. public async Task InitializeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var lists = await redb.SyncSchemeAsync(); var dictionaries = await redb.SyncSchemeAsync(); _clearSql = $"DELETE FROM _objects WHERE _id_scheme IN ({lists.Id}, {dictionaries.Id})"; await redb.Context.ExecuteAsync(_clearSql); } public async Task DisposeAsync() { await using var scope = _services.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().Context.ExecuteAsync(_clearSql); } private static CollectionGroupKeyProps List(int mark, params string[] tags) => new() { Label = "x", Mark = mark, Tags = tags.ToList() }; private static CollectionGroupKeyDictProps Dict(int mark, params (string Key, string Value)[] entries) => new() { Label = "x", Mark = mark, Codes = entries.ToDictionary(e => e.Key, e => e.Value) }; // Every group must hold objects of one mark only, and the marks must have the expected counts. private static void ShouldBeGroups(IEnumerable<(int Min, int Max, int Count)> rows, params (int Mark, int Count)[] expected) { var list = rows.ToList(); list.Should().OnlyContain(r => r.Min == r.Max, "one group holds the objects of one key only"); list.Select(r => (r.Min, r.Count)).Should().BeEquivalentTo(expected); } // Marks: 1 - t3,t1,t2 twice (the second one written by the bulk path); 2 - the same elements as t1,t2,t3; // 3 - t3,t9 twice; 4 - t9,t3. private static readonly (int Mark, string[] Tags)[] Lists = { (1, new[] { "t3", "t1", "t2" }), (1, new[] { "t3", "t1", "t2" }), (2, new[] { "t1", "t2", "t3" }), (3, new[] { "t3", "t9" }), (3, new[] { "t3", "t9" }), (4, new[] { "t9", "t3" }), }; private static readonly (int, int)[] ListGroups = { (1, 2), (2, 1), (3, 2), (4, 1) }; [Fact] public async Task GroupBy_OverAWholeList_EqualListsAreOneGroup_AnotherOrderIsAnother() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(new RedbObject { Name = "a", Props = List(Lists[0].Mark, Lists[0].Tags) }); await redb.AddNewObjectsAsync(Lists.Skip(1).Select((l, i) => new RedbObject { Name = $"n{i}", Props = List(l.Mark, l.Tags) }).ToArray()); var rows = await redb.Query().GroupBy(x => x.Tags) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(rows.Select(r => (r.Min, r.Max, r.N)), ListGroups); var filtered = await redb.Query().Where(x => x.Label == "x").GroupBy(x => x.Tags) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(filtered.Select(r => (r.Min, r.Max, r.N)), ListGroups); } [Fact] public async Task GroupBy_OverAWholeList_InATree_EqualListsAreOneGroup_AnotherOrderIsAnother() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var root = new TreeRedbObject { name = "root", Props = List(0, "r") }; root.id = await redb.SaveAsync(root); for (var i = 0; i < Lists.Length; i++) await redb.CreateChildAsync(new TreeRedbObject { name = $"n{i}", Props = List(Lists[i].Mark, Lists[i].Tags) }, root); var rows = await redb.TreeQuery(root.id).GroupBy(x => x.Tags) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(rows.Where(r => r.Min != 0).Select(r => (r.Min, r.Max, r.N)), ListGroups); } [Fact] public async Task GroupBy_OverAWholeDictionary_GroupsByItsValuesInKeyOrder() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Values in key order: mark 1 -> 2,1 (keys written in either order); mark 2 -> 1,2. await redb.SaveAsync(new RedbObject { Name = "h", Props = Dict(1, ("b", "1"), ("a", "2")) }); await redb.SaveAsync(new RedbObject { Name = "k", Props = Dict(1, ("a", "2"), ("b", "1")) }); await redb.SaveAsync(new RedbObject { Name = "i", Props = Dict(2, ("a", "1"), ("b", "2")) }); var rows = await redb.Query().GroupBy(x => x.Codes) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(rows.Select(r => (r.Min, r.Max, r.N)), (1, 2), (2, 1)); } [Fact] public async Task GroupBy_OverAWholeList_WithAWindowOverTheGroups_KeysTheSameWay() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.AddNewObjectsAsync(Lists.Select((l, i) => new RedbObject { Name = $"n{i}", Props = List(l.Mark, l.Tags) }).ToArray()); var root = new TreeRedbObject { name = "root", Props = List(0, "r") }; root.id = await redb.SaveAsync(root); for (var i = 0; i < Lists.Length; i++) await redb.CreateChildAsync(new TreeRedbObject { name = $"t{i}", Props = List(Lists[i].Mark, Lists[i].Tags) }, root); var flat = await redb.Query().Where(x => x.Mark > 0).GroupBy(x => x.Tags) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g), Row = Win.RowNumber() }); // Every list is in the scheme twice over: once flat, once under the root. ShouldBeGroups(flat.Select(r => (r.Min, r.Max, r.N)), ListGroups.Select(g => (g.Item1, g.Item2 * 2)).ToArray()); var tree = await redb.TreeQuery(root.id).GroupBy(x => x.Tags) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g), Row = Win.RowNumber() }); ShouldBeGroups(tree.Where(r => r.Min != 0).Select(r => (r.Min, r.Max, r.N)), ListGroups); } // A dictionary entry cannot be an ordering or DistinctBy key: the expression is refused before any SQL, and the // message says so in words. [Fact] public async Task OrderByAndDistinctBy_OverADictionaryEntry_AreRefused_SayingWhatCanBeAKey() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(new RedbObject { Name = "p", Props = Dict(0, ("a", "3"), ("b", "1")) }); var attempts = new Func[] { () => redb.Query().OrderBy(x => x.Codes!["a"]).ToListAsync(), () => redb.Query().OrderByDescending(x => x.Codes!["b"]).ToListAsync(), () => redb.Query().Where(x => x.Label == "x").OrderBy(x => x.Codes!["a"]).ToListAsync(), () => redb.Query().DistinctBy(x => x.Codes!["a"]).ToListAsync(), () => redb.Query().Where(x => x.Label == "x").DistinctBy(x => x.Codes!["a"]).ToListAsync(), }; foreach (var attempt in attempts) (await attempt.Should().ThrowAsync()) .Which.Message.Should().Contain("dictionary entry").And.Contain("cannot be").And.Contain("x.Address.City"); } }