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

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = null }
            };

            nancyContext.SetMockInteraction(interactions);

            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();
            var mockProviderRepository = Substitute.For<IMockProviderRepository>();

            mockResponseMapper.Convert(Arg.Any<ProviderServiceResponse>())
                .Returns(new Response
                {
                    StatusCode = HttpStatusCode.InternalServerError
                });

            IMockProviderRequestHandler handler = new MockProviderRequestHandler(mockRequestMapper, mockResponseMapper, mockProviderRepository);

            var result = handler.Handle(nancyContext);

            mockResponseMapper.Received(1).Convert(Arg.Is<ProviderServiceResponse>(x => x.Status == 500));
            Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
        }
        public void GetMatchingInteraction_WithNoMatchingInteraction_ThrowsArgumentException()
        {
            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/hello" }, Response = new ProviderServiceResponse()}
            };

            var context = new NancyContext();
            context.SetMockInteraction(interactions);

            Assert.Throws<ArgumentException>(() => context.GetMatchingInteraction(HttpVerb.Get, "/events"));
        }
        public void SetMockInteraction_WithInteractionAndNoExistingItemsInNancyContext_AddsInteractionToNancyContextItems()
        {
            var context = new NancyContext();
            
            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = new ProviderServiceResponse() }
            };

            context.SetMockInteraction(interactions);

            Assert.Equal(1, context.Items.Count);
            Assert.Equal(interactions, context.Items[Constants.PactMockInteractionsKey]);
        }
        public NancyContext Create(Request request)
        {
            var nancyContext = new NancyContext
            {
                Request = request, 
                Trace = _requestTraceFactory.Create(request)
            };

            nancyContext.Culture = _cultureService.DetermineCurrentCulture(nancyContext);
            nancyContext.Text = new TextResourceFinder(_textResource, nancyContext);

            nancyContext.SetMockInteraction(_mockContextService.GetExpectedRequestResponsePairs());

            return nancyContext;
        }
        public void GetMatchingInteraction_WithOneMatchingInteraction_ReturnsInteraction()
        {
            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/events" }, Response = new ProviderServiceResponse()},
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Post, Path = "/events" }, Response = new ProviderServiceResponse()},
            };

            var context = new NancyContext();
            context.SetMockInteraction(interactions);

            var result = context.GetMatchingInteraction(HttpVerb.Get, "/events");

            Assert.Equal(interactions.First(), result);
        }
        public void SetMockInteraction_WithInteractionAndExistingItemsInNancyContext_AddsInteractionToNancyContextItems()
        {
            var context = new NancyContext();
            context.Items.Add(new KeyValuePair<string, object>("test", "tester"));

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = new ProviderServiceResponse() },
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = new ProviderServiceResponse() }
            };

            context.SetMockInteraction(interactions);

            Assert.Equal(2, context.Items.Count);
            Assert.Equal(interactions, context.Items[Constants.PactMockInteractionsKey]);
        }
        public void SetMockInteraction_WithInteractionAndExistingInteractionsInNancyContext_OverwritesInteractionsInNancyContextItem()
        {
            var context = new NancyContext();
            context.Items.Add(new KeyValuePair<string, object>(Constants.PactMockInteractionsKey, new List<KeyValuePair<ProviderServiceRequest, ProviderServiceResponse>>
            {
                new KeyValuePair<ProviderServiceRequest, ProviderServiceResponse>(new ProviderServiceRequest(), new ProviderServiceResponse()),
                new KeyValuePair<ProviderServiceRequest, ProviderServiceResponse>(new ProviderServiceRequest(), new ProviderServiceResponse())
            }));

            var interactions = new List<ProviderServiceInteraction>()
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = new ProviderServiceResponse()},
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = new ProviderServiceResponse()}
            };

            context.SetMockInteraction(interactions);

            Assert.Equal(1, context.Items.Count);
            Assert.Equal(interactions, context.Items[Constants.PactMockInteractionsKey]);
        }
        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 mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();
            var mockProviderRepository = Substitute.For<IMockProviderRepository>();

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

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = expectedRequest, Response = expectedResponse }
            };

            nancyContext.SetMockInteraction(interactions);

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

            IMockProviderRequestHandler handler = new MockProviderRequestHandler(mockRequestMapper, mockResponseMapper, mockProviderRepository);

            var response = handler.Handle(nancyContext);

            Assert.Equal(nancyResponse, response);
        }
        public void Handle_WithNancyContext_AddHandledRequestIsCalledOnTheMockProviderRepository()
        {   
            var expectedRequest = new ProviderServiceRequest();
            var expectedResponse = new ProviderServiceResponse();
            var actualRequest = new ProviderServiceRequest();

            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();
            var mockProviderRepository = Substitute.For<IMockProviderRepository>();

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

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = expectedRequest, Response = expectedResponse }
            };

            nancyContext.SetMockInteraction(interactions);

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

            IMockProviderRequestHandler handler = new MockProviderRequestHandler(mockRequestMapper, mockResponseMapper, mockProviderRepository);

            handler.Handle(nancyContext);

            mockProviderRepository.Received(1).AddHandledRequest(Arg.Is<HandledRequest>(x => x.ActualRequest == actualRequest && x.MatchedInteraction == interactions.First()));
        }
        public void Handle_WithNancyContext_CompareIsCalledOnTheProviderServiceRequestComparer()
        {
            var expectedRequest = new ProviderServiceRequest();
            var expectedResponse = new ProviderServiceResponse();
            var actualRequest = new ProviderServiceRequest();

            var mockRequestComparer = Substitute.For<IProviderServiceRequestComparer>();
            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();

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

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = expectedRequest, Response = expectedResponse }
            };

            nancyContext.SetMockInteraction(interactions);

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

            IMockProviderNancyRequestHandler handler = new MockProviderNancyRequestHandler(mockRequestComparer, mockRequestMapper, mockResponseMapper);

            handler.Handle(nancyContext);

            mockRequestComparer.Received(1).Compare(expectedRequest, actualRequest);
        }
        public void Handle_WithNancyContextRequestThatDoesNotMatchExpectedRequest_ResponseMapperIsCalledAndReturns500Response()
        {
            var expectedRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path = "/Test"
            };
            var actualRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Put,
                Path = "/Test"
            };
            var expectedResponse = new ProviderServiceResponse { Status = 200 };
            var nancyResponse = new Response { StatusCode = HttpStatusCode.OK };
            var compareException = new CompareFailedException("Something failed");

            var mockRequestComparer = Substitute.For<IProviderServiceRequestComparer>();
            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();

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

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = expectedRequest, Response = expectedResponse }
            };

            nancyContext.SetMockInteraction(interactions);

            mockRequestMapper.Convert(nancyContext.Request).Returns(actualRequest);
            mockRequestComparer
                .When(x => x.Compare(expectedRequest, actualRequest))
                .Do(x => { throw compareException; });

            mockResponseMapper.Convert(expectedResponse).Returns(nancyResponse);

            mockResponseMapper.Convert(Arg.Any<ProviderServiceResponse>())
                .Returns(new Response
                {
                    StatusCode = HttpStatusCode.InternalServerError
                });

            IMockProviderNancyRequestHandler handler = new MockProviderNancyRequestHandler(mockRequestComparer, mockRequestMapper, mockResponseMapper);

            var response = handler.Handle(nancyContext);

            mockResponseMapper.Received(1).Convert(Arg.Is<ProviderServiceResponse>(x => x.Status == 500));
            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            Assert.NotEmpty(response.ReasonPhrase);
        }
        public void Handle_WithAGetRequestToInteractionsVerificationAndRegisteredInteractionWasCalledExactlyOnce_ReturnsOkResponse()
        {
            var context = new NancyContext
            {
                Request = new Request("GET", "/interactions/verification", "http")
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction()
            };

            var handler = GetSubject();

            context.SetMockInteraction(interactions);

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

            var response = handler.Handle(context);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        public void GetMatchingMockInteraction_WithMoreThanOneMatchingInteraction_ThrowsPactFailureException()
        {
            var requestResponsePairs = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/events" }, Response = new ProviderServiceResponse() },
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/events" }, Response = new ProviderServiceResponse()},
            };

            var context = new NancyContext();
            context.SetMockInteraction(requestResponsePairs);

            Assert.Throws<PactFailureException>(() => context.GetMatchingMockInteraction(HttpVerb.Get, "/events"));
        }
        public void Handle_WithAGetRequestToInteractionsVerificationAndReporterHasErrors_ReturnsErrorResponseContent()
        {
            const string exceptionMessage = "Registered mock interaction with description 'My description' and provider state 'My provider state', was not used by the test.";
            var context = new NancyContext
            {
                Request = new Request("GET", "/interactions/verification", "http")
            };

            var handler = GetSubject();

            context.SetMockInteraction(new List<ProviderServiceInteraction> { new ProviderServiceInteraction() });

            _mockReporter
                .When(x => x.ThrowIfAnyErrors())
                .Do(x => { throw new PactFailureException(exceptionMessage); });

            var response = handler.Handle(context);

            string content;
            using (var stream = new MemoryStream())
            {
                response.Contents(stream);
                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    content = reader.ReadToEnd();
                }
            }

            Assert.Equal(exceptionMessage, content);
        }
        public void Handle_WithAGetRequestToInteractionsVerificationAndReporterHasErrors_ReturnsInternalServerErrorResponse()
        {
            const string exceptionMessage = "Registered mock interaction with description 'My description' and provider state 'My provider state', was not used by the test.";
            var context = new NancyContext
            {
                Request = new Request("GET", "/interactions/verification", "http")
            };

            var handler = GetSubject();
            
            context.SetMockInteraction(new List<ProviderServiceInteraction> { new ProviderServiceInteraction() });

            _mockReporter
                .When(x => x.ThrowIfAnyErrors())
                .Do(x => { throw new PactFailureException(exceptionMessage); });

            var response = handler.Handle(context);

            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
        }
        public void Handle_WithAGetRequestToInteractionsVerificationAndRegisteredInteractionWasCalledMultipleTimes_ReportErrorIsCalledOnReporter()
        {
            var context = new NancyContext
            {
                Request = new Request("GET", "/interactions/verification", "http")
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction()
            };

            var handler = GetSubject();

            context.SetMockInteraction(interactions);

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

            handler.Handle(context);

            _mockReporter.Received(1).ReportError(Arg.Any<string>());
        }
        public void Handle_WithAGetRequestToInteractionsVerificationAndRegisteredInteractionWasNotCalled_ReportErrorIsCalledOnReporter()
        {
            var context = new NancyContext
            {
                Request = new Request("GET", "/interactions/verification", "http")
            };
            
            var handler = GetSubject();

            context.SetMockInteraction(new List<ProviderServiceInteraction> { new ProviderServiceInteraction() });

            handler.Handle(context);

            _mockReporter.Received(1).ReportError(Arg.Any<string>());
        }
        public void Handle_WithNancyContext_ConvertIsCalledOnThProviderServiceRequestMapper()
        {
            var expectedRequest = new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path = "/"
            };
            var expectedResponse = new ProviderServiceResponse();
            var nancyContext = new NancyContext
            {
                Request = new Request("GET", "/", "HTTP")
            };

            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();
            var mockProviderRepository = Substitute.For<IMockProviderRepository>();

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

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = expectedRequest, Response = expectedResponse}
            };

            nancyContext.SetMockInteraction(interactions);

            IMockProviderRequestHandler handler = new MockProviderRequestHandler(mockRequestMapper, mockResponseMapper, mockProviderRepository);

            handler.Handle(nancyContext);

            mockRequestMapper.Received(1).Convert(nancyContext.Request);
        }
        public void GetMockInteractions_WithRegisteredInteractions_ReturnsInteractions()
        {
            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/events" }, Response = new ProviderServiceResponse()},
                new ProviderServiceInteraction { Request = new ProviderServiceRequest { Method = HttpVerb.Post, Path = "/events" }, Response = new ProviderServiceResponse()},
            };

            var context = new NancyContext();
            context.SetMockInteraction(interactions);

            var result = context.GetMockInteractions().ToList();

            Assert.Equal(2, result.Count());
            Assert.Equal(interactions.First(), result.First());
            Assert.Equal(interactions.Last(), result.Last());
        }