|
| 1 | +using System; |
| 2 | +using System.Collections.ObjectModel; |
| 3 | +using System.Collections.Specialized; |
| 4 | +using NETworkManager.Utilities; |
| 5 | +using Xunit; |
| 6 | + |
| 7 | +namespace NETworkManager.Tests.Utilities; |
| 8 | + |
| 9 | +public class ListHelperTests |
| 10 | +{ |
| 11 | + [Fact] |
| 12 | + public void AddsNewEntryAtTheTop() |
| 13 | + { |
| 14 | + ObservableCollection<string> list = ["b", "c"]; |
| 15 | + |
| 16 | + ListHelper.Modify(list, "a", 5); |
| 17 | + |
| 18 | + Assert.Equal(["a", "b", "c"], list); |
| 19 | + } |
| 20 | + |
| 21 | + [Fact] |
| 22 | + public void MovesExistingEntryToTheTop() |
| 23 | + { |
| 24 | + ObservableCollection<string> list = ["a", "b", "c"]; |
| 25 | + |
| 26 | + ListHelper.Modify(list, "c", 5); |
| 27 | + |
| 28 | + Assert.Equal(["c", "a", "b"], list); |
| 29 | + } |
| 30 | + |
| 31 | + [Fact] |
| 32 | + public void RemovesOldestEntriesBeyondTheLength() |
| 33 | + { |
| 34 | + ObservableCollection<string> list = ["b", "c", "d"]; |
| 35 | + |
| 36 | + ListHelper.Modify(list, "a", 3); |
| 37 | + |
| 38 | + Assert.Equal(["a", "b", "c"], list); |
| 39 | + } |
| 40 | + |
| 41 | + [Fact] |
| 42 | + public void ShortensAListThatIsTooLong() |
| 43 | + { |
| 44 | + // E.g. after the history length was reduced in the settings. |
| 45 | + ObservableCollection<string> list = ["a", "b", "c", "d"]; |
| 46 | + |
| 47 | + ListHelper.Modify(list, "a", 2); |
| 48 | + |
| 49 | + Assert.Equal(["a", "b"], list); |
| 50 | + } |
| 51 | + |
| 52 | + [Fact] |
| 53 | + public void RemovesDuplicatesOfTheEntry() |
| 54 | + { |
| 55 | + ObservableCollection<int> list = [1, 2, 3, 2]; |
| 56 | + |
| 57 | + ListHelper.Modify(list, 2, 10); |
| 58 | + |
| 59 | + Assert.Equal([2, 1, 3], list); |
| 60 | + } |
| 61 | + |
| 62 | + [Fact] |
| 63 | + public void DoesNotChangeTheListIfTheEntryIsAlreadyTheNewest() |
| 64 | + { |
| 65 | + ObservableCollection<string> list = ["a", "b"]; |
| 66 | + var changes = 0; |
| 67 | + list.CollectionChanged += (_, _) => changes++; |
| 68 | + |
| 69 | + ListHelper.Modify(list, "a", 5); |
| 70 | + |
| 71 | + Assert.Equal(0, changes); |
| 72 | + } |
| 73 | + |
| 74 | + [Fact] |
| 75 | + public void MovesInsteadOfResetting() |
| 76 | + { |
| 77 | + // A reset (Clear) would remove the entry that a ComboBox shows, which can clear its text. |
| 78 | + ObservableCollection<string> list = ["a", "b", "c"]; |
| 79 | + var actions = new System.Collections.Generic.List<NotifyCollectionChangedAction>(); |
| 80 | + list.CollectionChanged += (_, e) => actions.Add(e.Action); |
| 81 | + |
| 82 | + ListHelper.Modify(list, "b", 5); |
| 83 | + |
| 84 | + Assert.Equal([NotifyCollectionChangedAction.Move], actions); |
| 85 | + } |
| 86 | + |
| 87 | + [Fact] |
| 88 | + public void ThrowsIfTheLengthIsNotPositive() |
| 89 | + { |
| 90 | + Assert.Throws<ArgumentOutOfRangeException>(() => ListHelper.Modify(new ObservableCollection<string>(), "a", 0)); |
| 91 | + } |
| 92 | +} |
0 commit comments