Files
Terminal.Gui/Tests/UnitTests/Application/ApplicationTests.cs
Copilot b9f55a5a96 Fixes #4410, #4413, #4414, #4415 - MessageBox nullable, Clipboard refactor, fence for legacy/modern App, and makes internal classes thread safe. (#4411)
* Initial plan

* Change MessageBox to return nullable int instead of -1

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Initial plan

* Add fencing to prevent mixing Application models

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Fix fence logic to work with parallel tests

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* WIP: Fixing Application issues.

* Refactor error messages into constants

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Refactor ConfigurationProperty properties to use static backing fields and raise events

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Reset static Application properties in ResetStateStatic

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Refactor tests to decouple from global Application state

Commented out `driver ??= Application.Driver` assignments in
`DriverAssert` to prevent automatic global driver assignment.
Removed `Application.ResetState(true)` calls and commented out
state validation assertions in `GlobalTestSetup` to reduce
dependency on global state.

Reintroduced `ApplicationForceDriverTests` and
`ApplicationModelFencingTests` to validate `ForceDriver` behavior
and ensure proper handling of legacy and modern Application
models. Skipped certain `ToAnsiTests` that rely on `Application`.

Removed direct `Application.Driver` assignments in
`ViewDrawingClippingTests` and `ViewDrawingFlowTests`.
Performed general cleanup of redundant code and unused imports
to simplify the codebase.

* WIP: Fixed Parallel tests; non-Parallel still broken

Refactor application model usage tracking

Refactored `ApplicationModelUsage` into a public enum in the new `Terminal.Gui.App` namespace, making it accessible across the codebase. Replaced the private `_modelUsage` field in `ApplicationImpl` with a public static `ModelUsage` property to improve clarity and accessibility.

Renamed error message constants for consistency and updated methods like `SetInstance` and `MarkInstanceBasedModelUsed` to use the new `ModelUsage` property. Removed the private `ApplicationModelUsage` enum from `ApplicationImpl`.

Updated test cases to use `ApplicationImpl.Instance` instead of `Application.Create` to enforce the legacy static model. Skipped obsolete tests in `ApplicationForceDriverTests` and added null checks in `DriverAssert` and `SelectorBase` to handle edge cases.

Commented out an unused line in `WindowsOutput` and made general improvements to code readability, maintainability, and consistency.

* WIP: Almost there!

Refactored tests and code to align with the modern instance-based
application model. Key changes include:

- Disabled Sixel rendering in `OutputBase.cs` due to dependency on
  legacy static `Application` object.
- Hardcoded `force16Colors` to `false` in `WindowsOutput.cs` with a
  `BUGBUG` note.
- Updated `ApplicationImplTests` to use `ApplicationImpl.SetInstance`
  and return `ApplicationImpl.Instance`.
- Refactored `ApplicationModelFencingTests` to use `Application.Create()`
  and added `ResetModelUsageTracking()` for model switching.
- Removed legacy `DriverTests` and reintroduced updated versions with
  cross-platform driver tests.
- Reverted `ArrangementTests` and `ShortcutTests` to use legacy static
  `ApplicationImpl.Instance`.
- Reintroduced driver tests in `DriverTests.cs` with modern `Application.Create()`
  and added `TestTop` for driver content verification.
- General cleanup, including removal of outdated code and addition of
  `BUGBUG` notes for temporary workarounds.

* Fixed all modelusage bugs?

Replaced static `Application` references with instance-based `App`
context across the codebase. Updated calls to `Application.RequestStop()`
and `Application.Screen` to use `App?.RequestStop()` and `App?.Screen`
for better encapsulation and flexibility.

Refactored test infrastructure to align with the new context, including
reintroducing `FakeApplicationFactory` and `FakeApplicationLifecycle`
for testing purposes. Improved logging, error handling, and test
clarity by adding `logWriter` support and simplifying test setup.

Removed redundant or obsolete code, such as `NetSequences` and the old
`FakeApplicationFactory` implementation. Updated documentation to
reflect the new `IApplication.RequestStop()` usage.

* merged

* Refactor KeyboardImpl and modernize MessageBoxTests

Refactored the `KeyboardImpl` class to remove hardcoded default key
values, replacing them with uninitialized fields for dynamic
configuration. Updated key binding logic to use `ReplaceCommands`
instead of `Add` for better handling of dynamic changes. Removed
unnecessary `KeyBindings.Clear()` calls to avoid side effects.

Rewrote `MessageBoxTests.cs` to improve readability, maintainability,
and adherence to modern C# standards. Enabled nullable reference
checks, updated the namespace, and restructured test methods for
clarity. Marked non-functional tests with `[Theory(Skip)]` and
improved test organization with parameterized inputs.

Enhanced test assertions, lifecycle handling, and error handling
across the test suite. Updated `UICatalog_AboutBox` to use multiline
string literals for expected outputs. These changes improve the
overall maintainability and flexibility of the codebase.

* Atempt to fix windows only CI/CD Unit tests failure

Refactor Application lifecycle and test cleanup

Refactored the `Application` class to phase out legacy static
properties `SessionStack` and `TopRunnable` from
`Application.Current.cs`. These were reintroduced in a new file
`Application.TopRunnable.cs` for better modularity, while retaining
their `[Obsolete]` status.

Updated `ApplicationPopoverTests.cs` to replace
`Application.ResetState(true)` with `Application.Shutdown()` for
consistent application state cleanup. Added explicit cleanup for
`Application.TopRunnable` in relevant test cases to ensure proper
resource management.

Adjusted namespaces and `using` directives to support the new
structure. These changes improve code organization and align with
updated application lifecycle management practices.

* Fixes #<Issue> - Dispose TopRunnable in cleanup logic

Updated the `finally` block in `ApplicationPopoverTests` to dispose of the `Application.TopRunnable` object if it is not null, ensuring proper resource cleanup. Previously, the property was being set to `null` without disposal. The `Application.Shutdown()` call remains unchanged.

* Improve thread safety, reduce static dependencies, and align the codebase with the updated `IApplication` interface.

Refactored the `MainThreadId` property to improve encapsulation:
- Updated `Application.MainThreadId` to use `ApplicationImpl.Instance` directly.
- Added `MainThreadId` to `ApplicationImpl` and `IApplication`.
- Removed redundant `MainThreadId` from `ApplicationImpl.Run.cs`.

Updated `EnqueueMouseEvent` to include an `IApplication?` parameter:
- Modified `FakeInputProcessor`, `InputProcessorImpl`, and `WindowsInputProcessor` to support the new parameter.
- Updated `IInputProcessor` interface to reflect the new method signature.
- Adjusted `GuiTestContext` and `EnqueueMouseEventTests` to pass `IApplication` where required.

Improved test coverage and code maintainability:
- Added test cases for negative positions and empty mouse events.
- Commented out legacy code in `GraphView` and `FakeDriverBase`.
- Enhanced readability in `EnqueueMouseEventTests`.

These changes improve thread safety, reduce static dependencies, and align the codebase with the updated `IApplication` interface.

* Fixed more bugs.

Enabled nullable reference types across multiple files to improve code safety. Refactored and modularized test classes, improving readability and maintainability. Removed outdated test cases and added new tests for edge cases, including culture-specific and non-Gregorian calendar handling.

Addressed timeout issues in `ScenarioTests` with a watchdog timer and improved error handling. Updated `ApplicationImplTests` to use instance fields instead of static references for better test isolation. Refactored `ScenarioTests` to dynamically load and test all UI Catalog scenarios, with macOS-specific skips for known issues.

Aligned `MessageBox.Query` calls with updated API signatures. Performed general code cleanup, including removing unused directives, improving formatting, and consolidating repetitive logic into helper methods.

* Made the `InputBindings<TEvent, TBinding>` class thread-safe by replacing the internal `Dictionary<TEvent, TBinding>` with `ConcurrentDictionary<TEvent, TBinding>`. This fixes parallel test failures where "Collection was modified; enumeration operation may not execute" exceptions were thrown.

## Changes Made

### 1. InputBindings.cs
- **File**: `Terminal.Gui/Input/InputBindings.cs`
- **Change**: Replaced `Dictionary` with `ConcurrentDictionary`
- **Key modifications**:
  - Changed `_bindings` from `Dictionary<TEvent, TBinding>` to `ConcurrentDictionary<TEvent, TBinding>`
  - Updated `Add()` methods to use `TryAdd()` instead of checking with `TryGet()` then `Add()`
  - Updated `Remove()` to use `TryRemove()` (no need to check existence first)
  - Updated `ReplaceCommands()` to use `ContainsKey()` instead of `TryGet()`
  - Added `.ToList()` to `GetAllFromCommands()` to create a snapshot for safe enumeration
  - Added comment explaining that `ConcurrentDictionary` provides snapshot enumeration in `GetBindings()`
  - Added `.ToArray()` to `Clear(Command[])` to create snapshot before iteration

### 2. Thread Safety Test Suite
- **File**: `Tests/UnitTestsParallelizable/Input/InputBindingsThreadSafetyTests.cs`
- **New file** with comprehensive thread safety tests:
  - `Add_ConcurrentAccess_NoExceptions` - Tests concurrent additions
  - `GetBindings_DuringConcurrentModification_NoExceptions` - Tests enumeration during modifications
  - `TryGet_ConcurrentAccess_ReturnsConsistentResults` - Tests concurrent reads
  - `Clear_ConcurrentAccess_NoExceptions` - Tests concurrent clearing
  - `Remove_ConcurrentAccess_NoExceptions` - Tests concurrent removals
  - `Replace_ConcurrentAccess_NoExceptions` - Tests concurrent replacements
  - `GetAllFromCommands_DuringModification_NoExceptions` - Tests LINQ queries during modifications
  - `MixedOperations_ConcurrentAccess_NoExceptions` - Tests mixed operations (add/read/remove)
  - `KeyBindings_ConcurrentAccess_NoExceptions` - Tests actual `KeyBindings` class
  - `MouseBindings_ConcurrentAccess_NoExceptions` - Tests actual `MouseBindings` class

## Benefits of ConcurrentDictionary Approach

1. **Lock-Free Reads**: Most read operations don't require locks, improving performance
2. **Snapshot Enumeration**: Built-in support for safe enumeration during concurrent modifications
3. **Simplified Code**: No need for explicit `lock` statements or lock objects
4. **Better Scalability**: Multiple threads can read/write simultaneously
5. **No "Collection was modified" Exceptions**: Enumeration creates a snapshot

## Performance Characteristics

- **Read Operations**: Lock-free, very fast
- **Write Operations**: Uses fine-grained locking internally, minimal contention
- **Memory Overhead**: Slightly higher than `Dictionary` but negligible in practice
- **Enumeration**: Creates a snapshot, safe for concurrent modifications

## Test Results

- **Original failing test now passes**: `ApplicationImplTests.Init_CreatesKeybindings`
- **10 new thread safety tests**: All passing
- **All 11,741 parallelizable tests**: All passing (11,731 passed, 10 skipped)
- **All 1,779 non-parallelizable tests**: All passing (1,762 passed, 17 skipped)
- **No compilation errors**: Clean build with no xUnit1031 warnings (suppressed with pragmas)

## Verification

The original failure was:
```
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
```

This occurred in parallelizable tests when multiple threads accessed `KeyBindings.GetBindings()` simultaneously. The `ConcurrentDictionary` implementation resolves this by providing thread-safe operations and snapshot enumeration.

## Notes

- The xUnit1031 warnings about using `Task.WaitAll` instead of `async/await` have been suppressed with `#pragma warning disable xUnit1031` directives, as these are intentional blocking operations in stress tests that test concurrent scenarios
- All existing functionality is preserved; this is a drop-in replacement
- No changes to public API surface
- Existing tests continue to pass

* Make InputBindings and KeyboardImpl thread-safe for concurrent access

Replace Dictionary with ConcurrentDictionary in InputBindings<TEvent, TBinding>
and KeyboardImpl to enable safe parallel test execution and multi-threaded usage.

Changes:
- InputBindings: Replace Dictionary with ConcurrentDictionary for _bindings
- InputBindings: Make Replace() atomic using AddOrUpdate instead of Remove+Add
- InputBindings: Make ReplaceCommands() atomic using AddOrUpdate
- InputBindings: Add IsValid() check to both Add() overloads
- InputBindings: Add defensive .ToList()/.ToArray() for safe LINQ enumeration
- KeyboardImpl: Replace Dictionary with ConcurrentDictionary for _commandImplementations
- KeyboardImpl: Change AddKeyBindings() to use ReplaceCommands for idempotent initialization
- Add 10 comprehensive thread safety tests for InputBindings
- Add 9 comprehensive thread safety tests for KeyboardImpl

The ConcurrentDictionary implementation provides:
- Lock-free reads for better performance under concurrent access
- Atomic operations for Replace/ReplaceCommands preventing race conditions
- Snapshot enumeration preventing "Collection was modified" exceptions
- No breaking API changes - maintains backward compatibility

All 11,750 parallelizable tests pass (11,740 passed, 10 skipped).

Fixes race conditions that caused ApplicationImplTests.Init_CreatesKeybindings
to fail intermittently during parallel test execution.

* Decouple ApplicationImpl from Application static props

Removed initialization of `Force16Colors` and `ForceDriver`
from `Application` static properties in the `ApplicationImpl`
constructor. The class still subscribes to the
`Force16ColorsChanged` and `ForceDriverChanged` events, but
no longer sets initial values for these properties. This
change simplifies the constructor and reduces coupling
between `ApplicationImpl` and `Application`.

* Refactored keyboard initialization in `ApplicationImpl` to use `Application` static properties for default key assignments, ensuring synchronization with pre-`Init()` changes. Improved `KeyboardImpl` initialization to avoid premature `ApplicationImpl.Instance` access, enhancing testability.

Standardized constant naming conventions and improved code readability in thread safety tests for `KeyboardImpl` and `InputBindings`. Updated `TestInputBindings` implementation for clarity and conciseness.

Applied consistent code style improvements across files, including spacing, formatting, and variable naming, to enhance maintainability and readability.

* Fix race conditions in parallel tests - thread-safe ApplicationImpl and KeyboardImpl

Fixes intermittent failures in parallel tests caused by three separate race conditions:

1. **KeyboardImpl constructor race condition**
   - Constructor was accessing Application.QuitKey/ArrangeKey/etc which triggered
     ApplicationImpl.Instance getter, setting ModelUsage=LegacyStatic before
     Application.Create() was called
   - Changed constructor to initialize keys with hard-coded defaults instead
   - Added synchronization from Application static properties during Init()

2. **InputBindings.Replace() race condition**
   - Between GetOrAdd(oldEventArgs) and AddOrUpdate(newEventArgs), another thread
     could modify bindings, causing stale data to overwrite valid bindings
   - Added early return for same-key case (oldEventArgs == newEventArgs)
   - Kept atomic operations with proper updateValueFactory handling
   - Added detailed thread-safety documentation

3. **ApplicationImpl model usage fence checks race condition**
   - Two threads calling Init() simultaneously could both pass fence checks before
     either set ModelUsage, allowing improper model mixing
   - Added _modelUsageLock for thread-safe synchronization
   - Made all ModelUsage operations atomic (Instance getter, SetInstance,
     MarkInstanceBasedModelUsed, ResetModelUsageTracking, Init fence checks)

**Files Changed:**
- Terminal.Gui/App/ApplicationImpl.cs - Added _modelUsageLock, made all ModelUsage
  access thread-safe
- Terminal.Gui/App/ApplicationImpl.Lifecycle.cs - Thread-safe fence checks in Init(),
  sync keyboard keys from Application properties
- Terminal.Gui/App/Keyboard/KeyboardImpl.cs - Fixed constructor to not trigger
  ApplicationImpl.Instance
- Terminal.Gui/Input/InputBindings.cs - Fixed Replace() race condition with proper
  atomic operations

**Testing:**
- All 11 ApplicationImplTests pass
- All 9 KeyboardImplThreadSafetyTests pass
- All 10 InputBindingsThreadSafetyTests pass
- No more intermittent "Cannot use modern instance-based model after using legacy
  static Application model" errors in parallel test execution

The root cause was KeyboardImpl constructor accessing Application static properties
during object creation, which would lazily initialize ApplicationImpl.Instance and
set the wrong ModelUsage before Application.Create() could mark it as InstanceBased.

* Warning cleanup

* docs: Add comprehensive MessageBox and Clipboard API documentation

- Updated MessageBox class docs with nullable return value explanation
- Created docfx/docs/messagebox-clipboard-changes-v2.md migration guide
- Updated migratingfromv1.md with quick links to major changes
- Created PR-SUMMARY.md documenting all changes
- Added examples for both instance-based and legacy patterns
- Documented application model fencing and thread safety improvements

The documentation covers:
• MessageBox nullable int? returns (null = cancelled)
• Clipboard refactoring from static to instance-based
• Application model usage fencing to prevent pattern mixing
• Thread safety improvements in KeyboardImpl and InputBindings
• Complete migration guide with code examples
• Benefits and rationale for all changes

* Refactor static properties to use backing fields

Refactored static properties in multiple classes (`Button`,
`CheckBox`, `Dialog`, `FrameView`, `MessageBox`, `StatusBar`,
and `Window`) to use private backing fields for better
encapsulation and configurability. Default values are now
stored in private static fields, allowing overrides via
configuration files (e.g., `Resources/config.json`).

Updated property definitions to use `get`/`set` accessors
interacting with the backing fields. Retained the
`[ConfigurationProperty]` attribute to ensure runtime
configurability.

Removed redundant code, improved XML documentation, adjusted
namespace declarations for consistency, and performed general
code cleanup to enhance readability and maintainability.

* Fix Windows-only parallel test failure by preventing ConfigurationManager from triggering ApplicationImpl.Instance

Problem:
`MessageBoxTests.Location_And_Size_Correct` was failing only on Windows in parallel tests with:
System.InvalidOperationException: Cannot use modern instance-based model (Application.Create)
after using legacy static Application model (Application.Init/ApplicationImpl.Instance).

Root Cause (maybe):
View classes (MessageBox, Dialog, Window, Button, CheckBox, FrameView, StatusBar) had
`[ConfigurationProperty]` decorated auto-properties with inline initializers. When
ConfigurationManager's module initializer scanned assemblies using reflection, accessing
these auto-properties could trigger lazy initialization of other static members, which in
some cases indirectly referenced `ApplicationImpl.Instance`, marking the model as "legacy"
before parallel tests called `Application.Create()`.

Solution:
Converted all `[ConfigurationProperty]` auto-properties in View classes to use private
backing fields with explicit getters/setters, matching the pattern used by `Application.QuitKey`.
This prevents any code execution during reflection-based property discovery.

Files Changed:
- Terminal.Gui/Views/MessageBox.cs - 4 properties converted
- Terminal.Gui/Views/Dialog.cs - 6 properties converted
- Terminal.Gui/Views/Window.cs - 2 properties converted
- Terminal.Gui/Views/Button.cs - 2 properties converted
- Terminal.Gui/Views/CheckBox.cs - 1 property converted
- Terminal.Gui/Views/FrameView.cs - 1 property converted
- Terminal.Gui/Views/StatusBar.cs - 1 property converted

Test Reorganization:
- Moved `ConfigurationManagerTests.GetConfigPropertiesByScope_Gets` from UnitTestsParallelizable
  to UnitTests (defines custom ConfigurationProperty which affects global state)
- Moved `SourcesManagerTests.Sources_StaysConsistentWhenUpdateFails` from UnitTestsParallelizable
  to UnitTests (modifies static ConfigurationManager.ThrowOnJsonErrors property)

Best Practice:
All `[ConfigurationProperty]` decorated static properties should use private backing fields
to avoid triggering lazy initialization during ConfigurationManager's module initialization.

Fixes: Windows-only parallel test failure in MessageBoxTests

* Add thread-safety to CollectionNavigator classes

- Add lock-based synchronization to CollectionNavigatorBase for _searchString and _lastKeystroke fields
- Add lock-based synchronization to CollectionNavigator for Collection property access
- Protect ElementAt and GetCollectionLength methods with locks
- Add 6 comprehensive thread-safety tests covering:
  - Concurrent SearchString access
  - Concurrent Collection property access
  - Concurrent navigation operations (50 parallel tasks)
  - Concurrent collection modification with readers/writers
  - Concurrent search string changes
  - Stress test with 100 tasks × 1000 operations each

All tests pass (31/31) including new thread-safety tests.

The implementation uses lock-based synchronization rather than concurrent collections because:
- IList interface is not thread-safe by design
- CollectionNavigator is internal and used by UI components (ListView/TreeView)
- Matches existing Terminal.Gui patterns (Scope<T>, ConfigProperty)
- Provides simpler and more predictable behavior

Fixes thread-safety issues when CollectionNavigator is accessed from multiple threads.

* cleanup

* Run parallel unit tests 10 times with varying parallelization to expose concurrency issues

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Fix parallel unit tests workflow - use proper xUnit parallelization parameters

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Fix environment variable reference in workflow - use proper bash syntax

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Run parallel tests 10 times sequentially instead of matrix expansion

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Make ConfigurationManager thread-safe - use ConcurrentDictionary and add locks

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Add Debug.Fail to detect legacy Application usage in parallelizable tests

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Move ScrollSliderTests to UnitTests project - they access legacy Application model

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Revert ScrollSliderTests move and document root cause analysis

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Remove Debug.Fail and move ScrollSliderTests to UnitTests project

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Re-add Debug.Fail to detect legacy Application usage in parallelizable tests

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Refactor tests and improve parallelization support

Commented out `Debug.Fail` statements in `Application.Lifecycle.cs`
and `ApplicationImpl.cs` to prevent interruptions during parallel
tests. Refactored `ToString` in `ApplicationImpl.cs` to use an
expression-bodied member and removed unused imports.

Rewrote tests in `ClipRegionTests.cs` and `ScrollSliderTests.cs`
to remove global state dependencies and migrated them to the
`UnitTests_Parallelizable` namespace. Enabled nullable annotations
and updated assertions for clarity and modern patterns. Improved
test coverage by adding scenarios for clamping, layout, and size
calculations.

Updated `README.md` to include `[SetupFakeApplication]` in the
list of patterns that block parallelization and clarified migration
guidelines. Replaced `[SetupFakeDriver]` with `[SetupFakeApplication]`
in examples.

Added `<Folder Include="Drivers\" />` to `UnitTests.csproj` for
better organization. Adjusted test project references to reflect
test migration. Enhanced test output validation in `ScrollSliderTests.cs`.

Removed redundant test cases and improved documentation to align
with modern C# practices and ensure maintainability.

* marked as a "TODO" for potential future configurability.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: tig <585482+tig@users.noreply.github.com>
Co-authored-by: Tig <tig@users.noreply.github.com>
2025-11-25 06:36:21 -08:00

938 lines
29 KiB
C#

#nullable enable
using System.Diagnostics;
using Xunit.Abstractions;
using static Terminal.Gui.Configuration.ConfigurationManager;
// Alias Console to MockConsole so we don't accidentally use Console
namespace UnitTests.ApplicationTests;
public class ApplicationTests
{
public ApplicationTests (ITestOutputHelper output)
{
_output = output;
#if DEBUG_IDISPOSABLE
View.EnableDebugIDisposableAsserts = true;
View.Instances.Clear ();
SessionToken.Instances.Clear ();
#endif
}
private readonly ITestOutputHelper _output;
[Fact]
public void AddTimeout_Fires ()
{
IApplication app = ApplicationImpl.Instance; // Force legacy
app.Init ("fake");
uint timeoutTime = 100;
var timeoutFired = false;
// Setup a timeout that will fire
app.AddTimeout (
TimeSpan.FromMilliseconds (timeoutTime),
() =>
{
timeoutFired = true;
// Return false so the timer does not repeat
return false;
}
);
// The timeout has not fired yet
Assert.False (timeoutFired);
// Block the thread to prove the timeout does not fire on a background thread
Thread.Sleep ((int)timeoutTime * 2);
Assert.False (timeoutFired);
app.StopAfterFirstIteration = true;
app.Run<Toplevel> ().Dispose ();
// The timeout should have fired
Assert.True (timeoutFired);
app.Shutdown ();
}
[Fact]
[SetupFakeApplication]
public void Begin_Null_Toplevel_Throws ()
{
// Test null Toplevel
Assert.Throws<ArgumentNullException> (() => Application.Begin (null!));
}
[Fact]
[SetupFakeApplication]
public void Begin_Sets_Application_Top_To_Console_Size ()
{
Assert.Null (Application.TopRunnable);
Application.Driver!.SetScreenSize (80, 25);
Toplevel top = new ();
Application.Begin (top);
Assert.Equal (new (0, 0, 80, 25), Application.TopRunnable!.Frame);
Application.Driver!.SetScreenSize (5, 5);
Assert.Equal (new (0, 0, 5, 5), Application.TopRunnable!.Frame);
top.Dispose ();
}
[Fact]
[SetupFakeApplication]
public void End_And_Shutdown_Should_Not_Dispose_ApplicationTop ()
{
Assert.Null (Application.TopRunnable);
SessionToken rs = Application.Begin (new ());
Application.TopRunnable!.Title = "End_And_Shutdown_Should_Not_Dispose_ApplicationTop";
Assert.Equal (rs.Toplevel, Application.TopRunnable);
Application.End (rs);
#if DEBUG_IDISPOSABLE
Assert.True (rs.WasDisposed);
Assert.False (Application.TopRunnable!.WasDisposed); // Is true because the rs.Toplevel is the same as Application.TopRunnable
#endif
Assert.Null (rs.Toplevel);
Toplevel top = Application.TopRunnable;
#if DEBUG_IDISPOSABLE
Exception exception = Record.Exception (Application.Shutdown);
Assert.NotNull (exception);
Assert.False (top.WasDisposed);
top.Dispose ();
Assert.True (top.WasDisposed);
#endif
}
[Fact]
[SetupFakeApplication]
public void Init_Begin_End_Cleans_Up ()
{
// Start stopwatch
var stopwatch = new Stopwatch ();
stopwatch.Start ();
SessionToken? sessionToken = null;
EventHandler<SessionTokenEventArgs> newSessionTokenFn = (s, e) =>
{
Assert.NotNull (e.State);
sessionToken = e.State;
};
Application.SessionBegun += newSessionTokenFn;
var topLevel = new Toplevel ();
SessionToken rs = Application.Begin (topLevel);
Assert.NotNull (rs);
Assert.NotNull (sessionToken);
Assert.Equal (rs, sessionToken);
Assert.Equal (topLevel, Application.TopRunnable);
Application.SessionBegun -= newSessionTokenFn;
Application.End (sessionToken);
Assert.NotNull (Application.TopRunnable);
Assert.NotNull (Application.Driver);
topLevel.Dispose ();
// Stop stopwatch
stopwatch.Stop ();
_output.WriteLine ($"Load took {stopwatch.ElapsedMilliseconds} ms");
}
[Fact]
public void Init_KeyBindings_Are_Not_Reset ()
{
Debug.Assert (!IsEnabled);
try
{
// arrange
ThrowOnJsonErrors = true;
Application.QuitKey = Key.Q;
Assert.Equal (Key.Q, Application.QuitKey);
Application.Init ("fake");
Assert.Equal (Key.Q, Application.QuitKey);
}
finally
{
Application.ResetState ();
}
}
[Fact]
public void Init_NoParam_ForceDriver_Works ()
{
Application.ForceDriver = "Fake";
Application.Init ();
Assert.Equal ("fake", Application.Driver!.GetName ());
Application.ResetState ();
}
[Fact]
public void Init_Null_Driver_Should_Pick_A_Driver ()
{
Application.Init ();
Assert.NotNull (Application.Driver);
Application.Shutdown ();
}
[Fact]
public void Init_ResetState_Resets_Properties ()
{
ThrowOnJsonErrors = true;
// For all the fields/properties of Application, check that they are reset to their default values
// Set some values
Application.Init (driverName: "fake");
// Application.IsInitialized = true;
// Reset
Application.ResetState ();
CheckReset ();
// Set the values that can be set
Application.Initialized = true;
Application.MainThreadId = 1;
//Application._topLevels = new List<Toplevel> ();
Application.CachedViewsUnderMouse.Clear ();
//Application.SupportedCultures = new List<CultureInfo> ();
Application.Force16Colors = true;
//Application.ForceDriver = "driver";
Application.StopAfterFirstIteration = true;
Application.PrevTabGroupKey = Key.A;
Application.NextTabGroupKey = Key.B;
Application.QuitKey = Key.C;
Application.KeyBindings.Add (Key.D, Command.Cancel);
Application.CachedViewsUnderMouse.Clear ();
//Application.WantContinuousButtonPressedView = new View ();
// Mouse
Application.LastMousePosition = new Point (1, 1);
Application.ResetState ();
CheckReset ();
ThrowOnJsonErrors = false;
return;
void CheckReset ()
{
// Check that all fields and properties are set to their default values
// Public Properties
Assert.Null (Application.TopRunnable);
Assert.Null (Application.Mouse.MouseGrabView);
// Don't check Application.ForceDriver
// Assert.Empty (Application.ForceDriver);
// Don't check Application.Force16Colors
//Assert.False (Application.Force16Colors);
Assert.Null (Application.Driver);
Assert.False (Application.StopAfterFirstIteration);
// Commented out because if CM changed the defaults, those changes should
// persist across Inits.
//Assert.Equal (Key.Tab.WithShift, Application.PrevTabKey);
//Assert.Equal (Key.Tab, Application.NextTabKey);
//Assert.Equal (Key.F6.WithShift, Application.PrevTabGroupKey);
//Assert.Equal (Key.F6, Application.NextTabGroupKey);
//Assert.Equal (Key.Esc, Application.QuitKey);
// Internal properties
Assert.False (Application.Initialized);
Assert.Equal (Application.GetSupportedCultures (), Application.SupportedCultures);
Assert.Equal (Application.GetAvailableCulturesFromEmbeddedResources (), Application.SupportedCultures);
Assert.Null (Application.MainThreadId);
Assert.Empty (Application.SessionStack);
Assert.Empty (Application.CachedViewsUnderMouse);
// Mouse
// Do not reset _lastMousePosition
//Assert.Null (Application._lastMousePosition);
// Navigation
// Assert.Null (Application.Navigation);
// Popover
//Assert.Null (Application.Popover);
// Events - Can't check
//Assert.Null (GetEventSubscribers (typeof (Application), "InitializedChanged"));
//Assert.Null (GetEventSubscribers (typeof (Application), "SessionBegun"));
//Assert.Null (GetEventSubscribers (typeof (Application), "Iteration"));
//Assert.Null (GetEventSubscribers (typeof (Application), "ScreenChanged"));
//Assert.Null (GetEventSubscribers (typeof (Application.Mouse), "MouseEvent"));
//Assert.Null (GetEventSubscribers (typeof (Application.Keyboard), "KeyDown"));
//Assert.Null (GetEventSubscribers (typeof (Application.Keyboard), "KeyUp"));
}
}
[Fact]
public void Init_Shutdown_Cleans_Up ()
{
// Verify initial state is per spec
//Pre_Init_State ();
Application.Init ("fake");
// Verify post-Init state is correct
//Post_Init_State ();
Application.Shutdown ();
// Verify state is back to initial
//Pre_Init_State ();
#if DEBUG_IDISPOSABLE
// Validate there are no outstanding Responder-based instances
// after a scenario was selected to run. This proves the main UI Catalog
// 'app' closed cleanly.
Assert.Empty (View.Instances);
#endif
}
[Fact]
public void Init_Shutdown_Fire_InitializedChanged ()
{
var initialized = false;
var shutdown = false;
Application.InitializedChanged += OnApplicationOnInitializedChanged;
Application.Init (driverName: "fake");
Assert.True (initialized);
Assert.False (shutdown);
Application.Shutdown ();
Assert.True (initialized);
Assert.True (shutdown);
Application.InitializedChanged -= OnApplicationOnInitializedChanged;
return;
void OnApplicationOnInitializedChanged (object? s, EventArgs<bool> a)
{
if (a.Value)
{
initialized = true;
}
else
{
shutdown = true;
}
}
}
[Fact]
[SetupFakeApplication]
public void Init_Unbalanced_Throws ()
{
Assert.Throws<InvalidOperationException> (() =>
Application.Init ("fake")
);
}
[Fact]
[SetupFakeApplication]
public void Init_Unbalanced_Throws2 ()
{
// Now try the other way
Assert.Throws<InvalidOperationException> (() => Application.Init ("fake"));
}
[Fact]
public void Init_WithoutTopLevelFactory_Begin_End_Cleans_Up ()
{
Application.StopAfterFirstIteration = true;
// NOTE: Run<T>, when called after Init has been called behaves differently than
// when called if Init has not been called.
Toplevel topLevel = new ();
Application.Init ("fake");
SessionToken? sessionToken = null;
EventHandler<SessionTokenEventArgs> newSessionTokenFn = (s, e) =>
{
Assert.NotNull (e.State);
sessionToken = e.State;
};
Application.SessionBegun += newSessionTokenFn;
SessionToken rs = Application.Begin (topLevel);
Assert.NotNull (rs);
Assert.NotNull (sessionToken);
Assert.Equal (rs, sessionToken);
Assert.Equal (topLevel, Application.TopRunnable);
Application.SessionBegun -= newSessionTokenFn;
Application.End (sessionToken);
Assert.NotNull (Application.TopRunnable);
Assert.NotNull (Application.Driver);
topLevel.Dispose ();
Application.Shutdown ();
Assert.Null (Application.TopRunnable);
Assert.Null (Application.Driver);
}
[Fact]
[SetupFakeApplication]
public void Internal_Properties_Correct ()
{
Assert.True (Application.Initialized);
Assert.Null (Application.TopRunnable);
SessionToken rs = Application.Begin (new ());
Assert.Equal (Application.TopRunnable, rs.Toplevel);
Assert.Null (Application.Mouse.MouseGrabView); // public
Application.TopRunnable!.Dispose ();
}
// Invoke Tests
// TODO: Test with threading scenarios
[Fact]
[SetupFakeApplication]
public void Invoke_Adds_Idle ()
{
Toplevel top = new ();
SessionToken rs = Application.Begin (top);
var actionCalled = 0;
Application.Invoke ((_) => { actionCalled++; });
Application.TimedEvents!.RunTimers ();
Assert.Equal (1, actionCalled);
top.Dispose ();
}
[Fact]
public void Run_Iteration_Fires ()
{
var iteration = 0;
Application.Init ("fake");
Application.Iteration += Application_Iteration;
Application.Run<Toplevel> ().Dispose ();
Application.Iteration -= Application_Iteration;
Assert.Equal (1, iteration);
Application.Shutdown ();
return;
void Application_Iteration (object? sender, EventArgs<IApplication?> e)
{
if (iteration > 0)
{
Assert.Fail ();
}
iteration++;
Application.RequestStop ();
}
}
[Fact]
[SetupFakeApplication]
public void Screen_Size_Changes ()
{
IDriver? driver = Application.Driver;
Application.Driver!.SetScreenSize (80, 25);
Assert.Equal (new (0, 0, 80, 25), driver!.Screen);
Assert.Equal (new (0, 0, 80, 25), Application.Screen);
// TODO: Should not be possible to manually change these at whim!
driver.Cols = 100;
driver.Rows = 30;
// IDriver.Screen isn't assignable
//driver.Screen = new (0, 0, driver.Cols, Rows);
Application.Driver!.SetScreenSize (100, 30);
Assert.Equal (new (0, 0, 100, 30), driver.Screen);
// Assert does not make sense
// Assert.NotEqual (new (0, 0, 100, 30), Application.Screen);
// Assert.Equal (new (0, 0, 80, 25), Application.Screen);
Application.Screen = new (0, 0, driver.Cols, driver.Rows);
Assert.Equal (new (0, 0, 100, 30), driver.Screen);
}
[Fact]
public void Shutdown_Alone_Does_Nothing () { Application.Shutdown (); }
//[Fact]
//public void InitState_Throws_If_Driver_Is_Null ()
//{
// Assert.Throws<ArgumentNullException> (static () => Application.SubscribeDriverEvents ());
//}
#region RunTests
[Fact]
[SetupFakeApplication]
public void Run_T_After_InitWithDriver_with_TopLevel_Does_Not_Throws ()
{
Application.StopAfterFirstIteration = true;
// Run<Toplevel> when already initialized or not with a Driver will not throw (because Window is derived from Toplevel)
// Using another type not derived from Toplevel will throws at compile time
Application.Run<Window> ();
Assert.True (Application.TopRunnable is Window);
Application.TopRunnable!.Dispose ();
}
[Fact]
public void Run_T_After_InitWithDriver_with_TopLevel_and_Driver_Does_Not_Throws ()
{
Application.StopAfterFirstIteration = true;
// Run<Toplevel> when already initialized or not with a Driver will not throw (because Window is derived from Toplevel)
// Using another type not derived from Toplevel will throws at compile time
Application.Run<Window> (null, "fake");
Assert.True (Application.TopRunnable is Window);
Application.TopRunnable!.Dispose ();
// Run<Toplevel> when already initialized or not with a Driver will not throw (because Dialog is derived from Toplevel)
Application.Run<Dialog> (null, "fake");
Assert.True (Application.TopRunnable is Dialog);
Application.TopRunnable!.Dispose ();
Application.Shutdown ();
}
[Fact]
[SetupFakeApplication]
public void Run_T_After_Init_Does_Not_Disposes_Application_Top ()
{
// Init doesn't create a Toplevel and assigned it to Application.TopRunnable
// but Begin does
var initTop = new Toplevel ();
Application.Iteration += OnApplicationOnIteration;
Application.Run<Toplevel> ();
Application.Iteration -= OnApplicationOnIteration;
#if DEBUG_IDISPOSABLE
Assert.False (initTop.WasDisposed);
initTop.Dispose ();
Assert.True (initTop.WasDisposed);
#endif
Application.TopRunnable!.Dispose ();
return;
void OnApplicationOnIteration (object? s, EventArgs<IApplication?> a)
{
Assert.NotEqual (initTop, Application.TopRunnable);
#if DEBUG_IDISPOSABLE
Assert.False (initTop.WasDisposed);
#endif
Application.RequestStop ();
}
}
[Fact]
[SetupFakeApplication]
public void Run_T_After_InitWithDriver_with_TestTopLevel_DoesNotThrow ()
{
Application.StopAfterFirstIteration = true;
// Init has been called and we're passing no driver to Run<TestTopLevel>. This is ok.
Application.Run<Toplevel> ();
Application.TopRunnable!.Dispose ();
}
[Fact]
[SetupFakeApplication]
public void Run_T_After_InitNullDriver_with_TestTopLevel_DoesNotThrow ()
{
Application.StopAfterFirstIteration = true;
// Init has been called, selecting FakeDriver; we're passing no driver to Run<TestTopLevel>. Should be fine.
Application.Run<Toplevel> ();
Application.TopRunnable!.Dispose ();
}
[Fact]
[SetupFakeApplication]
public void Run_T_Init_Driver_Cleared_with_TestTopLevel_Throws ()
{
Application.Driver = null;
// Init has been called, but Driver has been set to null. Bad.
Assert.Throws<InvalidOperationException> (() => Application.Run<Toplevel> ());
}
[Fact]
[SetupFakeApplication]
public void Run_T_NoInit_DoesNotThrow ()
{
Application.StopAfterFirstIteration = true;
Application.Run<Toplevel> ().Dispose ();
}
[Fact]
[SetupFakeApplication]
public void Run_T_NoInit_WithDriver_DoesNotThrow ()
{
Application.StopAfterFirstIteration = true;
// Init has NOT been called and we're passing a valid driver to Run<TestTopLevel>. This is ok.
Application.Run<Toplevel> (null, "fake");
Application.TopRunnable!.Dispose ();
}
[Fact]
[SetupFakeApplication]
public void Run_RequestStop_Stops ()
{
var top = new Toplevel ();
SessionToken rs = Application.Begin (top);
Assert.NotNull (rs);
Application.Iteration += OnApplicationOnIteration;
Application.Run (top);
Application.Iteration -= OnApplicationOnIteration;
top.Dispose ();
return;
void OnApplicationOnIteration (object? s, EventArgs<IApplication?> a) { Application.RequestStop (); }
}
[Fact]
[SetupFakeApplication]
public void Run_Sets_Running_True ()
{
var top = new Toplevel ();
SessionToken rs = Application.Begin (top);
Assert.NotNull (rs);
Application.Iteration += OnApplicationOnIteration;
Application.Run (top);
Application.Iteration -= OnApplicationOnIteration;
top.Dispose ();
return;
void OnApplicationOnIteration (object? s, EventArgs<IApplication?> a)
{
Assert.True (top.Running);
top.RequestStop ();
}
}
[Fact]
[SetupFakeApplication]
public void Run_RunningFalse_Stops ()
{
var top = new Toplevel ();
SessionToken rs = Application.Begin (top);
Assert.NotNull (rs);
Application.Iteration += OnApplicationOnIteration;
Application.Run (top);
Application.Iteration -= OnApplicationOnIteration;
top.Dispose ();
return;
void OnApplicationOnIteration (object? s, EventArgs<IApplication?> a) { top.Running = false; }
}
[Fact]
[SetupFakeApplication]
public void Run_Loaded_Ready_Unloaded_Events ()
{
Application.StopAfterFirstIteration = true;
Toplevel top = new ();
var count = 0;
top.Loaded += (s, e) => count++;
top.Ready += (s, e) => count++;
top.Unloaded += (s, e) => count++;
Application.Run (top);
top.Dispose ();
}
// TODO: All Toplevel layout tests should be moved to ToplevelTests.cs
[Fact]
[SetupFakeApplication]
public void Run_A_Modal_Toplevel_Refresh_Background_On_Moving ()
{
// Don't use Dialog here as it has more layout logic. Use Window instead.
var w = new Window
{
Width = 5, Height = 5,
Arrangement = ViewArrangement.Movable
};
Application.Driver!.SetScreenSize (10, 10);
SessionToken rs = Application.Begin (w);
// Don't use visuals to test as style of border can change over time.
Assert.Equal (new (0, 0), w.Frame.Location);
Application.RaiseMouseEvent (new () { Flags = MouseFlags.Button1Pressed });
Assert.Equal (w.Border, Application.Mouse.MouseGrabView);
Assert.Equal (new (0, 0), w.Frame.Location);
// Move down and to the right.
Application.RaiseMouseEvent (new () { ScreenPosition = new (1, 1), Flags = MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition });
Assert.Equal (new (1, 1), w.Frame.Location);
Application.End (rs);
w.Dispose ();
}
[Fact]
[SetupFakeApplication]
public void End_Does_Not_Dispose ()
{
var top = new Toplevel ();
Window w = new ();
Application.StopAfterFirstIteration = true;
Application.Run (w);
#if DEBUG_IDISPOSABLE
Assert.False (w.WasDisposed);
#endif
Assert.NotNull (w);
Assert.Equal (string.Empty, w.Title); // Valid - w has not been disposed. The user may want to run it again
Assert.NotNull (Application.TopRunnable);
Assert.Equal (w, Application.TopRunnable);
Assert.NotEqual (top, Application.TopRunnable);
Application.Run (w); // Valid - w has not been disposed.
#if DEBUG_IDISPOSABLE
Assert.False (w.WasDisposed);
Exception exception = Record.Exception (Application.Shutdown); // Invalid - w has not been disposed.
Assert.NotNull (exception);
w.Dispose ();
Assert.True (w.WasDisposed);
//exception = Record.Exception (
// () => Application.Run (
// w)); // Invalid - w has not been disposed. Run it in debug mode will throw, otherwise the user may want to run it again
//Assert.NotNull (exception);
// TODO: Re-enable this when we are done debug logging of ctx.Source.Title in RaiseSelecting
//exception = Record.Exception (() => Assert.Equal (string.Empty, w.Title)); // Invalid - w has been disposed and cannot be accessed
//Assert.NotNull (exception);
//exception = Record.Exception (() => w.Title = "NewTitle"); // Invalid - w has been disposed and cannot be accessed
//Assert.NotNull (exception);
#endif
}
[Fact]
public void Run_Creates_Top_Without_Init ()
{
Assert.Null (Application.TopRunnable);
Application.StopAfterFirstIteration = true;
Application.Iteration += OnApplicationOnIteration;
Toplevel top = Application.Run (null, "fake");
Application.Iteration -= OnApplicationOnIteration;
#if DEBUG_IDISPOSABLE
Assert.Equal (top, Application.TopRunnable);
Assert.False (top.WasDisposed);
Exception exception = Record.Exception (Application.Shutdown);
Assert.NotNull (exception);
Assert.False (top.WasDisposed);
#endif
// It's up to caller to dispose it
top.Dispose ();
#if DEBUG_IDISPOSABLE
Assert.True (top.WasDisposed);
#endif
Assert.NotNull (Application.TopRunnable);
Application.Shutdown ();
Assert.Null (Application.TopRunnable);
return;
void OnApplicationOnIteration (object? s, EventArgs<IApplication?> e) { Assert.NotNull (Application.TopRunnable); }
}
[Fact]
public void Run_T_Creates_Top_Without_Init ()
{
Assert.Null (Application.TopRunnable);
Application.StopAfterFirstIteration = true;
Application.Run<Toplevel> (null, "fake");
#if DEBUG_IDISPOSABLE
Assert.False (Application.TopRunnable!.WasDisposed);
Exception exception = Record.Exception (Application.Shutdown);
Assert.NotNull (exception);
Assert.False (Application.TopRunnable!.WasDisposed);
// It's up to caller to dispose it
Application.TopRunnable!.Dispose ();
Assert.True (Application.TopRunnable!.WasDisposed);
#endif
Assert.NotNull (Application.TopRunnable);
Application.Shutdown ();
Assert.Null (Application.TopRunnable);
}
[Fact]
public void Run_t_Does_Not_Creates_Top_Without_Init ()
{
// When a Toplevel is created it must already have all the Application configuration loaded
// This is only possible by two ways:
// 1 - Using Application.Init first
// 2 - Using Application.Run() or Application.Run<T>()
// The Application.Run(new(Toplevel)) must always call Application.Init() first because
// the new(Toplevel) may be a derived class that is possible using Application static
// properties that is only available after the Application.Init was called
Assert.Null (Application.TopRunnable);
Assert.Throws<NotInitializedException> (() => Application.Run (new Toplevel ()));
Application.Init ("fake");
Application.Iteration += OnApplication_OnIteration;
Application.Run (new Toplevel ());
Application.Iteration -= OnApplication_OnIteration;
#if DEBUG_IDISPOSABLE
Assert.False (Application.TopRunnable!.WasDisposed);
Exception exception = Record.Exception (Application.Shutdown);
Assert.NotNull (exception);
Assert.False (Application.TopRunnable!.WasDisposed);
// It's up to caller to dispose it
Application.TopRunnable!.Dispose ();
Assert.True (Application.TopRunnable!.WasDisposed);
#endif
Assert.NotNull (Application.TopRunnable);
Application.Shutdown ();
Assert.Null (Application.TopRunnable);
return;
void OnApplication_OnIteration (object? s, EventArgs<IApplication?> e)
{
Assert.NotNull (Application.TopRunnable);
Application.RequestStop ();
}
}
private class TestToplevel : Toplevel
{ }
[Fact]
public void Run_T_With_V2_Driver_Does_Not_Call_ResetState_After_Init ()
{
Assert.False (Application.Initialized);
Application.Init ("fake");
Assert.True (Application.Initialized);
Task.Run (() => { Task.Delay (300).Wait (); })
.ContinueWith (
(t, _) =>
{
// no longer loading
Application.Invoke ((app) => { app.RequestStop (); });
},
TaskScheduler.FromCurrentSynchronizationContext ());
Application.Run<TestToplevel> ();
Assert.NotNull (Application.Driver);
Assert.NotNull (Application.TopRunnable);
Assert.False (Application.TopRunnable!.Running);
Application.TopRunnable!.Dispose ();
Application.Shutdown ();
}
// TODO: Add tests for Run that test errorHandler
#endregion
#region ShutdownTests
[Fact]
public async Task Shutdown_Allows_Async ()
{
var isCompletedSuccessfully = false;
async Task TaskWithAsyncContinuation ()
{
await Task.Yield ();
await Task.Yield ();
isCompletedSuccessfully = true;
}
Application.Shutdown ();
Assert.False (isCompletedSuccessfully);
await TaskWithAsyncContinuation ();
Thread.Sleep (100);
Assert.True (isCompletedSuccessfully);
}
[Fact]
public void Shutdown_Resets_SyncContext ()
{
Application.Shutdown ();
Assert.Null (SynchronizationContext.Current);
}
#endregion
}