|
10 | 10 | using DevProxy.Plugins.Models; |
11 | 11 | using Microsoft.Extensions.Configuration; |
12 | 12 | using Microsoft.Extensions.DependencyInjection; |
| 13 | +using Microsoft.Extensions.FileSystemGlobbing; |
13 | 14 | using Microsoft.Extensions.Logging; |
14 | 15 | using System.Collections.Concurrent; |
15 | 16 | using System.CommandLine; |
| 17 | +using System.CommandLine.Invocation; |
16 | 18 | using System.CommandLine.Parsing; |
17 | 19 | using System.Globalization; |
18 | 20 | using System.Net; |
@@ -58,6 +60,8 @@ public class MockResponsePlugin( |
58 | 60 | private readonly ConcurrentDictionary<string, int> _appliedMocks = []; |
59 | 61 |
|
60 | 62 | private MockResponsesLoader? _loader; |
| 63 | + private Argument<IEnumerable<string>>? _httpResponseFilesArgument; |
| 64 | + private Option<string>? _httpResponseMocksFileNameOption; |
61 | 65 |
|
62 | 66 | public override string Name => nameof(MockResponsePlugin); |
63 | 67 |
|
@@ -86,6 +90,31 @@ public override Option[] GetOptions() |
86 | 90 | return [_noMocks, _mocksFile]; |
87 | 91 | } |
88 | 92 |
|
| 93 | + public override Command[] GetCommands() |
| 94 | + { |
| 95 | + var mocksCommand = new Command("mocks", "Manage mock responses"); |
| 96 | + var mocksFromHttpResponseCommand = new Command("from-http-responses", "Create a mock response from HTTP responses"); |
| 97 | + _httpResponseFilesArgument = new Argument<IEnumerable<string>>("http-response-files", "Glob pattern to the file(s) containing HTTP responses to create mock responses from") |
| 98 | + { |
| 99 | + Arity = ArgumentArity.OneOrMore |
| 100 | + }; |
| 101 | + mocksFromHttpResponseCommand.AddArgument(_httpResponseFilesArgument); |
| 102 | + _httpResponseMocksFileNameOption = new Option<string>("--mocks-file", "File to save the generated mock responses to") |
| 103 | + { |
| 104 | + ArgumentHelpName = "mocks file", |
| 105 | + Arity = ArgumentArity.ExactlyOne, |
| 106 | + IsRequired = true |
| 107 | + }; |
| 108 | + mocksFromHttpResponseCommand.AddOption(_httpResponseMocksFileNameOption); |
| 109 | + mocksFromHttpResponseCommand.SetHandler(GenerateMocksFromHttpResponsesAsync); |
| 110 | + |
| 111 | + mocksCommand.AddCommands(new[] |
| 112 | + { |
| 113 | + mocksFromHttpResponseCommand |
| 114 | + }.OrderByName()); |
| 115 | + return [mocksCommand]; |
| 116 | + } |
| 117 | + |
89 | 118 | public override void OptionsLoaded(OptionsLoadedArgs e) |
90 | 119 | { |
91 | 120 | ArgumentNullException.ThrowIfNull(e); |
@@ -389,6 +418,75 @@ private void ProcessMockResponseInternal(ProxyRequestArgs e, MockResponse matchi |
389 | 418 | Logger.LogRequest($"{matchingResponse.Response?.StatusCode ?? 200} {matchingResponse.Request?.Url}", MessageType.Mocked, new(e.Session)); |
390 | 419 | } |
391 | 420 |
|
| 421 | + private async Task GenerateMocksFromHttpResponsesAsync(InvocationContext context) |
| 422 | + { |
| 423 | + Logger.LogTrace("{Method} called", nameof(GenerateMocksFromHttpResponsesAsync)); |
| 424 | + |
| 425 | + if (_httpResponseFilesArgument is null) |
| 426 | + { |
| 427 | + throw new InvalidOperationException("HTTP response files argument is not initialized."); |
| 428 | + } |
| 429 | + if (_httpResponseMocksFileNameOption is null) |
| 430 | + { |
| 431 | + throw new InvalidOperationException("HTTP response mocks file name option is not initialized."); |
| 432 | + } |
| 433 | + |
| 434 | + var outputFilePath = context.ParseResult.GetValueForOption(_httpResponseMocksFileNameOption); |
| 435 | + if (string.IsNullOrEmpty(outputFilePath)) |
| 436 | + { |
| 437 | + Logger.LogError("No output file path provided for mock responses."); |
| 438 | + return; |
| 439 | + } |
| 440 | + |
| 441 | + var httpResponseFiles = context.ParseResult.GetValueForArgument(_httpResponseFilesArgument); |
| 442 | + if (httpResponseFiles is null || !httpResponseFiles.Any()) |
| 443 | + { |
| 444 | + Logger.LogError("No HTTP response files provided."); |
| 445 | + return; |
| 446 | + } |
| 447 | + |
| 448 | + var matcher = new Matcher(); |
| 449 | + matcher.AddIncludePatterns(httpResponseFiles); |
| 450 | + |
| 451 | + var matchingFiles = matcher.GetResultsInFullPath("."); |
| 452 | + if (!matchingFiles.Any()) |
| 453 | + { |
| 454 | + Logger.LogError("No matching HTTP response files found."); |
| 455 | + return; |
| 456 | + } |
| 457 | + |
| 458 | + Logger.LogInformation("Found {FileCount} matching HTTP response files", matchingFiles.Count()); |
| 459 | + Logger.LogDebug("Matching files: {Files}", string.Join(", ", matchingFiles)); |
| 460 | + |
| 461 | + var mockResponses = new List<MockResponse>(); |
| 462 | + foreach (var file in matchingFiles) |
| 463 | + { |
| 464 | + Logger.LogInformation("Processing file: {File}", Path.GetRelativePath(".", file)); |
| 465 | + try |
| 466 | + { |
| 467 | + mockResponses.Add(MockResponse.FromHttpResponse(await File.ReadAllTextAsync(file), Logger)); |
| 468 | + } |
| 469 | + catch (Exception ex) |
| 470 | + { |
| 471 | + Logger.LogError(ex, "Error processing file {File}", file); |
| 472 | + continue; |
| 473 | + } |
| 474 | + } |
| 475 | + |
| 476 | + var mocksFile = new MockResponseConfiguration |
| 477 | + { |
| 478 | + Mocks = mockResponses |
| 479 | + }; |
| 480 | + await File.WriteAllTextAsync( |
| 481 | + outputFilePath, |
| 482 | + JsonSerializer.Serialize(mocksFile, ProxyUtils.JsonSerializerOptions) |
| 483 | + ); |
| 484 | + |
| 485 | + Logger.LogInformation("Generated mock responses saved to {OutputFile}", outputFilePath); |
| 486 | + |
| 487 | + Logger.LogTrace("Left {Method}", nameof(GenerateMocksFromHttpResponsesAsync)); |
| 488 | + } |
| 489 | + |
392 | 490 | private static bool HasMatchingBody(MockResponse mockResponse, Request request) |
393 | 491 | { |
394 | 492 | if (request.Method == "GET") |
|
0 commit comments