public void MatcherModelMapper_Map_WildcardMatcher_With_PatternAsFile() { // Arrange var file = "c:\\test.txt"; var fileContent = "c"; var stringPattern = new StringPattern { Pattern = fileContent, PatternAsFile = file }; var fileSystemHandleMock = new Mock <IFileSystemHandler>(); fileSystemHandleMock.Setup(f => f.ReadFileAsString(file)).Returns(fileContent); var model = new MatcherModel { Name = "WildcardMatcher", PatternAsFile = file }; var settings = new WireMockServerSettings { FileSystemHandler = fileSystemHandleMock.Object }; var sut = new MatcherMapper(settings); // Act var matcher = (WildcardMatcher)sut.Map(model); // Assert matcher.GetPatterns().Should().HaveCount(1).And.Contain(new AnyOf <string, StringPattern>(stringPattern)); matcher.IsMatch("c").Should().Be(1.0d); }
public MatcherModelMapperTests() { _settingsMock = new Mock <IFluentMockServerSettings>(); _settingsMock.SetupAllProperties(); _sut = new MatcherMapper(_settingsMock.Object); }
public void MatcherModelMapper_Map_CSharpCodeMatcher() { // Assign var model = new MatcherModel { Name = "CSharpCodeMatcher", Patterns = new[] { "return it == \"x\";" } }; var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = true }); // Act 1 var matcher1 = (ICSharpCodeMatcher)sut.Map(model); // Assert 1 matcher1.Should().NotBeNull(); matcher1.IsMatch("x").Should().Be(1.0d); // Act 2 var matcher2 = (ICSharpCodeMatcher)sut.Map(model); // Assert 2 matcher2.Should().NotBeNull(); matcher2.IsMatch("x").Should().Be(1.0d); }
public void MatcherMapper_Map_IMatchers_Null() { // Act var model = MatcherMapper.Map((IMatcher[])null); // Assert Check.That(model).IsNull(); }
public void MatcherModelMapper_Map_Null() { // Act IMatcher matcher = MatcherMapper.Map((MatcherModel)null); // Assert Check.That(matcher).IsNull(); }
public void MatcherMapper_Map_MatcherModel_Null() { // Act var result = MatcherMapper.Map((MatcherModel)null); // Assert Check.That(result).IsNull(); }
public void MatcherMapper_Map_MatcherModel_Exception() { // Assign var model = new MatcherModel { Name = "test" }; // Act and Assert Check.ThatCode(() => MatcherMapper.Map(model)).Throws <NotSupportedException>(); }
public void MatcherMapper_Map_IMatchers() { // Assign var matcherMock1 = new Mock <IStringMatcher>(); var matcherMock2 = new Mock <IStringMatcher>(); // Act var models = MatcherMapper.Map(new[] { matcherMock1.Object, matcherMock2.Object }); // Assert Check.That(models).HasSize(2); }
public void MatcherModelMapper_Map_SimMetricsMatcher_Throws2() { // Assign var model = new MatcherModel { Name = "SimMetricsMatcher.error", Pattern = "x" }; // Act Check.ThatCode(() => MatcherMapper.Map(model)).Throws <NotSupportedException>(); }
public void MatcherMapper_Map_IIgnoreCaseMatcher() { // Assign var matcherMock = new Mock <IIgnoreCaseMatcher>(); matcherMock.Setup(m => m.IgnoreCase).Returns(true); // Act var model = MatcherMapper.Map(matcherMock.Object); // Assert Check.That(model.IgnoreCase).Equals(true); }
public void MatcherMapper_Map_IMatcher_LinqMatcher_Pattern() { // Assign var matcher = new LinqMatcher(MatchBehaviour.AcceptOnMatch, "p"); // Act var result = MatcherMapper.Map(matcher); // Assert Check.That(result).IsNotNull(); Check.That(result.Name).IsEqualTo("LinqMatcher"); Check.That(result.IgnoreCase).IsNull(); Check.That(result.Pattern).IsEqualTo("p"); Check.That(result.Patterns).IsNull(); }
public void MatcherModelMapper_Map_ExactObjectMatcher_Pattern() { // Assign var model = new MatcherModel { Name = "ExactObjectMatcher", Patterns = new object[] { "c3RlZg==" } }; // Act var matcher = (ExactObjectMatcher)MatcherMapper.Map(model); // Assert Check.That(matcher.ValueAsBytes).ContainsExactly(new byte[] { 115, 116, 101, 102 }); }
public void MatcherModelMapper_Map_ExactMatcher_Patterns() { // Assign var model = new MatcherModel { Name = "ExactMatcher", Patterns = new[] { "x", "y" } }; // Act var matcher = (ExactMatcher)MatcherMapper.Map(model); // Assert Check.That(matcher.GetPatterns()).ContainsExactly("x", "y"); }
public void MatcherModelMapper_Map_SimMetricsMatcher_BlockDistance() { // Assign var model = new MatcherModel { Name = "SimMetricsMatcher.BlockDistance", Pattern = "x" }; // Act var matcher = (SimMetricsMatcher)MatcherMapper.Map(model); // Assert Check.That(matcher.GetPatterns()).ContainsExactly("x"); }
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Patterns() { // Assign var model = new MatcherModel { Name = "LinqMatcher", Patterns = new[] { "p1", "p2" } }; // Act var matcher = (LinqMatcher)MatcherMapper.Map(model); // Assert Check.That(matcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch); Check.That(matcher.GetPatterns()).ContainsExactly("p1", "p2"); }
public void MatcherModelMapper_Map_WildcardMatcher() { // Assign var model = new MatcherModel { Name = "WildcardMatcher", Patterns = new[] { "x", "y" }, IgnoreCase = true }; // Act var matcher = (WildcardMatcher)MatcherMapper.Map(model); // Assert Check.That(matcher.GetPatterns()).ContainsExactly("x", "y"); Check.That(matcher.IsMatch("X")).IsEqualTo(0.5d); }
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Pattern() { // Assign var model = new MatcherModel { Name = "LinqMatcher", Pattern = "p" }; // Act var matcher = MatcherMapper.Map(model) as LinqMatcher; // Assert Check.That(matcher).IsNotNull(); Check.That(matcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch); Check.That(matcher.GetPatterns()).ContainsExactly("p"); }
public void MatcherMapper_Map_IStringMatcher() { // Assign var matcherMock = new Mock <IStringMatcher>(); matcherMock.Setup(m => m.Name).Returns("test"); matcherMock.Setup(m => m.GetPatterns()).Returns(new[] { "p1", "p2" }); // Act var model = MatcherMapper.Map(matcherMock.Object); // Assert Check.That(model.IgnoreCase).IsNull(); Check.That(model.Name).Equals("test"); Check.That(model.Pattern).IsNull(); Check.That(model.Patterns).ContainsExactly("p1", "p2"); }
public void MatcherModelMapper_Map_CSharpCodeMatcher_NotAllowed_ThrowsException() { // Assign var model = new MatcherModel { Name = "CSharpCodeMatcher", Patterns = new[] { "x" } }; var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = false }); // Act Action action = () => sut.Map(model); // Assert action.Should().Throw <NotSupportedException>(); }
public void MatcherModelMapper_Map_ThrowExceptionWhenMatcherFails_True(string name) { // Assign var settings = new WireMockServerSettings { ThrowExceptionWhenMatcherFails = true }; var sut = new MatcherMapper(settings); var model = new MatcherModel { Name = name, Patterns = new[] { "" } }; // Act var matcher = sut.Map(model); // Assert matcher.ThrowException.Should().BeTrue(); }
private IRequestBuilder InitRequestBuilder(RequestModel requestModel) { IRequestBuilder requestBuilder = Request.Create(); if (requestModel.ClientIP != null) { if (requestModel.ClientIP is string clientIP) { requestBuilder = requestBuilder.WithClientIP(clientIP); } else { var clientIPModel = JsonUtils.ParseJTokenToObject <ClientIPModel>(requestModel.ClientIP); if (clientIPModel?.Matchers != null) { requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } } if (requestModel.Path != null) { if (requestModel.Path is string path) { requestBuilder = requestBuilder.WithPath(path); } else { var pathModel = JsonUtils.ParseJTokenToObject <PathModel>(requestModel.Path); if (pathModel?.Matchers != null) { requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } } if (requestModel.Url != null) { if (requestModel.Url is string url) { requestBuilder = requestBuilder.WithUrl(url); } else { var urlModel = JsonUtils.ParseJTokenToObject <UrlModel>(requestModel.Url); if (urlModel?.Matchers != null) { requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } } if (requestModel.Methods != null) { requestBuilder = requestBuilder.UsingMethod(requestModel.Methods); } if (requestModel.Headers != null) { foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null)) { requestBuilder = requestBuilder.WithHeader(headerModel.Name, headerModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } if (requestModel.Cookies != null) { foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null)) { requestBuilder = requestBuilder.WithCookie(cookieModel.Name, cookieModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } if (requestModel.Params != null) { foreach (var paramModel in requestModel.Params.Where(c => c.Matchers != null)) { requestBuilder = requestBuilder.WithParam(paramModel.Name, paramModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } if (requestModel.Body?.Matcher != null) { var bodyMatcher = MatcherMapper.Map(requestModel.Body.Matcher); requestBuilder = requestBuilder.WithBody(bodyMatcher); } return(requestBuilder); }
private async Task InvokeInternal(IContext ctx) { var request = await _requestMapper.MapAsync(ctx.Request, _options); bool logRequest = false; ResponseMessage response = null; (MappingMatcherResult Match, MappingMatcherResult Partial)result = (null, null); try { foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null)) { // Set scenario start if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState) { _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState { Name = mapping.Scenario }); } } result = _mappingMatcher.FindBestMatch(request); var targetMapping = result.Match?.Mapping; if (targetMapping == null) { logRequest = true; _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found"); response = ResponseMessageBuilder.Create("No matching mapping found", 404); return; } logRequest = targetMapping.LogMapping; if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null) { bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList <string> authorization); if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect) { _options.Logger.Error("HttpStatusCode set to 401"); response = ResponseMessageBuilder.Create(null, 401); return; } } if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero) { await Task.Delay(_options.RequestProcessingDelay.Value); } response = await targetMapping.ProvideResponseAsync(request); var responseBuilder = targetMapping.Provider as Response; if (!targetMapping.IsAdminInterface) { if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMapping == true) { _options.Mappings.TryAdd(targetMapping.Guid, targetMapping); } if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMappingToFile == true) { var matcherMapper = new MatcherMapper(targetMapping.Settings); var mappingConverter = new MappingConverter(matcherMapper); var mappingToFileSaver = new MappingToFileSaver(targetMapping.Settings, mappingConverter); mappingToFileSaver.SaveMappingToFile(targetMapping); } } if (targetMapping.Scenario != null) { UpdateScenarioState(targetMapping); } } catch (Exception ex) { _options.Logger.Error($"Providing a Response for Mapping '{result.Match?.Mapping?.Guid}' failed. HttpStatusCode set to 500. Exception: {ex}"); response = ResponseMessageBuilder.Create(ex.Message, 500); } finally { var log = new LogEntry { Guid = Guid.NewGuid(), RequestMessage = request, ResponseMessage = response, MappingGuid = result.Match?.Mapping?.Guid, MappingTitle = result.Match?.Mapping?.Title, RequestMatchResult = result.Match?.RequestMatchResult, PartialMappingGuid = result.Partial?.Mapping?.Guid, PartialMappingTitle = result.Partial?.Mapping?.Title, PartialMatchResult = result.Partial?.RequestMatchResult }; LogRequest(log, logRequest); await _responseMapper.MapAsync(response, ctx.Response); } await CompletedTask; }
private IRequestBuilder InitRequestBuilder(RequestModel requestModel, bool pathOrUrlRequired) { IRequestBuilder requestBuilder = Request.Create(); if (requestModel.ClientIP != null) { if (requestModel.ClientIP is string clientIP) { requestBuilder = requestBuilder.WithClientIP(clientIP); } else { var clientIPModel = JsonUtils.ParseJTokenToObject <ClientIPModel>(requestModel.ClientIP); if (clientIPModel?.Matchers != null) { requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } } bool pathOrUrlmatchersValid = false; if (requestModel.Path != null) { if (requestModel.Path is string path) { requestBuilder = requestBuilder.WithPath(path); pathOrUrlmatchersValid = true; } else { var pathModel = JsonUtils.ParseJTokenToObject <PathModel>(requestModel.Path); if (pathModel?.Matchers != null) { requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); pathOrUrlmatchersValid = true; } } } else if (requestModel.Url != null) { if (requestModel.Url is string url) { requestBuilder = requestBuilder.WithUrl(url); pathOrUrlmatchersValid = true; } else { var urlModel = JsonUtils.ParseJTokenToObject <UrlModel>(requestModel.Url); if (urlModel?.Matchers != null) { requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); pathOrUrlmatchersValid = true; } } } if (pathOrUrlRequired && !pathOrUrlmatchersValid) { _logger.Error("Path or Url matcher is missing for this mapping, this mapping will not be added."); return(null); } if (requestModel.Methods != null) { requestBuilder = requestBuilder.UsingMethod(requestModel.Methods); } if (requestModel.Headers != null) { foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null)) { requestBuilder = requestBuilder.WithHeader(headerModel.Name, headerModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } if (requestModel.Cookies != null) { foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null)) { requestBuilder = requestBuilder.WithCookie(cookieModel.Name, cookieModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } if (requestModel.Params != null) { foreach (var paramModel in requestModel.Params.Where(c => c.Matchers != null)) { bool ignoreCase = paramModel?.IgnoreCase ?? false; requestBuilder = requestBuilder.WithParam(paramModel.Name, ignoreCase, paramModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray()); } } if (requestModel.Body?.Matcher != null) { var bodyMatcher = MatcherMapper.Map(requestModel.Body.Matcher); requestBuilder = requestBuilder.WithBody(bodyMatcher); } return(requestBuilder); }
protected WireMockServer(IWireMockServerSettings settings) { _settings = settings; // Set default values if not provided _settings.Logger = settings.Logger ?? new WireMockNullLogger(); _settings.FileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler(); _settings.Logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); _settings.Logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); HostUrlOptions urlOptions; if (settings.Urls != null) { urlOptions = new HostUrlOptions { Urls = settings.Urls }; } else { urlOptions = new HostUrlOptions { UseSSL = settings.UseSSL == true, Port = settings.Port }; } _options.FileSystemHandler = _settings.FileSystemHandler; _options.PreWireMockMiddlewareInit = _settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = _settings.PostWireMockMiddlewareInit; _options.Logger = _settings.Logger; _options.DisableJsonBodyParsing = _settings.DisableJsonBodyParsing; _matcherMapper = new MatcherMapper(_settings); _mappingConverter = new MappingConverter(_matcherMapper); #if USE_ASPNETCORE _httpServer = new AspNetCoreSelfHost(_options, urlOptions); #else _httpServer = new OwinSelfHost(_options, urlOptions); #endif var startTask = _httpServer.StartAsync(); using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) { while (!_httpServer.IsStarted) { // Throw exception if service start fails if (_httpServer.RunningException != null) { throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException); } if (ctsStartTimeout.IsCancellationRequested) { // In case of an aggregate exception, throw the exception. if (startTask.Exception != null) { throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception); } // Else throw TimeoutException throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}"); } ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs); } Urls = _httpServer.Urls.ToArray(); Ports = _httpServer.Ports; } if (settings.AllowBodyForAllHttpMethods == true) { _options.AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods; _settings.Logger.Info("AllowBodyForAllHttpMethods is set to True"); } if (settings.AllowOnlyDefinedHttpStatusCodeInResponse == true) { _options.AllowOnlyDefinedHttpStatusCodeInResponse = _settings.AllowOnlyDefinedHttpStatusCodeInResponse; _settings.Logger.Info("AllowOnlyDefinedHttpStatusCodeInResponse is set to True"); } if (settings.AllowPartialMapping == true) { AllowPartialMapping(); } if (settings.StartAdminInterface == true) { if (!string.IsNullOrEmpty(settings.AdminUsername) && !string.IsNullOrEmpty(settings.AdminPassword)) { SetBasicAuthentication(settings.AdminUsername, settings.AdminPassword); } InitAdmin(); } if (settings.ReadStaticMappings == true) { ReadStaticMappings(); } if (settings.WatchStaticMappings == true) { WatchStaticMappings(); } if (settings.ProxyAndRecordSettings != null) { InitProxyAndRecord(settings); } if (settings.RequestLogExpirationDuration != null) { SetRequestLogExpirationDuration(settings.RequestLogExpirationDuration); } if (settings.MaxRequestLogCount != null) { SetMaxRequestLogCount(settings.MaxRequestLogCount); } }
public MatcherModelMapperTests() { _sut = new MatcherMapper(_settings); }
private FluentMockServer(IFluentMockServerSettings settings) { _settings = settings; // Set default values if not provided _settings.Logger = settings.Logger ?? new WireMockNullLogger(); _settings.FileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler(); _settings.Logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); _settings.Logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); if (settings.Urls != null) { Urls = settings.Urls.ToArray(); } else { int port = settings.Port > 0 ? settings.Port.Value : PortUtils.FindFreeTcpPort(); Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" }; } _options.FileSystemHandler = _settings.FileSystemHandler; _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; _options.Logger = _settings.Logger; _matcherMapper = new MatcherMapper(_settings); _mappingConverter = new MappingConverter(_matcherMapper); #if USE_ASPNETCORE _httpServer = new AspNetCoreSelfHost(_options, Urls); #else _httpServer = new OwinSelfHost(_options, Urls); #endif Ports = _httpServer.Ports; var startTask = _httpServer.StartAsync(); using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) { while (!_httpServer.IsStarted) { // Throw exception if service start fails if (_httpServer.RunningException != null) { throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException); } if (ctsStartTimeout.IsCancellationRequested) { // In case of an aggregate exception, throw the exception. if (startTask.Exception != null) { throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception); } // Else throw TimeoutException throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}"); } ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs); } } if (settings.AllowPartialMapping == true) { AllowPartialMapping(); } if (settings.StartAdminInterface == true) { if (!string.IsNullOrEmpty(settings.AdminUsername) && !string.IsNullOrEmpty(settings.AdminPassword)) { SetBasicAuthentication(settings.AdminUsername, settings.AdminPassword); } InitAdmin(); } if (settings.ReadStaticMappings == true) { ReadStaticMappings(); } if (settings.WatchStaticMappings == true) { WatchStaticMappings(); } if (settings.ProxyAndRecordSettings != null) { InitProxyAndRecord(settings); } if (settings.RequestLogExpirationDuration != null) { SetRequestLogExpirationDuration(settings.RequestLogExpirationDuration); } if (settings.MaxRequestLogCount != null) { SetMaxRequestLogCount(settings.MaxRequestLogCount); } }