public void Validate_ProviderStatesTearDownDefined_TearDownActionIsInvokedForEachInteraction()
        {
            var actionInvocationCount = 0;
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    },
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction 2"
                    }
                }
            };
            var providerStates = new ProviderStates(setUp: null, tearDown: () => { actionInvocationCount++; });

            var validator = GetSubject();

            validator.Validate(pact, providerStates);

            Assert.Equal(pact.Interactions.Count(), actionInvocationCount);
        }
        public void Validate_ProviderStatesTearDownDefined_TearDownActionIsInvoked()
        {
            var actionInkoved = false;
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    }
                }
            };
            var providerStates = new ProviderStates(setUp: null, tearDown: () => { actionInkoved = true; });

            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            providerServiceValidator.Validate(pact, providerStates);

            Assert.True(actionInkoved, "Provider states pact tearDown action is invoked");
        }
        public void Validate_WithNullProvider_ThrowsArgumentException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
            };

            var validator = GetSubject();

            Assert.Throws<ArgumentException>(() => validator.Validate(pact, null));
        }
        public void Validate_WithEmptyConsumerName_ThrowsArgumentException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = String.Empty },
                Provider = new Party { Name = "My Provider" }
            };

            var validator = GetSubject();

            Assert.Throws<ArgumentException>(() => validator.Validate(pact, null));
        }
        public void Handle_WithAPostRequestToPactAndNoInteractionsHaveBeenRegistered_NewPactFileIsSavedWithNoInteractions()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = new ProviderServiceInteraction[0]
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

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

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

            var handler = GetSubject();

            handler.Handle(context);

            _mockFileSystem.File.Received(1).WriteAllText(Path.Combine(Constants.DefaultPactDir, pactDetails.GeneratePactFileName()), pactFileJson);
        }
        public void Handle_WithAPostRequestToPactAndDirectoryDoesNotExist_DirectoryIsCreatedAndNewPactFileIsSavedWithInteractions()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My description",
                    Request = new ProviderServiceRequest
                    {
                        Method = HttpVerb.Get,
                        Path = "/test"
                    },
                    Response = new ProviderServiceResponse
                    {
                        Status = (int)HttpStatusCode.NoContent
                    }
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = interactions
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

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

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

            var filePath = Path.Combine(Constants.DefaultPactDir, pactDetails.GeneratePactFileName());

            var handler = GetSubject();

            _mockProviderRepository.Interactions.Returns(interactions);

            var writeAllTextCount = 0;
            _mockFileSystem.File
                .When(x => x.WriteAllText(filePath, pactFileJson))
                .Do(x =>
                {
                    writeAllTextCount++;
                    if (writeAllTextCount == 1)
                    {
                        throw new DirectoryNotFoundException("It doesn't exist");
                    }
                });

            handler.Handle(context);

            _mockFileSystem.File.Received(2).WriteAllText(filePath, pactFileJson);
        }
        private Response HandlePostPactRequest(NancyContext context)
        {
            var pactDetailsJson = ReadContent(context.Request.Body);
            var pactDetails = JsonConvert.DeserializeObject<PactDetails>(pactDetailsJson);
            var pactFilePath = Path.Combine(_pactConfig.PactDir, pactDetails.GeneratePactFileName());

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = _mockProviderRepository.Interactions
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);

            try
            {
                _fileSystem.File.WriteAllText(pactFilePath, pactFileJson);
            }
            catch (DirectoryNotFoundException)
            {
                _fileSystem.Directory.CreateDirectory(_pactConfig.PactDir);
                _fileSystem.File.WriteAllText(pactFilePath, pactFileJson);
            }

            return GenerateResponse(HttpStatusCode.OK, pactFileJson, "application/json");
        }
        public void Validate_WithNullInteractionsInPactFile_DoesNotCallTheHttpRequestSenderOrRequestComparer()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" }
            };

            var validator = GetSubject();

            validator.Validate(pact, null);

            _mockResponseComparer.Received(0).Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>());
            _mockHttpRequestSender.Received(0).Send(Arg.Any<ProviderServiceRequest>());
        }
        public void Validate_WithInteractionsInPactFile_CallsSendOnHttpRequestSender()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction",
                        Request = new ProviderServiceRequest(),
                        Response = new ProviderServiceResponse()
                    }
                }
            };

            var validator = GetSubject();

            validator.Validate(pact, null);

            _mockHttpRequestSender.Received(1).Send(pact.Interactions.First().Request);
        }
        public void Validate_WithTwoInteractionsAndProviderStateSetupAndTearDownDefined_SetUpIsInvokedBeforeCompareAndTearDownIsInvokedAfterCompare()
        {
            const string providerState1 = "My Provider State";
            const string providerState2 = "My Provider State 2";

            const string setUpSuffix = "-SetUp";
            const string tearDownSuffix = "-TearDown";

            var actionInvocationLog = new List<string>();
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        ProviderState = providerState1,
                        Description = "My interaction"
                    },
                    new ProviderServiceInteraction
                    {
                        ProviderState = providerState2,
                        Description = "My interaction"
                    },
                }
            };
            var providerStates = new ProviderStates();
            providerStates.Add(new ProviderState(providerState1, setUp: () => actionInvocationLog.Add(providerState1 + setUpSuffix), tearDown: () => actionInvocationLog.Add(providerState1 + tearDownSuffix)));
            providerStates.Add(new ProviderState(providerState2, setUp: () => actionInvocationLog.Add(providerState2 + setUpSuffix), tearDown: () => actionInvocationLog.Add(providerState2 + tearDownSuffix)));

            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            providerServiceValidator.Validate(pact, providerStates);

            Assert.Equal(4, actionInvocationLog.Count());
            Assert.Equal(providerState1 + setUpSuffix, actionInvocationLog.First());
            Assert.Equal(providerState1 + tearDownSuffix, actionInvocationLog.Skip(1).First());
            Assert.Equal(providerState2 + setUpSuffix, actionInvocationLog.Skip(2).First());
            Assert.Equal(providerState2 + tearDownSuffix, actionInvocationLog.Last());
        }
        public void Validate_WithNullInteractionsInPactFile_DoesNotCallHttpClientOrAnyOfTheMappersOrValidators()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" }
            };
            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            providerServiceValidator.Validate(pact, null);

            mockProviderServiceResponseComparer.Received(0).Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>());
            Assert.Equal(0, fakeHttpClient.SendAsyncCallCount);
            mockHttpRequestMessageMapper.Received(0).Convert(Arg.Any<ProviderServiceRequest>());
            mockProviderServiceResponseMapper.Received(0).Convert(Arg.Any<HttpResponseMessage>());
        }
        public void Validate_WithNoInteractionsAndProviderStatesSetUpDefined_SetUpActionIsNotInvoked()
        {
            var actionInkoved = false;
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = null
            };
            var providerStates = new ProviderStates(setUp: () => { actionInkoved = true; }, tearDown: null);

            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            providerServiceValidator.Validate(pact, providerStates);

            Assert.False(actionInkoved, "Provider states pact setUp action is not invoked");
        }
        public void Validate_WithInteractionsInPactFile_CallsValidateOnTheProviderServiceResponseValidator()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    }
                }
            };
            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            providerServiceValidator.Validate(pact, null);

            mockProviderServiceResponseComparer.Received(1).Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>());
        }
        public void Validate_WhenReporterHasErrors_ThrowsCompareFailedException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    },
                }
            };

            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();
            var mockReporter = Substitute.For<IReporter>();

            mockReporter
                .When(x => x.ThrowIfAnyErrors())
                .Do(info => { throw new CompareFailedException("Compare failed"); });

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                mockReporter);

            Assert.Throws<CompareFailedException>(() => providerServiceValidator.Validate(pact, null));
            mockReporter.Received(1).ThrowIfAnyErrors();
        }
        public void Validate_WhenProviderServiceResponseValidatorThrowsACompareFailedException_ThrowsACompareFailedException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    }
                }
            };
            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            mockProviderServiceResponseComparer
                .When(x => x.Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>()))
                .Do(x => { throw new CompareFailedException("Expected response cannot be null"); });

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            Assert.Throws<CompareFailedException>(() => providerServiceValidator.Validate(pact, null));
        }
        public void Validate_WhenProviderServiceResponseComparerThrowsAndProviderStatesTearDownDefined_TearDownActionIsInvoked()
        {
            var actionInkoved = false;
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    }
                }
            };
            var providerStates = new ProviderStates(setUp: null, tearDown: () => { actionInkoved = true; });

            var validator = GetSubject();

            _mockResponseComparer
                .When(x => x.Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>()))
                .Do(x => { throw new PactFailureException("Expected response cannot be null"); });

            Assert.Throws<PactFailureException>(() => validator.Validate(pact, providerStates));

            Assert.True(actionInkoved, "Provider states pact tearDown action is invoked");
        }
        public void Validate_WhenProviderServiceResponseComparerThrowsPactFailureException_ThrowsPactFailureException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    }
                }
            };

            var validator = GetSubject();

            _mockResponseComparer
                .When(x => x.Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>()))
                .Do(x => { throw new PactFailureException("Expected response cannot be null"); });

            Assert.Throws<PactFailureException>(() => validator.Validate(pact, null));
        }
        public void Validate_WhenInteractionDefinesAProviderStateAndNoProviderStatesAreSupplied_ThrowsInvalidOperationException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Party { Name = "My client" },
                Provider = new Party { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        ProviderState = "My Provider State",
                        Description = "My interaction"
                    }
                }
            };

            var mockProviderServiceResponseComparer = Substitute.For<IProviderServiceResponseComparer>();
            var fakeHttpClient = new FakeHttpClient();
            var mockHttpRequestMessageMapper = Substitute.For<IHttpRequestMessageMapper>();
            var mockProviderServiceResponseMapper = Substitute.For<IProviderServiceResponseMapper>();

            var providerServiceValidator = new ProviderServiceValidator(
                mockProviderServiceResponseComparer,
                fakeHttpClient,
                mockHttpRequestMessageMapper,
                mockProviderServiceResponseMapper,
                new Reporter(new NoOpReportOutputter()));

            Assert.Throws<InvalidOperationException>(() => providerServiceValidator.Validate(pact, null));
        }
        public void Validate_WithNoInteractionsAndProviderStatesSetUpDefined_SetUpActionIsNotInvoked()
        {
            var actionInkoved = false;
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = null
            };
            var providerStates = new ProviderStates(setUp: () => { actionInkoved = true; }, tearDown: null);

            var validator = GetSubject();

            validator.Validate(pact, providerStates);

            Assert.False(actionInkoved, "Provider states pact setUp action is not invoked");
        }
        public void Interactions_WithNoInteractions_ReturnsNull()
        {
            var pactFile = new ProviderServicePactFile();

            Assert.Null(pactFile.Interactions);
        }
        public void Validate_WithTwoInteractionsAndProviderStateSetupAndTearDownDefined_SetUpIsInvokedBeforeCompareAndTearDownIsInvokedAfterCompare()
        {
            const string providerState1 = "My Provider State";
            const string providerState2 = "My Provider State 2";

            const string setUpSuffix = "-SetUp";
            const string tearDownSuffix = "-TearDown";

            var actionInvocationLog = new List<string>();
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        ProviderState = providerState1,
                        Description = "My interaction"
                    },
                    new ProviderServiceInteraction
                    {
                        ProviderState = providerState2,
                        Description = "My interaction"
                    },
                }
            };
            var providerStates = new ProviderStates();
            providerStates.Add(new ProviderState(providerState1, setUp: () => actionInvocationLog.Add(providerState1 + setUpSuffix), tearDown: () => actionInvocationLog.Add(providerState1 + tearDownSuffix)));
            providerStates.Add(new ProviderState(providerState2, setUp: () => actionInvocationLog.Add(providerState2 + setUpSuffix), tearDown: () => actionInvocationLog.Add(providerState2 + tearDownSuffix)));

            var validator = GetSubject();

            validator.Validate(pact, providerStates);

            Assert.Equal(4, actionInvocationLog.Count());
            Assert.Equal(providerState1 + setUpSuffix, actionInvocationLog.First());
            Assert.Equal(providerState1 + tearDownSuffix, actionInvocationLog.Skip(1).First());
            Assert.Equal(providerState2 + setUpSuffix, actionInvocationLog.Skip(2).First());
            Assert.Equal(providerState2 + tearDownSuffix, actionInvocationLog.Last());
        }
Ejemplo n.º 22
0
        private void PersistPactFile()
        {
            if (String.IsNullOrEmpty(ConsumerName))
            {
                throw new InvalidOperationException("ConsumerName has not been set, please supply a consumer name using the ServiceConsumer method.");
            }

            if (String.IsNullOrEmpty(ProviderName))
            {
                throw new InvalidOperationException("ProviderName has not been set, please supply a provider name using the HasPactWith method.");
            }

            var pactFile = new ProviderServicePactFile
            {
                Provider = new Party { Name = ProviderName },
                Consumer = new Party { Name = ConsumerName }
            };

            if (_mockProviderService != null)
            {
                var interactions = _mockProviderService.Interactions;
                if (interactions != null)
                {
                    pactFile.Interactions = interactions as IEnumerable<ProviderServiceInteraction>;
                }
            }

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);

            try
            {
                _fileSystem.File.WriteAllText(PactFileUri, pactFileJson);
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                _fileSystem.Directory.CreateDirectory(PactFileDirectory);
                _fileSystem.File.WriteAllText(PactFileUri, pactFileJson);
            }
        }
        public void Validate_WhenAFailureOccurs_ThrowsPactFailureException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        Description = "My interaction"
                    },
                }
            };

            var comparisonResult = new ComparisonResult();
            comparisonResult.RecordFailure(new ErrorMessageComparisonFailure("It failed"));

            var validator = GetSubject();

            _mockResponseComparer
                .Compare(Arg.Any<ProviderServiceResponse>(), Arg.Any<ProviderServiceResponse>())
                .Returns(comparisonResult);

            Assert.Throws<PactFailureException>(() => validator.Validate(pact, null));
        }
Ejemplo n.º 24
0
        public void Validate(ProviderServicePactFile pactFile, ProviderStates providerStates)
        {
            if (pactFile == null)
            {
                throw new ArgumentException("Please supply a non null pactFile");
            }

            if (pactFile.Consumer == null || String.IsNullOrEmpty(pactFile.Consumer.Name))
            {
                throw new ArgumentException("Please supply a non null or empty Consumer name in the pactFile");
            }

            if (pactFile.Provider == null || String.IsNullOrEmpty(pactFile.Provider.Name))
            {
                throw new ArgumentException("Please supply a non null or empty Provider name in the pactFile");
            }

            if (pactFile.Interactions != null && pactFile.Interactions.Any())
            {
                InvokePactSetUpIfApplicable(providerStates);

                var interationNumber = 1;
                try //TODO: Clean this up once the validators/comparers no longer throw
                {
                    foreach (var interaction in pactFile.Interactions)
                    {
                        ProviderState providerStateItem = null;

                        if (interaction.ProviderState != null)
                        {
                            try
                            {
                                providerStateItem = providerStates.Find(interaction.ProviderState);
                            }
                            catch (Exception)
                            {
                                providerStateItem = null;
                            }

                            if (providerStateItem == null)
                            {
                                throw new InvalidOperationException(String.Format("providerState '{0}' was defined by a consumer, however could not be found. Please supply this provider state.", interaction.ProviderState));
                            }
                        }

                        InvokeInteractionSetUpIfApplicable(providerStateItem);

                        _reporter.ReportInfo(String.Format("{0}) Verifying a Pact between {1} and {2} - {3}.", interationNumber, pactFile.Consumer.Name, pactFile.Provider.Name, interaction.Description));

                        try
                        {
                            ValidateInteraction(interaction);
                        }
                        finally
                        {
                            InvokeInteractionIfApplicable(providerStateItem);
                        }
                        
                        interationNumber++;
                    }

                    _reporter.ThrowIfAnyErrors();
                }
                finally 
                {
                    InvokeTearDownIfApplicable(providerStates);
                }
            }
        }
        public void Validate(ProviderServicePactFile pactFile, ProviderStates providerStates)
        {
            if (pactFile == null)
            {
                throw new ArgumentException("Please supply a non null pactFile");
            }

            if (pactFile.Consumer == null || String.IsNullOrEmpty(pactFile.Consumer.Name))
            {
                throw new ArgumentException("Please supply a non null or empty Consumer name in the pactFile");
            }

            if (pactFile.Provider == null || String.IsNullOrEmpty(pactFile.Provider.Name))
            {
                throw new ArgumentException("Please supply a non null or empty Provider name in the pactFile");
            }

            if (pactFile.Interactions != null && pactFile.Interactions.Any())
            {
                _reporter.ReportInfo(String.Format("Verifying a Pact between {0} and {1}", pactFile.Consumer.Name, pactFile.Provider.Name));

                var comparisonResult = new ComparisonResult();

                foreach (var interaction in pactFile.Interactions)
                {
                    InvokePactSetUpIfApplicable(providerStates);

                    _reporter.ResetIndentation();

                    ProviderState providerStateItem = null;

                    if (interaction.ProviderState != null)
                    {
                        try
                        {
                            providerStateItem = providerStates.Find(interaction.ProviderState);
                        }
                        catch (Exception)
                        {
                            providerStateItem = null;
                        }

                        if (providerStateItem == null)
                        {
                            throw new InvalidOperationException(String.Format("providerState '{0}' was defined by a consumer, however could not be found. Please supply this provider state.", interaction.ProviderState));
                        }
                    }

                    InvokeProviderStateSetUpIfApplicable(providerStateItem);

                    if (!String.IsNullOrEmpty(interaction.ProviderState))
                    {
                        _reporter.Indent();
                        _reporter.ReportInfo(String.Format("Given {0}", interaction.ProviderState));
                    }

                    _reporter.Indent();
                    _reporter.ReportInfo(String.Format("{0}", interaction.Description));

                    if (interaction.Request != null)
                    {
                        _reporter.Indent();
                        _reporter.ReportInfo(String.Format("with {0} {1}", interaction.Request.Method.ToString().ToUpper(), interaction.Request.Path));
                    }

                    try
                    {
                        var interactionComparisonResult = ValidateInteraction(interaction);
                        comparisonResult.AddChildResult(interactionComparisonResult);
                        _reporter.Indent();
                        _reporter.ReportSummary(interactionComparisonResult);
                    }
                    finally
                    {
                        InvokeProviderStateTearDownIfApplicable(providerStateItem);
                        InvokeTearDownIfApplicable(providerStates);
                    }
                }

                _reporter.ResetIndentation();
                _reporter.ReportFailureReasons(comparisonResult);
                _reporter.Flush();

                if (comparisonResult.HasFailure)
                {
                    throw new PactFailureException(String.Format("See test output or {0} for failure details.",
                        !String.IsNullOrEmpty(_config.LoggerName) ? LogProvider.CurrentLogProvider.ResolveLogPath(_config.LoggerName) : "logs"));
                }
            }
        }
        public void Validate_WhenInteractionDefinesAProviderStateAndProviderStateIsSuppliedWithNoSetUpOrTearDown_NoProviderStateSetUpOrTearDownActionsAreInvoked()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        ProviderState = "My Provider State",
                        Description = "My interaction"
                    }
                }
            };
            var providerStates = new ProviderStates();
            providerStates.Add(new ProviderState("My Provider State"));

            var validator = GetSubject();

            validator.Validate(pact, providerStates);
        }
        public void Handle_WithAPostRequestToPactAndInteractionsHaveBeenRegistered_ReturnsResponseWithPactFileJson()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My description",
                    Request = new ProviderServiceRequest
                    {
                        Method = HttpVerb.Get,
                        Path = "/test"
                    },
                    Response = new ProviderServiceResponse
                    {
                        Status = (int)HttpStatusCode.NoContent
                    }
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = interactions
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

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

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

            var handler = GetSubject();

            _mockProviderRepository.Interactions.Returns(interactions);

            var response = handler.Handle(context);

            Assert.Equal("application/json", response.Headers["Content-Type"]);
            Assert.Equal(pactFileJson, ReadResponseContent(response.Contents));
        }
        public void Validate_WhenInteractionDefinesAProviderStateAndProviderStateTearDownDefined_TearDownActionIsInvoked()
        {
            var actionInkoved = false;
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        ProviderState = "My Provider State",
                        Description = "My interaction"
                    }
                }
            };
            var providerStates = new ProviderStates();
            providerStates.Add(new ProviderState("My Provider State", setUp: null, tearDown: () => { actionInkoved = true; }));

            var validator = GetSubject();

            validator.Validate(pact, providerStates);

            Assert.True(actionInkoved, "Provider state tearDown action is invoked");
        }
        public void Handle_WithAPostRequestToPactAndPactDirIsDifferentFromDefault_NewPactFileIsSavedWithInteractionsInTheSpecifiedPath()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My description",
                    Request = new ProviderServiceRequest
                    {
                        Method = HttpVerb.Get,
                        Path = "/test"
                    },
                    Response = new ProviderServiceResponse
                    {
                        Status = (int)HttpStatusCode.NoContent
                    }
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = interactions
            };

            var config = new PactConfig { PactDir = @"C:\temp" };
            var filePath = Path.Combine(config.PactDir, pactDetails.GeneratePactFileName());

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

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

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

            var handler = GetSubject(config);

            _mockProviderRepository.Interactions.Returns(interactions);

            var response = handler.Handle(context);

            _mockFileSystem.File.Received(1).WriteAllText(filePath, pactFileJson);
        }
        public void Validate_WhenInteractionDefinesAProviderStateButNoProviderStateIsSupplied_ThrowsInvalidOperationException()
        {
            var pact = new ProviderServicePactFile
            {
                Consumer = new Pacticipant { Name = "My client" },
                Provider = new Pacticipant { Name = "My Provider" },
                Interactions = new List<ProviderServiceInteraction>
                {
                    new ProviderServiceInteraction
                    {
                        ProviderState = "My Provider State",
                        Description = "My interaction"
                    }
                }
            };
            var providerStates = new ProviderStates();

            var validator = GetSubject();

            Assert.Throws<InvalidOperationException>(() => validator.Validate(pact, providerStates));
        }