Esempio n. 1
0
        public Task RegisterRpcHandlerAsync(IRequestMatcher pattern, Func <Message, CancellationToken, Task <Message> > handler, RouteExecution execution = RouteExecution.Synchronous, RouteMode mode = RouteMode.Capture, CancellationToken cancellationToken = default)
        {
            return(_registration.RegisterRpcHandlerAsync(
                       pattern,
                       async(message, handlerToken) =>
            {
                Trace.Current = ExtractTracing(message);

                var trace = Trace.Current;
                trace.Record(Annotations.ServerRecv());
                trace.Record(Annotations.ServiceName(_serviceName));
                trace.Record(Annotations.Rpc("TODO"));
                try
                {
                    var response = await handler(message, handlerToken);
                    trace.Record(Annotations.ServerSend());
                    return response;
                }
                catch (Exception ex)
                {
                    trace.Record(Annotations.Tag("error", ex.Message));
                    trace.Record(Annotations.LocalOperationStop());

                    throw;
                }
            },
                       execution,
                       mode,
                       cancellationToken));
        }
 /// <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="fileSystemHandler">The fileSystemHandler.</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, IFileSystemHandler fileSystemHandler, bool saveToFile = false)
 {
     _registrationCallback = registrationCallback;
     _requestMatcher       = requestMatcher;
     _fileSystemHandler    = fileSystemHandler;
     _saveToFile           = saveToFile;
 }
Esempio n. 3
0
 /// <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 WireMockServerSettings.</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, IWireMockServerSettings settings, bool saveToFile = false)
 {
     _registrationCallback = registrationCallback;
     _requestMatcher       = requestMatcher;
     _settings             = settings;
     _saveToFile           = saveToFile;
 }
Esempio n. 4
0
 /// <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 WireMockServerSettings.</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>
 /// <param name="stateTimes">Only when the current state is executed this number, the next state which will occur. [Optional]</param>
 public Mapping(
     Guid guid,
     [CanBeNull] string title,
     [CanBeNull] string path,
     [NotNull] IWireMockServerSettings settings,
     [NotNull] IRequestMatcher requestMatcher,
     [NotNull] IResponseProvider provider,
     int priority,
     [CanBeNull] string scenario,
     [CanBeNull] string executionConditionState,
     [CanBeNull] string nextState,
     [CanBeNull] int?stateTimes)
 {
     Guid                    = guid;
     Title                   = title;
     Path                    = path;
     Settings                = settings;
     RequestMatcher          = requestMatcher;
     Provider                = provider;
     Priority                = priority;
     Scenario                = scenario;
     ExecutionConditionState = executionConditionState;
     NextState               = nextState;
     StateTimes              = stateTimes;
 }
Esempio n. 5
0
 public CheckAccessCommandHandler(IApplicationDbContext applicationDbContext, IRequestStore requestStore,
                                  IRequestMatcher requestMatcher)
 {
     _applicationDbContext = applicationDbContext;
     _requestStore         = requestStore;
     _requestMatcher       = requestMatcher;
 }
Esempio n. 6
0
 public RouterEntry(string serviceKey, IRequestMatcher route, RouteTargetType targetType, string target)
 {
     ServiceKey = serviceKey;
     Route      = route;
     TargetType = targetType;
     Target     = target;
 }
Esempio n. 7
0
 /// <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="requestMatcher">The request matcher.</param>
 /// <param name="provider">The provider.</param>
 /// <param name="priority">The priority for this mapping.</param>
 public Mapping(Guid guid, [CanBeNull] string title, IRequestMatcher requestMatcher, IResponseProvider provider, int priority)
 {
     Priority       = priority;
     Guid           = guid;
     Title          = title;
     RequestMatcher = requestMatcher;
     Provider       = provider;
 }
Esempio n. 8
0
        public RequestEvaluator(IBehaviorRepository repository,
                                IRequestMatcher matcher, ILogger logger)
        {
            _repository = repository;

            _matcher = matcher;
            _logger  = logger;
        }
 public Task RegisterRpcHandlerAsync(IRequestMatcher pattern, Func <Message, CancellationToken, Task <Message> > handler, RouteExecution execution = RouteExecution.Synchronous, RouteMode mode = RouteMode.Capture, CancellationToken cancellationToken = default)
 {
     return(_policy.ExecuteAsync((_, registerPolicyToken) => _registration.RegisterRpcHandlerAsync(
                                     pattern,
                                     (message, handlerToken) => _policy.AsAsyncPolicy <Message>().ExecuteAsync((__, handlerPolicyToken) => handler(message, handlerPolicyToken), new Context(), handlerToken),
                                     execution,
                                     mode,
                                     registerPolicyToken
                                     ), new Context(), cancellationToken));
 }
Esempio n. 10
0
        public int Register(string serviceKey, IRequestMatcher route, TData data)
        {
            var entryId = Interlocked.Increment(ref _entryCounter);

            if (!_routes.TryAdd(entryId, new Entry(serviceKey, route, data)))
            {
                throw new InvalidOperationException();
            }
            return(entryId);
        }
Esempio n. 11
0
 /// <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="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, IRequestMatcher requestMatcher, IResponseProvider provider, int priority, [CanBeNull] string scenario, [CanBeNull] object executionConditionState, [CanBeNull] object nextState)
 {
     Guid                    = guid;
     Title                   = title;
     RequestMatcher          = requestMatcher;
     Provider                = provider;
     Priority                = priority;
     Scenario                = scenario;
     ExecutionConditionState = executionConditionState;
     NextState               = nextState;
 }
        public static string UnParse(IRequestMatcher matcher)
        {
            switch (matcher)
            {
            case AndMatcher andMatcher:
                return(string.Join(",", andMatcher.RequestMatchers.Select(UnParse)));

            case FieldMatcher fieldMatcher:
                return($"{fieldMatcher.FieldName}:{UnParse(fieldMatcher.FieldValue)}");

            default: throw new ArgumentOutOfRangeException(nameof(matcher));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpRecorderDelegatingHandler" /> class.
 /// </summary>
 /// <param name="interactionName">
 /// The name of the interaction.
 /// If you use the default <see cref="IInteractionRepository"/>, this will be the path to the HAR file (relative or absolute) and
 /// if no file extension is provided, .har will be used.
 /// </param>
 /// <param name="mode">The <see cref="HttpRecorderMode" />. Defaults to <see cref="HttpRecorderMode.Auto" />.</param>
 /// <param name="matcher">
 /// The <see cref="IRequestMatcher"/> to use to match interactions with incoming <see cref="HttpRequestMessage"/>.
 /// Defaults to matching Once by <see cref="HttpMethod"/> and <see cref="HttpRequestMessage.RequestUri"/>.
 /// <see cref="RulesMatcher.ByHttpMethod"/> and <see cref="RulesMatcher.ByRequestUri"/>.
 /// </param>
 /// <param name="repository">
 /// The <see cref="IInteractionRepository"/> to use to read/write the interaction.
 /// Defaults to <see cref="HttpArchiveInteractionRepository"/>.
 /// </param>
 /// <param name="anonymizer">
 /// The <see cref="IInteractionAnonymizer"/> to use to anonymize the interaction.
 /// Defaults to <see cref="RulesInteractionAnonymizer.Default"/>.
 /// </param>
 public HttpRecorderDelegatingHandler(
     string interactionName,
     HttpRecorderMode mode             = HttpRecorderMode.Auto,
     IRequestMatcher matcher           = null,
     IInteractionRepository repository = null,
     IInteractionAnonymizer anonymizer = null)
 {
     InteractionName = interactionName;
     Mode            = mode;
     _matcher        = matcher ?? RulesMatcher.MatchOnce.ByHttpMethod().ByRequestUri();
     _repository     = repository ?? new HttpArchiveInteractionRepository();
     _anonymizer     = anonymizer ?? RulesInteractionAnonymizer.Default;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpRecorderDelegatingHandler" /> class.
 /// </summary>
 /// <param name="interactionName">
 /// The name of the interaction.
 /// If you use the default <see cref="IInteractionRepository"/>, this will be the path to the HAR file (relative or absolute) and
 /// if no file extension is provided, .har will be used.
 /// </param>
 /// <param name="mode">The <see cref="HttpRecorderMode" />. Defaults to <see cref="HttpRecorderMode.Auto" />.</param>
 /// <param name="innerHandler">The inner <see cref="HttpMessageHandler" /> to configure. If not provided, <see cref="HttpClientHandler" /> will be used.</param>
 /// <param name="matcher">
 /// The <see cref="IRequestMatcher"/> to use to match interactions with incoming <see cref="HttpRequestMessage"/>.
 /// Defaults to matching Once by <see cref="HttpMethod"/> and <see cref="HttpRequestMessage.RequestUri"/>.
 /// <see cref="RulesMatcher.ByHttpMethod"/> and <see cref="RulesMatcher.ByRequestUri"/>.
 /// </param>
 /// <param name="repository">
 /// The <see cref="IInteractionRepository"/> to use to read/write the interaction.
 /// Defaults to <see cref="HttpArchiveInteractionRepository"/>.
 /// </param>
 public HttpRecorderDelegatingHandler(
     string interactionName,
     HttpRecorderMode mode             = HttpRecorderMode.Auto,
     HttpMessageHandler innerHandler   = null,
     IRequestMatcher matcher           = null,
     IInteractionRepository repository = null)
     : base(innerHandler ?? new HttpClientHandler())
 {
     InteractionName = interactionName;
     Mode            = mode;
     _matcher        = matcher ?? RulesMatcher.MatchOnce.ByHttpMethod().ByRequestUri();
     _repository     = repository ?? new HttpArchiveInteractionRepository();
 }
Esempio n. 15
0
 /// <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="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>
 /// <param name="logOnMatchFail">Should this log when match on this mapping fails? [Optional - Default: false]</param>
 public Mapping(Guid guid, [CanBeNull] string title, [CanBeNull] string path, IRequestMatcher requestMatcher, IResponseProvider provider, int priority, [CanBeNull] string scenario, [CanBeNull] object executionConditionState, [CanBeNull] object nextState, bool logOnMatchFail = false)
 {
     Guid                    = guid;
     Title                   = title;
     Path                    = path;
     RequestMatcher          = requestMatcher;
     Provider                = provider;
     Priority                = priority;
     Scenario                = scenario;
     ExecutionConditionState = executionConditionState;
     NextState               = nextState;
     LogOnMatchFailure       = logOnMatchFail;
 }
Esempio n. 16
0
 /// <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="fileSystemHandler">The fileSystemHandler.</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] IFileSystemHandler fileSystemHandler, [NotNull] IRequestMatcher requestMatcher, [NotNull] IResponseProvider provider,
                int priority, [CanBeNull] string scenario, [CanBeNull] string executionConditionState, [CanBeNull] string nextState)
 {
     Guid                    = guid;
     Title                   = title;
     Path                    = path;
     FileSystemHandler       = fileSystemHandler;
     RequestMatcher          = requestMatcher;
     Provider                = provider;
     Priority                = priority;
     Scenario                = scenario;
     ExecutionConditionState = executionConditionState;
     NextState               = nextState;
 }
Esempio n. 17
0
        private HttpClient CreateHttpClient(
            [CallerMemberName] string testName = "",
            [CallerFilePath] string filePath   = "",
            HttpRecorderMode mode   = HttpRecorderMode.Auto,
            IRequestMatcher matcher = null)
        {
            var interactionName = Path.Join(
                Path.GetDirectoryName(filePath),
                $"{Path.GetFileNameWithoutExtension(filePath)}Fixtures",
                testName);

            return(new HttpClient(new HttpRecorderDelegatingHandler(interactionName, mode: mode, matcher: matcher))
            {
                BaseAddress = new Uri("https://reqres.in/"),
            });
        }
Esempio n. 18
0
        /// <summary>
        /// Adds <see cref="HttpRecorderDelegatingHandler"/> as a HttpMessageHandler in the client pipeline.
        /// </summary>
        /// <param name="httpClientBuilder">The <see cref="IHttpClientBuilder"/>.</param>
        /// <param name="interactionName">
        /// The name of the interaction.
        /// If you use the default <see cref="IInteractionRepository"/>, this will be the path to the HAR file (relative or absolute) and
        /// if no file extension is provided, .har will be used.
        /// </param>
        /// <param name="mode">The <see cref="HttpRecorderMode" />. Defaults to <see cref="HttpRecorderMode.Auto" />.</param>
        /// <param name="matcher">
        /// The <see cref="IRequestMatcher"/> to use to match interactions with incoming <see cref="HttpRequestMessage"/>.
        /// Defaults to matching Once by <see cref="HttpMethod"/> and <see cref="HttpRequestMessage.RequestUri"/>.
        /// <see cref="RulesMatcher.ByHttpMethod"/> and <see cref="RulesMatcher.ByRequestUri"/>.
        /// </param>
        /// <param name="repository">
        /// The <see cref="IInteractionRepository"/> to use to read/write the interaction.
        /// Defaults to <see cref="HttpArchiveInteractionRepository"/>.
        /// </param>
        /// <param name="anonymizer">
        /// The <see cref="IInteractionAnonymizer"/> to use to anonymize the interaction.
        /// Defaults to <see cref="RulesInteractionAnonymizer.Default"/>.
        /// </param>
        /// <returns>The updated <see cref="IHttpClientBuilder"/>.</returns>
        public static IHttpClientBuilder AddHttpRecorder(
            this IHttpClientBuilder httpClientBuilder,
            string interactionName,
            HttpRecorderMode mode             = HttpRecorderMode.Auto,
            IRequestMatcher matcher           = null,
            IInteractionRepository repository = null,
            IInteractionAnonymizer anonymizer = null)
        {
            var recorder = new HttpRecorderDelegatingHandler(
                interactionName,
                mode: mode,
                matcher: matcher,
                repository: repository,
                anonymizer: anonymizer);

            return(httpClientBuilder.AddHttpMessageHandler((sp) => recorder));
        }
Esempio n. 19
0
        private bool Matches(IRequestMatcher route, IReadOnlyDictionary <string, object> message)
        {
            switch (route)
            {
            case AndMatcher andMatcher:
                return(andMatcher.RequestMatchers.All(matcher => Matches(matcher, message)));

            case FieldMatcher fieldMatcher:
                if (!(message.TryGetValue(fieldMatcher.FieldName, out var fieldValue)))
                {
                    return(false);
                }

                return(Matches(fieldMatcher.FieldValue, fieldValue));

            default: throw new ArgumentOutOfRangeException(nameof(route));
            }
        }
        public async Task RegisterRpcHandlerAsync(IRequestMatcher pattern, Func <Message, CancellationToken, Task <Message> > handler, RouteExecution execution = RouteExecution.Synchronous, RouteMode mode = RouteMode.Capture, CancellationToken cancellationToken = default)
        {
            // TODO better route key? needs to be consistent across a cluster of services per route
            var route = $"{_serviceKey}-{pattern}";

            await _rpc.SendAsync("toxon.micro.router.register", JsonMessage.Write(new RegisterRoute
            {
                ServiceKey = _serviceKey,
                RouteKey   = route,

                ServiceHealthEndpoint = await _serviceHealthEndpoint.Value,

                RequestMatcher = pattern,
                Execution      = execution,
                Mode           = mode
            }), cancellationToken).ConfigureAwait(false);

            await _rpc.RegisterHandlerAsync(route, handler, cancellationToken);
        }
Esempio n. 21
0
        internal Cassette(ICasseteStorage storage, string name, RecordMode recordMode, IRequestMatcher requestMatcher)
        {
            _storage        = storage ?? throw new ArgumentNullException(nameof(storage));
            _name           = name ?? throw new ArgumentNullException(nameof(name));
            _requestMatcher = requestMatcher ?? throw new ArgumentNullException(nameof(requestMatcher));
            _recordMode     = recordMode;

            var httpInteractions = storage.Load(name);

            if (httpInteractions == null)
            {
                _isNew            = true;
                _httpInteractions = new List <HttpInteraction>();
            }
            else
            {
                _isNew            = false;
                _httpInteractions = httpInteractions;
            }
        }
Esempio n. 22
0
        public RequestStore(
            IDateTimeProvider dateTimeProvider,
            IQueueWrapper queueWrapper,
            ILogger logger,
            IRequestMatcher requestMatcher,
            IConfigurationManager config,
            IBackplane backplane
            )
        {
            this.queueWrapper     = queueWrapper;
            this.logger           = logger;
            this.requestMatcher   = requestMatcher;
            this.dateTimeProvider = dateTimeProvider;

            const int defaultBusTimeoutMilliseconds = 5000;

            busTimeoutMilliseconds = config.Get("BusTimeoutMilliseconds", defaultBusTimeoutMilliseconds);

            this.backplane = backplane;
            Methods        = new List <string>();
        }
Esempio n. 23
0
 public IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false)
 {
     return(new RespondWithAProvider(RegisterMapping, requestMatcher, _settings, saveToFile));
 }
Esempio n. 24
0
 public FillerConfig(IRequestMatcher matcher, IHandlerConfig parent, AppContext context)
 {
     _matcher = matcher;
     _parent  = parent;
     _context = context;
 }
Esempio n. 25
0
 /// <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>
 public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher)
 {
     _registrationCallback = registrationCallback;
     _requestMatcher       = requestMatcher;
 }
Esempio n. 26
0
 private IRespondWithAProvider When(IRequestMatcher requestMatcher)
 {
     return(_server.Given(requestMatcher));
 }
Esempio n. 27
0
 /// <summary>
 /// Creates or uses cassette with given name to record HTTP interactions.
 /// </summary>
 /// <param name="name">Cassette name</param>
 /// <param name="recordMode">Rercording mode</param>
 /// <param name="requestMatcher">Request matcher to use with this cassette</param>
 /// <returns></returns>
 public Cassette UseCassette(string name, RecordMode recordMode = RecordMode.Once, IRequestMatcher requestMatcher = null)
 {
     Cassette = new Cassette(Storage, name, recordMode, requestMatcher ?? DefaultMatcher);
     return(Cassette);
 }
 public DefaultRequestHandler(IRequestMatcher matcher, IResponseFiller responseFiller)
 {
     _matcher = matcher;
     _responseFiller = responseFiller;
 }
Esempio n. 29
0
 public DefaultRequestHandler(IRequestMatcher matcher, IResponseFiller responseFiller)
 {
     _matcher        = matcher;
     _responseFiller = responseFiller;
 }
 public IRespondWithAProvider Given(IRequestMatcher requestMatcher)
 {
     return(new RespondWithAProvider(RegisterMapping, requestMatcher));
 }
 public Task RegisterRpcHandlerAsync(IRequestMatcher pattern, Func <Message, CancellationToken, Task <Message> > handler, RouteExecution execution = RouteExecution.Synchronous, RouteMode mode = RouteMode.Capture, CancellationToken cancellationToken = default)
 {
     _rpcRouter.Register(string.Empty, pattern, new RpcRoutingData(handler));
     return(Task.CompletedTask);
 }