Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Navigation.Test/JsonFilePersistenceProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace ktsu.Navigation.Test;

using System.Text.Json;
using ktsu.Navigation.Models;
using ktsu.Navigation.Services;

Expand Down Expand Up @@ -58,17 +59,55 @@
Assert.IsNull(await provider.LoadStateAsync().ConfigureAwait(false));
}

[TestMethod]
public void NavigationItem_JsonRoundTrip_KeepsCreatedAtAndMetadata()
{
// Arrange
string json = """{"Id":"x","DisplayName":"X","CreatedAt":"2020-01-01T00:00:00Z","Metadata":{"k":"v"}}""";

// Act
NavigationItem item = JsonSerializer.Deserialize<NavigationItem>(json)!;

// Assert
Assert.AreEqual(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc), item.CreatedAt);
Assert.HasCount(1, item.Metadata);
Assert.AreEqual("v", ((JsonElement)item.Metadata["k"]).GetString());
}

[TestMethod]
public async Task SaveThenLoad_KeepsItemCreatedAtAndMetadata()
{
// Arrange
JsonFilePersistenceProvider<NavigationItem> provider = new(_filePath!);
Navigation<NavigationItem> navigation = new(null, provider);
NavigationItem item = new("a", "A");
item.SetMetadata("scroll", 42);
navigation.NavigateTo(item);
await navigation.SaveStateAsync().ConfigureAwait(false);

Check warning on line 86 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaDnKkRnBiDDEjYci0Sv&open=AaDnKkRnBiDDEjYci0Sv&pullRequest=65

// Act
Navigation<NavigationItem> restored = new(null, provider);
bool loaded = await restored.LoadStateAsync().ConfigureAwait(false);

Check warning on line 90 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaDnKkRnBiDDEjYci0Sw&open=AaDnKkRnBiDDEjYci0Sw&pullRequest=65

// Assert
Assert.IsTrue(loaded);
NavigationItem current = restored.Current!;
Assert.AreEqual(item.CreatedAt, current.CreatedAt);
Assert.HasCount(1, current.Metadata);
Assert.AreEqual(42, ((JsonElement)current.Metadata["scroll"]).GetInt32());
}

[TestMethod]
public async Task LoadStateAsync_NullItem_ReturnsFalseAndLeavesStackUnchanged()
{
// Arrange
await File.WriteAllTextAsync(_filePath!, """{"items":[null],"currentIndex":0}""").ConfigureAwait(false);

Check warning on line 104 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaDnRevyDWzmChX-mC5l&open=AaDnRevyDWzmChX-mC5l&pullRequest=65
JsonFilePersistenceProvider<NavigationItem> provider = new(_filePath!);
Navigation<NavigationItem> navigation = new(null, provider);
navigation.NavigateTo(new NavigationItem("a", "A"));

// Act
bool loaded = await navigation.LoadStateAsync().ConfigureAwait(false);

Check warning on line 110 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaDnRevyDWzmChX-mC5m&open=AaDnRevyDWzmChX-mC5m&pullRequest=65

// Assert
Assert.IsFalse(loaded);
Expand Down
33 changes: 33 additions & 0 deletions Navigation/Models/NavigationItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace ktsu.Navigation.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.Json.Serialization;
using ktsu.Navigation.Contracts;

/// <summary>
Expand Down Expand Up @@ -37,6 +39,37 @@ public NavigationItem(string id, string displayName)
_metadata = [];
}

/// <summary>
/// Initializes a new instance of the <see cref="NavigationItem"/> class when deserializing, keeping the
/// creation time and metadata that were saved. System.Text.Json requires each constructor parameter to have
/// the same name and type as the property it binds to.
/// </summary>
/// <remarks>
/// Metadata values read from JSON are <see cref="System.Text.Json.JsonElement"/> instances rather than
/// their original CLR types, because the saved JSON does not record those types.
/// </remarks>
/// <param name="id">The unique identifier for this navigation item</param>
/// <param name="displayName">The display name for this navigation item</param>
/// <param name="createdAt">The timestamp when this navigation item was first created</param>
/// <param name="metadata">The metadata to restore; null entries are skipped</param>
[JsonConstructor]
public NavigationItem(string id, string displayName, DateTime createdAt, IReadOnlyDictionary<string, object>? metadata)
: this(id, displayName)
{
if (createdAt != default)
{
CreatedAt = createdAt;
}

if (metadata != null)
{
foreach (KeyValuePair<string, object> entry in metadata.Where(entry => !string.IsNullOrWhiteSpace(entry.Key) && entry.Value != null))
{
_metadata[entry.Key] = entry.Value;
}
}
}

/// <inheritdoc />
public string Id { get; }

Expand Down
4 changes: 4 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,12 @@ public class NavigationItem : INavigationItem

```csharp
public NavigationItem(string id, string displayName)
public NavigationItem(string id, string displayName, DateTime createdAt, IReadOnlyDictionary<string, object>? metadata)
```

The second constructor is the one System.Text.Json uses, so `CreatedAt` and `Metadata` survive a save and load.
Metadata values read back from JSON are `JsonElement` instances rather than their original CLR types.

#### Method Overrides

| Method | Return Type | Description |
Expand Down
Loading