Exemplo n.º 1
0
        public ConsumerMyApiPact()
        {
            PactBuilder = new PactBuilder(new PactConfig {
                PactDir = @"D:\Pact", LogDir = @"D:\Pact"
            });;

            PactBuilder
            .ServiceConsumer(ClientName)
            .HasPactWith(ProviderName);     // Provider Name

            MockProviderService = PactBuilder.MockService(MockServerPort);
            //Configure the http mock server

            MockProviderService = PactBuilder.MockService(MockServerPort, false);
            // By passing true as the second param, you can enabled SSL.
            // This will however require a valid SSL certificate installed and bound
            // with netsh (netsh http add sslcert ipport=0.0.0.0:port certhash=thumbprint appid={app-guid})
            // on the machine running the test. See https://groups.google.com/forum/#!topic/nancy-web-framework/t75dKyfgzpg
            //or


            MockProviderService = PactBuilder.MockService(MockServerPort, bindOnAllAdapters: false);
            //By passing true as the bindOnAllAdapters parameter the http mock server will be
            // able to accept external network requests, but will require admin privileges in order to run

            MockProviderService = PactBuilder.MockService(MockServerPort, new JsonSerializerSettings());
            //You can also change the default Json serialization settings using this overload
        }
Exemplo n.º 2
0
        public ConsumerMyApiPact()
        {
            PactBuilder = new PactBuilder(); //Defaults to specification version 1.1.0, uses default directories. PactDir: ..\..\pacts and LogDir: ..\..\logs
                                             //or
            PactBuilder = new PactBuilder(new PactConfig {
                SpecificationVersion = "2.0.0"
            });                                                                               //Configures the Specification Version
                                                                                              //or
            PactBuilder = new PactBuilder(new PactConfig {
                PactDir = @"..\pacts", LogDir = @"c:\temp\logs"
            });                                                                                                //Configures the PactDir and/or LogDir.

            PactBuilder
            .ServiceConsumer("Consumer")
            .HasPactWith("Something API");

            MockProviderService = PactBuilder.MockService(MockServerPort); //Configure the http mock server
            //                                                               //or
            //MockProviderService = PactBuilder.MockService(MockServerPort, true); //By passing true as the second param, you can enabled SSL. A self signed SSL cert will be provisioned by default.
            //                                                                     //or
            //MockProviderService = PactBuilder.MockService(MockServerPort, true, sslCert: sslCert, sslKey: sslKey); //By passing true as the second param and an sslCert and sslKey, you can enabled SSL with a custom certificate. See "Using a Custom SSL Certificate" for more details.
            //                                                                                                       //or
            MockProviderService = PactBuilder.MockService(MockServerPort, new JsonSerializerSettings()); //You can also change the default Json serialization settings using this overload
                                                                                                         //or
            MockProviderService = PactBuilder.MockService(MockServerPort, host: IPAddress.Any);          //By passing host as IPAddress.Any, the mock provider service will bind and listen on all ip addresses
        }
Exemplo n.º 3
0
        public void UseBaseUrlIfset()
        {
            var builder = new PactBuilder(new PactConfig("/api"), s => output.WriteLine(s));

            var(client, verify) = builder
                                  .ServiceConsumer("Me")
                                  .HasPactWith("Someone")
                                  .Given("something given")
                                  .UponReceiving("upon receiving stuff")
                                  .With(new ProviderServiceRequest
            {
                Method = HttpVerb.get,
                Path   = "/api/test/something",
                Query  = "a=b",
            })
                                  .WillRespondWith(new ProviderServiceResponse
            {
                Status  = HttpStatusCode.OK,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new { SomeProperty = "test" }
            })
                                  .Client();
            var request = new HttpRequestMessage(HttpMethod.Get, "test/something?a=b");

            client.SendAsync(request);
            verify();
        }
Exemplo n.º 4
0
        public async Task PostThrowsIfBodyIsDifferent()
        {
            var builder = new PactBuilder();

            var(client, verify) =
                builder
                .ServiceConsumer("Me")
                .HasPactWith("Someone")
                .With(new ProviderServiceRequest
            {
                Method = HttpVerb.post,
                Path   = "/api/test/something",
                Body   = new { SomeProperty = "test" }
            })
                .WillRespondWith(new ProviderServiceResponse
            {
                Status = HttpStatusCode.Created
            })
                .Client();
            Assert.NotNull(client);
            var r = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress + "/api/test/something");

            r.Content = new StringContent(JsonConvert.SerializeObject(new { SomeOtherProperty = "test" }), Encoding.UTF8, "application/json");
            var response = await client.SendAsync(r);

            Assert.Throws <ExpectationException>(() => verify());
        }
Exemplo n.º 5
0
        public void BuildDoesNotThrow()
        {
            var builder = new PactBuilder();

            builder
            .ServiceConsumer("Me")
            .HasPactWith("Someone")
            .Given("something given")
            .UponReceiving("upon receiving stuff")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.get,
                Path    = "/api/test/something",
                Query   = "a=b",
                Headers = new Dictionary <string, string>
                {
                    { "Authorization", "Bearer accesstoken" }
                },
                Body = new { SomeProperty = "test" }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = HttpStatusCode.OK,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new { SomeProperty = "test" }
            })
            .Client();
            builder.Build();
        }
Exemplo n.º 6
0
        public async Task QueryCanContainMultipleSegments()
        {
            var builder = new PactBuilder(s => output.WriteLine(s));

            var(client, verify) =
                builder
                .ServiceConsumer("Me")
                .HasPactWith("Someone")
                .Given("something given")
                .UponReceiving("upon receiving stuff")
                .With(new ProviderServiceRequest
            {
                Method = HttpVerb.get,
                Path   = "/api/test/something",
                Query  = "a=b&test=quest"
            })
                .WillRespondWith(new ProviderServiceResponse
            {
                Status = HttpStatusCode.OK
            })
                .Client();
            var response = await client.GetAsync("/api/test/something?a=b&test=quest");

            Assert.NotNull(response);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            verify();
        }
Exemplo n.º 7
0
        public async Task ThrowsIfQueryIsDifferent()
        {
            var builder = new PactBuilder();

            var(client, verify) =
                builder
                .ServiceConsumer("Me")
                .HasPactWith("Someone")
                .With(new ProviderServiceRequest
            {
                Method = HttpVerb.get,
                Path   = "/api/test/something",
                Query  = "a=b"
            })
                .WillRespondWith(new ProviderServiceResponse
            {
                Status = HttpStatusCode.OK
            })
                .Client();
            var response = await client.GetAsync("/api/test/something?a=c");

            Assert.NotNull(response);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            Assert.Throws <ExpectationException>(() => verify());
        }
Exemplo n.º 8
0
        public HttpResponseMessage PactRegistration(string payload, HttpListenerContext listenerContext)
        {
            Uri uriResult;
            var isUri = Uri.TryCreate(payload, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

            if (isUri)
            {
                payload = Helper.GetPactViaBroker(payload);
            }

            Logger.Warning("The specified payload {0}... is not a valid Url, so will treat it as Pact document.", payload.Substring(0, 8));

            if (!Helper.IsValidJson(payload))
            {
                Logger.Warning("The payload {0}... doesn't seem to be a valid JSON.", payload.Substring(0, 8));
            }

            payload = Helper.ApplyStaticRules(payload);
            var pactFile = JsonConvert.DeserializeObject <ProviderServicePactFile>(payload);
            var pb       = new PactBuilder();

            pb.ServiceConsumer(pactFile.Consumer.Name);

            var responseToCurrentRequest = Helper.GetResponseForRequestFromPact(pactFile, listenerContext.Request);

            return(responseToCurrentRequest);
        }
Exemplo n.º 9
0
        public ConsumerPactClassFixture()
        {
            var pactConfig = new PactConfig
            {
                SpecificationVersion = "2.0.0",
                PactDir = @"..\..\..\..\..\pacts",
                LogDir  = @".\pact_logs"
            };

            PactBuilder = new PactBuilder(pactConfig);

            PactBuilder.ServiceConsumer("Consumer")
            .HasPactWith("Provider");

            MockProviderService = PactBuilder.MockService(MockServerPort);

            var builder = new WebHostBuilder()
                          .ConfigureServices(s =>
                                             s.Configure <MembershipApiSettings>(settings => settings.BaseUri = MockProviderServiceBaseUri))
                          .UseStartup <TStartup>();

            _server            = new TestServer(builder);
            Client             = _server.CreateClient();
            Client.BaseAddress = new Uri("http://localhost:5000");
        }
Exemplo n.º 10
0
 public ConsumerMyApiPact()
 {
     PactBuilder = new PactBuilder();
     PactBuilder
     .ServiceConsumer("TeamA.Consumer")
     .HasPactWith("TeamB.Producer");
     MockProviderService = PactBuilder.MockService(MockServerPort);
 }
 public FooApiConsumerPactClassFixture()
 {
     _pactBuilder = new PactBuilder(new PactConfig {
         SpecificationVersion = "2.0.0"
     });
     _pactBuilder.ServiceConsumer("Something API").HasPactWith("Foo API");
     MockProviderService = _pactBuilder.MockService(MockServerPort, host: IPAddress.Any);
 }
Exemplo n.º 12
0
        public void MockService_WhenCalledWithoutProviderNameSet_ThrowsInvalidOperationException()
        {
            IPactBuilder pactBuilder = new PactBuilder((port, ssl, consumerName, providerName, hsot) => Substitute.For <IMockProviderService>());

            pactBuilder
            .ServiceConsumer("Event Client");

            Assert.Throws <InvalidOperationException>(() => pactBuilder.MockService(1234));
        }
Exemplo n.º 13
0
        public ProviderApiPact()
        {
            PactBuilder = new PactBuilder();
            PactBuilder
            .ServiceConsumer("Consumer")
            .HasPactWith("Something API");

            MockProviderService = PactBuilder.MockService(MockServerPort);
        }
Exemplo n.º 14
0
        public MailServiceApiConsumerPact()
        {
            PactBuilder =
                new PactBuilder(); // Defaults to specification version 1.1.0, uses default directories. PactDir: ..\..\pacts and LogDir: ..\..\logs

            PactBuilder.ServiceConsumer("Mail Service Consumer").HasPactWith("Mail Service API");

            MockProviderService = PactBuilder.MockService(MockServerPort); // Configure the http mock server
        }
Exemplo n.º 15
0
        public void Build_WhenCalledWithoutProviderNameSet_ThrowsInvalidOperationException()
        {
            IPactBuilder pactBuilder = new PactBuilder((port, ssl, providerName) => Substitute.For<IMockProviderService>());
            pactBuilder.MockService(1234);
            pactBuilder
                .ServiceConsumer("Event Client");

            Assert.Throws<InvalidOperationException>(() => pactBuilder.Build());
        }
Exemplo n.º 16
0
        public RecipeServicePact()
        {
            PactBuilder = new PactBuilder();

            PactBuilder
            .ServiceConsumer("API GW")
            .HasPactWith("Recipe Service");

            MockProviderService = PactBuilder.MockService(9222);
        }
Exemplo n.º 17
0
        public BeerCalculatorPact()
        {
            PactBuilder = new PactBuilder();

            PactBuilder
            .ServiceConsumer("API GW")
            .HasPactWith("Beer Calculator");

            MockProviderService = PactBuilder.MockService(9221);
        }
Exemplo n.º 18
0
        public static HttpResponseMessage PactRegistration(string payload, HttpListenerContext listenerContext, string providerState, string description, bool matchBody)
        {
            var pactFile = JsonConvert.DeserializeObject <ProviderServicePactFile>(payload);
            var pb       = new PactBuilder();

            pb.ServiceConsumer(pactFile.Consumer.Name);

            var responseToCurrentRequest = GetResponseForRequestFromPact(pactFile, listenerContext.Request, providerState, description, matchBody);

            return(responseToCurrentRequest);
        }
Exemplo n.º 19
0
        public ConsumerApiPact()
        {
            PactBuilder = new PactBuilder(); //Defaults to specification version 1.1.0, uses default directories. PactDir: ..\..\pacts and LogDir: ..\..\logs

            PactBuilder
            .ServiceConsumer("Consumer")
            .HasPactWith("Some API");

            MockProviderService = PactBuilder.MockService(MockServerPort, false); //By passing true as the second param, you can enabled SSL. A self signed SSL cert will be provisioned by default.
                                                                                  //or
        }
Exemplo n.º 20
0
        public static void SetPactRelationship(string cosumer, string provider)
        {
            Provider = provider.Replace(" ", "_").ToLower();
            Consumer = cosumer.Replace(" ", "_").ToLower();

            PactFilename = $"{Consumer}-{Provider}";

            PactBuilder
            .ServiceConsumer(cosumer)
            .HasPactWith(provider);
        }
Exemplo n.º 21
0
    public ConsumerMyApiPact()
    {
        PactBuilder = new PactBuilder(new PactConfig {
            SpecificationVersion = "2.0.0", PactDir = @"..\pacts", LogDir = @"..\logs"
        });

        PactBuilder
        .ServiceConsumer("beer-randomizer")
        .HasPactWith("beer-api");

        MockProviderService = PactBuilder.MockService(MockServerPort);
    }
    public ConsumerApiPactFixture()
    {
        PactBuilder = new PactBuilder(new PactConfig {
            SpecificationVersion = "2.0.0"
        });

        PactBuilder
        .ServiceConsumer("PactNet Consumer")
        .HasPactWith("PactNet Provider");

        MockProviderService = PactBuilder.MockService(MockServerPort);
    }
        public QuizServiceApiPact()
        {
            PactBuilder = new PactBuilder(new PactConfig {
                SpecificationVersion = "2.0.0", PactDir = @"..\pacts"
            });

            PactBuilder
            .ServiceConsumer("QuizClient")
            .HasPactWith("QuizService");

            MockProviderService = PactBuilder.MockService(MockServerPort);
        }
Exemplo n.º 24
0
        public OrderConsumerPact()
        {
            PactBuilder = new PactBuilder(new PactConfig {
                SpecificationVersion = "2.0.0"
            });

            PactBuilder
            .ServiceConsumer("CommandLine")
            .HasPactWith("OrderApi");

            MockProviderService = PactBuilder.MockService(MockServerPort, JsonSettings);
        }
        public WeatherForecastApiPact()
        {
            PactBuilder = new PactBuilder(new PactConfig {
                SpecificationVersion = "2.0.0"
            });                                                                               //Configures the Specification Version

            PactBuilder
            .ServiceConsumer("Consumer")
            .HasPactWith("Weather Forecast API");

            MockProviderService = new MockProviderServiceDecorator(PactBuilder.MockService(MockServerPort, GetSerializerSettings()));
        }
Exemplo n.º 26
0
        public void Verify_Api_Pact()
        {
            var pactBuilder = new PactBuilder();

            pactBuilder
            .ServiceConsumer("Web")
            .HasPactWith("Api");
            var mockProviderService = pactBuilder.MockService(5000, host: IPAddress.Any);

            mockProviderService
            .Given("Valid advertisement Id")
            .UponReceiving("GET request to retrieve advertisement")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/api/Advertisements/debdedbf-1524-4d83-8d74-7d05ffb02d6e",
                Headers = new Dictionary <string, object>
                {
                    { "Host", "localhost:5000" },
                    { "Version", "HTTP/1.1" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new{
                    id              = "debdedbf-1524-4d83-8d74-7d05ffb02d6e",
                    title           = "Title",
                    description     = "Description",
                    price           = 1.0,
                    publicationDate = "2019-01-10T00:00:00"
                }
            });

            IAdvertisementService service = RestClient.For <IAdvertisementService>("http://localhost:5000/api/");

            var result = service.FindById(Guid.Parse("debdedbf-1524-4d83-8d74-7d05ffb02d6e")).GetAwaiter().GetResult();

            result.ShouldNotBeNull();
            result.Id.ShouldBe(Guid.Parse("debdedbf-1524-4d83-8d74-7d05ffb02d6e"));
            result.Title.ShouldBe("Title");
            result.Description.ShouldBe("Description");
            result.Price.ShouldBe(1);
            result.PublicationDate.ShouldBe(new DateTime(2019, 1, 10));

            mockProviderService.VerifyInteractions();

            pactBuilder.Build();
        }
Exemplo n.º 27
0
 public SqaConferenceServiceIntegrationTestSetup()
 {
     _pactBuilder = new PactBuilder(new PactConfig {
         SpecificationVersion = "2.0.0"
     });
     _pactBuilder.ServiceConsumer("sqa-conference-service")
     .HasPactWith("sqa-speakers-service");
     SpeakersServiceMock = _pactBuilder.MockService(
         5001, new JsonSerializerSettings {
         ContractResolver = new CamelCasePropertyNamesContractResolver()
     });
 }
Exemplo n.º 28
0
        public CardApiPact()
        {
            PactBuilder = new PactBuilder(
                new PactConfig {
                PactDir = @"D:/pacts/", LogDir = @"D:/logs/"
            }
                );
            PactBuilder
            .ServiceConsumer("Consumer")
            .HasPactWith("Cards Api");

            MockProviderService = PactBuilder.MockService(MockServicePort);
        }
Exemplo n.º 29
0
        public PactTestFixture()
        {
            var pactConfig = new PactConfig
            {
                SpecificationVersion = "2.0.0",
                PactDir = @"..\..\..\..\..\pacts",
                LogDir  = @".\pact_logs"
            };

            PactBuilder = new PactBuilder(pactConfig);
            PactBuilder.ServiceConsumer("Consumer").HasPactWith("Provider");
            MockProviderService = PactBuilder.MockService(MockServicePort);
        }
        public ConsumeHttpSequencerPact(string consumerName, int port)
        {
            PactBuilder = new PactBuilder(new PactConfig {
                Outputters = new[] { new ConsoleOutputter() }, SpecificationVersion = "2.0.0"
            });                                                                                                                               //Configures the Specification Version

            PactBuilder
            .ServiceConsumer(consumerName)
            .HasPactWith("Something API");

            //needs elevated, or port opening
            MockProviderService = PactBuilder.MockService(port, false, IPAddress.Any);
        }
Exemplo n.º 31
0
        public void MockService_WhenCalledWithNoJsonSerializerSettings_DoesNotSetTheGlobalApiSerializerSettingsToNull()
        {
            var mockMockProviderService = Substitute.For <IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl, consumerName, providerName, host) => mockMockProviderService);

            pactBuilder
            .ServiceConsumer("Event Client")
            .HasPactWith("Event API");

            pactBuilder.MockService(1234);

            Assert.NotNull(JsonConfig.ApiSerializerSettings);
        }
Exemplo n.º 32
0
        public void Build_WhenCalledWithTheMockProviderServiceIsInitialised_CallsSendAdminHttpRequestOnTheMockProviderService()
        {
            const string consumerName = "Event Client";
            const string providerName = "Event API";
            var mockProviderService = Substitute.For<IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, ssl, provider) => mockProviderService);
            pactBuilder.MockService(1234);
            pactBuilder
                .ServiceConsumer(consumerName)
                .HasPactWith(providerName);

            pactBuilder.Build();

            mockProviderService.Received(1).SendAdminHttpRequest(HttpVerb.Post, Constants.PactPath, Arg.Is<PactDetails>(x => x.Consumer.Name == consumerName && x.Provider.Name == providerName));
        }