Exemplo n.º 1
0
        public void Handle_WithNancyContext_AddHandledRequestIsCalledOnTheMockProviderRepository()
        {
            var expectedRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/"
            };
            var actualRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/",
                Body   = new {}
            };
            var expectedResponse = new ProviderServiceResponse();

            var handler = GetSubject();

            var nancyContext = new NancyContext
            {
                Request = new Request("GET", "/", "HTTP")
            };

            var interaction = new ProviderServiceInteraction {
                Request = expectedRequest, Response = expectedResponse
            };

            _mockProviderRepository.GetMatchingTestScopedInteraction(Arg.Any <ProviderServiceRequest>())
            .Returns(interaction);

            _mockRequestMapper.Convert(nancyContext.Request).Returns(actualRequest);

            handler.Handle(nancyContext);

            _mockProviderRepository.Received(1).AddHandledRequest(Arg.Is <HandledRequest>(x => x.ActualRequest == actualRequest && x.MatchedInteraction == interaction));
        }
        public void GetMatchingTestScopedInteraction_WithNoMatchingTestScopedInteraction_ThrowsPactFailureException()
        {
            var interaction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request     = new ProviderServiceRequest
                {
                    Method = HttpVerb.Head,
                    Path   = "/tester"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };

            var nonMatchingRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/tester"
            };

            var repo = GetSubject();

            _mockReporter.When(x => x.ThrowIfAnyErrors())
            .Do(x => { throw new PactFailureException("[Failure] Expected: Head, Actual: Get"); });

            repo.AddInteraction(interaction);

            Assert.Throws <PactFailureException>(() => repo.GetMatchingTestScopedInteraction(nonMatchingRequest));
        }
        public void GetMatchingTestScopedInteraction_WithNoMatchingTestScopedInteraction_ThrowsPactFailureException()
        {
            var interaction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request     = new ProviderServiceRequest
                {
                    Method = HttpVerb.Head,
                    Path   = "/tester"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };

            var nonMatchingRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/tester"
            };

            var repo = GetSubject();

            repo.AddInteraction(interaction);

            Assert.Throws <PactFailureException>(() => repo.GetMatchingTestScopedInteraction(nonMatchingRequest));
        }
        public void Handle_WithALowercasedPostRequestToInteractions_ReturnsOkResponse()
        {
            var interaction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request     = new ProviderServiceRequest
                {
                    Method = HttpVerb.Get,
                    Path   = "/test"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };
            var interactionJson = interaction.AsJsonString();

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(interactionJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context       = new NancyContext
            {
                Request = new Request("post", new Url("http://localhost/interactions"), requestStream)
            };

            var handler = GetSubject();

            var response = handler.Handle(context);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Exemplo n.º 5
0
        private void RegisterInteraction()
        {
            if (String.IsNullOrEmpty(_description))
            {
                throw new InvalidOperationException("description has not been set, please supply using the UponReceiving method.");
            }

            if (_request == null)
            {
                throw new InvalidOperationException("request has not been set, please supply using the With method.");
            }

            if (_response == null)
            {
                throw new InvalidOperationException("response has not been set, please supply using the WillRespondWith method.");
            }

            var interaction = new ProviderServiceInteraction
            {
                ProviderState = _providerState,
                Description   = _description,
                Request       = _request,
                Response      = _response
            };

            var testContext = BuildTestContext();

            SendAdminHttpRequest(HttpVerb.Post, Constants.InteractionsPath, interaction, new Dictionary <string, string> {
                { Constants.AdministrativeRequestTestContextHeaderKey, testContext }
            });

            ClearTrasientState();
        }
        private ComparisonResult ValidateInteraction(ProviderServiceInteraction interaction)
        {
            var expectedResponse = interaction.Response;
            var actualResponse   = _httpRequestSender.Send(interaction.Request);

            return(_providerServiceResponseComparer.Compare(expectedResponse, actualResponse));
        }
Exemplo n.º 7
0
        public void GetMatchingTestScopedInteraction_WithOneMatchingTestScopedInteraction_WithQueryString()
        {
            var expectedInteraction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request     = new ProviderServiceRequest
                {
                    Method = HttpVerb.Get,
                    Path   = "/tester",
                    Query  = "params=test"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };

            var repo = GetSubject();

            repo.AddInteraction(expectedInteraction);

            var interaction = repo.GetMatchingTestScopedInteraction(HttpVerb.Get, "/tester?params=test");

            Assert.Equal(expectedInteraction, interaction);
        }
Exemplo n.º 8
0
        private void ValidateInteraction(ProviderServiceInteraction interaction)
        {
            var expectedResponse = interaction.Response;
            var actualResponse   = _httpRequestSender.Send(interaction.Request);

            _providerServiceResponseComparer.Compare(expectedResponse, actualResponse);
        }
Exemplo n.º 9
0
        public void Handle_WithNancyContext_ConvertIsCalledOnTheNancyResponseMapper()
        {
            var expectedRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/"
            };
            var expectedResponse = new ProviderServiceResponse();
            var nancyContext     = new NancyContext
            {
                Request = new Request("GET", "/", "HTTP")
            };

            var handler = GetSubject();

            _mockRequestMapper.Convert(nancyContext.Request).Returns(expectedRequest);

            var interaction = new ProviderServiceInteraction {
                Request = expectedRequest, Response = expectedResponse
            };

            _mockProviderRepository.GetMatchingTestScopedInteraction(expectedRequest)
            .Returns(interaction);

            handler.Handle(nancyContext);

            _mockResponseMapper.Received(1).Convert(expectedResponse);
        }
        public void With_WithRequest_SetsRequest()
        {
            var description = "My description";
            var request     = new ProviderServiceRequest
            {
                Method = HttpVerb.Head,
                Path   = "/tester/testing/1"
            };
            var response = new ProviderServiceResponse
            {
                Status = (int)HttpStatusCode.ProxyAuthenticationRequired
            };

            var expectedInteraction = new ProviderServiceInteraction
            {
                Description = description,
                Request     = request,
                Response    = response
            };
            var expectedInteractionJson = expectedInteraction.AsJsonString();

            var mockService = GetSubject();

            mockService.Start();

            mockService.UponReceiving(description)
            .With(request)
            .WillRespondWith(response);

            var actualInteractionJson = _fakeHttpMessageHandler.RequestContentRecieved.Single();

            Assert.Equal(expectedInteractionJson, actualInteractionJson);
        }
        public void GetMatchingTestScopedInteraction_WithOneMatchingTestScopedInteraction_DoesNotThrowAPactFailureException()
        {
            var expectedInteraction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request     = new ProviderServiceRequest
                {
                    Method = HttpVerb.Head,
                    Path   = "/tester"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };

            var repo = GetSubject();

            _mockComparer
            .Compare(expectedInteraction.Request, expectedInteraction.Request)
            .Returns(new ComparisonResult());

            repo.AddInteraction(expectedInteraction);

            var interaction = repo.GetMatchingTestScopedInteraction(expectedInteraction.Request);

            Assert.Equal(expectedInteraction, interaction);
        }
        public void Handle_WithAPostRequestToInteractions_AddInteractionIsCalledOnTheMockProviderRepository()
        {
            var interaction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request     = new ProviderServiceRequest
                {
                    Method = HttpVerb.Get,
                    Path   = "/test"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };
            var interactionJson = interaction.AsJsonString();

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(interactionJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context       = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/interactions"), requestStream)
            };

            var handler = GetSubject();

            handler.Handle(context);

            _mockProviderRepository.Received(1).AddInteraction(Arg.Is <ProviderServiceInteraction>(x => x.AsJsonString() == interactionJson));
        }
Exemplo n.º 13
0
        private void RegisterInteraction()
        {
            if (IsNullOrEmpty(_description))
            {
                throw new InvalidOperationException("description has not been set, please supply using the UponReceiving method.");
            }

            if (_request == null)
            {
                throw new InvalidOperationException("request has not been set, please supply using the With method.");
            }

            if (_response == null)
            {
                throw new InvalidOperationException("response has not been set, please supply using the WillRespondWith method.");
            }

            var interaction = new ProviderServiceInteraction
            {
                ProviderState = _providerState,
                Description   = _description,
                Request       = _request,
                Response      = _response
            };

            // TODO
            throw new NotImplementedException();

            ClearTrasientState();
        }
        public void Handle_WithAGetRequestToInteractionsVerificationAndCorrectlyMatchedHandledRequest_ReturnsOkResponse()
        {
            var context = new NancyContext
            {
                Request = new Request("GET", "/interactions/verification", "http")
            };
            var interaction = new ProviderServiceInteraction();

            var handler = GetSubject();


            _mockProviderRepository.TestScopedInteractions.Returns(new List <ProviderServiceInteraction>
            {
                interaction
            });

            _mockProviderRepository.HandledRequests.Returns(new List <HandledRequest>
            {
                new HandledRequest(new ProviderServiceRequest(), interaction)
            });

            var response = handler.Handle(context);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Exemplo n.º 15
0
        private void RegisterInteraction()
        {
            if (IsNullOrEmpty(_description))
            {
                throw new InvalidOperationException("description has not been set, please supply using the UponReceiving method.");
            }

            if (_request == null)
            {
                throw new InvalidOperationException("request has not been set, please supply using the With method.");
            }

            if (_response == null)
            {
                throw new InvalidOperationException("response has not been set, please supply using the WillRespondWith method.");
            }

            var interaction = new ProviderServiceInteraction
            {
                ProviderState = _providerState,
                Description   = _description,
                Request       = _request,
                Response      = _response
            };

            Async.RunSync(() => _adminHttpClient.SendAdminHttpRequest(HttpVerb.Post, Constants.InteractionsPath, interaction));

            ClearTrasientState();
        }
Exemplo n.º 16
0
        public void AddInteraction(ProviderServiceInteraction interaction)
        {
            if (interaction == null)
            {
                throw new ArgumentNullException("interaction");
            }

            //You cannot have any duplicate interaction defined in a test scope
            if (_testScopedInteractions.Any(x => x.Description == interaction.Description &&
                                            x.ProviderState == interaction.ProviderState))
            {
                throw new PactFailureException(String.Format("An interaction already exists with the description '{0}' and provider state '{1}' in this test. Please supply a different description or provider state.", interaction.Description, interaction.ProviderState));
            }

            //From a Pact specification perspective, I should de-dupe any interactions that have been registered by another test as long as they match exactly!
            var duplicateInteractions = _interactions.Where(x => x.Description == interaction.Description && x.ProviderState == interaction.ProviderState).ToList();

            if (!duplicateInteractions.Any())
            {
                _interactions.Add(interaction);
            }
            else if (duplicateInteractions.Any(di => di.AsJsonString() != interaction.AsJsonString()))
            {
                //If the interaction description and provider state match, however anything else in the interaction is different, throw
                throw new PactFailureException(String.Format("An interaction registered by another test already exists with the description '{0}' and provider state '{1}', however the interaction does not match exactly. Please supply a different description or provider state. Alternatively align this interaction to match the duplicate exactly.", interaction.Description, interaction.ProviderState));
            }

            _testScopedInteractions.Add(interaction);
        }
        public void IncrementUsage_WhenCalled_SetsUsageCountToOne()
        {
            var interaction = new ProviderServiceInteraction();

            interaction.IncrementUsage();

            Assert.Equal(1, interaction.UsageCount);
        }
        private void ValidateInteraction(ProviderServiceInteraction interaction)
        {
            var request = _httpRequestMessageMapper.Convert(interaction.Request);

            var response = _httpClient.SendAsync(request, CancellationToken.None).Result;

            var expectedResponse = interaction.Response;
            var actualResponse = _providerServiceResponseMapper.Convert(response);

            _providerServiceResponseComparer.Compare(expectedResponse, actualResponse);
        }
Exemplo n.º 19
0
        public MissingInteractionComparisonFailure(ProviderServiceInteraction interaction)
        {
            var requestMethod = interaction.Request != null?interaction.Request.Method.ToString().ToUpperInvariant() : "No Method";

            var requestPath = interaction.Request != null ? interaction.Request.Path : "No Path";

            RequestDescription = String.Format("{0} {1}", requestMethod, requestPath);
            Result             = String.Format(
                "The interaction with description '{0}' and provider state '{1}', was not used by the test. Missing request {2}.",
                interaction.Description,
                interaction.ProviderState,
                RequestDescription);
        }
        public void AddInteraction_WithInteraction_InteractionIsAddedToInteractionsAndTestScopedInteractions()
        {
            var interaction = new ProviderServiceInteraction {
                Description = "My description 1"
            };

            var repo = GetSubject();

            repo.AddInteraction(interaction);

            Assert.Equal(interaction, repo.Interactions.Single());
            Assert.Equal(interaction, repo.TestScopedInteractions.Single());
        }
        public void ClearTestScopedInteractions_WithTestScopedInteractions_TestScopedInteractionsRequestIsEmpty()
        {
            var interaction1 = new ProviderServiceInteraction {
                Description = "My description 1"
            };
            var interaction2 = new ProviderServiceInteraction {
                Description = "My description 2"
            };

            var repo = GetSubject();

            repo.AddInteraction(interaction1);
            repo.AddInteraction(interaction2);

            repo.ClearTestScopedInteractions();

            Assert.Empty(repo.TestScopedInteractions);
        }
        public void AddInteraction_WhenAddingADuplicateTestScopedInteraction_ThrowsInvalidOperationException()
        {
            var interaction1 = new ProviderServiceInteraction {
                Description = "My description 1"
            };
            var interaction2 = new ProviderServiceInteraction {
                Description = "My description 1"
            };

            var repo = GetSubject();

            repo.AddInteraction(interaction1);

            Assert.Throws <InvalidOperationException>(() => repo.AddInteraction(interaction2));

            Assert.Equal(interaction1, repo.Interactions.Single());
            Assert.Equal(interaction1, repo.TestScopedInteractions.Single());
        }
Exemplo n.º 23
0
        private void RegisterInteraction()
        {
            if (String.IsNullOrEmpty(_description))
            {
                throw new InvalidOperationException("description has not been set, please supply using the UponReceiving method.");
            }

            if (_request == null)
            {
                throw new InvalidOperationException("request has not been set, please supply using the With method.");
            }

            if (_response == null)
            {
                throw new InvalidOperationException("response has not been set, please supply using the WillRespondWith method.");
            }

            var interaction = new ProviderServiceInteraction
            {
                ProviderState = _providerState,
                Description   = _description,
                Request       = _request,
                Response      = _response
            };

            _testScopedInteractions = _testScopedInteractions ?? new List <ProviderServiceInteraction>();
            _interactions           = _interactions ?? new List <ProviderServiceInteraction>();

            if (_testScopedInteractions.Any(x => x.Description == interaction.Description &&
                                            x.ProviderState == interaction.ProviderState))
            {
                throw new InvalidOperationException(String.Format("An interaction already exists with the description \"{0}\" and provider state \"{1}\". Please supply a different description or provider state.", interaction.Description, interaction.ProviderState));
            }

            if (!_interactions.Any(x => x.Description == interaction.Description &&
                                   x.ProviderState == interaction.ProviderState))
            {
                _interactions.Add(interaction);
            }

            _testScopedInteractions.Add(interaction);

            ClearTrasientState();
        }
Exemplo n.º 24
0
 public void AddInteraction(ProviderServiceInteraction PSI)
 {
     MockProviderService
     .Given(PSI.ProviderState)
     .UponReceiving(PSI.Description)
     .With(new ProviderServiceRequest
     {
         Method  = PSI.Request.Method,
         Path    = PSI.Request.Path,
         Headers = PSI.Request.Headers,
         Body    = PSI.Request.Body
     })
     .WillRespondWith(new ProviderServiceResponse
     {
         Status  = PSI.Response.Status,
         Headers = PSI.Response.Headers,
         Body    = PSI.Response.Body
     });
 }
        public void AddInteraction_WhenAddingAnInteractionThatHasBeenAddedInAPreviousTest_InteractionIsDeDuplicatedFromInteractions()
        {
            var interaction1 = new ProviderServiceInteraction {
                Description = "My description 1"
            };
            var interaction2 = new ProviderServiceInteraction {
                Description = "My description 1"
            };

            var repo = GetSubject();

            repo.AddInteraction(interaction1);
            repo.ClearTestScopedInteractions();

            repo.AddInteraction(interaction2);

            Assert.Equal(interaction1, repo.Interactions.Single());
            Assert.Equal(interaction2, repo.TestScopedInteractions.Single());
        }
        public void WillRespondWith_WithValidInteraction_PerformsAdminInteractionsPostRequestWithInteraction()
        {
            var providerState = "My provider state";
            var description   = "My description";
            var request       = new ProviderServiceRequest
            {
                Method = HttpVerb.Head,
                Path   = "/tester/testing/1"
            };
            var response = new ProviderServiceResponse
            {
                Status = (int)HttpStatusCode.ProxyAuthenticationRequired
            };

            var expectedInteraction = new ProviderServiceInteraction
            {
                ProviderState = providerState,
                Description   = description,
                Request       = request,
                Response      = response
            };
            var expectedInteractionJson = expectedInteraction.AsJsonString();

            var mockService = GetSubject();

            mockService.Start();

            mockService
            .Given(providerState)
            .UponReceiving(description)
            .With(request)
            .WillRespondWith(response);

            var actualRequest         = _fakeHttpMessageHandler.RequestsRecieved.Single();
            var actualInteractionJson = _fakeHttpMessageHandler.RequestContentRecieved.Single();

            Assert.Equal(HttpMethod.Post, actualRequest.Method);
            Assert.Equal("http://localhost:1234/interactions", actualRequest.RequestUri.OriginalString);
            Assert.True(actualRequest.Headers.Contains(Constants.AdministrativeRequestHeaderKey));

            Assert.Equal(expectedInteractionJson, actualInteractionJson);
        }
Exemplo n.º 27
0
        private static bool RequestPathMatches(HttpListenerRequest request, ProviderServiceInteraction providerServiceInteraction)
        {
            // Compare base url
            var baseUrlMatches = string.Compare(request.Url.LocalPath, providerServiceInteraction.Request.Path, StringComparison.OrdinalIgnoreCase) == 0;

            if (baseUrlMatches)
            {
                // Compare query string
                if (string.IsNullOrEmpty(request.Url.Query))
                {
                    return(string.IsNullOrEmpty(providerServiceInteraction.Request.Query));
                }

                var currentPactQuery = HttpUtility.ParseQueryString(providerServiceInteraction.Request.Query ?? "");
                var currentQuery     = HttpUtility.ParseQueryString(request.Url.Query);
                var isCurrentPactQueryTheSameAsCurrentRequestQuery = currentPactQuery.FilterCollection().CollectionEquals(currentQuery.FilterCollection());
                return(isCurrentPactQueryTheSameAsCurrentRequestQuery);
            }
            return(false);
        }
Exemplo n.º 28
0
        public void Handle_WithNancyContextRequestThatMatchesExpectedRequest_ReturnsNancyResponse()
        {
            var expectedRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/Test"
            };
            var actualRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/Test"
            };
            var expectedResponse = new ProviderServiceResponse {
                Status = 200
            };
            var nancyResponse = new Response {
                StatusCode = HttpStatusCode.OK
            };

            var handler = GetSubject();

            var nancyContext = new NancyContext
            {
                Request = new Request("GET", "/Test", "HTTP")
            };

            var interaction = new ProviderServiceInteraction {
                Request = expectedRequest, Response = expectedResponse
            };

            _mockProviderRepository.GetMatchingTestScopedInteraction(Arg.Any <ProviderServiceRequest>())
            .Returns(interaction);

            _mockRequestMapper.Convert(nancyContext.Request).Returns(actualRequest);
            //mockRequestComparer.Compare Doesnt throw any exceptions
            _mockResponseMapper.Convert(expectedResponse).Returns(nancyResponse);

            var response = handler.Handle(nancyContext);

            Assert.Equal(nancyResponse, response);
        }
        public void ToString_WhenCalled_ReturnsJsonRepresentation()
        {
            const string expectedInteractionJson = "{\"description\":\"My description\",\"provider_state\":\"My provider state\",\"request\":{\"method\":\"delete\",\"path\":\"/tester\",\"query\":\"test=2\",\"headers\":{\"Accept\":\"application/json\"},\"body\":{\"test\":\"hello\"}},\"response\":{\"status\":407,\"headers\":{\"Content-Type\":\"application/json\"},\"body\":{\"yep\":\"it worked\"}}}";
            var          interaction             = new ProviderServiceInteraction
            {
                Request = new ProviderServiceRequest
                {
                    Method = HttpVerb.Delete,
                    Body   = new
                    {
                        test = "hello"
                    },
                    Headers = new Dictionary <string, object>
                    {
                        { "Accept", "application/json" }
                    },
                    Path  = "/tester",
                    Query = "test=2"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.ProxyAuthenticationRequired,
                    Body   = new
                    {
                        yep = "it worked"
                    },
                    Headers = new Dictionary <string, object>
                    {
                        { "Content-Type", "application/json" }
                    }
                },
                Description   = "My description",
                ProviderState = "My provider state",
            };

            var actualInteractionJson = interaction.AsJsonString();

            Assert.Equal(expectedInteractionJson, actualInteractionJson);
        }
        public void AddInteraction_WhenAddingAnInteractionThatHasBeenAddedInAPreviousTestHoweverTheDataIsDifferent_ThrowsInvalidOperationException()
        {
            var interaction1 = new ProviderServiceInteraction {
                Description = "My description 1", Request = new ProviderServiceRequest {
                    Method = HttpVerb.Get
                }
            };
            var interaction2 = new ProviderServiceInteraction {
                Description = "My description 1", Request = new ProviderServiceRequest {
                    Method = HttpVerb.Delete
                }
            };

            var repo = GetSubject();

            repo.AddInteraction(interaction1);
            repo.ClearTestScopedInteractions();

            Assert.Throws <InvalidOperationException>(() => repo.AddInteraction(interaction2));

            Assert.Equal(interaction1, repo.Interactions.Single());
            Assert.Empty(repo.TestScopedInteractions);
        }
Exemplo n.º 31
0
 public HandledRequest(ProviderServiceRequest actualRequest, ProviderServiceInteraction matchedInteraction)
 {
     ActualRequest = actualRequest;
     MatchedInteraction = matchedInteraction;
 }