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
23 changes: 10 additions & 13 deletions DevProxy.Integration.Tests/ProcessSmokeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -486,11 +486,10 @@ private static JsonElement GetResultData(string output)
}
}

// Options before a command can't be fully resolved until plugins register theirs, so these
// run the real host to verify which command runs and where its output goes.
// Run the real host to verify which command runs and where its output goes.
[Theory]
[InlineData(new[] { "cert", "export" }, "text")]
[InlineData(new[] { "--log-level", "debug", "cert", "export" }, "text")]
[InlineData(new[] { "cert", "export", "--log-level", "debug" }, "text")]
[InlineData(new[] { "cert", "export", "--output", "json" }, "json")]
public async Task CertExport_WritesOnlyResultToStdout(string[] args, string output)
{
Expand Down Expand Up @@ -529,10 +528,10 @@ public async Task CertExport_WritesOnlyResultToStdout(string[] args, string outp
}
}

// cert is the value of a plugin option here, so the export runs but plugins that initialize
// before the command is resolved may still log to stdout
// Options must follow the subcommand, so a plugin option before cert export is rejected
// without exporting the certificate
[Fact]
public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate()
public async Task CertExport_AfterPluginOptionWithCertValue_IsRejected()
{
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
try
Expand All @@ -545,9 +544,8 @@ public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate()
["--mocks-file", "cert", "cert", "export", "--output", "json", "--file", file],
environment);

Assert.Equal(0, result.ExitCode);
Assert.True(File.Exists(file), result.Error);
Assert.Contains("\"path\"", result.Output, StringComparison.Ordinal);
Assert.Equal(2, result.ExitCode);
Assert.False(File.Exists(file));
}
finally
{
Expand All @@ -557,8 +555,7 @@ public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate()

// cert and export are values of plugin options or arguments of a plugin command here
[Theory]
[InlineData("--failure-rate", "10", "mocks", "from-http-responses", "cert", "export", "--mocks-file", "out.json")]
[InlineData("--no-mocks", "mocks", "from-http-responses", "cert", "export", "--mocks-file", "generated.json")]
[InlineData("mocks", "from-http-responses", "cert", "export", "--mocks-file", "out.json")]
public async Task PluginCommand_WithCertExportArguments_ReportsPluginErrors(params string[] args)
{
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
Expand All @@ -580,8 +577,8 @@ public async Task PluginCommand_WithCertExportArguments_ReportsPluginErrors(para
}

[Theory]
[InlineData("--mocks-file", "cert", "--watch-process-names", "export", "jwt", "create", "--output", "json")]
[InlineData("--mocks-file", "cert", "jwt", "create", "--scopes", "export", "--output", "json")]
[InlineData("jwt", "create", "--name", "cert", "--scopes", "export", "--output", "json")]
[InlineData("jwt", "create", "--scopes", "cert", "export", "--output", "json")]
public async Task JwtCreate_WithCertExportArguments_WritesResultToStdout(params string[] args)
{
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
Expand Down
13 changes: 8 additions & 5 deletions DevProxy.Tests/ConfigValidateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -383,19 +383,22 @@ public async Task AcceptsCaseInsensitiveKeyCollisionsInYaml()
[Theory]
[InlineData(new[] { "validate" }, true)]
[InlineData(new[] { "config", "validate" }, true)]
[InlineData(new[] { "--output", "json", "validate" }, true)]
[InlineData(new[] { "--output=json", "config", "validate" }, true)]
[InlineData(new[] { "--output:json", "validate" }, true)]
[InlineData(new[] { "--log-level:Warning", "validate" }, true)]
[InlineData(new[] { "validate", "--output", "json" }, true)]
[InlineData(new[] { "config", "validate", "--output=json" }, true)]
[InlineData(new[] { "--output", "json", "validate" }, false)]
[InlineData(new[] { "validate", "--help" }, false)]
[InlineData(new[] { "config", "get", "validate" }, false)]
[InlineData(new[] { "--config-file", "validate" }, false)]
[InlineData(new[] { "config", "--output", "json", "validate" }, true)]
[InlineData(new[] { "config", "--no-color", "--log-level:Warning", "validate" }, true)]
[InlineData(new[] { "config", "--output", "validate" }, false)]
public void DetectsValidateInvocation(string[] args, bool expected) =>
Assert.Equal(expected, DevProxyCommand.IsValidateInvocation(args));

[Theory]
[InlineData(new[] { "validate", "--config-file=my.json" }, "my.json")]
[InlineData(new[] { "--output", "json", "config", "validate", "-c", "my.json" }, "my.json")]
[InlineData(new[] { "config", "validate", "--output", "json", "-c", "my.json" }, "my.json")]
[InlineData(new[] { "config", "--output", "json", "validate", "-c", "my.json" }, "my.json")]
public void ParsesValidateArgs(string[] args, string expectedConfigFile)
{
var parseResult = ConfigCommand.ParseValidateArgs(args, out var configFileOptions, out _);
Expand Down
106 changes: 99 additions & 7 deletions DevProxy.Tests/DevProxyCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using DevProxy.Commands;
using System.CommandLine;

using Xunit;

Expand Down Expand Up @@ -54,15 +55,106 @@ public void ApplyDiscoverOption_False_KeepsRecordingEnabledFromOtherSources()

[Theory]
[InlineData(true, "stdio", "npx", "@devproxy/mcp")]
[InlineData(true, "--log-level", "debug", "stdio", "npx")]
[InlineData(true, "stdio", "-c", "myconfig.json", "node", "app.js")]
[InlineData(false, "--log-level", "debug", "stdio", "npx")]
[InlineData(false, "jwt", "create", "--name", "stdio", "--output", "json")]
[InlineData(true, "--env", "A=1", "B=2", "stdio", "node", "server.js")]
[InlineData(true, "-e", "A=1", "B=2", "--log-level", "debug", "stdio", "node")]
[InlineData(true, "--urls-to-watch", "https://a/*", "https://b/*", "stdio", "node")]
[InlineData(true, "--watch-pids", "1", "2", "stdio", "node")]
[InlineData(true, "--watch-process-names", "a", "b", "stdio", "node")]
[InlineData(false, "config", "get", "stdio")]
[InlineData(false)]
public void IsStdioSubcommand_DetectsSubcommandNotArgumentValues(bool expected, params string[] args) =>
public void IsStdioSubcommand_DetectsSubcommandOnlyAsFirstArgument(bool expected, params string[] args) =>
Assert.Equal(expected, DevProxyCommand.IsStdioSubcommand(args));

[Theory]
[InlineData(null)]
[InlineData(null, "--port", "0")]
[InlineData(null, "--help")]
[InlineData(null, "api", "show", "--log-level", "debug")]
[InlineData("api show", "--log-level", "debug", "api", "show")]
[InlineData("api show", "--port", "1", "api", "show")]
[InlineData("api", "--output", "json", "api")]
public void GetLeadingOptionsError_RejectsOptionsBeforeSubcommand(string? expectedCommandPath, params string[] args)
{
var logLevelOption = new Option<string>(DevProxyCommand.LogLevelOptionName) { Recursive = true };
var outputOption = new Option<string>(DevProxyCommand.OutputOptionName) { Recursive = true };
var portOption = new Option<int?>(DevProxyCommand.PortOptionName);
var apiCommand = new Command("api") { new Command("show") };
var rootCommand = new RootCommand { logLevelOption, outputOption, portOption, apiCommand };

var error = DevProxyCommand.GetLeadingOptionsError(rootCommand.Parse(args), args);

if (expectedCommandPath is null)
{
Assert.Null(error);
}
else
{
Assert.Contains($"devproxy {expectedCommandPath} [options]", error, StringComparison.Ordinal);
}
}

[Theory]
[InlineData("mocks", "from-http-responses", "r.http", "-c", "{0}")]
[InlineData("mocks", "--config-file", "{0}", "from-http-responses", "r.http")]
public void AddConfigFileOption_AcceptsConfigFileAfterPluginSubcommand(params string[] args)
{
var configFile = Path.GetTempFileName();
try
{
var mocksCommand = new Command("mocks") { new Command("from-http-responses") { new Argument<string[]>("files") } };
DevProxyCommand.AddConfigFileOption(mocksCommand, resolvedConfigFile: null);
var rootCommand = new RootCommand { mocksCommand };

var parseResult = rootCommand.Parse([.. args.Select(a => a == "{0}" ? configFile : a)]);

Assert.Empty(parseResult.Errors);
Assert.Equal(configFile, parseResult.GetValue<string?>(DevProxyCommand.ConfigFileOptionName));
}
finally
{
File.Delete(configFile);
}
}

[Fact]
public void AddConfigFileOption_RejectsMissingConfigFile()
{
var command = new Command("open");
DevProxyCommand.AddConfigFileOption(command, resolvedConfigFile: null);
var rootCommand = new RootCommand { new Command("config") { command } };

var parseResult = rootCommand.Parse(["config", "open", "-c", "missing-devproxyrc.json"]);

Assert.Contains(parseResult.Errors, e => e.Message.Contains("does not exist", StringComparison.Ordinal));
}

[Fact]
public void AddConfigFileOption_ValidatesResolvedConfigFile()
{
// --env can change what a token such as ~dataFolder expands to after the
// config file was resolved and loaded, so validate the resolved path.
var configFile = Path.GetTempFileName();
try
{
var command = new Command("open");
DevProxyCommand.AddConfigFileOption(command, configFile);
var rootCommand = new RootCommand { new Command("config") { command } };

var parseResult = rootCommand.Parse(["config", "open", "-c", "missing-devproxyrc.json"]);

Assert.Empty(parseResult.Errors);
}
finally
{
File.Delete(configFile);
}
}

[Fact]
public void AddConfigFileOption_KeepsPluginDeclaredOption()
{
var pluginOption = new Option<string>("--count", "-c");
var mocksCommand = new Command("mocks") { new Command("from-http-responses") { pluginOption } };
DevProxyCommand.AddConfigFileOption(mocksCommand, resolvedConfigFile: null);

Assert.Empty(mocksCommand.Options);
}
}
7 changes: 3 additions & 4 deletions DevProxy.Tests/DevProxyConfigOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,11 @@ public void Discover_ParsesOptionalValue(string[] args, bool expected)
}

[Fact]
public void ParseOptions_MultipleEnvValuesBeforeStdio_SelectsStdio()
public void ParseOptions_ReadsConfigFileAfterPluginSubcommand()
{
var options = new DevProxyConfigOptions();
options.ParseOptions(["--env", "A=1", "B=2", "stdio", "node", "server.js"]);
options.ParseOptions(["mocks", "from-http-responses", "r.http", "--mocks-file", "out.json", "-c", "mocks.json"]);

Assert.True(options.IsStdioMode);
Assert.Equal(new Dictionary<string, string> { ["A"] = "1", ["B"] = "2" }, options.Env);
Assert.Equal(Path.GetFullPath("mocks.json"), options.ConfigFile);
}
}
37 changes: 37 additions & 0 deletions DevProxy.Tests/LoggingConfigurationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,43 @@ public void ConfigureDevProxyLogging_Interactive_HonorsShowTimestamps(bool showT
Assert.False(options.IncludeFullTimestamps);
}

[Theory]
[InlineData(true, false)]
[InlineData(false, true)]
public void ConfigureDevProxyLogging_UsesPlainOutputOnlyForSubcommands(bool isRootCommand, bool expectedPlainOutput)
{
using var configuration = new ConfigurationManager();
var services = new ServiceCollection();
services.AddLogging(builder => builder.ConfigureDevProxyLogging(configuration, new DevProxyConfigOptions(), isStdioCommand: false, isJwtCommand: false, isRootCommand));
using var provider = services.BuildServiceProvider();

var options = provider.GetRequiredService<IOptions<ProxyConsoleFormatterOptions>>().Value;

Assert.Equal(expectedPlainOutput, options.PlainOutput);
}

[Fact]
public void ConfigureDevProxyLogging_Subcommand_ShowsPluginMessagesOnlyWhilePluginCommandRuns()
{
using var configuration = new ConfigurationManager();
var services = new ServiceCollection();
services.AddLogging(builder => builder.ConfigureDevProxyLogging(configuration, new DevProxyConfigOptions(), isStdioCommand: false, isJwtCommand: false, isRootCommand: false));
using var provider = services.BuildServiceProvider();
var logger = provider.GetRequiredService<ILoggerFactory>().CreateLogger("DevProxy.Plugins.Mocking.MockResponsePlugin");

Assert.False(logger.IsEnabled(LogLevel.Error));
DevProxyCommand.IsPluginCommandRunning = true;
try
{
Assert.True(logger.IsEnabled(LogLevel.Error));
Assert.False(logger.IsEnabled(LogLevel.Debug));
}
finally
{
DevProxyCommand.IsPluginCommandRunning = false;
}
}

[Theory]
[InlineData(LogLevel.Warning)]
[InlineData(LogLevel.Error)]
Expand Down
16 changes: 16 additions & 0 deletions DevProxy.Tests/ProxyConsoleFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ public void FinishedProcessingRequest_WriterThrows_ReleasesBufferedLines()
Assert.DoesNotContain("https://first", output, StringComparison.Ordinal);
}

[Theory]
[InlineData(LogLevel.Information, "Base URL: http://127.0.0.1:8897")]
[InlineData(LogLevel.Warning, "warning: Base URL: http://127.0.0.1:8897")]
[InlineData(LogLevel.Error, "error: Base URL: http://127.0.0.1:8897")]
[InlineData(LogLevel.Critical, "error: Base URL: http://127.0.0.1:8897")]
public void PlainOutput_WritesMessageWithoutLevelLabel(LogLevel level, string expected)
{
var formatter = new ProxyConsoleFormatter(Options.Create(new ProxyConsoleFormatterOptions { PlainOutput = true }));
using var writer = new StringWriter(CultureInfo.InvariantCulture);
var entry = new LogEntry<string>(level, "Tests", new EventId(0), "Base URL: http://127.0.0.1:8897", null, (state, _) => state);

formatter.Write(entry, null, writer);

Assert.Equal(expected + Environment.NewLine, writer.ToString());
}

private static void Write(ProxyConsoleFormatter formatter, IExternalScopeProvider scopeProvider, TextWriter writer, string message, MessageType type)
{
var log = new RequestLog(message, type, context: null);
Expand Down
12 changes: 12 additions & 0 deletions DevProxy.Tests/SystemProxyManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,18 @@ public async Task RunResetStandalone_InvalidArguments_ReturnsUsageError(params s
Assert.Equal(2, exitCode);
}

// Must be rejected before reset changes any system proxy settings
[Theory]
[InlineData("--output", "json", "system-proxy", "reset", "--force")]
[InlineData("--log-level", "debug", "system-proxy", "reset")]
[InlineData("-c", "devproxyrc.json", "system-proxy", "reset")]
public async Task RunResetStandalone_LeadingOptions_ReturnsUsageError(params string[] args)
{
var exitCode = await DevProxy.Commands.SystemProxyCommand.RunResetStandaloneAsync(args);

Assert.Equal(2, exitCode);
}

[Theory]
[InlineData("system-proxy", "reset")]
[InlineData("system-proxy", "reset", "--force")]
Expand Down
5 changes: 4 additions & 1 deletion DevProxy/Commands/ApiCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ namespace DevProxy.Commands;
sealed class ApiCommand : Command
{
private readonly IProxyConfiguration _proxyConfiguration;
private readonly DevProxyConfigOptions _configOptions;
private readonly ILogger _logger;

public ApiCommand(IProxyConfiguration proxyConfiguration, ILogger<ApiCommand> logger) :
public ApiCommand(IProxyConfiguration proxyConfiguration, DevProxyConfigOptions configOptions, ILogger<ApiCommand> logger) :
base("api", "Manage Dev Proxy API information")
{
_proxyConfiguration = proxyConfiguration;
_configOptions = configOptions;
_logger = logger;
ConfigureCommand();
}
Expand All @@ -33,6 +35,7 @@ private void ConfigureCommand()
var outputFormat = parseResult.GetValueOrDefault<OutputFormat?>(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text;
PrintApiInfo(outputFormat);
});
DevProxyCommand.AddConfigFileOption(apiShowCommand, _configOptions.ConfigFile);

var apiTokenCommand = new Command("token", """
Print the API token of a running Dev Proxy instance.
Expand Down
5 changes: 5 additions & 0 deletions DevProxy/Commands/ConfigCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,21 @@ private enum ConfigFileFormat
private readonly ILogger _logger;
private readonly IProxyConfiguration _proxyConfiguration;
private readonly HttpClient _httpClient;
private readonly DevProxyConfigOptions _configOptions;
private const string ConfigTemplatesFolder = "config-templates";
private static readonly string[] configFilePatterns = ["*.json", "*.yaml", "*.yml"];

public ConfigCommand(
HttpClient httpClient,
IProxyConfiguration proxyConfiguration,
DevProxyConfigOptions configOptions,
ILogger<ConfigCommand> logger) :
base("config", "Manage Dev Proxy configs")
{
_proxyConfiguration = proxyConfiguration;
_logger = logger;
_httpClient = httpClient;
_configOptions = configOptions;
_httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("dev-proxy", ProxyUtils.ProductVersion));
ConfigureCommand();
}
Expand Down Expand Up @@ -111,6 +114,7 @@ internal static async Task<int> RunValidateStandaloneAsync(string[] args)
formatterOptions.IncludeScopes = false;
formatterOptions.ShowSkipMessages = true;
formatterOptions.ShowTimestamps = false;
formatterOptions.PlainOutput = true;
})
.AddConsoleFormatter<JsonConsoleFormatter, ProxyConsoleFormatterOptions>(formatterOptions =>
{
Expand Down Expand Up @@ -210,6 +214,7 @@ private void ConfigureCommand()
};
_ = Process.Start(cfgPsi);
});
DevProxyCommand.AddConfigFileOption(configOpenCommand, _configOptions.ConfigFile);

var configValidateCommand = new Command("validate", "Validate a Dev Proxy configuration file without starting the proxy");
var validateConfigFileOption = CreateValidateConfigFileOption();
Expand Down
Loading
Loading