|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System.Text.Json; |
| 5 | +using Microsoft.Extensions.Configuration; |
| 6 | +using Microsoft365.DeveloperProxy.Abstractions; |
| 7 | +using Microsoft365.DeveloperProxy.Plugins.MockResponses; |
| 8 | +using Titanium.Web.Proxy.EventArguments; |
| 9 | + |
| 10 | +namespace Microsoft365.DeveloperProxy.Plugins.RequestLogs; |
| 11 | + |
| 12 | +public class MockGeneratorPlugin : BaseProxyPlugin |
| 13 | +{ |
| 14 | + public override string Name => nameof(MockGeneratorPlugin); |
| 15 | + |
| 16 | + public override void Register(IPluginEvents pluginEvents, |
| 17 | + IProxyContext context, |
| 18 | + ISet<UrlToWatch> urlsToWatch, |
| 19 | + IConfigurationSection? configSection = null) |
| 20 | + { |
| 21 | + base.Register(pluginEvents, context, urlsToWatch, configSection); |
| 22 | + |
| 23 | + pluginEvents.AfterRecordingStop += AfterRecordingStop; |
| 24 | + } |
| 25 | + |
| 26 | + private void AfterRecordingStop(object? sender, RecordingArgs e) |
| 27 | + { |
| 28 | + _logger?.LogInfo("Creating mocks from recorded requests..."); |
| 29 | + |
| 30 | + if (!e.RequestLogs.Any()) |
| 31 | + { |
| 32 | + _logger?.LogDebug("No requests to process"); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + var methodAndUrlComparer = new MethodAndUrlComparer(); |
| 37 | + var mocks = new List<MockResponse>(); |
| 38 | + |
| 39 | + foreach (var request in e.RequestLogs) |
| 40 | + { |
| 41 | + if (request.MessageType != MessageType.InterceptedResponse || |
| 42 | + request.Context is null || |
| 43 | + request.Context.Session is null) |
| 44 | + { |
| 45 | + continue; |
| 46 | + } |
| 47 | + |
| 48 | + var methodAndUrlString = request.Message.First(); |
| 49 | + _logger?.LogDebug($"Processing request {methodAndUrlString}..."); |
| 50 | + |
| 51 | + var methodAndUrl = GetMethodAndUrl(methodAndUrlString); |
| 52 | + var response = request.Context.Session.HttpClient.Response; |
| 53 | + |
| 54 | + var mock = new MockResponse |
| 55 | + { |
| 56 | + Method = methodAndUrl.Item1, |
| 57 | + Url = methodAndUrl.Item2, |
| 58 | + ResponseCode = response.StatusCode, |
| 59 | + ResponseHeaders = response.Headers |
| 60 | + .Select(h => new KeyValuePair<string, string>(h.Name, h.Value)) |
| 61 | + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value), |
| 62 | + ResponseBody = GetResponseBody(request.Context.Session).Result |
| 63 | + }; |
| 64 | + // skip mock if it's 200 but has no body |
| 65 | + if (mock.ResponseCode == 200 && mock.ResponseBody is null) |
| 66 | + { |
| 67 | + _logger?.LogDebug("Skipping mock with 200 response code and no body"); |
| 68 | + continue; |
| 69 | + } |
| 70 | + |
| 71 | + mocks.Add(mock); |
| 72 | + _logger?.LogDebug($"Added mock for {mock.Method} {mock.Url}"); |
| 73 | + } |
| 74 | + |
| 75 | + _logger?.LogDebug($"Sorting mocks..."); |
| 76 | + // sort mocks descending by url length so that most specific mocks are first |
| 77 | + mocks.Sort((a, b) => b.Url.CompareTo(a.Url)); |
| 78 | + |
| 79 | + var mocksFile = new MockResponseConfiguration { Responses = mocks }; |
| 80 | + |
| 81 | + _logger?.LogDebug($"Serializing mocks..."); |
| 82 | + var mocksFileJson = JsonSerializer.Serialize(mocksFile, new JsonSerializerOptions { WriteIndented = true }); |
| 83 | + var fileName = $"mocks-{DateTime.Now.ToString("yyyyMMddHHmmss")}.json"; |
| 84 | + |
| 85 | + _logger?.LogDebug($"Writing mocks to {fileName}..."); |
| 86 | + File.WriteAllText(fileName, mocksFileJson); |
| 87 | + |
| 88 | + _logger?.LogInfo($"Created mock file {fileName} with {mocks.Count} mocks"); |
| 89 | + } |
| 90 | + |
| 91 | + /// <summary> |
| 92 | + /// Returns the body of the response. For binary responses, |
| 93 | + /// saves the binary response as a file on disk and returns @filename |
| 94 | + /// </summary> |
| 95 | + /// <param name="session">Request session</param> |
| 96 | + /// <returns>Response body or @filename for binary responses</returns> |
| 97 | + private async Task<dynamic?> GetResponseBody(SessionEventArgs session) |
| 98 | + { |
| 99 | + _logger?.LogDebug("Getting response body..."); |
| 100 | + |
| 101 | + var response = session.HttpClient.Response; |
| 102 | + if (response.ContentType is null || !response.HasBody) |
| 103 | + { |
| 104 | + _logger?.LogDebug("Response has no content-type set or has no body. Skipping"); |
| 105 | + return null; |
| 106 | + } |
| 107 | + |
| 108 | + if (response.ContentType.Contains("application/json")) |
| 109 | + { |
| 110 | + _logger?.LogDebug("Response is JSON"); |
| 111 | + |
| 112 | + try |
| 113 | + { |
| 114 | + _logger?.LogDebug("Reading response body as string..."); |
| 115 | + var body = response.IsBodyRead ? response.BodyString : await session.GetResponseBodyAsString(); |
| 116 | + _logger?.LogDebug($"Body: {body}"); |
| 117 | + _logger?.LogDebug("Deserializing response body..."); |
| 118 | + return JsonSerializer.Deserialize<dynamic>(body); |
| 119 | + } |
| 120 | + catch (Exception ex) |
| 121 | + { |
| 122 | + _logger?.LogError($"Error reading response body: {ex.Message}"); |
| 123 | + return null; |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + _logger?.LogDebug("Response is binary"); |
| 128 | + // assume body is binary |
| 129 | + try |
| 130 | + { |
| 131 | + var filename = $"response-{DateTime.Now.ToString("yyyyMMddHHmmss")}.bin"; |
| 132 | + _logger?.LogDebug("Reading response body as bytes..."); |
| 133 | + var body = await session.GetResponseBody(); |
| 134 | + _logger?.LogDebug($"Writing response body to {filename}..."); |
| 135 | + File.WriteAllBytes(filename, body); |
| 136 | + return $"@{filename}"; |
| 137 | + } |
| 138 | + catch (Exception ex) |
| 139 | + { |
| 140 | + _logger?.LogError($"Error reading response body: {ex.Message}"); |
| 141 | + return null; |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + private Tuple<string, string> GetMethodAndUrl(string message) |
| 146 | + { |
| 147 | + var info = message.Split(" "); |
| 148 | + if (info.Length > 2) |
| 149 | + { |
| 150 | + info = new[] { info[0], String.Join(" ", info.Skip(1)) }; |
| 151 | + } |
| 152 | + return new Tuple<string, string>(info[0], info[1]); |
| 153 | + } |
| 154 | +} |
0 commit comments