Exemplo n.º 1
0
        public override async Task <HttpResponseMessage> SendAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
        {
            int nextRequestIndex = IncrementIfLessThan(ref _requestIndex, _responseSequence.Count - 1);

            // TODO: if Reset() has been called from other thread, this can result in IndexOutOfRangeException. Have to handle this is some way and make it thread safe.
            IResponseStrategy responseStrategy = nextRequestIndex >= 0
                                ? _responseSequence[nextRequestIndex]
                                : null;

            if (responseStrategy is null)
            {
                // TODO: clarify which mock.
                throw new HttpMockException("No response configured for mock.");
            }

            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                Callback?.Invoke(requestContext.Request);
                HttpResponseMessage responseMessage = await responseStrategy.ProduceResponseAsync(requestContext, cancellationToken).ConfigureAwait(false);

                responseMessage.RequestMessage = requestContext.Request;
                return(responseMessage);
            }
            finally
            {
                IsInvoked = true;
            }
        }
Exemplo n.º 2
0
 public override Task <HttpResponseMessage> ProduceResponseAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
 {
     return(Task.FromResult(new HttpResponseMessage(StatusCode)
     {
         Content = new ObjectContent(TypeOfValue, ValueFactory(requestContext.Request), Formatter, MediaType)
     }));
 }
Exemplo n.º 3
0
        public void Init()
        {
            var            context        = new MockHttpRequestContext();
            RequestContext requestContext = new RequestContext(context, new RouteData());

            UrlHelper = new UrlHelper(requestContext);
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public Task <bool> IsMatchAsync(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(Matchers.AnyAsync(requestContext));
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        public async Task <bool> IsMatchAsync(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(!await _matcher.IsMatchAsync(requestContext).ConfigureAwait(false));
        }
Exemplo n.º 6
0
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(requestContext.Request.Version.Equals(Value));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Checks that the request matches a condition.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <returns><see langword="true"/> if the request matches, <see langword="false"/> otherwise.</returns>
        public Task <bool> IsMatchAsync(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(Task.FromResult(IsMatch(requestContext)));
        }
Exemplo n.º 8
0
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(_func(requestContext.Request));
        }
Exemplo n.º 9
0
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(requestContext.Request.Content?.Headers.ContentType?.Equals(Value) ?? false);
        }
Exemplo n.º 10
0
        public async Task Given_null_context_when_matching_it_should_throw()
        {
            MockHttpRequestContext requestContext = null;

            // Act
            // ReSharper disable once ExpressionIsAlwaysNull
            Func <Task> act = () => _sut.IsMatchAsync(requestContext);

            // Assert
            await act.Should()
            .ThrowAsync <ArgumentNullException>()
            .WithParamName(nameof(requestContext));
        }
Exemplo n.º 11
0
        public async Task Given_null_context_when_matching_it_should_throw()
        {
            _sut = new HttpHeadersMatcher(new List <KeyValuePair <string, IEnumerable <string> > >());
            MockHttpRequestContext requestContext = null;

            // Act
            // ReSharper disable once ExpressionIsAlwaysNull
            Func <Task> act = () => _sut.IsMatchAsync(requestContext);

            // Assert
            await act.Should()
            .ThrowAsync <ArgumentNullException>()
            .WithParamName(nameof(requestContext));
        }
Exemplo n.º 12
0
        public void Given_null_context_when_matching_it_should_throw()
        {
            _sut = new RequestUriMatcher("*/controller/*");
            MockHttpRequestContext requestContext = null;

            // Act
            // ReSharper disable once ExpressionIsAlwaysNull
            Action act = () => _sut.IsMatch(requestContext);

            // Assert
            act.Should()
            .Throw <ArgumentNullException>()
            .WithParamName(nameof(requestContext));
        }
Exemplo n.º 13
0
        public void Given_null_context_when_matching_it_should_throw()
        {
            _sut = new MediaTypeHeaderMatcher(new MediaTypeHeaderValue("text/plain"));
            MockHttpRequestContext requestContext = null;

            // Act
            // ReSharper disable once ExpressionIsAlwaysNull
            Action act = () => _sut.IsMatch(requestContext);

            // Assert
            act.Should()
            .Throw <ArgumentNullException>()
            .WithParamName(nameof(requestContext));
        }
Exemplo n.º 14
0
        public async Task Given_source_json_when_matching_it_should_succeed(object expectedJsonContentAsObject, string requestJson)
        {
            var request = new HttpRequestMessage
            {
                Content = new StringContent(requestJson)
            };
            var context = new MockHttpRequestContext(request);
            var sut     = new JsonContentMatcher(expectedJsonContentAsObject);

            // Act
            bool result = await sut.IsMatchAsync(context);

            // Assert
            result.Should().BeTrue();
        }
Exemplo n.º 15
0
        public virtual async Task <HttpResponseMessage> SendAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
        {
            IsInvoked = true;

            if (_responseStrategy is null)
            {
                // TODO: clarify which mock.
                throw new HttpMockException("No response configured for mock.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            Callback?.Invoke(requestContext.Request);
            HttpResponseMessage responseMessage = await _responseStrategy.ProduceResponseAsync(requestContext, cancellationToken).ConfigureAwait(false);

            responseMessage.RequestMessage = requestContext.Request;
            return(responseMessage);
        }
Exemplo n.º 16
0
        public async Task Given_request_content_equals_expected_content_when_matching_twice_should_match_twice()
        {
            const string content         = "some http request content";
            const string expectedContent = content;

            var request = new HttpRequestMessage
            {
                Content = new StringContent(content)
            };

            _sut = new ContentMatcher(expectedContent, Encoding.UTF8);

            // Act & assert
            var ctx = new MockHttpRequestContext(request);

            (await _sut.IsMatchAsync(ctx)).Should().BeTrue();
            (await _sut.IsMatchAsync(ctx)).Should().BeTrue("the content should be buffered and matchable more than once");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Verifies that a request matching the specified match conditions has been sent.
        /// </summary>
        /// <param name="matching">The conditions to match.</param>
        /// <param name="times">The number of times a request is allowed to be sent.</param>
        /// <param name="because">The reasoning for this expectation.</param>
        public async Task VerifyAsync(Action <RequestMatching> matching, IsSent times, string because = null)
        {
            if (matching is null)
            {
                throw new ArgumentNullException(nameof(matching));
            }

            if (times is null)
            {
                times = IsSent.AtLeastOnce();
            }

            var rm = new RequestMatching();

            matching(rm);

            IReadOnlyCollection <IAsyncHttpRequestMatcher> matchers        = rm.Build();
            IReadOnlyList <IInvokedHttpRequest>            matchedRequests = InvokedRequests;

            if (matchers.Count > 0)
            {
                var list = new List <IInvokedHttpRequest>();
                foreach (IInvokedHttpRequest invokedHttpRequest in InvokedRequests)
                {
                    var requestContext = new MockHttpRequestContext(invokedHttpRequest.Request);
                    if (await matchers.AllAsync(requestContext).ConfigureAwait(false))
                    {
                        list.Add(invokedHttpRequest);
                    }
                }

                matchedRequests = list;
            }

            if (!times.Verify(matchedRequests.Count))
            {
                throw new HttpMockException(times.GetErrorMessage(matchedRequests.Count, BecauseMessage(because)));
            }

            foreach (InvokedHttpRequest r in matchedRequests.Cast <InvokedHttpRequest>())
            {
                r.MarkAsVerified();
            }
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            QueryString query = QueryString.Parse(requestContext.Request.RequestUri.Query);

            // When match collection is empty, behavior is flipped, and we expect no query string parameters on request.
            if (_matchQs.Count == 0 && query.Count > 0)
            {
                return(false);
            }

            return(_matchQs.All(q => query.ContainsKey(q.Key) &&
                                (BothAreEmpty(query[q.Key], q.Value) ||
                                 HasOneOf(query[q.Key], q.Value))
                                ));
        }
Exemplo n.º 19
0
        /// <inheritdoc />
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            await LoadIntoBufferAsync(request.Content).ConfigureAwait(false);

            var requestContext = new MockHttpRequestContext(request, _readOnlyItems);

            foreach (HttpCall setup in _setups.Reverse())
            {
                if (await setup.Matchers.AllAsync(requestContext).ConfigureAwait(false))
                {
                    return(await SendAsync(setup, requestContext, cancellationToken).ConfigureAwait(false));
                }
            }

            return(await SendAsync(_fallbackSetup, requestContext, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 20
0
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            Uri requestUri = requestContext.Request.RequestUri;

            if (requestUri is null)
            {
                return(false);
            }

            if (_uriPatternMatcher is null)
            {
                return(IsAbsoluteUriMatch(requestUri) || IsRelativeUriMatch(requestUri));
            }

            return(_uriPatternMatcher.IsMatch(requestUri.ToString()));
        }
Exemplo n.º 21
0
        public async Task <bool> IsMatchAsync(MockHttpRequestContext requestContext)
        {
            string requestContent = null;

            if (requestContext.Request.Content is { } && requestContext.Request.Content.Headers.ContentLength > 0)
Exemplo n.º 22
0
 /// <summary>
 /// Checks that the request matches a condition.
 /// </summary>
 /// <param name="requestContext">The request context.</param>
 /// <returns><see langword="true"/> if the request matches, <see langword="false"/> otherwise.</returns>
 public abstract bool IsMatch(MockHttpRequestContext requestContext);
Exemplo n.º 23
0
 public Task <HttpResponseMessage> ProduceResponseAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 24
0
 private Task <HttpResponseMessage> SendAsync(HttpCall setup, MockHttpRequestContext requestContext, CancellationToken cancellationToken)
 {
     ((InvokedHttpRequestCollection)InvokedRequests).Add(new InvokedHttpRequest(setup, requestContext.Request));
     return(setup.SendAsync(requestContext, cancellationToken));
 }
Exemplo n.º 25
0
 public void Init()
 {
     var context = new MockHttpRequestContext();
     RequestContext requestContext = new RequestContext(context, new RouteData());
     UrlHelper = new UrlHelper(requestContext);
 }
Exemplo n.º 26
0
 /// <inheritdoc />
 public override bool IsMatch(MockHttpRequestContext requestContext)
 {
     return(Value.All(h => IsMatch(h, requestContext.Request.Headers) || IsMatch(h, requestContext.Request.Content?.Headers)));
 }