SourcesManagerTests.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Reflection;
  2. using System.Text.Json;
  3. namespace UnitTests.ConfigurationTests;
  4. public class SourcesManagerTests
  5. {
  6. [Fact]
  7. public void Sources_StaysConsistentWhenUpdateFails ()
  8. {
  9. // Arrange
  10. var sourcesManager = new SourcesManager ();
  11. var settingsScope = new SettingsScope ();
  12. // Add one successful source
  13. var validSource = "valid.json";
  14. var validLocation = ConfigLocations.Runtime;
  15. sourcesManager.Load (settingsScope, """{"Application.QuitKey": "Ctrl+Z"}""", validSource, validLocation);
  16. try
  17. {
  18. // Configure to throw on errors
  19. ConfigurationManager.ThrowOnJsonErrors = true;
  20. // Act & Assert - attempt to update with invalid JSON
  21. var invalidSource = "invalid.json";
  22. var invalidLocation = ConfigLocations.AppCurrent;
  23. var invalidJson = "{ invalid json }";
  24. Assert.Throws<JsonException> (
  25. () =>
  26. sourcesManager.Load (settingsScope, invalidJson, invalidSource, invalidLocation));
  27. // The valid source should still be there
  28. Assert.Single (sourcesManager.Sources);
  29. Assert.Equal (validSource, sourcesManager.Sources [validLocation]);
  30. // The invalid source should not have been added
  31. Assert.DoesNotContain (invalidLocation, sourcesManager.Sources.Keys);
  32. }
  33. finally
  34. {
  35. // Reset for other tests
  36. ConfigurationManager.ThrowOnJsonErrors = false;
  37. }
  38. }
  39. // NOTE: This test causes the static CM._jsonErrors to be modified; can't use in a parallel test
  40. [Fact]
  41. public void Load_WithInvalidJson_AddsJsonError ()
  42. {
  43. // Arrange
  44. var sourcesManager = new SourcesManager ();
  45. var settingsScope = new SettingsScope ();
  46. var invalidJson = "{ invalid json }";
  47. var stream = new MemoryStream ();
  48. var writer = new StreamWriter (stream);
  49. writer.Write (invalidJson);
  50. writer.Flush ();
  51. stream.Position = 0;
  52. var source = "Load_WithInvalidJson_AddsJsonError";
  53. var location = ConfigLocations.AppCurrent;
  54. // Act
  55. bool result = sourcesManager.Load (settingsScope, stream, source, location);
  56. // Assert
  57. Assert.False (result);
  58. // Assuming AddJsonError logs errors, verify the error was logged (mock or inspect logs if possible).
  59. }
  60. }