From 8ec09aa871d3c177915e93f463cab8e01af6554a Mon Sep 17 00:00:00 2001 From: Mike Corsaro Date: Tue, 2 Jul 2024 10:35:04 -0700 Subject: [PATCH] Add leak test --- .../CollectionViewTests.Windows.cs | 72 ++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Windows.cs b/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Windows.cs index 329e43b92c07..805603b775f1 100644 --- a/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Windows.cs +++ b/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Windows.cs @@ -1,4 +1,6 @@ -using System.Collections.ObjectModel; +using System; +using System.Collections.ObjectModel; +using System.Collections.Specialized; using System.Linq; using System.Threading.Tasks; using Microsoft.Maui.Controls; @@ -202,6 +204,45 @@ await CreateHandlerAndAddToWindow(layout, async (handler) => Assert.True(data.Count == 30); }); } + + [Fact] + public async Task VerifyGroupCollectionDoesntLeak() + { + var groupHeaderTemplate = new Controls.DataTemplate(() => + { + var label = new Label(); + label.SetBinding(Label.TextProperty, new Binding("Name")); + return label; + }); + var footerTemplate = new Controls.DataTemplate(() => + { + var label = new Label(); + label.SetBinding(Label.TextProperty, new Binding("Count")); + return label; + }); + var itemTemplate = new Controls.DataTemplate(() => + { + var label = new Label(); + label.SetBinding(Label.TextProperty, new Binding("Name")); + return label; + }); + + WeakReference reference; + var itemSource = new ObservableCollection() { "Hello", "World" }; + { + var collection = new GroupedItemTemplateCollection(itemSource, + itemTemplate, groupHeaderTemplate, footerTemplate, null); + + reference = new WeakReference(collection); + collection.Dispose(); + } + + await Task.Yield(); + GC.Collect(); + GC.WaitForPendingFinalizers(); + + Assert.False(reference.IsAlive, "Subscriber should not be alive!"); + } [Fact] public async Task CollectionViewContentHeightChanged() @@ -260,5 +301,34 @@ Rect GetCollectionViewCellBounds(IView cellContent) return cellContent.ToPlatform().GetParentOfType().GetBoundingBox(); } + + class Subscriber + { + public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { } + } + + private interface IItem { } + + private class AnimalGroup : ObservableCollection, IItem + { + internal string Name { get; } + + internal AnimalGroup(string name, ObservableCollection animals) : base(animals) + { + Name = name; + } + } + + private class Animal : IItem + { + internal string Name { get; } + internal string Location { get; } + + internal Animal(string name, string location) + { + Name = name; + Location = location; + } + } } } \ No newline at end of file