Files
Terminal.Gui/Tests/UnitTestsParallelizable/Configuration/SourcesManagerTests.cs
Tig a6258ed398 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>
2025-11-19 20:39:34 -05:00

562 lines
18 KiB
C#

using System.Reflection;
using System.Text.Json;
namespace UnitTests_Parallelizable.ConfigurationTests;
public class SourcesManagerTests
{
#region Update (Stream)
[Fact]
public void Load_WithNullSettingsScope_ReturnsFalse ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var stream = new MemoryStream ();
var source = "test.json";
var location = ConfigLocations.AppCurrent;
// Act
bool result = sourcesManager.Load (null, stream, source, location);
// Assert
Assert.False (result);
}
[Fact]
public void Load_WithValidStream_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
settingsScope ["Application.QuitKey"].PropertyValue = Key.Q.WithCtrl;
var json = """
{
"Application.QuitKey": "Ctrl+Z"
}
""";
var location = ConfigLocations.HardCoded;
var source = "stream";
var stream = new MemoryStream ();
var writer = new StreamWriter (stream);
writer.Write (json);
writer.Flush ();
stream.Position = 0;
// Act
bool result = sourcesManager.Load (settingsScope, stream, source, location);
// Assert
// Assert
Assert.True (result);
Assert.Equal (Key.Z.WithCtrl, settingsScope ["Application.QuitKey"].PropertyValue as Key);
Assert.Contains (source, sourcesManager.Sources.Values);
}
[Fact]
public void Load_WithInvalidJson_AddsJsonError ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
var invalidJson = "{ invalid json }";
var stream = new MemoryStream ();
var writer = new StreamWriter (stream);
writer.Write (invalidJson);
writer.Flush ();
stream.Position = 0;
var source = "test.json";
var location = ConfigLocations.AppCurrent;
// Act
bool result = sourcesManager.Load (settingsScope, stream, source, location);
// Assert
Assert.False (result);
// Assuming AddJsonError logs errors, verify the error was logged (mock or inspect logs if possible).
}
#endregion
#region Update (FilePath)
[Fact]
public void Load_WithNonExistentFile_AddsToSourcesAndReturnsTrue ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
var filePath = "nonexistent.json";
var location = ConfigLocations.AppCurrent;
// Act
bool result = sourcesManager.Load (settingsScope, filePath, location);
// Assert
Assert.True (result);
Assert.Contains (filePath, sourcesManager.Sources.Values);
}
[Fact]
public void Load_WithValidFile_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
settingsScope ["Application.QuitKey"].PropertyValue = Key.Q.WithCtrl;
var json = """
{
"Application.QuitKey": "Ctrl+Z"
}
""";
var source = Path.GetTempFileName ();
var location = ConfigLocations.HardCoded;
File.WriteAllText (source, json);
try
{
// Act
bool result = sourcesManager.Load (settingsScope, source, location);
// Assert
Assert.True (result);
Assert.Equal (Key.Z.WithCtrl, settingsScope ["Application.QuitKey"].PropertyValue as Key);
Assert.Contains (source, sourcesManager.Sources.Values);
}
finally
{
// Cleanup
File.Delete (source);
}
}
[Fact]
public void Load_WithIOException_RetriesAndFailsGracefully ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
var filePath = "locked.json";
var json = "{\"Application.UseSystemConsole\": true}";
File.WriteAllText (filePath, json);
var location = ConfigLocations.AppCurrent;
try
{
using FileStream fileStream = File.Open (filePath, FileMode.Open, FileAccess.Read, FileShare.None);
// Act
bool result = sourcesManager.Load (settingsScope, filePath, location);
// Assert
Assert.False (result);
}
finally
{
// Cleanup
File.Delete (filePath);
}
}
#endregion
#region Update (Json String)
[Fact]
public void Load_WithNullOrEmptyJson_ReturnsFalse ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
var source = "test.json";
var location = ConfigLocations.AppCurrent;
// Act
bool resultWithNull = sourcesManager.Load (settingsScope, json: null, source, location);
bool resultWithEmpty = sourcesManager.Load (settingsScope, string.Empty, source, location);
// Assert
Assert.False (resultWithNull);
Assert.False (resultWithEmpty);
}
[Fact]
public void Load_WithValidJson_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
settingsScope ["Application.QuitKey"].PropertyValue = Key.Q.WithCtrl;
var json = """
{
"Application.QuitKey": "Ctrl+Z"
}
""";
var source = "test.json";
var location = ConfigLocations.HardCoded;
// Act
bool result = sourcesManager.Load (settingsScope, json, source, location);
// Assert
Assert.True (result);
Assert.Equal (Key.Z.WithCtrl, settingsScope ["Application.QuitKey"].PropertyValue as Key);
Assert.Contains (source, sourcesManager.Sources.Values);
}
//[Fact]
//public void Update_WithValidJson_UpdatesThemeScope ()
//{
// // Arrange
// var sourcesManager = new SourcesManager ();
// var themeScope = new ThemeScope ();
// themeScope.LoadHardCodedDefaults ();
// themeScope ["Button.DefaultShadowStyle"].PropertyValue = ShadowStyle.Opaque;
// var json = """
// {
// "Button.DefaultShadowStyle": "None"
// }
// """;
// var source = "test.json";
// var location = ConfigLocations.HardCoded;
// // Act
// bool result = sourcesManager.Load (themeScope, json, source, location);
// // Assert
// Assert.True (result);
// Assert.Equal (Key.Z.WithCtrl, themeScope ["Application.QuitKey"].PropertyValue as Key);
// Assert.Contains (source, sourcesManager.Sources.Values);
//}
#endregion
#region Load
[Fact]
public void Load_WithNullResourceName_ReturnsFalse ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
settingsScope ["Application.QuitKey"].PropertyValue = Key.Q.WithCtrl;
var assembly = Assembly.GetExecutingAssembly ();
var location = ConfigLocations.AppResources;
// Act
bool result = sourcesManager.Load (settingsScope, assembly, null, location);
// Assert
Assert.False (result);
}
[Fact]
public void Load_WithValidResource_UpdatesSettingsScope ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
var assembly = Assembly.GetAssembly (typeof (ConfigurationManager));
var resourceName = "Terminal.Gui.Resources.config.json";
var location = ConfigLocations.LibraryResources;
// Act
bool result = sourcesManager.Load (settingsScope, assembly!, resourceName, location);
// Assert
Assert.True (result);
// Verify settingsScope is updated as expected
}
[Fact]
public void Load_Runtime_Overrides ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
var assembly = Assembly.GetAssembly (typeof (ConfigurationManager));
var resourceName = "Terminal.Gui.Resources.config.json";
var location = ConfigLocations.LibraryResources;
sourcesManager.Load (settingsScope, assembly!, resourceName, location);
Assert.Equal (Key.Esc, settingsScope ["Application.QuitKey"].PropertyValue);
var runtimeJson = """
{
"Application.QuitKey": "Ctrl+Z"
}
""";
var runtimeSource = "runtime.json";
var runtimeLocation = ConfigLocations.Runtime;
var runtimeStream = new MemoryStream ();
var writer = new StreamWriter (runtimeStream);
writer.Write (runtimeJson);
writer.Flush ();
runtimeStream.Position = 0;
// Act
bool result = sourcesManager.Load (settingsScope, runtimeStream, runtimeSource, runtimeLocation);
// Assert
Assert.True (result);
// Verify settingsScope is updated as expected
Assert.Equal (Key.Z.WithCtrl, settingsScope ["Application.QuitKey"].PropertyValue);
}
#endregion
#region ToJson and ToStream
[Fact]
public void ToJson_WithValidScope_ReturnsJsonString ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
settingsScope ["Application.QuitKey"].PropertyValue = Key.Q.WithCtrl;
// Act
string json = sourcesManager.ToJson (settingsScope);
// Assert
Assert.Contains ("""Application.QuitKey": "Ctrl+Q""", json);
}
[Fact]
public void ToStream_WithValidScope_ReturnsStream ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
settingsScope.LoadHardCodedDefaults ();
settingsScope ["Application.QuitKey"].PropertyValue = Key.Q.WithCtrl;
// Act
var stream = sourcesManager.ToStream (settingsScope);
// Assert
Assert.NotNull (stream);
stream.Position = 0;
var reader = new StreamReader (stream);
string json = reader.ReadToEnd ();
Assert.Contains ("""Application.QuitKey": "Ctrl+Q""", json);
}
#endregion
#region Sources Dictionary Tests
[Fact]
public void Sources_Dictionary_IsInitializedEmpty ()
{
// Arrange & Act
var sourcesManager = new SourcesManager ();
// Assert
Assert.NotNull (sourcesManager.Sources);
Assert.Empty (sourcesManager.Sources);
}
[Fact]
public void Load_WhenCalledMultipleTimes_MaintainsLastSourceForLocation ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
// Act - Update with first source for location
var firstSource = "first.json";
sourcesManager.Load (settingsScope, """{"Application.QuitKey": "Ctrl+A"}""", firstSource, ConfigLocations.Runtime);
// Update with second source for same location
var secondSource = "second.json";
sourcesManager.Load (settingsScope, """{"Application.QuitKey": "Ctrl+B"}""", secondSource, ConfigLocations.Runtime);
// Assert - Only the last source should be stored for the location
Assert.Single (sourcesManager.Sources);
Assert.Equal (secondSource, sourcesManager.Sources [ConfigLocations.Runtime]);
}
[Fact]
public void Load_WithDifferentLocations_AddsAllSourcesToCollection ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
ConfigLocations [] locations =
[
ConfigLocations.LibraryResources,
ConfigLocations.Runtime,
ConfigLocations.AppCurrent,
ConfigLocations.GlobalHome
];
// Act - Update with different sources for different locations
foreach (var location in locations)
{
var source = $"config-{location}.json";
sourcesManager.Load (settingsScope, """{"Application.QuitKey": "Ctrl+Z"}""", source, location);
}
// Assert
Assert.Equal (locations.Length, sourcesManager.Sources.Count);
foreach (var location in locations)
{
Assert.Contains (location, sourcesManager.Sources.Keys);
Assert.Equal ($"config-{location}.json", sourcesManager.Sources [location]);
}
}
[Fact]
public void Load_AddsResourceSourceToCollection ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
var assembly = Assembly.GetAssembly (typeof (ConfigurationManager));
var resourceName = "Terminal.Gui.Resources.config.json";
var location = ConfigLocations.LibraryResources;
// Act
bool result = sourcesManager.Load (settingsScope, assembly!, resourceName, location);
// Assert
Assert.True (result);
Assert.Contains (location, sourcesManager.Sources.Keys);
Assert.Equal ($"resource://[{assembly!.GetName ().Name}]/{resourceName}", sourcesManager.Sources [location]);
}
[Fact]
public void Load_WithNonExistentFileAndDifferentLocations_TracksAllSources ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
// Define multiple files and locations
var fileLocations = new Dictionary<string, ConfigLocations> (StringComparer.InvariantCultureIgnoreCase)
{
{ "file1.json", ConfigLocations.AppCurrent },
{ "file2.json", ConfigLocations.GlobalHome },
{ "file3.json", ConfigLocations.AppHome }
};
// Act
foreach (var pair in fileLocations)
{
sourcesManager.Load (settingsScope, pair.Key, pair.Value);
}
// Assert
Assert.Equal (fileLocations.Count, sourcesManager.Sources.Count);
foreach (var pair in fileLocations)
{
Assert.Contains (pair.Value, sourcesManager.Sources.Keys);
Assert.Equal (pair.Key, sourcesManager.Sources [pair.Value]);
}
}
[Fact]
public void Sources_IsPreservedAcrossOperations ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
// First operation - file update
var filePath = "testfile.json";
var location1 = ConfigLocations.AppCurrent;
sourcesManager.Load (settingsScope, filePath, location1);
// Second operation - json string update
var jsonSource = "jsonstring";
var location2 = ConfigLocations.Runtime;
sourcesManager.Load (settingsScope, """{"Application.QuitKey": "Ctrl+Z"}""", jsonSource, location2);
// Perform a stream operation
var streamSource = "streamdata";
var location3 = ConfigLocations.GlobalCurrent;
var stream = new MemoryStream ();
var writer = new StreamWriter (stream);
writer.Write ("""{"Application.QuitKey": "Ctrl+Z"}""");
writer.Flush ();
stream.Position = 0;
sourcesManager.Load (settingsScope, stream, streamSource, location3);
// Assert - all sources should be preserved
Assert.Equal (3, sourcesManager.Sources.Count);
Assert.Equal (filePath, sourcesManager.Sources [location1]);
Assert.Equal (jsonSource, sourcesManager.Sources [location2]);
Assert.Equal (streamSource, sourcesManager.Sources [location3]);
}
[Fact]
public void Sources_StaysConsistentWhenUpdateFails ()
{
// Arrange
var sourcesManager = new SourcesManager ();
var settingsScope = new SettingsScope ();
// Add one successful source
var validSource = "valid.json";
var validLocation = ConfigLocations.Runtime;
sourcesManager.Load (settingsScope, """{"Application.QuitKey": "Ctrl+Z"}""", validSource, validLocation);
try
{
// Configure to throw on errors
ConfigurationManager.ThrowOnJsonErrors = true;
// Act & Assert - attempt to update with invalid JSON
var invalidSource = "invalid.json";
var invalidLocation = ConfigLocations.AppCurrent;
var invalidJson = "{ invalid json }";
Assert.Throws<JsonException> (
() =>
sourcesManager.Load (settingsScope, invalidJson, invalidSource, invalidLocation));
// The valid source should still be there
Assert.Single (sourcesManager.Sources);
Assert.Equal (validSource, sourcesManager.Sources [validLocation]);
// The invalid source should not have been added
Assert.DoesNotContain (invalidLocation, sourcesManager.Sources.Keys);
}
finally
{
// Reset for other tests
ConfigurationManager.ThrowOnJsonErrors = false;
}
}
#endregion
}