Browse Source

Validate source collection, and add tests.

pull/6485/head
Steven Kirk 5 years ago
parent
commit
5ae9a2d60c
  1. 21
      src/Avalonia.Controls/ItemsSourceView.cs
  2. 63
      tests/Avalonia.Controls.UnitTests/ItemsSourceViewTests.cs

21
src/Avalonia.Controls/ItemsSourceView.cs

@ -42,19 +42,16 @@ namespace Avalonia.Controls
public ItemsSourceView(IEnumerable source)
{
source = source ?? throw new ArgumentNullException(nameof(source));
if (source is IList list)
{
_inner = list;
}
else if (source is IEnumerable<object> objectEnumerable)
_inner = source switch
{
_inner = new List<object>(objectEnumerable);
}
else
{
_inner = new List<object>(source.Cast<object>());
}
ItemsSourceView => throw new ArgumentException("Cannot wrap an existing ItemsSourceView.", nameof(source)),
IList list => list,
INotifyCollectionChanged => throw new ArgumentException(
"Collection implements INotifyCollectionChanged by not IList.",
nameof(source)),
IEnumerable<object> iObj => new List<object>(iObj),
_ => new List<object>(source.Cast<object>())
};
}
/// <summary>

63
tests/Avalonia.Controls.UnitTests/ItemsSourceViewTests.cs

@ -0,0 +1,63 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using Avalonia.Collections;
using Avalonia.Diagnostics;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ItemsSourceViewTests
{
[Fact]
public void Only_Subscribes_To_Source_CollectionChanged_When_CollectionChanged_Subscribed()
{
var source = new AvaloniaList<string>();
var target = new ItemsSourceView<string>(source);
var debug = (INotifyCollectionChangedDebug)source;
Assert.Null(debug.GetCollectionChangedSubscribers());
void Handler(object sender, NotifyCollectionChangedEventArgs e) { }
target.CollectionChanged += Handler;
Assert.NotNull(debug.GetCollectionChangedSubscribers());
Assert.Equal(1, debug.GetCollectionChangedSubscribers().Length);
target.CollectionChanged -= Handler;
Assert.Null(debug.GetCollectionChangedSubscribers());
}
[Fact]
public void Cannot_Wrap_An_ItemsSourceView_In_Another()
{
var source = new ItemsSourceView<string>(new string[0]);
Assert.Throws<ArgumentException>(() => new ItemsSourceView<string>(source));
}
[Fact]
public void Cannot_Create_ItemsSourceView_With_Collection_That_Implements_INCC_But_Not_List()
{
var source = new InvalidCollection();
Assert.Throws<ArgumentException>(() => new ItemsSourceView<string>(source));
}
private class InvalidCollection : INotifyCollectionChanged, IEnumerable<string>
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public IEnumerator<string> GetEnumerator()
{
yield break;
}
IEnumerator IEnumerable.GetEnumerator()
{
yield break;
}
}
}
}
Loading…
Cancel
Save