コード例 #1
1
        public void Verify_WithProviderStateSet_CallsProviderServiceValidatorWithProviderState()
        {
            var httpClient = new HttpClient();

            var mockFileSystem = Substitute.For<IFileSystem>();
            var mockPactProviderServiceValidator = Substitute.For<IProviderServiceValidator>();
            mockFileSystem.File.ReadAllText(Arg.Any<string>()).Returns("{}");

            var pactVerifier = new PactVerifier(mockFileSystem, client => mockPactProviderServiceValidator);

            pactVerifier.ProviderStatesFor("My client")
                .ProviderState("My Provider State")
                .ProviderState("My Provider State 2");

            pactVerifier.ServiceProvider("Event API", httpClient)
                .HonoursPactWith("My client")
                .PactUri("/test.json");

            pactVerifier.Verify();

            mockPactProviderServiceValidator.Received(1).Validate(
                Arg.Any<ProviderServicePactFile>(),
                pactVerifier.ProviderStates);
        }
コード例 #2
0
        public void EnsureProviderApiHonoursPactWithConsumer()
        {
            // Arrange
            config = new PactVerifierConfig
            {
                Outputters = new List <IOutput>
                {
                    new XUnitOutput(_outputHelper)
                },


                Verbose = true
            };
            config.CustomHeader = new KeyValuePair <string, string>("X-Clarksons-Security-Cloud", "UqkejnjkHNM5gPY4VKeLNeoNv2eLUvZL8Di1xDqjc/I1dvdcQO9EGeUg6wYR0+ta+218kbu5Z5GgodKF92WmuGyTZGZ600fAS0OPKZ2kXIiwwqVO+a2apqxIOYLLrJdOFGkw6h6pZ8NurSQdQYvavA==");


            //Act / Assert
            pactVerifier = new PactVerifier(config);

            pactVerifier.ProviderState($"{_pactServiceUri}/provider-states")
            .ServiceProvider("fixture_api", _providerUri)
            .HonoursPactWith("EventAPIConsumer")
            .PactUri(@"http://104.214.219.231/pacts/provider/OperationServices/consumer/EventAPIConsumer/latest");
            pactVerifier.Verify();
        }
コード例 #3
0
        public void Verify_WithProviderStateSet_CallsProviderServiceValidatorWithProviderState()
        {
            var httpClient = new HttpClient();

            var mockFileSystem = Substitute.For <IFileSystem>();
            var mockPactProviderServiceValidator = Substitute.For <IProviderServiceValidator>();

            mockFileSystem.File.ReadAllText(Arg.Any <string>()).Returns("{}");

            var pactVerifier = new PactVerifier(mockFileSystem, client => mockPactProviderServiceValidator);

            pactVerifier.ProviderStatesFor("My client")
            .ProviderState("My Provider State")
            .ProviderState("My Provider State 2");

            pactVerifier.ServiceProvider("Event API", httpClient)
            .HonoursPactWith("My client")
            .PactUri("/test.json");

            pactVerifier.Verify();

            mockPactProviderServiceValidator.Received(1).Validate(
                Arg.Any <ProviderServicePactFile>(),
                pactVerifier.ProviderStates);
        }
コード例 #4
0
        public void Verify_WithDescriptionAndProviderState_CallsProviderServiceValidatorWith1FilteredInteractions()
        {
            var description   = "My Description";
            var providerState = "My Provider State";
            var pactUri       = "../../../Consumer.Tests/pacts/my_client-event_api.json";
            var pactFileJson  = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
            var httpClient    = new HttpClient();

            var mockFileSystem = Substitute.For <IFileSystem>();
            var mockPactProviderServiceValidator = Substitute.For <IProviderServiceValidator>();

            mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);

            var pactVerifier = new PactVerifier(mockFileSystem, client => mockPactProviderServiceValidator);

            pactVerifier.ProviderStatesFor("My client")
            .ProviderState("My Provider State")
            .ProviderState("My Provider State 2");

            pactVerifier.ServiceProvider("Event API", httpClient)
            .HonoursPactWith("My client")
            .PactUri(pactUri);

            pactVerifier.Verify(providerDescription: description, providerState: providerState);

            mockPactProviderServiceValidator.Received(1).Validate(
                Arg.Is <ProviderServicePactFile>(x => x.Interactions.Count() == 1 && x.Interactions.All(i => i.ProviderState.Equals(providerState) && i.Description.Equals(description))),
                Arg.Any <ProviderStates>());
        }
コード例 #5
0
        public void VerifyAllHealthCheckPacts()
        {
            // Arrange
            IPactVerifier pactVerifier = new PactVerifier(() => { }, () => { });

            var pactDetails = new PactDetails()
            {
                Provider = new Pacticipant {
                    Name = PactConstants.PactProviderNames.SqsPocApi
                },
                Consumer = new Pacticipant {
                    Name = PactConstants.PactConsumerNames.Product
                }
            };
            var pactLocation = $"{ PactConstants.PactRootLocation }\\{ PactConstants.PactProviderNames.SqsPocApi }\\{ PactConstants.PactConsumerNames.Product }\\{ pactDetails.GeneratePactFileName() }";

            pactVerifier
            .ProviderState("The service is up and running and all dependencies are available")
            .ProviderState("The service is up and running and some dependencies are not available", SetupDependenciesNotAvailable);

            // Act & Assert
            using (var testServer = TestServer.Create <Startup>()) //NOTE: This is using the Microsoft.Owin.Testing to test host an owin app :)
            {
                pactVerifier = pactVerifier
                               .ServiceProvider(pactDetails.Provider.Name, testServer.HttpClient)
                               .HonoursPactWith(pactDetails.Consumer.Name)
                               .PactUri(pactLocation);

                pactVerifier.Verify("A request for the status");
            }
        }
コード例 #6
0
        public void EnsureCustomerApiHonoursPactWithConsumer()
        {
            IPactVerifier pactVerifier = new PactVerifier(SetUp(), TearDown());

            pactVerifier.ProviderState("There is a customer with ID tester", setUp: AddTesterIfItDoesntExist);
            pactVerifier.ProviderState("Version is 1.2.3.4", setUp: SetVersion);

            using (var testServer = TestServer.Create <Startup>())
            {
                pactVerifier = pactVerifier
                               .ServiceProvider("Customer API", testServer.HttpClient)
                               .HonoursPactWith("Consumer")
                               .PactUri("../../../BinaryMash.PactDemo.Consumer.Tests/pacts/consumer-customer_api.json");

                pactVerifier.Verify();
            }
        }
コード例 #7
0
        public void EnsureApiHonorsPact()
        {
            var config = new PactVerifierConfig
            {
                Outputters = new List <IOutput> {
                    new XUnitOutput(_output)
                },
                Verbose = true
            };

            IPactVerifier verifier = new PactVerifier(config);

            verifier.ProviderState($"{_serviceUrl}/provider-states")
            .ServiceProvider("PactNet Provider", _providerUrl)
            .HonoursPactWith("PactNet Consumer")
            .PactUri(@"..\..\..\pacts\pactnet_consumer-pactnet_provider.json");
            verifier.Verify();
        }
コード例 #8
0
        public void EnsureProviderApiHonoursPactWithConsumer()
        {
            // Arrange
            var config = new PactVerifierConfig
            {
                // NOTE: We default to using a ConsoleOutput,
                // however xUnit 2 does not capture the console output,
                // so a custom outputter is required.
                Outputters = new List <IOutput>
                {
                    new ConsoleOutput()
                },

                // Output verbose verification logs to the test output
                Verbose = true,
                PublishVerificationResults = true,
                ProviderVersion            = System.Environment.GetEnvironmentVariable("TRAVIS_COMMIT")
            };

            IPactVerifier pactVerifier = new PactVerifier(config);
            string        pactUrl      = System.Environment.GetEnvironmentVariable("PACT_URL");

            pactVerifier
            .ProviderState($"{_pactServiceUri}/provider-states")
            .ServiceProvider("pactflow-example-provider-dotnet", _providerUri);

            if (pactUrl != "" && pactUrl != null)
            {
                // Webhook path - verify the specific pact
                pactVerifier.PactUri(pactUrl, new PactUriOptions(System.Environment.GetEnvironmentVariable("PACT_BROKER_TOKEN")));
            }
            else
            {
                // Standard verification path - run the
                pactVerifier.PactBroker(System.Environment.GetEnvironmentVariable("PACT_BROKER_BASE_URL"),
                                        uriOptions: new PactUriOptions(System.Environment.GetEnvironmentVariable("PACT_BROKER_TOKEN")),
                                        consumerVersionTags: new List <string> {
                    "master", "prod"
                });
            }

            // Act / Assert
            pactVerifier.Verify();
        }
コード例 #9
0
        public void Verify_WhenFileDoesNotExistOnFileSystem_ThrowsPactAssertException()
        {
            var serviceProvider = "Event API";
            var serviceConsumer = "My client";
            var pactUri         = "../../../Consumer.Tests/pacts/my_client-event_api.json";

            var mockFileSystem = Substitute.For <IFileSystem>();

            mockFileSystem.File.ReadAllText(pactUri).Returns(x => { throw new FileNotFoundException(); });

            var pactVerifier = new PactVerifier(mockFileSystem, null)
                               .ServiceProvider(serviceProvider, new HttpClient())
                               .HonoursPactWith(serviceConsumer)
                               .PactUri(pactUri);

            Assert.Throws <CompareFailedException>(() => pactVerifier.Verify());

            mockFileSystem.File.Received(1).ReadAllText(pactUri);
        }
コード例 #10
0
        public void Verify_WhenPactFileWithNoInteractionsExistOnFileSystem_CallsPactProviderValidator()
        {
            var serviceProvider = "Event API";
            var serviceConsumer = "My client";
            var pactUri         = "../../../Consumer.Tests/pacts/my_client-event_api.json";
            var pactFileJson    = "{ \"provider\": { \"name\": \"" + serviceProvider + "\" }, \"consumer\": { \"name\": \"" + serviceConsumer + "\" }, \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
            var httpClient      = new HttpClient();

            var mockFileSystem = Substitute.For <IFileSystem>();
            var mockPactProviderServiceValidator = Substitute.For <IProviderServiceValidator>();

            mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);

            var pactVerifier = new PactVerifier(mockFileSystem, client => mockPactProviderServiceValidator)
                               .ServiceProvider(serviceProvider, httpClient)
                               .HonoursPactWith(serviceConsumer)
                               .PactUri(pactUri);

            pactVerifier.Verify();

            mockFileSystem.File.Received(1).ReadAllText(pactUri);
            mockPactProviderServiceValidator.Received(1).Validate(Arg.Any <ProviderServicePactFile>(), Arg.Any <ProviderStates>());
        }
コード例 #11
0
        private PactnetVerificationResult VerifyUsingPactNet(string pactFile,
                                                             bool publishResultViaBroker, Models.Pact runningPact)
        {
            var result = new PactnetVerificationResult();

            var logger = new StringAppendOutput();

            var verifierConfig = new PactVerifierConfig
            {
                Outputters = new IOutput[] { logger },
                PublishVerificationResults = publishResultViaBroker,
                ProviderVersion            = "1"
            };

            var verifier = new PactVerifier(verifierConfig);

            verifier.ServiceProvider(runningPact.Provider?.Name, _serviceUri);

            verifier.PactUri(pactFile);

            try
            {
                verifier.Verify();

                result.Success = true;
            }
            catch (Exception e)
            {
                result.Success = false;

                result.Exception = e;
            }

            result.Logs = logger.Log;

            return(result);
        }
コード例 #12
0
        public void PactflowWebhook_EnsureProviderApiHonorsContractsWithPublishedPact()
        {
            // arrange

            // setup mocked Foo API
            const string guidRegex = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";

            _fooApiMock.ClearInteractions();

            _fooApiMock
            .Given("There is a foo with some-guid")
            .UponReceiving("A GET request to retrieve foo")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/foos",
                Query   = Match.Regex("name=00000000-0000-0000-0000-000000000000", $"^name={guidRegex}$"),
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new[]
                {
                    new
                    {
                        id          = "some id",
                        name        = "some name",
                        description = "some description"
                    }
                }
            });

            // get environment variables
            DotNetEnv.Env.TraversePath().Load();

            bool   isRunningInPipeline = "true".Equals(Environment.GetEnvironmentVariable("CI"));
            string pactBrokerBaseUrl   = Environment.GetEnvironmentVariable("PACT_BROKER_BASE_URL");
            string pactBrokerApiToken  = Environment.GetEnvironmentVariable("PACT_BROKER_API_TOKEN");
            string pactProviderTag     = Environment.GetEnvironmentVariable("PACT_PROVIDER_TAG");
            string pactUrl             = Environment.GetEnvironmentVariable("PACT_URL");
            string gitCommitShortSha   = Environment.GetEnvironmentVariable("GIT_COMMIT_SHORT_SHA");

            var pactVerifier = new PactVerifier(new PactVerifierConfig
            {
                ProviderVersion            = gitCommitShortSha,
                PublishVerificationResults = isRunningInPipeline,
                Outputters = new[] { new XUnitOutput(_outputHelper) },
                Verbose    = true
            });

            PactUriOptions pactUriOptions = new PactUriOptions().SetBearerAuthentication(pactBrokerApiToken);

            pactVerifier
            .ProviderState($"{TestServiceBaseUri}/provider-states")
            .ServiceProvider("Provider API", TestServiceBaseUri);

            // pactUrl is provided to pipeline triggered by pactflow webhook indicating what specific pact should be verified
            // if value is missing then default verification is performed for all consumers with tags: main, dev, uat, prod

            bool isVerifyingSpecificPact = !string.IsNullOrWhiteSpace(pactUrl);

            if (isVerifyingSpecificPact)
            {
                pactVerifier.PactUri(pactUrl, pactUriOptions);
            }
            else
            {
                var consumerVersionSelectors = new List <VersionTagSelector>
                {
                    new VersionTagSelector("refs/heads/main", latest: true),
                    new VersionTagSelector("dev", latest: true),
                    new VersionTagSelector("uat", latest: true),
                    new VersionTagSelector("prod", latest: true)
                };

                pactVerifier.PactBroker(pactBrokerBaseUrl,
                                        pactUriOptions,
                                        true,
                                        providerVersionTags: new[] { pactProviderTag },
                                        consumerVersionSelectors: consumerVersionSelectors);
            }

            // act
            // assert
            pactVerifier.Verify();
        }
コード例 #13
0
        public void Verify_WithProviderState_CallsProviderServiceValidatorWith2FilteredInteractions()
        {
            var providerState = "My Provider State";
            var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
            var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
            var httpClient = new HttpClient();

            var mockFileSystem = Substitute.For<IFileSystem>();
            var mockPactProviderServiceValidator = Substitute.For<IProviderServiceValidator>();
            mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);

            var pactVerifier = new PactVerifier(mockFileSystem, client => mockPactProviderServiceValidator);

            pactVerifier.ProviderStatesFor("My client")
                .ProviderState("My Provider State")
                .ProviderState("My Provider State 2");

            pactVerifier.ServiceProvider("Event API", httpClient)
                .HonoursPactWith("My client")
                .PactUri(pactUri);

            pactVerifier.Verify(providerState: providerState);

            mockPactProviderServiceValidator.Received(1).Validate(
                Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 2 && x.Interactions.All(i => i.ProviderState.Equals(providerState))),
                Arg.Any<ProviderStates>());
        }
コード例 #14
0
        public void Verify_WhenPactFileWithNoInteractionsExistOnFileSystem_CallsPactProviderValidator()
        {
            var serviceProvider = "Event API";
            var serviceConsumer = "My client";
            var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
            var pactFileJson = "{ \"provider\": { \"name\": \"" + serviceProvider + "\" }, \"consumer\": { \"name\": \"" + serviceConsumer + "\" }, \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
            var httpClient = new HttpClient();

            var mockFileSystem = Substitute.For<IFileSystem>();
            var mockPactProviderServiceValidator = Substitute.For<IProviderServiceValidator>();
            mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);

            var pactVerifier = new PactVerifier(mockFileSystem, client => mockPactProviderServiceValidator)
                .ServiceProvider(serviceProvider, httpClient)
                .HonoursPactWith(serviceConsumer)
                .PactUri(pactUri);

            pactVerifier.Verify();

            mockFileSystem.File.Received(1).ReadAllText(pactUri);
            mockPactProviderServiceValidator.Received(1).Validate(Arg.Any<ProviderServicePactFile>(), Arg.Any<ProviderStates>());
        }
コード例 #15
0
        public void Verify_WhenFileDoesNotExistOnFileSystem_ThrowsPactAssertException()
        {
            var serviceProvider = "Event API";
            var serviceConsumer = "My client";
            var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";

            var mockFileSystem = Substitute.For<IFileSystem>();
            mockFileSystem.File.ReadAllText(pactUri).Returns(x => { throw new FileNotFoundException(); });

            var pactVerifier = new PactVerifier(mockFileSystem, null)
                .ServiceProvider(serviceProvider, new HttpClient())
                .HonoursPactWith(serviceConsumer)
                .PactUri(pactUri);

            Assert.Throws<CompareFailedException>(() => pactVerifier.Verify());

            mockFileSystem.File.Received(1).ReadAllText(pactUri);
        }