| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.IO; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Net.Http; |
| | | 6 | | using System.Text; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using JetBrains.Annotations; |
| | | 9 | | using Newtonsoft.Json; |
| | | 10 | | using Newtonsoft.Json.Linq; |
| | | 11 | | using WireMock.Admin.Mappings; |
| | | 12 | | using WireMock.Admin.Requests; |
| | | 13 | | using WireMock.Admin.Settings; |
| | | 14 | | using WireMock.Http; |
| | | 15 | | using WireMock.Logging; |
| | | 16 | | using WireMock.Matchers; |
| | | 17 | | using WireMock.Matchers.Request; |
| | | 18 | | using WireMock.RequestBuilders; |
| | | 19 | | using WireMock.ResponseBuilders; |
| | | 20 | | using WireMock.ResponseProviders; |
| | | 21 | | using WireMock.Serialization; |
| | | 22 | | using WireMock.Settings; |
| | | 23 | | using WireMock.Util; |
| | | 24 | | using WireMock.Validation; |
| | | 25 | | |
| | | 26 | | namespace WireMock.Server |
| | | 27 | | { |
| | | 28 | | /// <summary> |
| | | 29 | | /// The fluent mock server. |
| | | 30 | | /// </summary> |
| | | 31 | | public partial class FluentMockServer |
| | | 32 | | { |
| | 1 | 33 | | private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings"); |
| | | 34 | | private const string ContentTypeJson = "application/json"; |
| | | 35 | | private const string AdminMappings = "/__admin/mappings"; |
| | | 36 | | private const string AdminRequests = "/__admin/requests"; |
| | | 37 | | private const string AdminSettings = "/__admin/settings"; |
| | | 38 | | private const string AdminScenarios = "/__admin/scenarios"; |
| | 47 | 39 | | private readonly RegexMatcher _adminMappingsGuidPathMatcher = new RegexMatcher(@"^\/__admin\/mappings\/(\{{0,1}( |
| | 47 | 40 | | private readonly RegexMatcher _adminRequestsGuidPathMatcher = new RegexMatcher(@"^\/__admin\/requests\/(\{{0,1}( |
| | | 41 | | |
| | 47 | 42 | | private readonly JsonSerializerSettings _settings = new JsonSerializerSettings |
| | 47 | 43 | | { |
| | 47 | 44 | | Formatting = Formatting.Indented, |
| | 47 | 45 | | NullValueHandling = NullValueHandling.Ignore, |
| | 47 | 46 | | }; |
| | | 47 | | |
| | | 48 | | #region InitAdmin |
| | | 49 | | private void InitAdmin() |
| | 3 | 50 | | { |
| | | 51 | | // __admin/settings |
| | 3 | 52 | | Given(Request.Create().WithPath(AdminSettings).UsingGet()).RespondWith(new DynamicResponseProvider(SettingsG |
| | 3 | 53 | | Given(Request.Create().WithPath(AdminSettings).UsingVerb("PUT", "POST").WithHeader(HttpKnownHeaderNames.Cont |
| | | 54 | | |
| | | 55 | | |
| | | 56 | | // __admin/mappings |
| | 3 | 57 | | Given(Request.Create().WithPath(AdminMappings).UsingGet()).RespondWith(new DynamicResponseProvider(MappingsG |
| | 3 | 58 | | Given(Request.Create().WithPath(AdminMappings).UsingPost().WithHeader(HttpKnownHeaderNames.ContentType, Cont |
| | 3 | 59 | | Given(Request.Create().WithPath(AdminMappings).UsingDelete()).RespondWith(new DynamicResponseProvider(Mappin |
| | | 60 | | |
| | | 61 | | // __admin/mappings/reset |
| | 3 | 62 | | Given(Request.Create().WithPath(AdminMappings + "/reset").UsingPost()).RespondWith(new DynamicResponseProvid |
| | | 63 | | |
| | | 64 | | // __admin/mappings/{guid} |
| | 3 | 65 | | Given(Request.Create().WithPath(_adminMappingsGuidPathMatcher).UsingGet()).RespondWith(new DynamicResponsePr |
| | 3 | 66 | | Given(Request.Create().WithPath(_adminMappingsGuidPathMatcher).UsingPut().WithHeader(HttpKnownHeaderNames.Co |
| | 3 | 67 | | Given(Request.Create().WithPath(_adminMappingsGuidPathMatcher).UsingDelete()).RespondWith(new DynamicRespons |
| | | 68 | | |
| | | 69 | | // __admin/mappings/save |
| | 3 | 70 | | Given(Request.Create().WithPath(AdminMappings + "/save").UsingPost()).RespondWith(new DynamicResponseProvide |
| | | 71 | | |
| | | 72 | | |
| | | 73 | | // __admin/requests |
| | 3 | 74 | | Given(Request.Create().WithPath(AdminRequests).UsingGet()).RespondWith(new DynamicResponseProvider(RequestsG |
| | 3 | 75 | | Given(Request.Create().WithPath(AdminRequests).UsingDelete()).RespondWith(new DynamicResponseProvider(Reques |
| | | 76 | | |
| | | 77 | | // __admin/requests/reset |
| | 3 | 78 | | Given(Request.Create().WithPath(AdminRequests + "/reset").UsingPost()).RespondWith(new DynamicResponseProvid |
| | | 79 | | |
| | | 80 | | // __admin/request/{guid} |
| | 3 | 81 | | Given(Request.Create().WithPath(_adminRequestsGuidPathMatcher).UsingGet()).RespondWith(new DynamicResponsePr |
| | 3 | 82 | | Given(Request.Create().WithPath(_adminRequestsGuidPathMatcher).UsingDelete()).RespondWith(new DynamicRespons |
| | | 83 | | |
| | | 84 | | // __admin/requests/find |
| | 3 | 85 | | Given(Request.Create().WithPath(AdminRequests + "/find").UsingPost()).RespondWith(new DynamicResponseProvide |
| | | 86 | | |
| | | 87 | | |
| | | 88 | | // __admin/scenarios |
| | 3 | 89 | | Given(Request.Create().WithPath(AdminScenarios).UsingGet()).RespondWith(new DynamicResponseProvider(Scenario |
| | 3 | 90 | | Given(Request.Create().WithPath(AdminScenarios).UsingDelete()).RespondWith(new DynamicResponseProvider(Scena |
| | | 91 | | |
| | | 92 | | // __admin/scenarios/reset |
| | 3 | 93 | | Given(Request.Create().WithPath(AdminScenarios + "/reset").UsingPost()).RespondWith(new DynamicResponseProvi |
| | 3 | 94 | | } |
| | | 95 | | #endregion |
| | | 96 | | |
| | | 97 | | #region StaticMappings |
| | | 98 | | /// <summary> |
| | | 99 | | /// Reads the static mappings from a folder. |
| | | 100 | | /// </summary> |
| | | 101 | | /// <param name="folder">The optional folder. If not defined, use \__admin\mappings\</param> |
| | | 102 | | [PublicAPI] |
| | | 103 | | public void ReadStaticMappings([CanBeNull] string folder = null) |
| | 1 | 104 | | { |
| | 1 | 105 | | if (folder == null) |
| | 0 | 106 | | { |
| | 0 | 107 | | folder = Path.Combine(Directory.GetCurrentDirectory(), AdminMappingsFolder); |
| | 0 | 108 | | } |
| | | 109 | | |
| | 1 | 110 | | if (!Directory.Exists(folder)) |
| | 0 | 111 | | { |
| | 0 | 112 | | return; |
| | | 113 | | } |
| | | 114 | | |
| | 9 | 115 | | foreach (string filename in Directory.EnumerateFiles(folder).OrderBy(f => f)) |
| | 2 | 116 | | { |
| | 2 | 117 | | _logger.Info("Reading Static MappingFile : '{0}'", filename); |
| | 2 | 118 | | ReadStaticMappingAndAddOrUpdate(filename); |
| | 2 | 119 | | } |
| | 1 | 120 | | } |
| | | 121 | | |
| | | 122 | | /// <summary> |
| | | 123 | | /// Watches the static mappings for changes. |
| | | 124 | | /// </summary> |
| | | 125 | | /// <param name="folder">The optional folder. If not defined, use \__admin\mappings\</param> |
| | | 126 | | [PublicAPI] |
| | | 127 | | public void WatchStaticMappings([CanBeNull] string folder = null) |
| | 0 | 128 | | { |
| | 0 | 129 | | if (folder == null) |
| | 0 | 130 | | { |
| | 0 | 131 | | folder = Path.Combine(Directory.GetCurrentDirectory(), AdminMappingsFolder); |
| | 0 | 132 | | } |
| | | 133 | | |
| | 0 | 134 | | if (!Directory.Exists(folder)) |
| | 0 | 135 | | { |
| | 0 | 136 | | return; |
| | | 137 | | } |
| | | 138 | | |
| | 0 | 139 | | _logger.Info("Watching folder '{0}' for new, updated and deleted MappingFiles.", folder); |
| | | 140 | | |
| | 0 | 141 | | var watcher = new EnhancedFileSystemWatcher(folder, "*.json", 1000); |
| | 0 | 142 | | watcher.Created += (sender, args) => |
| | 0 | 143 | | { |
| | 0 | 144 | | _logger.Info("New MappingFile created : '{0}'", args.FullPath); |
| | 0 | 145 | | ReadStaticMappingAndAddOrUpdate(args.FullPath); |
| | 0 | 146 | | }; |
| | 0 | 147 | | watcher.Changed += (sender, args) => |
| | 0 | 148 | | { |
| | 0 | 149 | | _logger.Info("New MappingFile updated : '{0}'", args.FullPath); |
| | 0 | 150 | | ReadStaticMappingAndAddOrUpdate(args.FullPath); |
| | 0 | 151 | | }; |
| | 0 | 152 | | watcher.Deleted += (sender, args) => |
| | 0 | 153 | | { |
| | 0 | 154 | | _logger.Info("New MappingFile deleted : '{0}'", args.FullPath); |
| | 0 | 155 | | string filenameWithoutExtension = Path.GetFileNameWithoutExtension(args.FullPath); |
| | 0 | 156 | | |
| | 0 | 157 | | if (Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename)) |
| | 0 | 158 | | { |
| | 0 | 159 | | DeleteMapping(guidFromFilename); |
| | 0 | 160 | | } |
| | 0 | 161 | | else |
| | 0 | 162 | | { |
| | 0 | 163 | | DeleteMapping(args.FullPath); |
| | 0 | 164 | | } |
| | 0 | 165 | | }; |
| | | 166 | | |
| | 0 | 167 | | watcher.EnableRaisingEvents = true; |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Reads a static mapping file and adds or updates the mapping. |
| | | 172 | | /// </summary> |
| | | 173 | | /// <param name="path">The path.</param> |
| | | 174 | | [PublicAPI] |
| | | 175 | | public void ReadStaticMappingAndAddOrUpdate([NotNull] string path) |
| | 4 | 176 | | { |
| | 4 | 177 | | Check.NotNull(path, nameof(path)); |
| | | 178 | | |
| | 4 | 179 | | string filenameWithoutExtension = Path.GetFileNameWithoutExtension(path); |
| | | 180 | | |
| | 4 | 181 | | MappingModel mappingModel = JsonConvert.DeserializeObject<MappingModel>(FileHelper.ReadAllText(path)); |
| | 4 | 182 | | if (Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename)) |
| | 2 | 183 | | { |
| | 2 | 184 | | DeserializeAndAddOrUpdateMapping(mappingModel, guidFromFilename, path); |
| | 2 | 185 | | } |
| | | 186 | | else |
| | 2 | 187 | | { |
| | 2 | 188 | | DeserializeAndAddOrUpdateMapping(mappingModel, null, path); |
| | 2 | 189 | | } |
| | 4 | 190 | | } |
| | | 191 | | #endregion |
| | | 192 | | |
| | | 193 | | #region Proxy and Record |
| | | 194 | | private HttpClient _httpClientForProxy; |
| | | 195 | | |
| | | 196 | | private void InitProxyAndRecord(IProxyAndRecordSettings settings) |
| | 2 | 197 | | { |
| | 2 | 198 | | _httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ClientX509Certificate2ThumbprintOrSubjectNa |
| | 2 | 199 | | Given(Request.Create().WithPath("/*").UsingAnyVerb()).RespondWith(new ProxyAsyncResponseProvider(ProxyAndRec |
| | 2 | 200 | | } |
| | | 201 | | |
| | | 202 | | private async Task<ResponseMessage> ProxyAndRecordAsync(RequestMessage requestMessage, IProxyAndRecordSettings s |
| | 2 | 203 | | { |
| | 2 | 204 | | var requestUri = new Uri(requestMessage.Url); |
| | 2 | 205 | | var proxyUri = new Uri(settings.Url); |
| | 2 | 206 | | var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery); |
| | | 207 | | |
| | 2 | 208 | | var responseMessage = await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequ |
| | | 209 | | |
| | 2 | 210 | | if (settings.SaveMapping) |
| | 2 | 211 | | { |
| | 2 | 212 | | var mapping = ToMapping(requestMessage, responseMessage, settings.BlackListedHeaders ?? new string[] { } |
| | 2 | 213 | | _options.Mappings.Add(mapping.Guid, mapping); |
| | | 214 | | |
| | 2 | 215 | | if (settings.SaveMappingToFile) |
| | 0 | 216 | | { |
| | 0 | 217 | | SaveMappingToFile(mapping); |
| | 0 | 218 | | } |
| | 2 | 219 | | } |
| | | 220 | | |
| | 2 | 221 | | return responseMessage; |
| | 2 | 222 | | } |
| | | 223 | | |
| | | 224 | | private Mapping ToMapping(RequestMessage requestMessage, ResponseMessage responseMessage, string[] blacklistedHe |
| | 2 | 225 | | { |
| | 2 | 226 | | var request = Request.Create(); |
| | 2 | 227 | | request.WithPath(requestMessage.Path); |
| | 2 | 228 | | request.UsingVerb(requestMessage.Method); |
| | | 229 | | |
| | 2 | 230 | | requestMessage.Query.Loop((key, value) => request.WithParam(key, value.ToArray())); |
| | 2 | 231 | | requestMessage.Cookies.Loop((key, value) => request.WithCookie(key, value)); |
| | | 232 | | |
| | 2 | 233 | | var allBlackListedHeaders = new List<string>(blacklistedHeaders) { "Cookie" }; |
| | 2 | 234 | | requestMessage.Headers.Loop((key, value) => |
| | 15 | 235 | | { |
| | 34 | 236 | | if (!allBlackListedHeaders.Any(b => string.Equals(key, b, StringComparison.OrdinalIgnoreCase))) |
| | 14 | 237 | | { |
| | 14 | 238 | | request.WithHeader(key, value.ToArray()); |
| | 14 | 239 | | } |
| | 15 | 240 | | }); |
| | | 241 | | |
| | 2 | 242 | | if (requestMessage.Body != null) |
| | 2 | 243 | | { |
| | 2 | 244 | | request.WithBody(new ExactMatcher(requestMessage.Body)); |
| | 2 | 245 | | } |
| | | 246 | | |
| | 2 | 247 | | var response = Response.Create(responseMessage); |
| | | 248 | | |
| | 2 | 249 | | return new Mapping(Guid.NewGuid(), string.Empty, null, request, response, 0, null, null, null); |
| | 2 | 250 | | } |
| | | 251 | | #endregion |
| | | 252 | | |
| | | 253 | | #region Settings |
| | | 254 | | private ResponseMessage SettingsGet(RequestMessage requestMessage) |
| | 0 | 255 | | { |
| | 0 | 256 | | var model = new SettingsModel |
| | 0 | 257 | | { |
| | 0 | 258 | | AllowPartialMapping = _options.AllowPartialMapping, |
| | 0 | 259 | | MaxRequestLogCount = _options.MaxRequestLogCount, |
| | 0 | 260 | | RequestLogExpirationDuration = _options.RequestLogExpirationDuration, |
| | 0 | 261 | | GlobalProcessingDelay = (int?)_options.RequestProcessingDelay?.TotalMilliseconds |
| | 0 | 262 | | }; |
| | | 263 | | |
| | 0 | 264 | | return ToJson(model); |
| | 0 | 265 | | } |
| | | 266 | | |
| | | 267 | | private ResponseMessage SettingsUpdate(RequestMessage requestMessage) |
| | 0 | 268 | | { |
| | 0 | 269 | | var settings = requestMessage.Body != null ? JsonConvert.DeserializeObject<SettingsModel>(requestMessage.Bod |
| | | 270 | | |
| | 0 | 271 | | if (settings.AllowPartialMapping != null) |
| | 0 | 272 | | _options.AllowPartialMapping = settings.AllowPartialMapping.Value; |
| | | 273 | | |
| | 0 | 274 | | _options.MaxRequestLogCount = settings.MaxRequestLogCount; |
| | | 275 | | |
| | 0 | 276 | | _options.RequestLogExpirationDuration = settings.RequestLogExpirationDuration; |
| | | 277 | | |
| | 0 | 278 | | if (settings.GlobalProcessingDelay != null) |
| | 0 | 279 | | _options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value); |
| | | 280 | | |
| | 0 | 281 | | return new ResponseMessage { Body = "Settings updated" }; |
| | 0 | 282 | | } |
| | | 283 | | #endregion Settings |
| | | 284 | | |
| | | 285 | | #region Mapping/{guid} |
| | | 286 | | private ResponseMessage MappingGet(RequestMessage requestMessage) |
| | 0 | 287 | | { |
| | 0 | 288 | | Guid guid = Guid.Parse(requestMessage.Path.Substring(AdminMappings.Length + 1)); |
| | 0 | 289 | | var mapping = Mappings.FirstOrDefault(m => !m.IsAdminInterface && m.Guid == guid); |
| | | 290 | | |
| | 0 | 291 | | if (mapping == null) |
| | 0 | 292 | | { |
| | 0 | 293 | | _logger.Warn("HttpStatusCode set to 404 : Mapping not found"); |
| | 0 | 294 | | return new ResponseMessage { StatusCode = 404, Body = "Mapping not found" }; |
| | | 295 | | } |
| | | 296 | | |
| | 0 | 297 | | var model = MappingConverter.ToMappingModel(mapping); |
| | | 298 | | |
| | 0 | 299 | | return ToJson(model); |
| | 0 | 300 | | } |
| | | 301 | | |
| | | 302 | | private ResponseMessage MappingPut(RequestMessage requestMessage) |
| | 0 | 303 | | { |
| | 0 | 304 | | Guid guid = Guid.Parse(requestMessage.Path.TrimStart(AdminMappings.ToCharArray())); |
| | | 305 | | |
| | 0 | 306 | | MappingModel mappingModel = requestMessage.Body != null ? JsonConvert.DeserializeObject<MappingModel>(reques |
| | 0 | 307 | | DeserializeAndAddOrUpdateMapping(mappingModel, guid); |
| | | 308 | | |
| | 0 | 309 | | return new ResponseMessage { Body = "Mapping added or updated" }; |
| | 0 | 310 | | } |
| | | 311 | | |
| | | 312 | | private ResponseMessage MappingDelete(RequestMessage requestMessage) |
| | 0 | 313 | | { |
| | 0 | 314 | | Guid guid = Guid.Parse(requestMessage.Path.Substring(AdminMappings.Length + 1)); |
| | | 315 | | |
| | 0 | 316 | | if (DeleteMapping(guid)) |
| | 0 | 317 | | { |
| | 0 | 318 | | return new ResponseMessage { Body = "Mapping removed" }; |
| | | 319 | | } |
| | | 320 | | |
| | 0 | 321 | | return new ResponseMessage { Body = "Mapping not found" }; |
| | 0 | 322 | | } |
| | | 323 | | #endregion Mapping/{guid} |
| | | 324 | | |
| | | 325 | | #region Mappings |
| | | 326 | | private ResponseMessage MappingsSave(RequestMessage requestMessage) |
| | 0 | 327 | | { |
| | 0 | 328 | | foreach (var mapping in Mappings.Where(m => !m.IsAdminInterface)) |
| | 0 | 329 | | { |
| | 0 | 330 | | SaveMappingToFile(mapping); |
| | 0 | 331 | | } |
| | | 332 | | |
| | 0 | 333 | | return new ResponseMessage { Body = "Mappings saved to disk" }; |
| | 0 | 334 | | } |
| | | 335 | | |
| | | 336 | | private void SaveMappingToFile(Mapping mapping) |
| | 0 | 337 | | { |
| | 0 | 338 | | string folder = Path.Combine(Directory.GetCurrentDirectory(), AdminMappingsFolder); |
| | 0 | 339 | | if (!Directory.Exists(folder)) |
| | 0 | 340 | | { |
| | 0 | 341 | | Directory.CreateDirectory(folder); |
| | 0 | 342 | | } |
| | | 343 | | |
| | 0 | 344 | | var model = MappingConverter.ToMappingModel(mapping); |
| | 0 | 345 | | string filename = !string.IsNullOrEmpty(mapping.Title) ? SanitizeFileName(mapping.Title) : mapping.Guid.ToSt |
| | | 346 | | |
| | 0 | 347 | | string filePath = Path.Combine(folder, filename + ".json"); |
| | 0 | 348 | | _logger.Info("Saving Mapping to file {0}", filePath); |
| | | 349 | | |
| | 0 | 350 | | File.WriteAllText(filePath, JsonConvert.SerializeObject(model, _settings)); |
| | 0 | 351 | | } |
| | | 352 | | |
| | | 353 | | private static string SanitizeFileName(string name, char replaceChar = '_') |
| | 0 | 354 | | { |
| | 0 | 355 | | return Path.GetInvalidFileNameChars().Aggregate(name, (current, c) => current.Replace(c, replaceChar)); |
| | 0 | 356 | | } |
| | | 357 | | |
| | | 358 | | private ResponseMessage MappingsGet(RequestMessage requestMessage) |
| | 0 | 359 | | { |
| | 0 | 360 | | var result = new List<MappingModel>(); |
| | 0 | 361 | | foreach (var mapping in Mappings.Where(m => !m.IsAdminInterface)) |
| | 0 | 362 | | { |
| | 0 | 363 | | var model = MappingConverter.ToMappingModel(mapping); |
| | 0 | 364 | | result.Add(model); |
| | 0 | 365 | | } |
| | | 366 | | |
| | 0 | 367 | | return ToJson(result); |
| | 0 | 368 | | } |
| | | 369 | | |
| | | 370 | | private ResponseMessage MappingsPost(RequestMessage requestMessage) |
| | 1 | 371 | | { |
| | | 372 | | try |
| | 1 | 373 | | { |
| | 1 | 374 | | MappingModel mappingModel = requestMessage.Body != null ? JsonConvert.DeserializeObject<MappingModel>(re |
| | 1 | 375 | | DeserializeAndAddOrUpdateMapping(mappingModel); |
| | 1 | 376 | | } |
| | 0 | 377 | | catch (ArgumentException a) |
| | 0 | 378 | | { |
| | 0 | 379 | | _logger.Error("HttpStatusCode set to 400 {0}", a); |
| | 0 | 380 | | return new ResponseMessage { StatusCode = 400, Body = a.Message }; |
| | | 381 | | } |
| | 0 | 382 | | catch (Exception e) |
| | 0 | 383 | | { |
| | 0 | 384 | | _logger.Error("HttpStatusCode set to 500 {0}", e); |
| | 0 | 385 | | return new ResponseMessage { StatusCode = 500, Body = e.ToString() }; |
| | | 386 | | } |
| | | 387 | | |
| | 1 | 388 | | return new ResponseMessage { StatusCode = 201, Body = "Mapping added" }; |
| | 1 | 389 | | } |
| | | 390 | | |
| | | 391 | | private void DeserializeAndAddOrUpdateMapping(MappingModel mappingModel, Guid? guid = null, string path = null) |
| | 5 | 392 | | { |
| | 5 | 393 | | Check.NotNull(mappingModel, nameof(mappingModel)); |
| | 5 | 394 | | Check.NotNull(mappingModel.Request, nameof(mappingModel.Request)); |
| | 5 | 395 | | Check.NotNull(mappingModel.Response, nameof(mappingModel.Response)); |
| | | 396 | | |
| | 5 | 397 | | var requestBuilder = InitRequestBuilder(mappingModel.Request); |
| | 5 | 398 | | var responseBuilder = InitResponseBuilder(mappingModel.Response); |
| | | 399 | | |
| | 5 | 400 | | IRespondWithAProvider respondProvider = Given(requestBuilder); |
| | | 401 | | |
| | 5 | 402 | | if (guid != null) |
| | 2 | 403 | | { |
| | 2 | 404 | | respondProvider = respondProvider.WithGuid(guid.Value); |
| | 2 | 405 | | } |
| | 3 | 406 | | else if (mappingModel.Guid != null && mappingModel.Guid != Guid.Empty) |
| | 2 | 407 | | { |
| | 2 | 408 | | respondProvider = respondProvider.WithGuid(mappingModel.Guid.Value); |
| | 2 | 409 | | } |
| | | 410 | | |
| | 5 | 411 | | if (path != null) |
| | 4 | 412 | | { |
| | 4 | 413 | | respondProvider = respondProvider.WithPath(path); |
| | 4 | 414 | | } |
| | | 415 | | |
| | 5 | 416 | | if (!string.IsNullOrEmpty(mappingModel.Title)) |
| | 3 | 417 | | { |
| | 3 | 418 | | respondProvider = respondProvider.WithTitle(mappingModel.Title); |
| | 3 | 419 | | } |
| | | 420 | | |
| | 5 | 421 | | if (mappingModel.Priority != null) |
| | 5 | 422 | | { |
| | 5 | 423 | | respondProvider = respondProvider.AtPriority(mappingModel.Priority.Value); |
| | 5 | 424 | | } |
| | | 425 | | |
| | 5 | 426 | | if (mappingModel.Scenario != null) |
| | 0 | 427 | | { |
| | 0 | 428 | | respondProvider = respondProvider.InScenario(mappingModel.Scenario); |
| | 0 | 429 | | respondProvider = respondProvider.WhenStateIs(mappingModel.WhenStateIs); |
| | 0 | 430 | | respondProvider = respondProvider.WillSetStateTo(mappingModel.SetStateTo); |
| | 0 | 431 | | } |
| | | 432 | | |
| | 5 | 433 | | respondProvider.RespondWith(responseBuilder); |
| | 5 | 434 | | } |
| | | 435 | | |
| | | 436 | | private ResponseMessage MappingsDelete(RequestMessage requestMessage) |
| | 0 | 437 | | { |
| | 0 | 438 | | ResetMappings(); |
| | | 439 | | |
| | 0 | 440 | | ResetScenarios(); |
| | | 441 | | |
| | 0 | 442 | | return new ResponseMessage { Body = "Mappings deleted" }; |
| | 0 | 443 | | } |
| | | 444 | | #endregion Mappings |
| | | 445 | | |
| | | 446 | | #region Request/{guid} |
| | | 447 | | private ResponseMessage RequestGet(RequestMessage requestMessage) |
| | 0 | 448 | | { |
| | 0 | 449 | | Guid guid = Guid.Parse(requestMessage.Path.Substring(AdminRequests.Length + 1)); |
| | 0 | 450 | | var entry = LogEntries.FirstOrDefault(r => !r.RequestMessage.Path.StartsWith("/__admin/") && r.Guid == guid) |
| | | 451 | | |
| | 0 | 452 | | if (entry == null) |
| | 0 | 453 | | { |
| | 0 | 454 | | _logger.Warn("HttpStatusCode set to 404 : Request not found"); |
| | 0 | 455 | | return new ResponseMessage { StatusCode = 404, Body = "Request not found" }; |
| | | 456 | | } |
| | | 457 | | |
| | 0 | 458 | | var model = ToLogEntryModel(entry); |
| | | 459 | | |
| | 0 | 460 | | return ToJson(model); |
| | 0 | 461 | | } |
| | | 462 | | |
| | | 463 | | private ResponseMessage RequestDelete(RequestMessage requestMessage) |
| | 0 | 464 | | { |
| | 0 | 465 | | Guid guid = Guid.Parse(requestMessage.Path.Substring(AdminRequests.Length + 1)); |
| | | 466 | | |
| | 0 | 467 | | if (DeleteLogEntry(guid)) |
| | 0 | 468 | | return new ResponseMessage { Body = "Request removed" }; |
| | | 469 | | |
| | 0 | 470 | | return new ResponseMessage { Body = "Request not found" }; |
| | 0 | 471 | | } |
| | | 472 | | #endregion Request/{guid} |
| | | 473 | | |
| | | 474 | | #region Requests |
| | | 475 | | private ResponseMessage RequestsGet(RequestMessage requestMessage) |
| | 1 | 476 | | { |
| | 1 | 477 | | var result = LogEntries |
| | 2 | 478 | | .Where(r => !r.RequestMessage.Path.StartsWith("/__admin/")) |
| | 1 | 479 | | .Select(ToLogEntryModel); |
| | | 480 | | |
| | 1 | 481 | | return ToJson(result); |
| | 1 | 482 | | } |
| | | 483 | | |
| | | 484 | | private LogEntryModel ToLogEntryModel(LogEntry logEntry) |
| | 2 | 485 | | { |
| | 2 | 486 | | return new LogEntryModel |
| | 2 | 487 | | { |
| | 2 | 488 | | Guid = logEntry.Guid, |
| | 2 | 489 | | Request = new LogRequestModel |
| | 2 | 490 | | { |
| | 2 | 491 | | DateTime = logEntry.RequestMessage.DateTime, |
| | 2 | 492 | | ClientIP = logEntry.RequestMessage.ClientIP, |
| | 2 | 493 | | Path = logEntry.RequestMessage.Path, |
| | 2 | 494 | | AbsoluteUrl = logEntry.RequestMessage.Url, |
| | 2 | 495 | | Query = logEntry.RequestMessage.Query, |
| | 2 | 496 | | Method = logEntry.RequestMessage.Method, |
| | 2 | 497 | | Body = logEntry.RequestMessage.Body, |
| | 2 | 498 | | BodyAsJson = logEntry.RequestMessage.BodyAsJson, |
| | 2 | 499 | | BodyAsBytes = logEntry.RequestMessage.BodyAsBytes, |
| | 2 | 500 | | Headers = logEntry.RequestMessage.Headers, |
| | 2 | 501 | | Cookies = logEntry.RequestMessage.Cookies, |
| | 2 | 502 | | BodyEncoding = logEntry.RequestMessage.BodyEncoding != null ? new EncodingModel |
| | 2 | 503 | | { |
| | 2 | 504 | | EncodingName = logEntry.RequestMessage.BodyEncoding.EncodingName, |
| | 2 | 505 | | CodePage = logEntry.RequestMessage.BodyEncoding.CodePage, |
| | 2 | 506 | | WebName = logEntry.RequestMessage.BodyEncoding.WebName |
| | 2 | 507 | | } : null |
| | 2 | 508 | | }, |
| | 2 | 509 | | Response = new LogResponseModel |
| | 2 | 510 | | { |
| | 2 | 511 | | StatusCode = logEntry.ResponseMessage.StatusCode, |
| | 2 | 512 | | BodyDestination = logEntry.ResponseMessage.BodyDestination, |
| | 2 | 513 | | Body = logEntry.ResponseMessage.Body, |
| | 2 | 514 | | BodyAsJson = logEntry.ResponseMessage.BodyAsJson, |
| | 2 | 515 | | BodyAsBytes = logEntry.ResponseMessage.BodyAsBytes, |
| | 2 | 516 | | BodyOriginal = logEntry.ResponseMessage.BodyOriginal, |
| | 2 | 517 | | BodyAsFile = logEntry.ResponseMessage.BodyAsFile, |
| | 2 | 518 | | BodyAsFileIsCached = logEntry.ResponseMessage.BodyAsFileIsCached, |
| | 2 | 519 | | Headers = logEntry.ResponseMessage.Headers, |
| | 2 | 520 | | BodyEncoding = logEntry.ResponseMessage.BodyEncoding != null ? new EncodingModel |
| | 2 | 521 | | { |
| | 2 | 522 | | EncodingName = logEntry.ResponseMessage.BodyEncoding.EncodingName, |
| | 2 | 523 | | CodePage = logEntry.ResponseMessage.BodyEncoding.CodePage, |
| | 2 | 524 | | WebName = logEntry.ResponseMessage.BodyEncoding.WebName |
| | 2 | 525 | | } : null |
| | 2 | 526 | | }, |
| | 2 | 527 | | MappingGuid = logEntry.MappingGuid, |
| | 2 | 528 | | MappingTitle = logEntry.MappingTitle, |
| | 2 | 529 | | RequestMatchResult = logEntry.RequestMatchResult != null ? new LogRequestMatchModel |
| | 2 | 530 | | { |
| | 2 | 531 | | TotalScore = logEntry.RequestMatchResult.TotalScore, |
| | 2 | 532 | | TotalNumber = logEntry.RequestMatchResult.TotalNumber, |
| | 2 | 533 | | IsPerfectMatch = logEntry.RequestMatchResult.IsPerfectMatch, |
| | 2 | 534 | | AverageTotalScore = logEntry.RequestMatchResult.AverageTotalScore, |
| | 2 | 535 | | MatchDetails = logEntry.RequestMatchResult.MatchDetails.Select(x => new |
| | 2 | 536 | | { |
| | 2 | 537 | | Name = x.Key.Name.Replace("RequestMessage", string.Empty), |
| | 2 | 538 | | Score = x.Value |
| | 2 | 539 | | } as object).ToList() |
| | 2 | 540 | | } : null |
| | 2 | 541 | | }; |
| | 2 | 542 | | } |
| | | 543 | | |
| | | 544 | | private ResponseMessage RequestsDelete(RequestMessage requestMessage) |
| | 0 | 545 | | { |
| | 0 | 546 | | ResetLogEntries(); |
| | | 547 | | |
| | 0 | 548 | | return new ResponseMessage { Body = "Requests deleted" }; |
| | 0 | 549 | | } |
| | | 550 | | #endregion Requests |
| | | 551 | | |
| | | 552 | | #region Requests/find |
| | | 553 | | private ResponseMessage RequestsFind(RequestMessage requestMessage) |
| | 1 | 554 | | { |
| | 1 | 555 | | var requestModel = requestMessage.Body != null ? JsonConvert.DeserializeObject<RequestModel>(requestMessage. |
| | | 556 | | |
| | 1 | 557 | | var request = (Request)InitRequestBuilder(requestModel); |
| | | 558 | | |
| | 1 | 559 | | var dict = new Dictionary<LogEntry, RequestMatchResult>(); |
| | 6 | 560 | | foreach (var logEntry in LogEntries.Where(le => !le.RequestMessage.Path.StartsWith("/__admin/"))) |
| | 1 | 561 | | { |
| | 1 | 562 | | var requestMatchResult = new RequestMatchResult(); |
| | 1 | 563 | | if (request.GetMatchingScore(logEntry.RequestMessage, requestMatchResult) > MatchScores.AlmostPerfect) |
| | 1 | 564 | | { |
| | 1 | 565 | | dict.Add(logEntry, requestMatchResult); |
| | 1 | 566 | | } |
| | 1 | 567 | | } |
| | | 568 | | |
| | 3 | 569 | | var result = dict.OrderBy(x => x.Value.AverageTotalScore).Select(x => x.Key).Select(ToLogEntryModel); |
| | | 570 | | |
| | 1 | 571 | | return ToJson(result); |
| | 1 | 572 | | } |
| | | 573 | | #endregion Requests/find |
| | | 574 | | |
| | | 575 | | #region Scenarios |
| | | 576 | | private ResponseMessage ScenariosGet(RequestMessage requestMessage) |
| | 0 | 577 | | { |
| | 0 | 578 | | var scenarios = Scenarios.Select(s => new |
| | 0 | 579 | | { |
| | 0 | 580 | | Name = s.Key, |
| | 0 | 581 | | Started = s.Value != null, |
| | 0 | 582 | | NextState = s.Value |
| | 0 | 583 | | }); |
| | 0 | 584 | | return ToJson(scenarios); |
| | 0 | 585 | | } |
| | | 586 | | |
| | | 587 | | private ResponseMessage ScenariosReset(RequestMessage requestMessage) |
| | 0 | 588 | | { |
| | 0 | 589 | | ResetScenarios(); |
| | | 590 | | |
| | 0 | 591 | | return new ResponseMessage { Body = "Scenarios reset" }; |
| | 0 | 592 | | } |
| | | 593 | | #endregion |
| | | 594 | | |
| | | 595 | | private IRequestBuilder InitRequestBuilder(RequestModel requestModel) |
| | 6 | 596 | | { |
| | 6 | 597 | | IRequestBuilder requestBuilder = Request.Create(); |
| | | 598 | | |
| | 6 | 599 | | if (requestModel.ClientIP != null) |
| | 0 | 600 | | { |
| | 0 | 601 | | string clientIP = requestModel.ClientIP as string; |
| | 0 | 602 | | if (clientIP != null) |
| | 0 | 603 | | { |
| | 0 | 604 | | requestBuilder = requestBuilder.WithClientIP(clientIP); |
| | 0 | 605 | | } |
| | | 606 | | else |
| | 0 | 607 | | { |
| | 0 | 608 | | var clientIPModel = JsonUtils.ParseJTokenToObject<ClientIPModel>(requestModel.ClientIP); |
| | 0 | 609 | | if (clientIPModel?.Matchers != null) |
| | 0 | 610 | | { |
| | 0 | 611 | | requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(MatcherModelMapper.Map).C |
| | 0 | 612 | | } |
| | 0 | 613 | | } |
| | 0 | 614 | | } |
| | | 615 | | |
| | 6 | 616 | | if (requestModel.Path != null) |
| | 5 | 617 | | { |
| | 5 | 618 | | string path = requestModel.Path as string; |
| | 5 | 619 | | if (path != null) |
| | 1 | 620 | | { |
| | 1 | 621 | | requestBuilder = requestBuilder.WithPath(path); |
| | 1 | 622 | | } |
| | | 623 | | else |
| | 4 | 624 | | { |
| | 4 | 625 | | var pathModel = JsonUtils.ParseJTokenToObject<PathModel>(requestModel.Path); |
| | 4 | 626 | | if (pathModel?.Matchers != null) |
| | 4 | 627 | | { |
| | 4 | 628 | | requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(MatcherModelMapper.Map).Cast< |
| | 4 | 629 | | } |
| | 4 | 630 | | } |
| | 5 | 631 | | } |
| | | 632 | | |
| | 6 | 633 | | if (requestModel.Url != null) |
| | 0 | 634 | | { |
| | 0 | 635 | | string url = requestModel.Url as string; |
| | 0 | 636 | | if (url != null) |
| | 0 | 637 | | { |
| | 0 | 638 | | requestBuilder = requestBuilder.WithUrl(url); |
| | 0 | 639 | | } |
| | | 640 | | else |
| | 0 | 641 | | { |
| | 0 | 642 | | var urlModel = JsonUtils.ParseJTokenToObject<UrlModel>(requestModel.Url); |
| | 0 | 643 | | if (urlModel?.Matchers != null) |
| | 0 | 644 | | { |
| | 0 | 645 | | requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(MatcherModelMapper.Map).Cast<IS |
| | 0 | 646 | | } |
| | 0 | 647 | | } |
| | 0 | 648 | | } |
| | | 649 | | |
| | 6 | 650 | | if (requestModel.Methods != null) |
| | 5 | 651 | | { |
| | 5 | 652 | | requestBuilder = requestBuilder.UsingVerb(requestModel.Methods); |
| | 5 | 653 | | } |
| | | 654 | | |
| | 6 | 655 | | if (requestModel.Headers != null) |
| | 0 | 656 | | { |
| | 0 | 657 | | foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null)) |
| | 0 | 658 | | { |
| | 0 | 659 | | requestBuilder = requestBuilder.WithHeader(headerModel.Name, headerModel.Matchers.Select(MatcherMode |
| | 0 | 660 | | } |
| | 0 | 661 | | } |
| | | 662 | | |
| | 6 | 663 | | if (requestModel.Cookies != null) |
| | 0 | 664 | | { |
| | 0 | 665 | | foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null)) |
| | 0 | 666 | | { |
| | 0 | 667 | | requestBuilder = requestBuilder.WithCookie(cookieModel.Name, cookieModel.Matchers.Select(MatcherMode |
| | 0 | 668 | | } |
| | 0 | 669 | | } |
| | | 670 | | |
| | 6 | 671 | | if (requestModel.Params != null) |
| | 0 | 672 | | { |
| | 0 | 673 | | foreach (var paramModel in requestModel.Params) |
| | 0 | 674 | | { |
| | 0 | 675 | | requestBuilder = paramModel.Values == null ? requestBuilder.WithParam(paramModel.Name) : requestBuil |
| | 0 | 676 | | } |
| | 0 | 677 | | } |
| | | 678 | | |
| | 6 | 679 | | if (requestModel.Body?.Matcher != null) |
| | 2 | 680 | | { |
| | 2 | 681 | | var bodyMatcher = MatcherModelMapper.Map(requestModel.Body.Matcher); |
| | 2 | 682 | | requestBuilder = requestBuilder.WithBody(bodyMatcher); |
| | 2 | 683 | | } |
| | | 684 | | |
| | 6 | 685 | | return requestBuilder; |
| | 6 | 686 | | } |
| | | 687 | | |
| | | 688 | | private IResponseBuilder InitResponseBuilder(ResponseModel responseModel) |
| | 5 | 689 | | { |
| | 5 | 690 | | IResponseBuilder responseBuilder = Response.Create(); |
| | | 691 | | |
| | 5 | 692 | | if (responseModel.Delay > 0) |
| | 0 | 693 | | { |
| | 0 | 694 | | responseBuilder = responseBuilder.WithDelay(responseModel.Delay.Value); |
| | 0 | 695 | | } |
| | | 696 | | |
| | 5 | 697 | | if (!string.IsNullOrEmpty(responseModel.ProxyUrl)) |
| | 0 | 698 | | { |
| | 0 | 699 | | if (string.IsNullOrEmpty(responseModel.X509Certificate2ThumbprintOrSubjectName)) |
| | 0 | 700 | | { |
| | 0 | 701 | | return responseBuilder.WithProxy(responseModel.ProxyUrl); |
| | | 702 | | } |
| | | 703 | | |
| | 0 | 704 | | return responseBuilder.WithProxy(responseModel.ProxyUrl, responseModel.X509Certificate2ThumbprintOrSubje |
| | | 705 | | } |
| | | 706 | | |
| | 5 | 707 | | if (responseModel.StatusCode.HasValue) |
| | 5 | 708 | | { |
| | 5 | 709 | | responseBuilder = responseBuilder.WithStatusCode(responseModel.StatusCode.Value); |
| | 5 | 710 | | } |
| | | 711 | | |
| | 5 | 712 | | if (responseModel.Headers != null) |
| | 4 | 713 | | { |
| | 116 | 714 | | foreach (var entry in responseModel.Headers) |
| | 52 | 715 | | { |
| | 52 | 716 | | responseBuilder = entry.Value is string value ? |
| | 52 | 717 | | responseBuilder.WithHeader(entry.Key, value) : |
| | 52 | 718 | | responseBuilder.WithHeader(entry.Key, JsonUtils.ParseJTokenToObject<string[]>(entry.Value)); |
| | 52 | 719 | | } |
| | 4 | 720 | | } |
| | 1 | 721 | | else if (responseModel.HeadersRaw != null) |
| | 0 | 722 | | { |
| | 0 | 723 | | foreach (string headerLine in responseModel.HeadersRaw.Split(new[] { "\n", "\r\n" }, StringSplitOptions. |
| | 0 | 724 | | { |
| | 0 | 725 | | int indexColon = headerLine.IndexOf(":", StringComparison.Ordinal); |
| | 0 | 726 | | string key = headerLine.Substring(0, indexColon).TrimStart(' ', '\t'); |
| | 0 | 727 | | string value = headerLine.Substring(indexColon + 1).TrimStart(' ', '\t'); |
| | 0 | 728 | | responseBuilder = responseBuilder.WithHeader(key, value); |
| | 0 | 729 | | } |
| | 0 | 730 | | } |
| | | 731 | | |
| | 5 | 732 | | if (responseModel.BodyAsBytes != null) |
| | 0 | 733 | | { |
| | 0 | 734 | | responseBuilder = responseBuilder.WithBody(responseModel.BodyAsBytes, responseModel.BodyDestination, ToE |
| | 0 | 735 | | } |
| | 5 | 736 | | else if (responseModel.Body != null) |
| | 5 | 737 | | { |
| | 5 | 738 | | responseBuilder = responseBuilder.WithBody(responseModel.Body, responseModel.BodyDestination, ToEncoding |
| | 5 | 739 | | } |
| | 0 | 740 | | else if (responseModel.BodyAsJson != null) |
| | 0 | 741 | | { |
| | 0 | 742 | | responseBuilder = responseBuilder.WithBodyAsJson(responseModel.BodyAsJson, ToEncoding(responseModel.Body |
| | 0 | 743 | | } |
| | 0 | 744 | | else if (responseModel.BodyFromBase64 != null) |
| | 0 | 745 | | { |
| | 0 | 746 | | responseBuilder = responseBuilder.WithBodyFromBase64(responseModel.BodyFromBase64, ToEncoding(responseMo |
| | 0 | 747 | | } |
| | | 748 | | |
| | 5 | 749 | | if (responseModel.UseTransformer) |
| | 0 | 750 | | { |
| | 0 | 751 | | responseBuilder = responseBuilder.WithTransformer(); |
| | 0 | 752 | | } |
| | | 753 | | |
| | 5 | 754 | | return responseBuilder; |
| | 5 | 755 | | } |
| | | 756 | | |
| | | 757 | | private ResponseMessage ToJson<T>(T result) |
| | 2 | 758 | | { |
| | 2 | 759 | | return new ResponseMessage |
| | 2 | 760 | | { |
| | 2 | 761 | | Body = JsonConvert.SerializeObject(result, _settings), |
| | 2 | 762 | | StatusCode = 200, |
| | 2 | 763 | | Headers = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMoc |
| | 2 | 764 | | }; |
| | 2 | 765 | | } |
| | | 766 | | |
| | | 767 | | private Encoding ToEncoding(EncodingModel encodingModel) |
| | 5 | 768 | | { |
| | 5 | 769 | | return encodingModel != null ? Encoding.GetEncoding(encodingModel.CodePage) : null; |
| | 5 | 770 | | } |
| | | 771 | | } |
| | | 772 | | } |