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