public WireMockService(ILoggerFactory factory, IFluentMockServerSettings settings) { _logger = factory.CreateLogger("WireMock .NET");; _settings = settings; _settings.Logger = new Logger(_logger); }
/// <summary> /// Initializes a new instance of the <see cref="RespondWithAProvider"/> class. /// </summary> /// <param name="registrationCallback">The registration callback.</param> /// <param name="requestMatcher">The request matcher.</param> /// <param name="settings">The FluentMockServerSettings.</param> /// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param> public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, IFluentMockServerSettings settings, bool saveToFile = false) { _registrationCallback = registrationCallback; _requestMatcher = requestMatcher; _settings = settings; _saveToFile = saveToFile; }
public WireMockService(ILogger logger, IFluentMockServerSettings settings) { _logger = logger; _settings = settings; _settings.Logger = new Logger(logger); }
public Task <ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) { Callback?.Invoke(requestMessage); return(Task.FromResult(new ResponseMessage() { StatusCode = (int)_responseCode })); }
public static FluentMockServer Start([NotNull] IFluentMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); var server = FluentMockServer.Start(settings); settings.Logger.Info("WireMock.Net server listening at {0}", string.Join(",", server.Urls)); return(server); }
private void InitProxyAndRecord(IFluentMockServerSettings settings) { _httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ProxyAndRecordSettings.ClientX509Certificate2ThumbprintOrSubjectName); var respondProvider = Given(Request.Create().WithPath("/*").UsingAnyMethod()); if (settings.StartAdminInterface == true) { respondProvider.AtPriority(ProxyPriority); } respondProvider.RespondWith(new ProxyAsyncResponseProvider(ProxyAndRecordAsync, settings.ProxyAndRecordSettings)); }
public HttpMockServer(string mappingPath, int?port = null, Action <IHandlebars, IFileSystemHandler> handlebarsRegistrationCallback = null) { _settings = new FluentMockServerSettings() { ReadStaticMappings = true, WatchStaticMappings = true, WatchStaticMappingsInSubdirectories = true, AllowPartialMapping = true, StartAdminInterface = true, Port = port ?? 36987, FileSystemHandler = new LocalFileSystemHandler(mappingPath), HandlebarsRegistrationCallback = handlebarsRegistrationCallback }; }
/// <summary> /// Initializes a new instance of the <see cref="Mapping"/> class. /// </summary> /// <param name="guid">The unique identifier.</param> /// <param name="title">The unique title (can be null).</param> /// <param name="path">The full file path from this mapping title (can be null).</param> /// <param name="settings">The FluentMockServerSettings.</param> /// <param name="requestMatcher">The request matcher.</param> /// <param name="provider">The provider.</param> /// <param name="priority">The priority for this mapping.</param> /// <param name="scenario">The scenario. [Optional]</param> /// <param name="executionConditionState">State in which the current mapping can occur. [Optional]</param> /// <param name="nextState">The next state which will occur after the current mapping execution. [Optional]</param> public Mapping(Guid guid, [CanBeNull] string title, [CanBeNull] string path, [NotNull] IFluentMockServerSettings settings, [NotNull] IRequestMatcher requestMatcher, [NotNull] IResponseProvider provider, int priority, [CanBeNull] string scenario, [CanBeNull] string executionConditionState, [CanBeNull] string nextState) { Guid = guid; Title = title; Path = path; Settings = settings; RequestMatcher = requestMatcher; Provider = provider; Priority = priority; Scenario = scenario; ExecutionConditionState = executionConditionState; NextState = nextState; }
private FluentMockServer(IFluentMockServerSettings settings) { settings.Logger = settings.Logger ?? new WireMockConsoleLogger(); _logger = settings.Logger; _logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); if (settings.Urls != null) { Urls = settings.Urls.Select(u => u.EndsWith("/") ? u : $"{u}/").ToArray(); } else { int port = settings.Port > 0 ? settings.Port.Value : PortUtil.FindFreeTcpPort(); Urls = new[] { (settings.UseSSL == true ? "https" : "http") + "://localhost:" + port + "/" }; } _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; _options.Logger = _logger; _options.TrafficLogFile = settings.TrafficLogFile; #if NETSTANDARD _httpServer = new AspNetCoreSelfHost(_options, Urls); #else _httpServer = new OwinSelfHost(_options, Urls); #endif Ports = _httpServer.Ports; _httpServer.StartAsync(); using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) { while (!_httpServer.IsStarted) { // Throw out exception if service start fails if (_httpServer.RunningException != null) { throw new Exception($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException); } // Respect start timeout setting by throwing TimeoutException if (ctsStartTimeout.IsCancellationRequested) { throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}"); } ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelay); } } 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(settings.StaticMappingsFolder); } if (settings.WatchStaticMappings == true) { WatchStaticMappings(settings.StaticMappingsFolder); } if (settings.ProxyAndRecordSettings != null) { InitProxyAndRecord(settings.ProxyAndRecordSettings); } if (settings.MaxRequestLogCount != null) { SetMaxRequestLogCount(settings.MaxRequestLogCount); } }
public FluentMockServer(IFluentMockServerSettings settings) : base((IWireMockServerSettings)settings) { }
public Task <ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) { return(_responseMessageFunc(requestMessage, _settings)); }
public ProxyAsyncResponseProvider(Func <RequestMessage, IFluentMockServerSettings, Task <ResponseMessage> > responseMessageFunc, IFluentMockServerSettings settings) { _responseMessageFunc = responseMessageFunc; _settings = settings; }
public HttpMock(IFluentMockServerSettings fluentMockServerSettings) { Server = FluentMockServer.Start(fluentMockServerSettings); }
public HttpMockServer(IFluentMockServerSettings fluentMockServerSettings) { _settings = fluentMockServerSettings; }
/// <inheritdoc cref="IResponseProvider.ProvideResponseAsync(RequestMessage, IFluentMockServerSettings)"/> public async Task <ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) { Check.NotNull(requestMessage, nameof(requestMessage)); Check.NotNull(settings, nameof(settings)); if (Delay != null) { await Task.Delay(Delay.Value); } if (Callback != null) { var callbackResponseMessage = Callback(requestMessage); if (!WithCallbackUsed) { // Copy StatusCode from ResponseMessage callbackResponseMessage.StatusCode = ResponseMessage.StatusCode; // Copy Headers from ResponseMessage (if defined) if (ResponseMessage.Headers != null) { callbackResponseMessage.Headers = ResponseMessage.Headers; } } return(callbackResponseMessage); } if (ProxyUrl != null && _httpClientForProxy != null) { var requestUri = new Uri(requestMessage.Url); var proxyUri = new Uri(ProxyUrl); var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery); return(await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri)); } if (UseTransformer) { var factory = new HandlebarsContextFactory(settings.FileSystemHandler, settings.HandlebarsRegistrationCallback); var responseMessageTransformer = new ResponseMessageTransformer(factory); return(responseMessageTransformer.Transform(requestMessage, ResponseMessage)); } if (!UseTransformer && ResponseMessage.BodyData?.BodyAsFileIsCached == true) { ResponseMessage.BodyData.BodyAsBytes = settings.FileSystemHandler.ReadResponseBodyAsFile(ResponseMessage.BodyData.BodyAsFile); } return(ResponseMessage); }
private FluentMockServer(IFluentMockServerSettings settings) { settings.Logger = settings.Logger ?? new WireMockConsoleLogger(); _logger = settings.Logger; _fileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler(); _logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); _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.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; _options.Logger = _logger; #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); } }
private async Task <ResponseMessage> ProxyAndRecordAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) { var requestUri = new Uri(requestMessage.Url); var proxyUri = new Uri(settings.ProxyAndRecordSettings.Url); var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery); var responseMessage = await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri); if (settings.ProxyAndRecordSettings.SaveMapping) { var mapping = ToMapping(requestMessage, responseMessage, settings.ProxyAndRecordSettings.BlackListedHeaders ?? new string[] { }); _options.Mappings.TryAdd(mapping.Guid, mapping); if (settings.ProxyAndRecordSettings.SaveMappingToFile) { SaveMappingToFile(mapping); } } return(responseMessage); }
public static FluentMockServer Start([NotNull] IFluentMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); return(FluentMockServer.Start(settings)); }
public MatcherMapper(IFluentMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); _settings = settings; }
public static FluentMockServer Start(IFluentMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); return(new FluentMockServer(settings)); }
private FluentMockServer(IFluentMockServerSettings settings) { Log.DebugFormat("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); if (settings.Urls != null) { Urls = settings.Urls.Select(u => u.EndsWith("/") ? u : $"{u}/").ToArray(); } else { int port = settings.Port > 0 ? settings.Port.Value : PortUtil.FindFreeTcpPort(); Urls = new[] { (settings.UseSSL == true ? "https" : "http") + "://localhost:" + port + "/" }; } _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; #if NETSTANDARD _httpServer = new AspNetCoreSelfHost(_options, Urls); #else _httpServer = new OwinSelfHost(_options, Urls); #endif IsStarted = _httpServer.IsStarted; Ports = _httpServer.Ports; _httpServer.StartAsync(); // Fix for 'Bug: Server not listening after Start() returns (on macOS)' Task.Delay(ServerStartDelay).Wait(); 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.ProxyAndRecordSettings); } if (settings.MaxRequestLogCount != null) { SetMaxRequestLogCount(settings.MaxRequestLogCount); } }