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