Skip to content

Commit

Permalink
Add test
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK committed Feb 8, 2025
1 parent f956895 commit 3b5ef58
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
{ "title", item.Tooltip ?? string.Empty }
};

<FluentMenuItem OnClick="() => HandleItemClicked(item)" Disabled="@item.IsDisabled" AdditionalAttributes="@additionalMenuItemAttributes">
<FluentMenuItem Id="@item.Id" OnClick="() => HandleItemClicked(item)" Disabled="@item.IsDisabled" AdditionalAttributes="@additionalMenuItemAttributes">
@item.Text
@if (item.Icon != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public partial class AspireMenuButton : FluentComponentBase
[Parameter]
public string? Title { get; set; }

public string MenuButtonId { get; } = Identifier.NewId();
[Parameter]
public string MenuButtonId { get; set; } = Identifier.NewId();

protected override void OnParametersSet()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ protected override void OnParametersSet()

_clearMenuItems.Add(new()
{
Id = "clear-menu-all",
Icon = s_clearAllResourcesIcon,
OnClick = () => HandleClearSignal(null),
Text = ControlsStringsLoc[name: nameof(ControlsStrings.ClearAllResources)],
});

_clearMenuItems.Add(new()
{
Id = "clear-menu-resource",
Icon = s_clearSelectedResourceIcon,
OnClick = () => HandleClearSignal(SelectedResource.Id?.GetApplicationKey()),
IsDisabled = SelectedResource.Id == null,
Expand Down
10 changes: 7 additions & 3 deletions src/Aspire.Dashboard/Components/Pages/ConsoleLogs.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ private sealed class ConsoleLogsSubscription
[Inject]
public required DashboardCommandExecutor DashboardCommandExecutor { get; init; }

[Inject]
public required BrowserTimeProvider TimeProvider { get; init; }

[CascadingParameter]
public required ViewportInformation ViewportInformation { get; init; }

Expand Down Expand Up @@ -556,22 +559,23 @@ private async Task DownloadLogsAsync()

using var streamReference = new DotNetStreamReference(stream);
var safeDisplayName = string.Join("_", PageViewModel.SelectedResource!.DisplayName.Split(Path.GetInvalidFileNameChars()));
var fileName = $"{safeDisplayName}-{DateTime.Now.ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture)}.txt";
var fileName = $"{safeDisplayName}-{TimeProvider.GetLocalNow().ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture)}.txt";

await JS.InvokeVoidAsync("downloadStreamAsFile", fileName, streamReference);
}

private async Task ClearConsoleLogs(ApplicationKey? key)
{
var now = TimeProvider.GetUtcNow().UtcDateTime;
if (key is null)
{
_consoleLogFilters.FilterAllLogsDate = DateTime.UtcNow;
_consoleLogFilters.FilterAllLogsDate = now;
_consoleLogFilters.FilterResourceLogsDates?.Clear();
}
else
{
_consoleLogFilters.FilterResourceLogsDates ??= [];
_consoleLogFilters.FilterResourceLogsDates[key.Value.ToString()] = DateTime.UtcNow;
_consoleLogFilters.FilterResourceLogsDates[key.Value.ToString()] = now;
}

// Save filters to session storage so they're persisted when navigating to and from the console logs page.
Expand Down
1 change: 1 addition & 0 deletions src/Aspire.Dashboard/Model/MenuButtonItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ public class MenuButtonItem
public Icon? Icon { get; set; }
public Func<Task>? OnClick { get; set; }
public bool IsDisabled { get; set; }
public string? Id { get; set; }
public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; }
}
62 changes: 60 additions & 2 deletions tests/Aspire.Dashboard.Components.Tests/Pages/ConsoleLogsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,62 @@ public async Task ResourceName_ViaUrlAndResourceLoaded_LogViewerUpdated()
cut.WaitForState(() => instance._logEntries.EntriesCount > 0);
}

private void SetupConsoleLogsServices(TestDashboardClient? dashboardClient = null)
[Fact]
public void ClearLogEntries_AllResources_LogsFilteredOut()
{
// Arrange
var consoleLogsChannel = Channel.CreateUnbounded<IReadOnlyList<ResourceLogLine>>();
var resourceChannel = Channel.CreateUnbounded<IReadOnlyList<ResourceViewModelChange>>();
var testResource = ModelTestHelpers.CreateResource(appName: "test-resource", state: KnownResourceState.Running);
var dashboardClient = new TestDashboardClient(
isEnabled: true,
consoleLogsChannelProvider: name => consoleLogsChannel,
resourceChannelProvider: () => resourceChannel,
initialResources: [ testResource ]);
var timeProvider = new TestTimeProvider();

SetupConsoleLogsServices(dashboardClient, timeProvider: timeProvider);

var dimensionManager = Services.GetRequiredService<DimensionManager>();
var viewport = new ViewportInformation(IsDesktop: true, IsUltraLowHeight: false, IsUltraLowWidth: false);
dimensionManager.InvokeOnViewportInformationChanged(viewport);

// Act
var cut = RenderComponent<Components.Pages.ConsoleLogs>(builder =>
{
builder.Add(p => p.ResourceName, "test-resource");
builder.Add(p => p.ViewportInformation, viewport);
});

var instance = cut.Instance;
var logger = Services.GetRequiredService<ILogger<ConsoleLogsTests>>();
var loc = Services.GetRequiredService<IStringLocalizer<Resources.ConsoleLogs>>();

// Assert
logger.LogInformation("Waiting for selected resource.");
cut.WaitForState(() => instance.PageViewModel.SelectedResource == testResource);
cut.WaitForState(() => instance.PageViewModel.Status == loc[nameof(Resources.ConsoleLogs.ConsoleLogsWatchingLogs)]);

logger.LogInformation("Log results are added to log viewer.");
consoleLogsChannel.Writer.TryWrite([new ResourceLogLine(1, "2025-02-08T10:16:08Z Hello world", IsErrorMessage: false)]);
cut.WaitForState(() => instance._logEntries.EntriesCount > 0);

// Set current time to the date of the first entry so all entries are cleared.
var earliestEntry = instance._logEntries.GetEntries()[0];
timeProvider.UtcNow = earliestEntry.Timestamp!.Value;

logger.LogInformation("Clear current entries.");
cut.Find(".clear-button").Click();
cut.Find("#clear-menu-all").Click();

cut.WaitForState(() => instance._logEntries.EntriesCount == 0);

logger.LogInformation("New log results are added to log viewer.");
consoleLogsChannel.Writer.TryWrite([new ResourceLogLine(2, "2025-03-08T10:16:08Z Hello world", IsErrorMessage: false)]);
cut.WaitForState(() => instance._logEntries.EntriesCount > 0);
}

private void SetupConsoleLogsServices(TestDashboardClient? dashboardClient = null, TestTimeProvider? timeProvider = null)
{
var version = typeof(FluentMain).Assembly.GetName().Version!;

Expand All @@ -153,14 +208,17 @@ private void SetupConsoleLogsServices(TestDashboardClient? dashboardClient = nul
var keycodeModule = JSInterop.SetupModule(GetFluentFile("./_content/Microsoft.FluentUI.AspNetCore.Components/Components/KeyCode/FluentKeyCode.razor.js", version));
keycodeModule.Setup<string>("RegisterKeyCode", _ => true);

JSInterop.SetupModule(GetFluentFile("./_content/Microsoft.FluentUI.AspNetCore.Components/Components/Anchor/FluentAnchor.razor.js", version));
JSInterop.SetupModule(GetFluentFile("./_content/Microsoft.FluentUI.AspNetCore.Components/Components/AnchoredRegion/FluentAnchoredRegion.razor.js", version));

JSInterop.SetupVoid("initializeContinuousScroll");
JSInterop.SetupVoid("resetContinuousScrollPosition");

var loggerFactory = IntegrationTestHelpers.CreateLoggerFactory(_testOutputHelper);

Services.AddLocalization();
Services.AddSingleton<ILoggerFactory>(loggerFactory);
Services.AddSingleton<BrowserTimeProvider, TestTimeProvider>();
Services.AddSingleton<BrowserTimeProvider>(timeProvider ?? new TestTimeProvider());
Services.AddSingleton<IMessageService, MessageService>();
Services.AddSingleton<IToastService, ToastService>();
Services.AddSingleton<IOptions<DashboardOptions>>(Options.Create(new DashboardOptions()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ public sealed class TestTimeProvider : BrowserTimeProvider
{
private TimeZoneInfo? _localTimeZone;

public DateTimeOffset UtcNow { get; set; }

public TestTimeProvider() : base(NullLoggerFactory.Instance)
{
UtcNow = new DateTimeOffset(2025, 12, 20, 23, 59, 59, TimeSpan.Zero);
}

public override DateTimeOffset GetUtcNow()
{
return new DateTimeOffset(2025, 12, 20, 23, 59, 59, TimeSpan.Zero);
return UtcNow;
}

public override TimeZoneInfo LocalTimeZone => _localTimeZone ??= TimeZoneInfo.CreateCustomTimeZone(nameof(TestTimeProvider), TimeSpan.FromHours(1), nameof(TestTimeProvider), nameof(TestTimeProvider));
Expand Down

0 comments on commit 3b5ef58

Please sign in to comment.