Updates IListDataSource.Render to rename the start parameter to viewportXOffset (#4392)

* Add comprehensive unit tests for WindowsKeyConverter

- Implement 118 parallelizable unit tests for WindowsKeyConverter

- Cover ToKey and ToKeyInfo methods with full bidirectional testing

- Test basic characters, modifiers, special keys, function keys

- Test VK_PACKET Unicode/IME input

- Test OEM keys, NumPad keys, and lock states

- Include round-trip conversion tests

- All tests passing successfully

Fixes #4389

* Rename `start` parameter to `viewportXOffset` for clarity

The `start` parameter in several methods and interfaces has been
renamed to `viewportXOffset` to better reflect its purpose as the
horizontal offset of the viewport during string rendering.

- Updated method signatures in `ListViewWithSelection` to use
  `viewportXOffset` instead of `start`, including default values.
- Modified the `RenderUstr` method in `ListViewWithSelection` to
  use `viewportXOffset` for calculating the starting index.
- Renamed the `start` parameter to `viewportXOffset` in the
  `IListDataSource` interface and updated its documentation.
- Replaced all occurrences of `start` with `viewportXOffset` in
  the `ListWrapper<T>` class, including method calls and logic.
- Updated the `RenderUstr` method in `ListWrapper<T>` to use
  `viewportXOffset` for substring calculations.
- Adjusted the test method in `ListViewTests.cs` to reflect the
  parameter name change.

These changes improve code readability and make the parameter's
role in rendering logic more explicit.

* Remove WindowsKeyConverterTests class that was added by mistake

* Modernized ListView and IListDataSource - Tons of new unit tests

Refactored `ListView` and `IListDataSource` to improve readability, maintainability, and functionality. Introduced `ListWrapper<T>` as a default implementation of `IListDataSource` for easier integration with standard collections.

Enhanced `ListView` with better handling of marking, selection, and scrolling. Replaced `viewportXOffset` with `viewportX` for horizontal scrolling. Added `EnsureSelectedItemVisible` to maintain visibility of the selected item.

Updated `IListDataSource` with detailed XML documentation and added `SuspendCollectionChangedEvent` for bulk updates. Improved null safety with nullable reference types.

Added comprehensive unit tests for `ListWrapper<T>` and `IListDataSource` to ensure robustness. Modernized the codebase with C# features like expression-bodied members and pattern matching. Fixed bugs related to `SelectedItem` validation and rendering artifacts.

* Improve index validation in ComboBox and ListView

Enhance robustness by adding stricter checks for valid indices
in ComboBox and ListView. Updated conditions in the
`_listview.SelectedItemChanged` event handler to ensure `e.Item`
is non-negative before accessing `_searchSet`. Modified the
`SetValue` method to use `e.Item` instead of `_listview.SelectedItem`.

In ListView, updated the `OnSelectedChanged` method to validate
that `SelectedItem` is non-negative (`>= 0`) before accessing
the `Source` list. These changes prevent potential out-of-range
errors and improve code safety.

* Refactor and enhance test coverage across modules

Refactored and added new tests to improve coverage, readability, and consistency across multiple test files. Key changes include:

- **ShortcutTests.cs**: Added tests for `BindKeyToApplication` and removed redundant tests.
- **SourcesManagerTests.cs**: Renamed `Update_*` tests to `Load_*` for clarity.
- **ArrangementTests.cs**: Reintroduced `MouseGrabHandler` tests, added `ViewArrangement` flag tests, and improved structure.
- **NeedsDrawTests.cs**: Replaced `Application.Screen.Size` with fixed dimensions for better isolation.
- **DimAutoTests.cs**: Updated layout tests to use fixed dimensions.
- **FrameTests.cs**: Standardized object initialization and validated frame behavior.
- **SubViewTests.cs**: Improved formatting and modernized event handling.
- **NumericUpDownTests.cs**: Decoupled layout tests from screen size.

General improvements:
- Enhanced formatting and removed redundant tests.
- Added comments for clarity.
- Introduced `ITestOutputHelper` for better debugging in `ArrangementTests`.

* Refactor to use nullable types for better null safety

Enabled nullable reference types across the codebase to improve null safety and prevent potential null reference issues. Refactored `SelectedItem` and related properties from `int` to `int?` to represent no selection with `null` instead of `-1`. Updated logic, event arguments, and method signatures to handle nullable values consistently.

Simplified object initialization using modern C# syntax and improved code readability with interpolated strings. Added null checks and early returns to prevent runtime errors. Enhanced error handling by throwing `ArgumentOutOfRangeException` for invalid values.

Updated tests to reflect the changes, replacing assertions for `-1` with `null` and ensuring proper handling of nullable values. Cleaned up redundant code and improved formatting for better maintainability.

* on` functionality has been deprecated, refactored, or removed from the `Shortcut` class.

* Refactor: Transition to instance-based architecture

Updated `Run-LocalCoverage.ps1` to increase `--blame-hang-timeout` from 10s to 60s. Improved null safety in `GuiTestContext` by adding null-conditional operators. Commented out problematic code in `SetupFakeApplicationAttribute.cs` to prevent test hangs.

Excluded `ViewBase` files from `UnitTests.Parallelizable.csproj` and removed redundant folder declarations. Simplified event handling in `IListDataSourceTests.cs` and updated `ListViewTests.cs` to use nullable reference types.

Enhanced documentation to emphasize the transition to an instance-based application architecture. Updated examples in `application.md`, `multitasking.md`, and `navigation.md` to reflect the use of `Application.Create()` and `View.App`. Clarified the obsolescence of the static `Application` class.

Revised table of contents in `toc.yml` to include new sections like "Application Deep Dive" and "Scheme Deep Dive." Added `dotnet-tools.json` for tool configuration.

These changes improve maintainability, testability, and alignment with modern C# practices.

* Refactor ListViewTests to use Terminal.Gui framework

The `ListViewTests` class has been refactored to replace the `AutoInitShutdown` attribute with explicit application lifecycle management using `IApplication` and `app.Init()` from the `Terminal.Gui` framework.

Key changes include:
- Rewriting tests to use `Terminal.Gui`'s application lifecycle.
- Adding a private `_output` field for logging test output via `ITestOutputHelper`.
- Updating `DriverAssert.AssertDriverContentsWithFrameAre` to include `app.Driver` for UI verification.
- Rewriting tests like `Clicking_On_Border_Is_Ignored`, `EnsureSelectedItemVisible_SelectedItem`, and others to align with the new framework.
- Adding explicit calls to `app.Shutdown()` for proper cleanup.
- Enabling nullable reference types with `#nullable enable`.
- Updating `using` directives and `namespace` to reflect the new structure.

These changes improve test maintainability, compatibility, and diagnostics.

* Update Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Examples/UICatalog/UICatalogTop.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Views/ListWrapper.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Views/ListWrapper.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Updated the `SetMark` method to return `Source.IsMarked(SelectedItem.Value)` for consistency and removed an outdated comment questioning its correctness.

Enhanced the exception message in the `SelectedItem` property setter to provide clearer guidance when the value is out of range.

* Add comprehensive ListView behavior test coverage

Added multiple test methods to validate `ListView` behavior:
- `Vertical_ScrollBar_Hides_And_Shows_As_Needed`: Ensures the vertical scrollbar auto-hides/shows based on content height.
- `Mouse_Wheel_Scrolls`: Verifies vertical scrolling with the mouse wheel updates `TopItem`.
- `SelectedItem_With_Source_Null_Does_Nothing`: Confirms no exceptions occur when setting `SelectedItem` with a `null` source.
- `Horizontal_Scroll`: Tests horizontal scrolling, including programmatic and mouse wheel interactions, ensuring `LeftItem` updates correctly.
- `SetSourceAsync_SetsSource`: Validates the asynchronous `SetSourceAsync` method updates the source and item count.
- `AllowsMultipleSelection_Set_To_False_Unmarks_All_But_Selected`: Ensures disabling multiple selection unmarks all but the selected item.
- `Source_CollectionChanged_Remove`: Confirms `SelectedItem` and source count update correctly when items are removed from the source collection.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Tig
2025-11-19 20:39:34 -05:00
committed by GitHub
parent c5906c2dc1
commit a6258ed398
44 changed files with 3372 additions and 2355 deletions

View File

@@ -317,7 +317,7 @@ public class ScenarioTests : TestsAllViews
hostPane.FillRect (hostPane.Viewport);
}
curView = CreateClass (viewClasses.Values.ToArray () [classListView.SelectedItem]);
curView = CreateClass (viewClasses.Values.ToArray () [classListView.SelectedItem!.Value]);
};
xOptionSelector.ValueChanged += (_, _) => DimPosChanged (curView);
@@ -404,7 +404,7 @@ public class ScenarioTests : TestsAllViews
{
Assert.Equal (
curView.GetType ().Name,
viewClasses.Values.ToArray () [classListView.SelectedItem].Name);
viewClasses.Values.ToArray () [classListView.SelectedItem!.Value].Name);
}
}
else

View File

@@ -24,7 +24,7 @@ public partial class GuiTestContext
{
// Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
// and the context menu is disposed when it is closed.
App.Popover?.Register (contextMenu);
App?.Popover?.Register (contextMenu);
contextMenu?.MakeVisible (e.ScreenPosition);
}
};

View File

@@ -28,11 +28,11 @@ public partial class GuiTestContext
/// <summary>
/// The last view added (e.g. with <see cref="Add"/>) or the root/current top.
/// </summary>
public View LastView => _lastView ?? App.Current ?? throw new ("Could not determine which view to add to");
public View LastView => _lastView ?? App?.Current ?? throw new ("Could not determine which view to add to");
private T Find<T> (Func<T, bool> evaluator) where T : View
{
Toplevel? t = App.Current;
Toplevel? t = App?.Current;
if (t == null)
{

View File

@@ -32,7 +32,10 @@ public class SetupFakeApplicationAttribute : BeforeAfterTestAttribute
_appDispose?.Dispose ();
_appDispose = null;
ApplicationImpl.SetInstance (null);
// TODO: This is troublesome; it seems to cause tests to hang when enabled, but shouldn't have any impact.
// TODO: Uncomment after investigation.
//ApplicationImpl.SetInstance (null);
base.After (methodUnderTest);
}

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,7 @@ public class SourcesManagerTests
#region Update (Stream)
[Fact]
public void Update_WithNullSettingsScope_ReturnsFalse ()
public void Load_WithNullSettingsScope_ReturnsFalse ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -23,7 +23,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithValidStream_UpdatesSettingsScope ()
public void Load_WithValidStream_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -56,7 +56,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithInvalidJson_AddsJsonError ()
public void Load_WithInvalidJson_AddsJsonError ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -86,7 +86,7 @@ public class SourcesManagerTests
#region Update (FilePath)
[Fact]
public void Update_WithNonExistentFile_AddsToSourcesAndReturnsTrue ()
public void Load_WithNonExistentFile_AddsToSourcesAndReturnsTrue ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -104,7 +104,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithValidFile_UpdatesSettingsScope ()
public void Load_WithValidFile_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -140,7 +140,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithIOException_RetriesAndFailsGracefully ()
public void Load_WithIOException_RetriesAndFailsGracefully ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -174,7 +174,7 @@ public class SourcesManagerTests
#region Update (Json String)
[Fact]
public void Update_WithNullOrEmptyJson_ReturnsFalse ()
public void Load_WithNullOrEmptyJson_ReturnsFalse ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -193,7 +193,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithValidJson_UpdatesSettingsScope ()
public void Load_WithValidJson_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -381,7 +381,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WhenCalledMultipleTimes_MaintainsLastSourceForLocation ()
public void Load_WhenCalledMultipleTimes_MaintainsLastSourceForLocation ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -401,7 +401,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithDifferentLocations_AddsAllSourcesToCollection ()
public void Load_WithDifferentLocations_AddsAllSourcesToCollection ()
{
// Arrange
var sourcesManager = new SourcesManager ();
@@ -452,7 +452,7 @@ public class SourcesManagerTests
}
[Fact]
public void Update_WithNonExistentFileAndDifferentLocations_TracksAllSources ()
public void Load_WithNonExistentFileAndDifferentLocations_TracksAllSources ()
{
// Arrange
var sourcesManager = new SourcesManager ();

View File

@@ -42,7 +42,7 @@ public class CollectionNavigatorTests
// cycling with 'a'
n = new CollectionNavigator (simpleStrings);
Assert.Equal (0, n.GetNextMatchingItem (-1, 'a'));
Assert.Equal (0, n.GetNextMatchingItem (null, 'a'));
Assert.Equal (1, n.GetNextMatchingItem (0, 'a'));
// if 4 (candle) is selected it should loop back to apricot
@@ -53,7 +53,7 @@ public class CollectionNavigatorTests
public void Delay ()
{
var strings = new [] { "$$", "$100.00", "$101.00", "$101.10", "$200.00", "apricot" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
// No delay
@@ -96,7 +96,7 @@ public class CollectionNavigatorTests
var strings = new [] { "apricot", "arm", "ta", "target", "text", "egg", "candle" };
var n = new CollectionNavigator (strings);
var current = 0;
int? current = 0;
Assert.Equal (strings.IndexOf ("ta"), current = n.GetNextMatchingItem (current, 't'));
// should match "te" in "text"
@@ -137,7 +137,7 @@ public class CollectionNavigatorTests
public void MinimizeMovement_False_ShouldMoveIfMultipleMatches ()
{
var strings = new [] { "$$", "$100.00", "$101.00", "$101.10", "$200.00", "apricot", "c", "car", "cart" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
Assert.Equal (strings.IndexOf ("$$"), current = n.GetNextMatchingItem (current, "$$"));
Assert.Equal (strings.IndexOf ("$100.00"), current = n.GetNextMatchingItem (current, "$"));
@@ -166,14 +166,14 @@ public class CollectionNavigatorTests
Assert.Equal (strings.IndexOf ("car"), current = n.GetNextMatchingItem (current, "car"));
Assert.Equal (strings.IndexOf ("cart"), current = n.GetNextMatchingItem (current, "car"));
Assert.Equal (-1, current = n.GetNextMatchingItem (current, "x"));
Assert.Null (n.GetNextMatchingItem (current, "x"));
}
[Fact]
public void MinimizeMovement_True_ShouldStayOnCurrentIfMultipleMatches ()
{
var strings = new [] { "$$", "$100.00", "$101.00", "$101.10", "$200.00", "apricot", "c", "car", "cart" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
Assert.Equal (strings.IndexOf ("$$"), current = n.GetNextMatchingItem (current, "$$", true));
Assert.Equal (strings.IndexOf ("$$"), current = n.GetNextMatchingItem (current, "$", true));
@@ -185,14 +185,14 @@ public class CollectionNavigatorTests
Assert.Equal (strings.IndexOf ("car"), current = n.GetNextMatchingItem (current, "car", true));
Assert.Equal (strings.IndexOf ("car"), current = n.GetNextMatchingItem (current, "car", true));
Assert.Equal (-1, current = n.GetNextMatchingItem (current, "x", true));
Assert.Null (n.GetNextMatchingItem (current, "x", true));
}
[Fact]
public void MutliKeySearchPlusWrongKeyStays ()
{
var strings = new [] { "a", "c", "can", "candle", "candy", "yellow", "zebra" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
// https://github.com/gui-cs/Terminal.Gui/pull/2132#issuecomment-1298425573
@@ -240,20 +240,20 @@ public class CollectionNavigatorTests
}
[Fact]
public void ShouldAcceptNegativeOne ()
public void ShouldAcceptNull ()
{
var n = new CollectionNavigator (simpleStrings);
// Expect that index of -1 (i.e. no selection) should work correctly
// Expect that index of null (i.e. no selection) should work correctly
// and select the first entry of the letter 'b'
Assert.Equal (2, n.GetNextMatchingItem (-1, 'b'));
Assert.Equal (2, n.GetNextMatchingItem (null, 'b'));
}
[Fact]
public void Symbols ()
{
var strings = new [] { "$$", "$100.00", "$101.00", "$101.10", "$200.00", "apricot" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
Assert.Equal (strings.IndexOf ("apricot"), current = n.GetNextMatchingItem (current, 'a'));
Assert.Equal ("a", n.SearchString);
@@ -293,7 +293,7 @@ public class CollectionNavigatorTests
var strings = new [] { "apricot", "arm", "ta", "丗丙业丞", "丗丙丛", "text", "egg", "candle" };
var n = new CollectionNavigator (strings);
var current = 0;
int? current = 0;
Assert.Equal (strings.IndexOf ("丗丙业丞"), current = n.GetNextMatchingItem (current, '丗'));
// 丗丙业丞 is as good a match as 丗丙丛
@@ -319,7 +319,7 @@ public class CollectionNavigatorTests
public void Word ()
{
var strings = new [] { "apricot", "arm", "bat", "batman", "bates hotel", "candle" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
Assert.Equal (strings.IndexOf ("bat"), current = n.GetNextMatchingItem (current, 'b')); // match bat
Assert.Equal (strings.IndexOf ("bat"), current = n.GetNextMatchingItem (current, 'a')); // match bat
@@ -344,7 +344,7 @@ public class CollectionNavigatorTests
public void CustomMatcher_NeverMatches ()
{
var strings = new [] { "apricot", "arm", "bat", "batman", "bates hotel", "candle" };
var current = 0;
int? current = 0;
var n = new CollectionNavigator (strings);
var matchNone = new Mock<ICollectionNavigatorMatcher> ();

View File

@@ -27,6 +27,11 @@
<PropertyGroup Condition="'$(Configuration)'=='Release'">
<Optimize>true</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Remove="ViewBase\**" />
<EmbeddedResource Remove="ViewBase\**" />
<None Remove="ViewBase\**" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\UnitTests\DriverAssert.cs" Link="DriverAssert.cs" />
@@ -69,7 +74,4 @@
<Using Include="Terminal.Gui" />
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Folder Include="ViewBase\" />
</ItemGroup>
</Project>

View File

@@ -130,14 +130,14 @@ public class NeedsDrawTests : FakeDriverBase
Assert.False (view.NeedsLayout);
// SRL won't change anything since the view frame wasn't changed
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.False (view.NeedsDraw);
view.SetNeedsLayout ();
// SRL won't change anything since the view frame wasn't changed
// SRL doesn't depend on NeedsLayout, but LayoutSubViews does
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.False (view.NeedsDraw);
Assert.True (view.NeedsLayout);
@@ -180,7 +180,7 @@ public class NeedsDrawTests : FakeDriverBase
Assert.True (view.NeedsDraw);
Assert.True (superView.NeedsDraw);
superView.SetRelativeLayout (Application.Screen.Size);
superView.SetRelativeLayout (new (100, 100));
Assert.True (view.NeedsDraw);
Assert.True (superView.NeedsDraw);
}
@@ -216,7 +216,7 @@ public class NeedsDrawTests : FakeDriverBase
view.EndInit ();
Assert.True (view.NeedsDraw);
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.True (view.NeedsDraw);
view.LayoutSubViews ();
@@ -235,7 +235,7 @@ public class NeedsDrawTests : FakeDriverBase
view.EndInit ();
Assert.True (view.NeedsDraw);
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.True (view.NeedsDraw);
view.LayoutSubViews ();

View File

@@ -597,7 +597,7 @@ public partial class DimAutoTests
// Without a subview, width should be 10
// Without a subview, height should be 1
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.Equal (10, view.Frame.Width);
Assert.Equal (1, view.Frame.Height);

View File

@@ -304,10 +304,10 @@ public partial class DimAutoTests (ITestOutputHelper output)
Width = Auto (),
Height = 1
};
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
lastSize = view.Frame.Size;
view.HotKeySpecifier = (Rune)'*';
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.NotEqual (lastSize, view.Frame.Size);
view = new ()
@@ -316,10 +316,10 @@ public partial class DimAutoTests (ITestOutputHelper output)
Width = Auto (),
Height = 1
};
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
lastSize = view.Frame.Size;
view.Text = "*ABCD";
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.NotEqual (lastSize, view.Frame.Size);
}
@@ -703,7 +703,7 @@ public partial class DimAutoTests (ITestOutputHelper output)
view.Text = text;
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.Equal (new (expectedW, expectedH), view.Frame.Size);
}
@@ -812,7 +812,7 @@ public partial class DimAutoTests (ITestOutputHelper output)
view.Text = text;
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.Equal (new (expectedW, expectedH), view.Frame.Size);
}
@@ -831,7 +831,7 @@ public partial class DimAutoTests (ITestOutputHelper output)
view.Text = text;
view.SetRelativeLayout (Application.Screen.Size);
view.SetRelativeLayout (new (100, 100));
Assert.Equal (new (expectedW, expectedH), view.Frame.Size);
}

View File

@@ -120,7 +120,7 @@ public class FrameTests
Assert.True (view.NeedsLayout);
view.Layout ();
Assert.False (view.NeedsLayout);
Assert.Equal (Application.Screen, view.Frame);
Assert.Equal (new Size (2048, 2048), view.Frame.Size);
view.Frame = Rectangle.Empty;
Assert.Equal (Rectangle.Empty, view.Frame);
@@ -165,7 +165,7 @@ public class FrameTests
Assert.Equal (Rectangle.Empty, v.Frame);
v.Dispose ();
v = new() { Frame = frame };
v = new () { Frame = frame };
Assert.Equal (frame, v.Frame);
v.Frame = newFrame;
@@ -181,7 +181,7 @@ public class FrameTests
Assert.Equal (Dim.Absolute (40), v.Height);
v.Dispose ();
v = new() { X = frame.X, Y = frame.Y, Text = "v" };
v = new () { X = frame.X, Y = frame.Y, Text = "v" };
v.Frame = newFrame;
Assert.Equal (newFrame, v.Frame);
@@ -196,7 +196,7 @@ public class FrameTests
v.Dispose ();
newFrame = new (10, 20, 30, 40);
v = new() { Frame = frame };
v = new () { Frame = frame };
v.Frame = newFrame;
Assert.Equal (newFrame, v.Frame);
@@ -210,7 +210,7 @@ public class FrameTests
Assert.Equal (Dim.Absolute (40), v.Height);
v.Dispose ();
v = new() { X = frame.X, Y = frame.Y, Text = "v" };
v = new () { X = frame.X, Y = frame.Y, Text = "v" };
v.Frame = newFrame;
Assert.Equal (newFrame, v.Frame);

View File

@@ -14,11 +14,11 @@ public class SubViewTests
super.SuperViewChanged += (s, e) =>
{
superRaisedCount++;
superRaisedCount++;
};
sub.SuperViewChanged += (s, e) =>
{
if (e.SuperView is {})
if (e.SuperView is { })
{
subRaisedCount++;
}
@@ -266,14 +266,14 @@ public class SubViewTests
superView.Add (subview1, subview2, subview3);
superView.MoveSubViewTowardsEnd (subview2);
Assert.Equal (subview2, superView.SubViews.ToArray() [^1]);
Assert.Equal (subview2, superView.SubViews.ToArray () [^1]);
superView.MoveSubViewTowardsEnd (subview1);
Assert.Equal (subview1, superView.SubViews.ToArray() [1]);
Assert.Equal (subview1, superView.SubViews.ToArray () [1]);
// Already at end, what happens?
superView.MoveSubViewTowardsEnd (subview2);
Assert.Equal (subview2, superView.SubViews.ToArray() [^1]);
Assert.Equal (subview2, superView.SubViews.ToArray () [^1]);
}
[Fact]
@@ -517,7 +517,7 @@ public class SubViewTests
Assert.False (v2AddedToWin.CanFocus);
Assert.False (svAddedTov1.CanFocus);
Application.LayoutAndDraw ();
top.Layout ();
};
winAddedToTop.Initialized += (s, e) =>

View File

@@ -0,0 +1,513 @@
#nullable enable
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using Xunit.Abstractions;
// ReSharper disable InconsistentNaming
namespace UnitTests_Parallelizable.ViewTests;
public class IListDataSourceTests (ITestOutputHelper output)
{
private readonly ITestOutputHelper _output = output;
#region Concurrent Modification Tests
[Fact]
public void ListWrapper_SuspendAndModify_NoEventsUntilResume ()
{
ObservableCollection<string> source = ["Item1"];
ListWrapper<string> wrapper = new (source);
var eventCount = 0;
wrapper.CollectionChanged += (s, e) => eventCount++;
wrapper.SuspendCollectionChangedEvent = true;
source.Add ("Item2");
source.Add ("Item3");
source.RemoveAt (0);
Assert.Equal (0, eventCount);
wrapper.SuspendCollectionChangedEvent = false;
// Should have adjusted marks for the removals that happened while suspended
Assert.Equal (2, wrapper.Count);
}
#endregion
/// <summary>
/// Test implementation of IListDataSource for testing custom implementations
/// </summary>
private class TestListDataSource : IListDataSource
{
private readonly List<string> _items = ["Custom Item 00", "Custom Item 01", "Custom Item 02"];
private readonly BitArray _marks = new (3);
public event NotifyCollectionChangedEventHandler? CollectionChanged;
public int Count => _items.Count;
public int Length => _items.Any () ? _items.Max (s => s?.Length ?? 0) : 0;
public bool SuspendCollectionChangedEvent { get; set; }
public bool IsMarked (int item)
{
if (item < 0 || item >= _items.Count)
{
return false;
}
return _marks [item];
}
public void SetMark (int item, bool value)
{
if (item >= 0 && item < _items.Count)
{
_marks [item] = value;
}
}
public void Render (ListView listView, bool selected, int item, int col, int line, int width, int viewportX = 0)
{
if (item < 0 || item >= _items.Count)
{
return;
}
listView.Move (col, line);
string text = _items [item] ?? "";
if (viewportX < text.Length)
{
text = text.Substring (viewportX);
}
else
{
text = "";
}
if (text.Length > width)
{
text = text.Substring (0, width);
}
listView.AddStr (text);
// Fill remaining width
for (int i = text.Length; i < width; i++)
{
listView.AddRune ((Rune)' ');
}
}
public IList ToList () { return _items; }
public void Dispose () { IsDisposed = true; }
public void AddItem (string item)
{
_items.Add (item);
// Resize marks
var newMarks = new BitArray (_items.Count);
for (var i = 0; i < Math.Min (_marks.Length, newMarks.Length); i++)
{
newMarks [i] = _marks [i];
}
if (!SuspendCollectionChangedEvent)
{
CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Add, item, _items.Count - 1));
}
}
public bool IsDisposed { get; private set; }
}
#region ListWrapper<T> Render Tests
[Fact]
public void ListWrapper_Render_NullItem_RendersEmpty ()
{
ObservableCollection<string?> source = [null, "Item2"];
ListWrapper<string?> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 2 };
listView.BeginInit ();
listView.EndInit ();
// Render the null item (index 0)
wrapper.Render (listView, false, 0, 0, 0, 20);
// Should not throw and should render empty/spaces
Assert.Equal (2, wrapper.Count);
}
[Fact]
public void ListWrapper_Render_EmptyString_RendersSpaces ()
{
ObservableCollection<string> source = [""];
ListWrapper<string> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 1 };
listView.BeginInit ();
listView.EndInit ();
wrapper.Render (listView, false, 0, 0, 0, 20);
Assert.Equal (1, wrapper.Count);
Assert.Equal (0, wrapper.Length); // Empty string has zero length
}
[Fact]
public void ListWrapper_Render_UnicodeText_CalculatesWidthCorrectly ()
{
ObservableCollection<string> source = ["Hello 你好", "Test"];
ListWrapper<string> wrapper = new (source);
// "Hello 你好" should be: "Hello " (6) + "你" (2) + "好" (2) = 10 columns
Assert.True (wrapper.Length >= 10);
}
[Fact]
public void ListWrapper_Render_LongString_ClipsToWidth ()
{
var longString = new string ('X', 100);
ObservableCollection<string> source = [longString];
ListWrapper<string> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 1 };
listView.BeginInit ();
listView.EndInit ();
wrapper.Render (listView, false, 0, 0, 0, 10);
Assert.Equal (100, wrapper.Length);
}
[Fact]
public void ListWrapper_Render_WithViewportX_ScrollsHorizontally ()
{
ObservableCollection<string> source = ["0123456789ABCDEF"];
ListWrapper<string> wrapper = new (source);
var listView = new ListView { Width = 10, Height = 1 };
listView.BeginInit ();
listView.EndInit ();
// Render with horizontal scroll offset of 5
wrapper.Render (listView, false, 0, 0, 0, 10, 5);
// Should render "56789ABCDE" (starting at position 5)
Assert.Equal (16, wrapper.Length);
}
[Fact]
public void ListWrapper_Render_ViewportXBeyondLength_RendersEmpty ()
{
ObservableCollection<string> source = ["Short"];
ListWrapper<string> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 1 };
listView.BeginInit ();
listView.EndInit ();
// Render with viewport beyond string length
wrapper.Render (listView, false, 0, 0, 0, 10, 100);
Assert.Equal (5, wrapper.Length);
}
[Fact]
public void ListWrapper_Render_ColAndLine_PositionsCorrectly ()
{
ObservableCollection<string> source = ["Item1", "Item2"];
ListWrapper<string> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 5 };
listView.BeginInit ();
listView.EndInit ();
// Render at different positions
wrapper.Render (listView, false, 0, 2, 1, 10); // col=2, line=1
wrapper.Render (listView, false, 1, 0, 3, 10); // col=0, line=3
Assert.Equal (2, wrapper.Count);
}
[Fact]
public void ListWrapper_Render_WidthConstraint_FillsRemaining ()
{
ObservableCollection<string> source = ["Hi"];
ListWrapper<string> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 1 };
listView.BeginInit ();
listView.EndInit ();
// Render "Hi" in width of 10 - should fill remaining 8 with spaces
wrapper.Render (listView, false, 0, 0, 0, 10);
Assert.Equal (2, wrapper.Length);
}
[Fact]
public void ListWrapper_Render_NonStringType_UsesToString ()
{
ObservableCollection<int> source = [42, 100, -5];
ListWrapper<int> wrapper = new (source);
var listView = new ListView { Width = 20, Height = 3 };
listView.BeginInit ();
listView.EndInit ();
wrapper.Render (listView, false, 0, 0, 0, 10);
wrapper.Render (listView, false, 1, 0, 1, 10);
wrapper.Render (listView, false, 2, 0, 2, 10);
Assert.Equal (3, wrapper.Count);
Assert.True (wrapper.Length >= 2); // "42" is 2 chars, "100" is 3 chars
}
#endregion
#region Custom IListDataSource Implementation Tests
[Fact]
public void CustomDataSource_AllMembers_WorkCorrectly ()
{
var customSource = new TestListDataSource ();
var listView = new ListView { Source = customSource, Width = 20, Height = 5 };
Assert.Equal (3, customSource.Count);
Assert.Equal (14, customSource.Length); // "Custom Item 00" is 14 chars
// Test marking
Assert.False (customSource.IsMarked (0));
customSource.SetMark (0, true);
Assert.True (customSource.IsMarked (0));
customSource.SetMark (0, false);
Assert.False (customSource.IsMarked (0));
// Test ToList
IList list = customSource.ToList ();
Assert.Equal (3, list.Count);
Assert.Equal ("Custom Item 00", list [0]);
// Test render doesn't throw
listView.BeginInit ();
listView.EndInit ();
Exception ex = Record.Exception (() => customSource.Render (listView, false, 0, 0, 0, 20));
Assert.Null (ex);
}
[Fact]
public void CustomDataSource_CollectionChanged_RaisedOnModification ()
{
var customSource = new TestListDataSource ();
var eventRaised = false;
NotifyCollectionChangedAction? action = null;
customSource.CollectionChanged += (s, e) =>
{
eventRaised = true;
action = e.Action;
};
customSource.AddItem ("New Item");
Assert.True (eventRaised);
Assert.Equal (NotifyCollectionChangedAction.Add, action);
Assert.Equal (4, customSource.Count);
}
[Fact]
public void CustomDataSource_SuspendCollectionChanged_SuppressesEvents ()
{
var customSource = new TestListDataSource ();
var eventCount = 0;
customSource.CollectionChanged += (s, e) => eventCount++;
customSource.SuspendCollectionChangedEvent = true;
customSource.AddItem ("Item 1");
customSource.AddItem ("Item 2");
Assert.Equal (0, eventCount); // No events raised
customSource.SuspendCollectionChangedEvent = false;
customSource.AddItem ("Item 3");
Assert.Equal (1, eventCount); // Event raised after resume
}
[Fact]
public void CustomDataSource_Dispose_CleansUp ()
{
var customSource = new TestListDataSource ();
customSource.Dispose ();
// After dispose, adding should not raise events (if implemented correctly)
customSource.AddItem ("New Item");
// The test source doesn't unsubscribe in dispose, but this shows the pattern
Assert.True (customSource.IsDisposed);
}
#endregion
#region Edge Cases
[Fact]
public void ListWrapper_EmptyCollection_PropertiesReturnZero ()
{
ObservableCollection<string> source = [];
ListWrapper<string> wrapper = new (source);
Assert.Equal (0, wrapper.Count);
Assert.Equal (0, wrapper.Length);
}
[Fact]
public void ListWrapper_NullSource_HandledGracefully ()
{
ListWrapper<string> wrapper = new (null);
Assert.Equal (0, wrapper.Count);
Assert.Equal (0, wrapper.Length);
// ToList should not throw
IList list = wrapper.ToList ();
Assert.Empty (list);
}
[Fact]
public void ListWrapper_IsMarked_OutOfBounds_ReturnsFalse ()
{
ObservableCollection<string> source = ["Item1"];
ListWrapper<string> wrapper = new (source);
Assert.False (wrapper.IsMarked (-1));
Assert.False (wrapper.IsMarked (1));
Assert.False (wrapper.IsMarked (100));
}
[Fact]
public void ListWrapper_SetMark_OutOfBounds_DoesNotThrow ()
{
ObservableCollection<string> source = ["Item1"];
ListWrapper<string> wrapper = new (source);
Exception ex = Record.Exception (() => wrapper.SetMark (-1, true));
Assert.Null (ex);
ex = Record.Exception (() => wrapper.SetMark (100, true));
Assert.Null (ex);
}
[Fact]
public void ListWrapper_CollectionShrinks_MarksAdjusted ()
{
ObservableCollection<string> source = ["Item1", "Item2", "Item3"];
ListWrapper<string> wrapper = new (source);
wrapper.SetMark (0, true);
wrapper.SetMark (2, true);
Assert.True (wrapper.IsMarked (0));
Assert.True (wrapper.IsMarked (2));
// Remove item 1 (middle item)
source.RemoveAt (1);
Assert.Equal (2, wrapper.Count);
Assert.True (wrapper.IsMarked (0)); // Still marked
// Item that was at index 2 is now at index 1
}
[Fact]
public void ListWrapper_CollectionGrows_MarksPreserved ()
{
ObservableCollection<string> source = ["Item1"];
ListWrapper<string> wrapper = new (source);
wrapper.SetMark (0, true);
Assert.True (wrapper.IsMarked (0));
source.Add ("Item2");
source.Add ("Item3");
Assert.Equal (3, wrapper.Count);
Assert.True (wrapper.IsMarked (0)); // Original mark preserved
Assert.False (wrapper.IsMarked (1));
Assert.False (wrapper.IsMarked (2));
}
[Fact]
public void ListWrapper_StartsWith_EmptyString_ReturnsFirst ()
{
ObservableCollection<string> source = ["Apple", "Banana", "Cherry"];
ListWrapper<string> wrapper = new (source);
// Searching for empty string might return -1 or 0 depending on implementation
int result = wrapper.StartsWith ("");
Assert.True (result == -1 || result == 0);
}
[Fact]
public void ListWrapper_StartsWith_NoMatch_ReturnsNegative ()
{
ObservableCollection<string> source = ["Apple", "Banana", "Cherry"];
ListWrapper<string> wrapper = new (source);
int result = wrapper.StartsWith ("Zebra");
Assert.Equal (-1, result);
}
[Fact]
public void ListWrapper_StartsWith_CaseInsensitive ()
{
ObservableCollection<string> source = ["Apple", "Banana", "Cherry"];
ListWrapper<string> wrapper = new (source);
Assert.Equal (0, wrapper.StartsWith ("app"));
Assert.Equal (0, wrapper.StartsWith ("APP"));
Assert.Equal (1, wrapper.StartsWith ("ban"));
Assert.Equal (1, wrapper.StartsWith ("BAN"));
}
[Fact]
public void ListWrapper_MaxLength_UpdatesOnCollectionChange ()
{
ObservableCollection<string> source = ["Hi"];
ListWrapper<string> wrapper = new (source);
Assert.Equal (2, wrapper.Length);
source.Add ("Very Long String Indeed");
Assert.Equal (23, wrapper.Length);
source.Clear ();
source.Add ("X");
Assert.Equal (1, wrapper.Length);
}
[Fact]
public void ListWrapper_Dispose_UnsubscribesFromCollectionChanged ()
{
ObservableCollection<string> source = ["Item1"];
ListWrapper<string> wrapper = new (source);
wrapper.CollectionChanged += (s, e) => { };
wrapper.Dispose ();
// After dispose, source changes should not raise wrapper events
source.Add ("Item2");
// The wrapper's event might still fire, but the wrapper won't propagate source events
// This depends on implementation
}
#endregion
}

File diff suppressed because it is too large Load Diff

View File

@@ -112,7 +112,7 @@ public class NumericUpDownTests
public void WhenCreated_ShouldHaveDefaultWidthAndHeight_int ()
{
NumericUpDown<int> numericUpDown = new ();
numericUpDown.SetRelativeLayout (Application.Screen.Size);
numericUpDown.SetRelativeLayout (new (100, 100));
Assert.Equal (3, numericUpDown.Frame.Width);
Assert.Equal (1, numericUpDown.Frame.Height);
@@ -122,7 +122,7 @@ public class NumericUpDownTests
public void WhenCreated_ShouldHaveDefaultWidthAndHeight_float ()
{
NumericUpDown<float> numericUpDown = new ();
numericUpDown.SetRelativeLayout (Application.Screen.Size);
numericUpDown.SetRelativeLayout (new (100, 100));
Assert.Equal (3, numericUpDown.Frame.Width);
Assert.Equal (1, numericUpDown.Frame.Height);
@@ -132,7 +132,7 @@ public class NumericUpDownTests
public void WhenCreated_ShouldHaveDefaultWidthAndHeight_double ()
{
NumericUpDown<double> numericUpDown = new ();
numericUpDown.SetRelativeLayout (Application.Screen.Size);
numericUpDown.SetRelativeLayout (new (100, 100));
Assert.Equal (3, numericUpDown.Frame.Width);
Assert.Equal (1, numericUpDown.Frame.Height);
@@ -142,7 +142,7 @@ public class NumericUpDownTests
public void WhenCreated_ShouldHaveDefaultWidthAndHeight_long ()
{
NumericUpDown<long> numericUpDown = new ();
numericUpDown.SetRelativeLayout (Application.Screen.Size);
numericUpDown.SetRelativeLayout (new (100, 100));
Assert.Equal (3, numericUpDown.Frame.Width);
Assert.Equal (1, numericUpDown.Frame.Height);
@@ -152,7 +152,7 @@ public class NumericUpDownTests
public void WhenCreated_ShouldHaveDefaultWidthAndHeight_decimal ()
{
NumericUpDown<decimal> numericUpDown = new ();
numericUpDown.SetRelativeLayout (Application.Screen.Size);
numericUpDown.SetRelativeLayout (new (100, 100));
Assert.Equal (3, numericUpDown.Frame.Width);
Assert.Equal (1, numericUpDown.Frame.Height);