public void Build_WhenCalledAndDirectoryDoesNotExist_DirectoryIsCreatedThenFileIsCreated()
        {
            var mockFileSystem = Substitute.For<IFileSystem>();

            IPactBuilder pactBuilder = new PactBuilder(null, mockFileSystem)
                .ServiceConsumer("Event Client")
                .HasPactWith("Event API");

            var pactFilePath = ((PactBuilder)pactBuilder).PactFileUri;

            var callCount = 0;
            mockFileSystem.File
                .When(x => x.WriteAllText(pactFilePath, Arg.Any<string>()))
                .Do(x =>
                {
                    if (callCount++ < 1)
                    {
                        throw new System.IO.DirectoryNotFoundException();
                    }
                });

            pactBuilder.Build();

            mockFileSystem.File.Received(2).WriteAllText(pactFilePath, Arg.Any<string>());
            mockFileSystem.Directory.Received(1).CreateDirectory(Arg.Any<string>());
        }
        public void Build_WhenCalledWithAnInitialisedMockProviderService_StopIsCallOnTheMockServiceProvider()
        {
            var mockMockProviderService = Substitute.For<IMockProviderService>();
            var mockFileSystem = Substitute.For<IFileSystem>();

            IPactBuilder pactBuilder = new PactBuilder(port => mockMockProviderService, mockFileSystem)
                .ServiceConsumer("Event Client")
                .HasPactWith("Event API");

            var pactFilePath = ((PactBuilder)pactBuilder).PactFileUri;

            pactBuilder.MockService(1234);

            var callCount = 0;
            mockFileSystem.File
                .When(x => x.WriteAllText(pactFilePath, Arg.Any<string>()))
                .Do(x =>
                {
                    if (callCount++ < 1)
                    {
                        throw new System.IO.DirectoryNotFoundException();
                    }
                });

            pactBuilder.Build();

            mockMockProviderService.Received(1).Stop();

            mockFileSystem.File.Received(2).WriteAllText(pactFilePath, Arg.Any<string>());
            mockFileSystem.Directory.Received(1).CreateDirectory(Arg.Any<string>());
        }
        public IntegrationTestsMyApiPact()
        {
            PactBuilder = new PactBuilder((port, enableSsl) => new MockProviderService(port, enableSsl), Substitute.For<IFileSystem>())
                .ServiceConsumer("IntegrationTests")
                .HasPactWith("MyApi");

            MockProviderService = PactBuilder.MockService(MockServerPort);
        }
Exemplo n.º 4
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.º 5
0
        public void Build_WhenCalledWithAnInitialisedMockProviderService_StopIsCallOnTheMockServiceProvider()
        {
            var mockMockProviderService = Substitute.For<IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl, providerName) => mockMockProviderService)
                .ServiceConsumer("Event Client")
                .HasPactWith("Event API");

            pactBuilder.MockService(1234);

            pactBuilder.Build();

            mockMockProviderService.Received(1).Stop();
        }
        public FailureIntegrationTestsMyApiPact()
        {
            var pactConfig = new PactConfig();

            PactBuilder = new PactBuilder((port, enableSsl, providerName) =>
                    new MockProviderService(
                        baseUri => new NancyHttpHost(baseUri, providerName, new IntegrationTestingMockProviderNancyBootstrapper(pactConfig), pactConfig.LogDir),
                        port, enableSsl,
                        baseUri => new HttpClient { BaseAddress = new Uri(baseUri) },
                        new HttpMethodMapper()))
                .ServiceConsumer("FailureIntegrationTests")
                .HasPactWith("MyApi");

            MockProviderService = PactBuilder.MockService(MockServerPort);
        }
Exemplo n.º 7
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));
        }
Exemplo n.º 8
0
        public void Build_WhenCalledBeforeTheMockProviderServiceIsInitialised_ThrowsInvalidOperationException()
        {
            IPactBuilder pactBuilder = new PactBuilder(null);

            Assert.Throws <InvalidOperationException>(() => pactBuilder.Build());
        }
Exemplo n.º 9
0
 public void Build()
 {
     PactBuilder.Build();
 }
Exemplo n.º 10
0
 public ApiTests(ApiConsumerFixture fixture)
 {
     _apiClient   = fixture._apiClient;
     _pactBuilder = fixture._pactBuilder;
 }
        public ServiceVirtualization(int Port = 0, string PathToSaveJsonFile = "", string ServiceConsumer = null, string HasPactWith = null)
        {
            if (Port == 0)
            {
                Port = FindFreePort();
            }
            MockServerPort = Port;
            // Init

            //FIXME
            String timeStamp  = DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss");
            string userFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            //FIXME path.combine
            string targetPath = userFolder + "\\Temp\\GingerTemp";

            if (string.IsNullOrEmpty(PathToSaveJsonFile))
            {
                PathToSaveJsonFile = targetPath;
            }
            else
            {
                PathToSaveJsonFile = PathToSaveJsonFile + @"\PactToJson" + timeStamp;
            }

            PactBuilder = new PactBuilder(new PactConfig {
                PactDir = PathToSaveJsonFile, LogDir = PathToSaveJsonFile + @"\logs"
            });

            if (string.IsNullOrEmpty(ServiceConsumer))
            {
                ServiceConsumer = "Consumer";
            }
            if (string.IsNullOrEmpty(HasPactWith))
            {
                HasPactWith = "Something API";
            }

            PactBuilder
            .ServiceConsumer(ServiceConsumer)
            .HasPactWith(HasPactWith);

            JsonSerializerSettings js  = new JsonSerializerSettings();
            CustomJsonConverter    cjc = new CustomJsonConverter();

            js.Converters.Add(cjc);

            //TODO: Try to read the json and inject to server before it's start


            //TODO: use try catch in calling func so will not be needed here
            try
            {
                MockProviderService = PactBuilder.MockService(MockServerPort, js); //You can also change the default Json serialization settings using this overload
            }
            catch (Exception ex)
            {
                Console.WriteLine(">>>>>>>>>>> ERROR <<<<<<<<<");
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 12
0
 public void SavePactFile()
 {
     PactBuilder.Build();
 }
Exemplo n.º 13
0
        public void MockService_WhenCalledWithNoJsonSerializerSettings_DoesNotSetTheGlobalApiSerializerSettingsToNull()
        {
            var mockMockProviderService = Substitute.For<IMockProviderService>();

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

            pactBuilder.MockService(1234);

            Assert.NotNull(JsonConfig.ApiSerializerSettings);
        }
Exemplo n.º 14
0
 public void Dispose()
 {
     PactBuilder.Build(); //Will save the pact file once finished
 }
Exemplo n.º 15
0
        public void Build_WhenCalledWithoutProviderNameSet_ThrowsInvalidOperationException()
        {
            IPactBuilder pact = new PactBuilder(null, null)
                .ServiceConsumer("Event Client");

            Assert.Throws<InvalidOperationException>(() => pact.Build());
        }
Exemplo n.º 16
0
        public void Build_WhenCalledWithAnInteractionOnTheMockProviderService_NewPactFileIsSavedWithTheInteraction()
        {
            var mockMockProviderService = Substitute.For<IMockProviderService>();
            var mockFileSystem = Substitute.For<IFileSystem>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl) => mockMockProviderService, mockFileSystem)
                .ServiceConsumer("Event Client")
                .HasPactWith("Event API");

            pactBuilder.MockService(1234);

            var pactFilePath = ((PactBuilder)pactBuilder).PactFileUri;

            mockFileSystem.File.ReadAllText(pactFilePath).Returns(x => { throw new System.IO.FileNotFoundException(); });
            mockMockProviderService.Interactions.Returns(new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My interaction",
                    Request = new ProviderServiceRequest(),
                    Response = new ProviderServiceResponse()
                }
            });

            pactBuilder.Build();

            var pactInteractions = mockMockProviderService.Received(1).Interactions;
            mockFileSystem.File.Received(1).WriteAllText(pactFilePath, Arg.Any<string>());
        }
Exemplo n.º 17
0
 public void Dispose()
 {
     PactBuilder.Build();
 }
Exemplo n.º 18
0
        public void MockService_WhenCalledWithEnableSslTrue_MockProviderServiceFactoryIsInvokedWithSslEnabled()
        {
            var calledWithSslEnabled = false;
            var mockMockProviderService = Substitute.For<IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl) =>
            {
                calledWithSslEnabled = enableSsl;
                return mockMockProviderService;
            }, null);

            pactBuilder.MockService(1234, true);

            Assert.True(calledWithSslEnabled);
        }
Exemplo n.º 19
0
        public async Task ShouldMatchRequest()
        {
            var url = "http://localhost:9396";

            var fakePactBrokerMessageHandler = new FakePactBrokerMessageHandler();

            fakePactBrokerMessageHandler.Configure(HttpMethod.Put, "http://localhost:9292").RespondsWith(HttpStatusCode.Created);
            var publisher = new PactPublisher(new HttpClient(fakePactBrokerMessageHandler)
            {
                BaseAddress = new Uri("http://localhost:9292")
            }, "1.0", "local");

            var builder = new PactBuilder("V3-consumer", "V3-provider", url, publisher);

            var recipeId = Guid.Parse("2860dedb-a193-425f-b73e-ef02db0aa8cf");

            var ingredient = Some.Object.With(
                Some.Element.Named("name").Like("Salt"),
                Some.Element.Named("amount").Like(5.5),
                Some.Element.Named("unit").Like("gram"));

            builder.SetUp(Pact.Interaction
                          .Given(new ProviderState {
                Name = $"There is a recipe with id `{recipeId}`"
            })
                          .UponReceiving("a request")
                          .With(Pact.Request
                                .WithHeader("Accept", "application/json")
                                .WithMethod(Method.GET)
                                .WithPath($"/api/recipes/{recipeId}"))
                          .WillRespondWith(Pact.Response
                                           .WithStatus(200)
                                           .WithHeader("Content-Type", "application/json")
                                           .WithBody(Pact.JsonContent.With(
                                                         Some.Element.Named("name").Like("A Recipe"),
                                                         Some.Element.Named("instructions").Like("Mix it up"),
                                                         Some.Array.Named("ingredients").Of(ingredient)
                                                         ))));

            using (var client = new HttpClient {
                BaseAddress = new Uri(url)
            })
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                var response = await client.GetAsync($"api/recipes/{recipeId}");

                Assert.IsTrue(response.IsSuccessStatusCode);
            }

            await builder.BuildAsync();

            // Check if pact has been published and tagged
            Assert.AreEqual("V3-consumer",
                            JsonConvert.DeserializeObject <Contract>(fakePactBrokerMessageHandler
                                                                     .GetStatus(HttpMethod.Put, "http://localhost:9292").SentRequestContents.First().Value).Consumer
                            .Name);
            Assert.IsTrue(fakePactBrokerMessageHandler.GetStatus(HttpMethod.Put, "http://localhost:9292")
                          .SentRequestContents.Last().Key.Contains("local"));

            // Check if pact has been written to project directory.
            var buildDirectory = AppContext.BaseDirectory;
            var pactDir        = Path.GetFullPath($"{buildDirectory}{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}pacts{Path.DirectorySeparatorChar}");
            var pactFile       = File.ReadAllText(pactDir + "V3-consumer-V3-provider.json");

            Assert.AreEqual("V3-consumer", JsonConvert.DeserializeObject <Contract>(pactFile).Consumer.Name);
            File.Delete(pactDir + "V3-consumer-V3-provider.json");
        }
Exemplo n.º 20
0
        public void Build_WhenCalledBeforeTheMockProviderServiceIsInitialised_ThrowsInvalidOperationException()
        {
            IPactBuilder pactBuilder = new PactBuilder(mockProviderServiceFactory: null);

            Assert.Throws<InvalidOperationException>(() => pactBuilder.Build());
        }
Exemplo n.º 21
0
        public void MockService_WhenCalled_MockProviderServiceFactoryIsInvokedWithSslNotEnabled()
        {
            var calledWithSslEnabled = false;
            var mockMockProviderService = Substitute.For<IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl, providerName) =>
            {
                calledWithSslEnabled = enableSsl;
                return mockMockProviderService;
            });

            pactBuilder.MockService(1234);

            Assert.False(calledWithSslEnabled);
        }
Exemplo n.º 22
0
 public void Dispose()
 {
     // Save the Pact once finished
     PactBuilder.Build();
 }
 public void Dispose()
 {
     PactBuilder.Build(); // Outputs the pact file.
 }
Exemplo n.º 24
0
        public static void CreateMockService()
        {
            MockProviderService = PactBuilder.MockService(MockServerPort);

            MockProviderService = PactBuilder.MockService(MockServerPort, new JsonSerializerSettings());
        }
Exemplo n.º 25
0
        public void MockService_WhenCalledWithJsonSerializerSettings_SetsTheGlobalApiSerializerSettings()
        {
            var serializerSettings = new JsonSerializerSettings();
            var mockMockProviderService = Substitute.For<IMockProviderService>();

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

            pactBuilder.MockService(1234, serializerSettings);

            Assert.Equal(serializerSettings, JsonConfig.ApiSerializerSettings);
        }
Exemplo n.º 26
0
        public void MockService_WhenCalledTwice_StopIsCalledTheSecondTime()
        {
            var mockMockProviderService = Substitute.For<IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl) => mockMockProviderService, null);

            pactBuilder.MockService(1234);
            mockMockProviderService.Received(0).Stop();

            pactBuilder.MockService(1234);
            mockMockProviderService.Received(1).Stop();
        }
Exemplo n.º 27
0
 public TribblePact(PactConfig config)
 {
     PactBuilder = new PactBuilder(config);
     PactBuilder.ServiceConsumer("Consumer").HasPactWith("Tribble API");
     MockProviderService = PactBuilder.MockService(MockServerPort);
 }
Exemplo n.º 28
0
        public void Build_WhenCalledWithoutConsumerNameSet_ThrowsInvalidOperationException()
        {
            IPactBuilder pactBuilder = new PactBuilder(null, null)
                .HasPactWith("Event API");

            Assert.Throws<InvalidOperationException>(() => pactBuilder.Build());
        }
Exemplo n.º 29
0
 public void SaveInteractions()
 {
     PactBuilder.Build();
 }
Exemplo n.º 30
0
        public void Build_WhenCalledWithNoMockProviderService_NewPactFileIsSavedWithNoInteractions()
        {
            var mockFileSystem = Substitute.For<IFileSystem>();

            IPactBuilder pactBuilder = new PactBuilder(null, mockFileSystem)
                .ServiceConsumer("Event Client")
                .HasPactWith("Event API");

            var pactFilePath = ((PactBuilder)pactBuilder).PactFileUri;

            pactBuilder.Build();

            mockFileSystem.File.Received(1).WriteAllText(pactFilePath, Arg.Any<string>());
        }
Exemplo n.º 31
0
 public static void Cleanup()
 {
     PactBuilder.Build(); //NOTE: Will save the pact file once finished
 }
Exemplo n.º 32
0
        public void MockService_WhenCalled_StartIsCalledAndMockProviderServiceIsReturned()
        {
            var mockMockProviderService = Substitute.For<IMockProviderService>();

            IPactBuilder pactBuilder = new PactBuilder((port, enableSsl) => mockMockProviderService, null);

            var mockProviderService = pactBuilder.MockService(1234);

            mockMockProviderService.Received(1).Start();
            Assert.Equal(mockMockProviderService, mockProviderService);
        }
Exemplo n.º 33
0
 private void CreatePactFile()
 {
     PactBuilder.Build();
 }