Files
2026-08-17 09:24:57 +08:00

39 lines
1.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.CommandLine;
namespace Gpulse.WCT.DataAnalyzer.Tests;
/// <summary>
/// 命令执行辅助:运行命令并捕获标准输出/标准错误。
/// 命令 handler 直接使用 Console.WriteLine因此重定向 System.Console 即可捕获;
/// System.CommandLine 自身的帮助/校验输出也会经默认控制台写入同一流。
/// </summary>
public static class CliTestExtensions
{
/// <summary>
/// 执行命令并返回 (退出码, 标准输出, 标准错误)。
/// </summary>
public static async Task<(int ExitCode, string StdOut, string StdErr)> RunCaptureAsync(
this Command command,
params string[] args)
{
var originalOut = Console.Out;
var originalError = Console.Error;
using var outWriter = new StringWriter();
using var errWriter = new StringWriter();
Console.SetOut(outWriter);
Console.SetError(errWriter);
try
{
var exitCode = await command.InvokeAsync(args);
return (exitCode, outWriter.ToString(), errWriter.ToString());
}
finally
{
Console.SetOut(originalOut);
Console.SetError(originalError);
}
}
}