コード例 #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;
            }
        }
コード例 #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)
     }));
 }
コード例 #3
0
        public void Init()
        {
            var            context        = new MockHttpRequestContext();
            RequestContext requestContext = new RequestContext(context, new RouteData());

            UrlHelper = new UrlHelper(requestContext);
        }
コード例 #4
0
ファイル: AnyMatcher.cs プロジェクト: skwasjer/MockHttp
        /// <inheritdoc />
        public Task <bool> IsMatchAsync(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(Matchers.AnyAsync(requestContext));
        }
コード例 #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));
        }
コード例 #6
0
ファイル: VersionMatcher.cs プロジェクト: skwasjer/MockHttp
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(requestContext.Request.Version.Equals(Value));
        }
コード例 #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)));
        }
コード例 #8
0
        /// <inheritdoc />
        public override bool IsMatch(MockHttpRequestContext requestContext)
        {
            if (requestContext is null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(_func(requestContext.Request));
        }
コード例 #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);
        }
コード例 #10
0
ファイル: AnyMatcherTests.cs プロジェクト: skwasjer/MockHttp
        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));
        }
コード例 #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));
        }
コード例 #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));
        }
コード例 #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));
        }
コード例 #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();
        }
コード例 #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);
        }
コード例 #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");
        }
コード例 #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();
            }
        }
コード例 #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))
                                ));
        }
コード例 #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));
        }
コード例 #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()));
        }
コード例 #21
0
        public async Task <bool> IsMatchAsync(MockHttpRequestContext requestContext)
        {
            string requestContent = null;

            if (requestContext.Request.Content is { } && requestContext.Request.Content.Headers.ContentLength > 0)
コード例 #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);
コード例 #23
0
 public Task <HttpResponseMessage> ProduceResponseAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
コード例 #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));
 }
コード例 #25
0
 public void Init()
 {
     var context = new MockHttpRequestContext();
     RequestContext requestContext = new RequestContext(context, new RouteData());
     UrlHelper = new UrlHelper(requestContext);
 }
コード例 #26
0
 /// <inheritdoc />
 public override bool IsMatch(MockHttpRequestContext requestContext)
 {
     return(Value.All(h => IsMatch(h, requestContext.Request.Headers) || IsMatch(h, requestContext.Request.Content?.Headers)));
 }