ExampleContextInjector.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. namespace Terminal.Gui.Examples;
  2. /// <summary>
  3. /// Handles automatic injection of test context into running examples.
  4. /// This class monitors for the presence of an <see cref="ExampleContext"/> in the environment
  5. /// and automatically injects keystrokes via <see cref="Application.Driver"/> after the application initializes.
  6. /// </summary>
  7. public static class ExampleContextInjector
  8. {
  9. private static bool _initialized;
  10. /// <summary>
  11. /// Sets up automatic key injection if a test context is present in the environment.
  12. /// Call this method before calling <see cref="Application.Init"/> or <see cref="IApplication.Init"/>.
  13. /// </summary>
  14. /// <param name="app"></param>
  15. /// <remarks>
  16. /// This method is safe to call multiple times - it will only set up injection once.
  17. /// The actual key injection happens after the application is initialized, via the
  18. /// <see cref="Application.InitializedChanged"/> event.
  19. /// </remarks>
  20. public static void SetupAutomaticInjection (IApplication? app)
  21. {
  22. if (_initialized)
  23. {
  24. return;
  25. }
  26. _initialized = true;
  27. // Check for test context in environment variable
  28. string? contextJson = Environment.GetEnvironmentVariable (ExampleContext.ENVIRONMENT_VARIABLE_NAME);
  29. if (string.IsNullOrEmpty (contextJson))
  30. {
  31. return;
  32. }
  33. ExampleContext? context = ExampleContext.FromJson (contextJson);
  34. if (context is null || context.KeysToInject.Count == 0)
  35. {
  36. return;
  37. }
  38. // Subscribe to InitializedChanged to inject keys after initialization
  39. app.SessionBegun += AppOnSessionBegun;
  40. return;
  41. void AppOnSessionBegun (object? sender, SessionTokenEventArgs e)
  42. {
  43. // Application has been initialized, inject the keys
  44. if (app.Driver is null)
  45. {
  46. return;
  47. }
  48. foreach (string keyStr in context.KeysToInject)
  49. {
  50. if (Input.Key.TryParse (keyStr, out Input.Key? key) && key is { })
  51. {
  52. app.Keyboard.RaiseKeyDownEvent (key);
  53. }
  54. }
  55. // Unsubscribe after injecting keys once
  56. app.SessionBegun -= AppOnSessionBegun;
  57. }
  58. }
  59. }