Skip to content

Commit 5ac93f0

Browse files
committed
Enhance logging and improve test reliability
Updated logging in Program.cs for template availability and site creation errors. Adjusted return statements for async operations. Improved assertions in BlakeNewCommandTests.cs for better reliability and added mock template registry tests. Modified RunBlakeFromDotnetAsync in TestFixtureBase.cs to support a debug flag for flexible command execution.
1 parent c9707bd commit 5ac93f0

File tree

3 files changed

+63
-27
lines changed

3 files changed

+63
-27
lines changed

src/Blake.CLI/Program.cs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -255,17 +255,21 @@ private static async Task<int> NewSiteAsync(string[] args, ILogger logger)
255255
// TODO: Improve this with Specter.Console or similar
256256
if (templateList.Count > 0)
257257
{
258+
logger.LogInformation("Available templates: {count}", templateList.Count);
258259
Console.WriteLine("Available templates:");
259260
Console.WriteLine("Template Name | Short name | Description | Main Category | Author");
260261
Console.WriteLine("--------------------------|------------------|---------------------------|---------------------|-----------------");
261262
foreach (var template in templateList)
262263
{
263264
Console.WriteLine($"{template.Name,-26} | {template.ShortName,-16} | {template.Description,-25} | {template.MainCategory,-19} | {template.Author}");
265+
logger.LogInformation("Template: {name} ({shortName}) - {description} | Category: {category} | Author: {author}",
266+
template.Name, template.ShortName, template.Description, template.MainCategory, template.Author);
264267
}
265268
}
266269
else
267270
{
268271
Console.WriteLine("No templates found.");
272+
logger.LogDebug("No templates found.");
269273
}
270274

271275
return 0;
@@ -355,12 +359,13 @@ private static async Task<int> NewSiteAsync(string[] args, ILogger logger)
355359
if (initResult == 0)
356360
{
357361
logger.LogInformation("✅ New site {newSiteName} created successfully.", newSiteName);
362+
return await BakeBlakeAsync([string.Empty, fileName], logger); // ensure path is second argument
358363
}
359364
else
360365
{
361-
logger.LogError("Failed to create new Blake site");
366+
logger.LogError("Failed to create new Blazor WASM site. Error: {error}", process.StandardError.ReadToEnd());
362367
}
363-
368+
364369
return initResult;
365370
}
366371
}
@@ -377,13 +382,14 @@ private static async Task<int> NewSiteAsync(string[] args, ILogger logger)
377382
if (newResult != 0)
378383
{
379384
logger.LogError("Failed to create new Blake site");
385+
return newResult;
380386
}
381387
else
382388
{
383389
logger.LogInformation("✅ New site {newSiteName} created successfully.", newSiteName);
384390
}
385-
386-
return newResult;
391+
392+
return await BakeBlakeAsync(args, logger);
387393
}
388394

389395
private static string GetPathFromArgs(string[] args)

tests/Blake.IntegrationTests/Commands/BlakeNewCommandTests.cs

Lines changed: 49 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
using Blake.CLI;
12
using Blake.IntegrationTests.Infrastructure;
3+
using Blake.Types;
24
using Microsoft.Extensions.Logging;
35

46
namespace Blake.IntegrationTests.Commands;
@@ -18,26 +20,53 @@ public async Task BlakeNew_WithNoArguments_ShowsHelp()
1820
// Assert
1921
Assert.NotEqual(0, result.ExitCode);
2022
// Should show help or error about missing path
21-
Assert.True(result.OutputText.Contains("path") ||
22-
result.ErrorText.Contains("path" ) ||
23-
result.OutputText.Contains("usage"));
23+
Assert.Contains(result.OutputText, o => o.Contains("path") || o.Contains("usage"));
2424
}
2525

2626
[Fact]
2727
public async Task BlakeNew_WithListOption_ShowsAvailableTemplates()
2828
{
2929
// Act
30-
var result = await RunBlakeCommandAsync(["new"," --list"]);
30+
31+
// create template registry file in user profile directory
32+
const string shortName1 = "tailwind-sample";
33+
const string shortName2 = "simpledocs";
34+
const string longName1 = "Blake Simple Tailwind Sample";
35+
const string longName2 = "Blake Simple Docs";
36+
37+
var templateRegistryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".blake", "TemplateRegistry.json");
38+
if(!File.Exists(templateRegistryPath))
39+
{
40+
// Create a mock TemplateRegistry.json for testing
41+
var templates = new List<SiteTemplate>
42+
{
43+
new (Guid.Empty, shortName1, longName1, "", "", "", DateTime.MinValue, ""),
44+
new (Guid.Empty, shortName2, longName2, "", "", "", DateTime.MinValue, "")
45+
};
46+
47+
var jsonContent = System.Text.Json.JsonSerializer.Serialize(templates, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
48+
Directory.CreateDirectory(Path.GetDirectoryName(templateRegistryPath)!);
49+
File.WriteAllText(templateRegistryPath, jsonContent);
50+
}
51+
52+
// Has to be run with debug to use local TemplateRegistry.json, otherwise it calls the repo
53+
var result = await RunBlakeFromDotnetAsync("new --list", debug: true);
3154

3255
// Assert
3356
Assert.Equal(0, result.ExitCode);
34-
Assert.Contains("Available templates", result.OutputText);
57+
Assert.Contains(result.OutputText, o => o.Contains("Available templates"));
3558

3659
// Should show templates from TemplateRegistry.json
37-
Assert.Contains("tailwind-sample", result.OutputText);
38-
Assert.Contains("blakedocs", result.OutputText);
39-
Assert.Contains("Blake Simple Tailwind Sample", result.OutputText);
40-
Assert.Contains("Blake Docs", result.OutputText);
60+
Assert.Contains(result.OutputText, o => o.Contains(shortName1));
61+
Assert.Contains(result.OutputText, o => o.Contains(shortName2));
62+
Assert.Contains(result.OutputText, o => o.Contains(longName1));
63+
Assert.Contains(result.OutputText, o => o.Contains(longName2));
64+
65+
// Cleanup the mock TemplateRegistry.json
66+
if (File.Exists(templateRegistryPath))
67+
{
68+
File.Delete(templateRegistryPath);
69+
}
4170
}
4271

4372
[Fact]
@@ -49,11 +78,11 @@ public async Task BlakeNew_DefaultTemplate_CreatesBlazorWasmProject()
4978
var projectPath = Path.Combine(testDir, projectName);
5079

5180
// Act
52-
var result = await RunBlakeCommandAsync(["bake", projectPath]);
81+
var result = await RunBlakeCommandAsync(["new", projectPath, "-s"]);
5382

5483
// Assert
5584
Assert.Equal(0, result.ExitCode);
56-
Assert.Contains("created successfully", result.OutputText);
85+
Assert.Contains(result.OutputText, o => o.Contains("created successfully"));
5786

5887
// Should create a Blazor WASM project structure
5988
FileSystemHelper.AssertDirectoryExists(projectPath);
@@ -62,11 +91,10 @@ public async Task BlakeNew_DefaultTemplate_CreatesBlazorWasmProject()
6291
FileSystemHelper.AssertFileExists(Path.Combine(projectPath, "App.razor"));
6392

6493
// Should have Blake-specific folders created by init
65-
FileSystemHelper.AssertDirectoryExists(Path.Combine(projectPath, "Posts"));
6694
FileSystemHelper.AssertDirectoryExists(Path.Combine(projectPath, "Pages"));
6795

6896
// Should contain sample content because init is called with includeSampleContent=true
69-
FileSystemHelper.AssertFileExists(Path.Combine(projectPath, "Posts", "hello-world.md"));
97+
FileSystemHelper.AssertFileExists(Path.Combine(projectPath, "Pages", "SamplePAge.md"));
7098
}
7199

72100
[Fact]
@@ -82,7 +110,7 @@ public async Task BlakeNew_WithSiteName_UsesProvidedName()
82110

83111
// Assert
84112
Assert.Equal(0, result.ExitCode);
85-
Assert.Contains("created successfully", result.OutputText);
113+
Assert.Contains(result.OutputText, o => o.Contains("created successfully"));
86114

87115
// Should use the provided site name for the project file
88116
FileSystemHelper.AssertFileExists(Path.Combine(projectPath, $"{projectName}.csproj"));
@@ -101,7 +129,7 @@ public async Task BlakeNew_InvalidSiteName_ShowsError()
101129

102130
// Assert
103131
Assert.NotEqual(0, result.ExitCode);
104-
Assert.Contains("invalid", result.ErrorText);
132+
Assert.Contains(result.ErrorText, e => e.Contains("invalid"));
105133
}
106134

107135
[Fact]
@@ -112,7 +140,7 @@ public async Task BlakeNew_NonExistentPath_CreatesDirectory()
112140
var projectPath = Path.Combine(testDir, "deeply", "nested", "path", "MyProject");
113141

114142
// Act
115-
var result = await RunBlakeCommandAsync(["bake", projectPath]);
143+
var result = await RunBlakeCommandAsync(["new", projectPath]);
116144

117145
// Assert
118146
Assert.Equal(0, result.ExitCode);
@@ -130,7 +158,7 @@ public async Task BlakeNew_ExistingNonEmptyDirectory_ShowsError()
130158
File.WriteAllText(Path.Combine(projectPath, "existing-file.txt"), "content");
131159

132160
// Act
133-
var result = await RunBlakeCommandAsync(["bake", projectPath]);
161+
var result = await RunBlakeCommandAsync(["new", projectPath]);
134162

135163
// Assert
136164
// The behavior might vary - some generators create anyway, others fail
@@ -175,7 +203,7 @@ public async Task BlakeNew_WithValidTemplate_UsesTemplate(string templateName)
175203
{
176204
// If successful, should have cloned the template
177205
FileSystemHelper.AssertDirectoryExists(projectPath);
178-
Assert.Contains("created successfully", result.OutputText);
206+
Assert.Contains(result.OutputText, o => o.Contains("created successfully"));
179207
}
180208
else
181209
{
@@ -203,7 +231,7 @@ public async Task BlakeNew_WithUrl_UsesCustomRepository()
203231
if (result.ExitCode == 0)
204232
{
205233
FileSystemHelper.AssertDirectoryExists(projectPath);
206-
Assert.Contains("created successfully", result.OutputText);
234+
Assert.Contains(result.OutputText, o => o.Contains("created successfully"));
207235
}
208236
else
209237
{
@@ -243,14 +271,14 @@ public async Task BlakeNew_ResultingProject_CanBuild()
243271
var projectPath = Path.Combine(testDir, projectName);
244272

245273
// Act - Create project
246-
var createResult = await RunBlakeCommandAsync(["new", projectPath]);
274+
var createResult = await RunBlakeCommandAsync(["new", projectPath, "-s"]);
247275
Assert.Equal(0, createResult.ExitCode);
248276

249277
// Act - Try to build the project
250278
var buildResult = await RunProcessAsync("dotnet", "build", projectPath);
251279

252280
// Assert
253281
Assert.Equal(0, buildResult.ExitCode);
254-
Assert.Contains("Build succeeded", buildResult.OutputText);
282+
Assert.Contains(buildResult.OutputText, o => o.Contains("Build succeeded"));
255283
}
256284
}

tests/Blake.IntegrationTests/Infrastructure/TestFixtureBase.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,11 @@ [.. _loggerProvider.Logs.Where(l => l.Level >= LogLevel.Error).Select(l => l.Mes
5959
/// <summary>
6060
/// Runs a CLI command using the blake executable.
6161
/// </summary>
62-
protected async Task<ProcessResult> RunBlakeFromDotnetAsync(string command, string workingDirectory = "", CancellationToken cancellationToken = default)
62+
protected async Task<ProcessResult> RunBlakeFromDotnetAsync(string command, string workingDirectory = "", bool debug = false, CancellationToken cancellationToken = default)
6363
{
64-
return await RunProcessAsync("dotnet", $"run --project \"{GetCliProjectPath()}\" -- {command}", workingDirectory, cancellationToken);
64+
string debugFlag = debug ? "-c Debug " : string.Empty;
65+
66+
return await RunProcessAsync("dotnet", $"run --project \"{GetCliProjectPath()}\" {debugFlag}-- {command}", workingDirectory, cancellationToken);
6567
}
6668

6769
/// <summary>

0 commit comments

Comments
 (0)