コード例 #1
0
        public async Task WireMockServer_Should_delay_responses_for_a_given_route()
        {
            // given
            var server = WireMockServer.Start();

            server
            .Given(Request.Create()
                   .WithPath("/*"))
            .RespondWith(Response.Create()
                         .WithBody(@"{ msg: ""Hello world!""}")
                         .WithDelay(TimeSpan.FromMilliseconds(200)));

            // when
            var watch = new Stopwatch();

            watch.Start();
            await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo");
            watch.Stop();

            // then
            Check.That(watch.ElapsedMilliseconds).IsStrictlyGreaterThan(200);
        }
コード例 #2
0
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var server = WireMockServer.Start(new WireMockServerSettings
            {
                Urls = new[] { _acquiringBankSettings.ApiUrl },
                StartAdminInterface = true,
                ReadStaticMappings  = true,
                Logger = new WireMockConsoleLogger()
            });

            server
            .Given(Request.Create()
                   .WithPath($"/api/payment").UsingPost())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody((new BankPaymentResponse {
                PaymentIdentifier = Guid.NewGuid().ToString(), PaymentStatus = PaymentStatus.Success
            }).ToJson()));

            return(Task.CompletedTask);
        }
コード例 #3
0
        public async Task WildcardMatcherTest()
        {
            var server = WireMockServer.Start();

            server
            .Given(Request.Create()
                   // a ? for a single character and * for any characters.
                   .WithPath(new WildcardMatcher("/some*", true)))
            .RespondWith(Response.Create().WithBody("wildcard match"));

            var client = new HttpClient();
            var body   = await client.GetStringAsync($"{server.Urls[0]}/something");

            Assert.Equal("wildcard match", body);

            body = await client.GetStringAsync($"{server.Urls[0]}/Something");

            Assert.Equal("wildcard match", body);

            await Assert.ThrowsAsync <HttpRequestException>(async() =>
                                                            await client.GetStringAsync($"{server.Urls[0]}/nothing"));
        }
コード例 #4
0
        public async Task WireMockServer_LogEntriesChanged_Parallel()
        {
            int expectedCount = 10;

            // Assign
            string path   = $"/log_p_{Guid.NewGuid()}";
            var    server = WireMockServer.Start();

            server
            .Given(Request.Create()
                   .WithPath(path)
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithSuccess());

            int count = 0;

            server.LogEntriesChanged += (sender, args) => count++;

            var http = new HttpClient();

            // Act
            var listOfTasks = new List <Task <HttpResponseMessage> >();

            for (var i = 0; i < expectedCount; i++)
            {
                Thread.Sleep(50);
                listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}"));
            }
            var responses = await Task.WhenAll(listOfTasks);

            var countResponsesWithStatusNotOk = responses.Count(r => r.StatusCode != HttpStatusCode.OK);

            // Assert
            Check.That(countResponsesWithStatusNotOk).Equals(0);
            Check.That(count).Equals(expectedCount);

            server.Dispose();
        }
コード例 #5
0
        public void WireMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue()
        {
            // Assign
            var staticMappingHandlerMock = new Mock <IFileSystemHandler>();

            staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder");
            staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny <string>())).Returns(true);
            staticMappingHandlerMock.Setup(m => m.EnumerateFiles(It.IsAny <string>(), It.IsAny <bool>())).Returns(new string[0]);

            var server = WireMockServer.Start(new WireMockServerSettings
            {
                FileSystemHandler = staticMappingHandlerMock.Object
            });

            // Act
            server.ReadStaticMappings();

            // Assert and Verify
            staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once);
            staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once);
            staticMappingHandlerMock.Verify(m => m.EnumerateFiles("folder", false), Times.Once);
        }
コード例 #6
0
        public async Task WireMockServer_Proxy_With_SaveMappingForStatusCodePattern_Is_False_Should_Not_SaveMapping()
        {
            // Assign
            var fileSystemHandlerMock = new Mock <IFileSystemHandler>();

            fileSystemHandlerMock.Setup(f => f.GetMappingFolder()).Returns("m");

            var settings = new WireMockServerSettings
            {
                ProxyAndRecordSettings = new ProxyAndRecordSettings
                {
                    Url               = "http://www.google.com",
                    SaveMapping       = true,
                    SaveMappingToFile = true,
                    SaveMappingForStatusCodePattern = "999" // Just make sure that we don't want this mapping
                },
                FileSystemHandler = fileSystemHandlerMock.Object
            };
            var server = WireMockServer.Start(settings);

            // Act
            var requestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri(server.Urls[0])
            };
            var httpClientHandler = new HttpClientHandler {
                AllowAutoRedirect = false
            };

            await new HttpClient(httpClientHandler).SendAsync(requestMessage);

            // Assert
            server.Mappings.Should().HaveCount(1);

            // Verify
            fileSystemHandlerMock.Verify(f => f.WriteMappingFile(It.IsAny <string>(), It.IsAny <string>()), Times.Never);
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: pitchart/WireMock.Net
        static void Main(string[] args)
        {
            XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

            if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
            {
                return;
            }

            settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

            _server = WireMockServer.Start(settings);

            _server
            .Given(Request.Create()
                   .UsingAnyMethod())
            .RespondWith(Response.Create()
                         .WithTransformer()
                         .WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}"));

            Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

            Console.CancelKeyPress += (s, e) =>
            {
                Stop("CancelKeyPress");
            };

            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
            {
                Stop("AssemblyLoadContext.Default.Unloading");
            };

            while (true)
            {
                Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
                Thread.Sleep(sleepTime);
            }
        }
コード例 #8
0
        public async Task WireMockServer_Admin_Mappings_AtPriority()
        {
            var server = WireMockServer.Start();

            // given
            server.Given(Request.Create().WithPath("/1").UsingGet())
            .AtPriority(2)
            .RespondWith(Response.Create().WithStatusCode(200));

            server.Given(Request.Create().WithPath("/1").UsingGet())
            .AtPriority(1)
            .RespondWith(Response.Create().WithStatusCode(400));

            var mappings = server.Mappings.ToArray();

            Check.That(mappings).HasSize(2);

            // when
            var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + "/1");

            // then
            Check.That((int)response.StatusCode).IsEqualTo(400);
        }
コード例 #9
0
        public async void WireMockServer_LogEntriesChanged()
        {
            // Assign
            string path   = $"/log_{Guid.NewGuid()}";
            var    server = WireMockServer.Start();

            server
            .Given(Request.Create()
                   .WithPath(path)
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithBody(@"{ msg: ""Hello world!""}"));

            int count = 0;

            server.LogEntriesChanged += (sender, args) => count++;

            // Act
            await new HttpClient().GetAsync($"http://localhost:{server.Ports[0]}{path}");

            // Assert
            Check.That(count).Equals(1);
        }
コード例 #10
0
        public async Task IWireMockAdminApi_GetRequestsAsync_JsonApi()
        {
            // Arrange
            var server = WireMockServer.Start(new WireMockServerSettings
            {
                StartAdminInterface = true,
                Logger = new WireMockNullLogger()
            });
            string serverUrl           = server.Urls[0];
            string data                = "{\"data\":[{\"type\":\"program\",\"attributes\":{\"alias\":\"T000001\",\"title\":\"Title Group Entity\"}}]}";
            string jsonApiAcceptHeader = "application/vnd.api+json";
            string jsonApiContentType  = "application/vnd.api+json";

            var request = new HttpRequestMessage(HttpMethod.Post, serverUrl);

            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonApiAcceptHeader));
            request.Content = new StringContent(data);
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);

            var response = await new HttpClient().SendAsync(request);

            Check.That(response).IsNotNull();

            var api = RestClient.For <IWireMockAdminApi>(serverUrl);

            // Act
            var requests = await api.GetRequestsAsync();

            // Assert
            Check.That(requests).HasSize(1);
            var requestLogged = requests.First();

            Check.That(requestLogged.Request.Method).IsEqualTo("POST");
            Check.That(requestLogged.Request.Body).IsNotNull();
            Check.That(requestLogged.Request.Body).Contains("T000001");
        }
コード例 #11
0
        public HttpWireServer()
        {
            _server = WireMockServer.Start();

            _server
            .Given(Request
                   .Create()
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithDelay(TimeSpan.FromMilliseconds(10))
                         .WithCallback(message => new ResponseMessage()
            {
                Headers = { ["Content-Type"] = new WireMockList <string>()
                            {
                            "application/json"
                            } },

                BodyData = new BodyData()
                {
                    DetectedBodyType = BodyType.Json,

                    BodyAsJson = new HttpMockModel
                    {
                        Id        = message.Query["id"].ToString(),
                        Timestamp = Guid.NewGuid().ToString().GetHashCode()
                    }
                }
            })


                         );



            Console.WriteLine($"Hades Mock listening on 127.0.0.1:{_server.Ports.First()}");
        }
コード例 #12
0
        public async Task WireMockServer_Proxy_Should_change_absolute_location_header_in_proxied_response()
        {
            // Assign
            string path     = $"/prx_{Guid.NewGuid().ToString()}";
            var    settings = new WireMockServerSettings {
                AllowPartialMapping = false
            };

            var serverForProxyForwarding = WireMockServer.Start(settings);

            serverForProxyForwarding
            .Given(Request.Create().WithPath(path))
            .RespondWith(Response.Create()
                         .WithStatusCode(HttpStatusCode.Redirect)
                         .WithHeader("Location", "/testpath"));

            var server = WireMockServer.Start(settings);

            server
            .Given(Request.Create().WithPath(path).UsingAnyMethod())
            .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));

            // Act
            var requestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"{server.Urls[0]}{path}")
            };
            var httpClientHandler = new HttpClientHandler {
                AllowAutoRedirect = false
            };
            var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage);

            // Assert
            Check.That(response.Headers.Contains("Location")).IsTrue();
            Check.That(response.Headers.GetValues("Location")).ContainsExactly("/testpath");
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: ruslanss/WireMock.Net
        static void Main(string[] args)
        {
            XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

            if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
            {
                return;
            }

            settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

            _server = WireMockServer.Start(settings);

            //_server
            //    .Given(Request.Create()
            //        .UsingAnyMethod())
            //    .RespondWith(Response.Create()
            //        .WithProxy("https://www.google.com"));

            Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

            Console.CancelKeyPress += (s, e) =>
            {
                Stop("CancelKeyPress");
            };

            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
            {
                Stop("AssemblyLoadContext.Default.Unloading");
            };

            while (true)
            {
                Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
                Thread.Sleep(sleepTime);
            }
        }
コード例 #14
0
        public async Task IWireMockAdminApi_GetRequestsAsync()
        {
            // Arrange
            var server = WireMockServer.Start(new WireMockServerSettings
            {
                StartAdminInterface = true,
                Logger = new WireMockNullLogger()
            });
            var serverUrl = "http://localhost:" + server.Ports[0];

            await new HttpClient().GetAsync(serverUrl + "/foo");
            var api = RestClient.For <IWireMockAdminApi>(serverUrl);

            // Act
            var requests = await api.GetRequestsAsync();

            // Assert
            Check.That(requests).HasSize(1);
            var requestLogged = requests.First();

            Check.That(requestLogged.Request.Method).IsEqualTo("GET");
            Check.That(requestLogged.Request.Body).IsNull();
            Check.That(requestLogged.Request.Path).IsEqualTo("/foo");
        }
コード例 #15
0
        public async Task Scenarios_With_Same_Path_Should_Use_Times_When_Moving_To_Next_State()
        {
            // given
            const int times  = 2;
            string    path   = $"/foo_{Guid.NewGuid()}";
            string    body1  = "Scenario S1, No State, Setting State T2";
            string    body2  = "Scenario S1, State T2, End";
            var       server = WireMockServer.Start();

            server
            .Given(Request.Create().WithPath(path).UsingGet())
            .InScenario(1)
            .WillSetStateTo(2, times)
            .RespondWith(Response.Create().WithBody(body1));

            server
            .Given(Request.Create().WithPath(path).UsingGet())
            .InScenario(1)
            .WhenStateIs(2)
            .RespondWith(Response.Create().WithBody(body2));

            // when
            var client            = new HttpClient();
            var responseScenario1 = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path);

            var responseScenario2 = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path);

            var responseWithState = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path);

            // then
            responseScenario1.Should().Be(body1);
            responseScenario2.Should().Be(body1);
            responseWithState.Should().Be(body2);

            server.Stop();
        }
コード例 #16
0
        [InlineData("SOME-UNKNOWN-METHOD")] // default behavior for unknown methods is to allow a body (see BodyParser.ShouldParseBody)
        public async Task WireMockServer_Should_not_exclude_body_for_supported_methods(string method)
        {
            // Assign
            string content = "hello";
            var    server  = WireMockServer.Start();

            server
            .Given(Request.Create().WithBody(content))
            .AtPriority(0)
            .RespondWith(Response.Create().WithStatusCode(200));
            server
            .Given(Request.Create())
            .AtPriority(1)
            .RespondWith(Response.Create().WithStatusCode(400));

            // Act
            var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/");

            request.Content = new StringContent(content);
            var response = await new HttpClient().SendAsync(request);

            // Assert
            Check.That(response.StatusCode).Equals(HttpStatusCode.OK);
        }
コード例 #17
0
        public async Task HttpClient_ErrorCircuitBreakerTest()
        {
            using var server = new WireServer(WireMockServer.Start());


            var httpClientCollection = HttpOptionsBuilder.Configure(builder =>
            {
                builder.Configure(options =>
                {
                    options.AddClient("service", clientOptions =>
                    {
                        server.ConfigureWireMockServer(clientOptions);
                        clientOptions.Polly.CircuitBreaker.SamplingDuration = 3000;
                        clientOptions.Polly.CircuitBreaker.Enabled          = true;
                    });
                }
                                  );
            }).Build();


            var factory = httpClientCollection.GetFactory();
            var client  = factory.CreateClient("service");

            await Observable
            .FromAsync(ct =>
                       client
                       .GetAsync("/error/5ms", ct))
            .Catch(Observable.Return(new HttpResponseMessage()))
            .Repeat(50)
            .RepeatWhen(c => c.DelaySubscription(TimeSpan.FromMilliseconds(10)))
            .TakeUntil(DateTimeOffset.Now.AddSeconds(5));

            Assert.That(async() => await client.GetAsync("/error/5ms"), Throws.InstanceOf <BrokenCircuitException>());
            Assert.That(async() => await client.GetAsync("/delay/5ms"), Throws.InstanceOf <BrokenCircuitException>());
            Assert.That(async() => await client.GetAsync("/delay/1s"), Throws.InstanceOf <BrokenCircuitException>());
        }
コード例 #18
0
 public TestLearnerMatchApi()
 {
     MockServer  = WireMockServer.Start();
     BaseAddress = MockServer.Urls[0];
 }
コード例 #19
0
 public MemberUnitTests()
 {
     _wireMockServer = WireMockServer.Start();
     _connectionInfo = new WireMockConnection(_wireMockServer.Urls.First()).ConnectionInfo;
 }
コード例 #20
0
 public SparqlRemoteEndpointTests()
 {
     _server = WireMockServer.Start();
 }
コード例 #21
0
 public void StartMockServer()
 {
     _server = WireMockServer.Start();
 }
 public TheIdentityHubServiceTests()
 {
     _Server = WireMockServer.Start();
     Assert.False(_Server.Urls.Length < 1, "WireMockServer not started correctly");
     _TheIdentityHubService = TestTheIdentityHubServiceCreator.CreateInstance(_Server);
 }
コード例 #23
0
 public WaitForInstanceTests()
 {
     server = WireMockServer.Start();
 }
コード例 #24
0
 public TestEmployerIncentivesApi()
 {
     MockServer   = WireMockServer.Start(ssl: false);
     BaseAddress  = MockServer.Urls[0];
     BaseAddress += "/api";
 }
コード例 #25
0
 public async Task SetUp()
 {
     _server = new WireServer(WireMockServer.Start());
 }
コード例 #26
0
 public WebServiceClientTests()
 {
     _server = WireMockServer.Start();
 }
 public MockApi()
 {
     MockServer  = WireMockServer.Start();
     BaseAddress = MockServer.Urls[0];
 }
コード例 #28
0
        public async Task ShouldAllowRetrievingReportedForecast()
        {
            var tenantId = Any.String();
            var userId   = Any.String();

            using var notificationRecipient = WireMockServer.Start();
            notificationRecipient.Given(
                Request.Create()
                .WithPath("/notifications")
                .UsingPost()).RespondWith(
                Response.Create()
                .WithStatusCode(HttpStatusCode.OK));

            var inputForecastDto = new WeatherForecastDto(
                tenantId,
                userId,
                Any.DateTime(),
                Any.Integer(),
                Any.String());

            using var host = Host
                             .CreateDefaultBuilder()
                             .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                .UseTestServer()
                .ConfigureAppConfiguration(appConfig =>
                {
                    appConfig.AddInMemoryCollection(new Dictionary <string, string>
                    {
                        ["NotificationsConfiguration:BaseUrl"] = notificationRecipient.Urls.Single()
                    });
                })
                .UseEnvironment("Development")
                .UseStartup <Startup>();
            }).Build();

            await host.StartAsync();

            var client = new FlurlClient(host.GetTestClient());

            using var postJsonAsync = await client.Request("WeatherForecast")
                                      .PostJsonAsync(inputForecastDto);

            var resultDto = await postJsonAsync.GetJsonAsync <ForecastCreationResultDto>();

            using var httpResponse = await client.Request("WeatherForecast")
                                     .AppendPathSegment(resultDto.Id)
                                     .AllowAnyHttpStatus()
                                     .GetAsync();

            var weatherForecastDto = await httpResponse.GetJsonAsync <WeatherForecastDto>();

            weatherForecastDto.Should().BeEquivalentTo(inputForecastDto);

            notificationRecipient.LogEntries.Should().ContainSingle(entry =>
                                                                    entry.RequestMatchResult.IsPerfectMatch &&
                                                                    entry.RequestMessage.Path == "/notifications" &&
                                                                    entry.RequestMessage.Method == "POST" &&
                                                                    JsonConvert.DeserializeObject <WeatherForecastSuccessfullyReportedEventDto>(
                                                                        entry.RequestMessage.Body) == new WeatherForecastSuccessfullyReportedEventDto(
                                                                        tenantId, userId, inputForecastDto.TemperatureC));
        }
コード例 #29
0
ファイル: MainApp.cs プロジェクト: tralivali1234/WireMock.Net
        public static void Run()
        {
            string url1 = "http://*****:*****@"{ ""result"": ""Contains x with FUNC 200""}"));

            server
            .Given(Request.Create()
                   .UsingGet()
                   .WithPath("/proxy-test-keep-alive")
                   )
            .RespondWith(Response.Create()
                         .WithHeader("Keep-Alive", "timeout=1, max=1")
                         );

            server
            .Given(Request.Create()
                   .UsingPost()
                   .WithHeader("postmanecho", "post")
                   )
            .RespondWith(Response.Create()
                         .WithProxy(new ProxyAndRecordSettings {
                Url = "http://postman-echo.com/post"
            })
                         );

            server
            .Given(Request.Create()
                   .UsingGet()
                   .WithHeader("postmanecho", "get")
                   )
            .RespondWith(Response.Create()
                         .WithProxy(new ProxyAndRecordSettings {
                Url = "http://postman-echo.com/get"
            })
                         );

            server
            .Given(Request.Create()
                   .UsingGet()
                   .WithHeader("postmanecho", "get2")
                   )
            .RespondWith(Response.Create()
                         .WithProxy(new ProxyAndRecordSettings
            {
                Url = "http://postman-echo.com/get",
                WebProxySettings = new WebProxySettings
                {
                    Address  = "http://company",
                    UserName = "******",
                    Password = "******"
                }
            })
                         );

            server
            .Given(Request.Create()
                   .UsingGet()
                   .WithPath("/proxy-execute-keep-alive")
                   )
            .RespondWith(Response.Create()
                         .WithProxy(new ProxyAndRecordSettings {
                Url = "http://*****:*****@.name == 'RequiredThing')]"))
                   .UsingPut())
            .RespondWith(Response.Create()
                         .WithBody(@"{ ""result"": ""JsonPathMatcher !!!""}"));

            server
            .Given(Request
                   .Create()
                   .WithPath("/jsonbodytest1")
                   .WithBody(new JsonMatcher("{ \"x\": 42, \"s\": \"s\" }"))
                   .UsingPost())
            .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
            .RespondWith(Response.Create()
                         .WithBody(@"{ ""result"": ""jsonbodytest1"" }"));

            server
            .Given(Request
                   .Create()
                   .WithPath("/jsonbodytest2")
                   .WithBody(new JsonMatcher(new { x = 42, s = "s" }))
                   .UsingPost())
            .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f3")
            .RespondWith(Response.Create()
                         .WithBody(@"{ ""result"": ""jsonbodytest2"" }"));

            server
            .Given(Request
                   .Create()
                   .WithPath(new WildcardMatcher("/navision/OData/Company('My Company')/School*", true))
                   .WithParam("$filter", "(substringof(Code, 'WA')")
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBody(@"{ ""result"": ""odata""}"));

            server
            .Given(Request
                   .Create()
                   .WithPath(new WildcardMatcher("/param2", true))
                   .WithParam("key", "test")
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { result = "param2" }));

            server
            .Given(Request
                   .Create()
                   .WithPath(new WildcardMatcher("/param3", true))
                   .WithParam("key", new WildcardMatcher("t*"))
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { result = "param3" }));

            server
            .Given(Request.Create().WithPath("/headers", "/headers_test").UsingPost().WithHeader("Content-Type", "application/json*"))
            .RespondWith(Response.Create()
                         .WithStatusCode(201)
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { result = "data:headers posted with 201" }));

            if (!System.IO.File.Exists(@"c:\temp\x.json"))
            {
                System.IO.File.WriteAllText(@"c:\temp\x.json", "{ \"hello\": \"world\", \"answer\": 42 }");
            }

            server
            .Given(Request.Create().WithPath("/file").UsingGet())
            .RespondWith(Response.Create()
                         .WithBodyFromFile(@"c:\temp\x.json", false)
                         );

            server
            .Given(Request.Create().WithPath("/filecache").UsingGet())
            .RespondWith(Response.Create()
                         .WithBodyFromFile(@"c:\temp\x.json")
                         );

            server
            .Given(Request.Create().WithPath("/file_rel").UsingGet())
            .WithGuid("0000aaaa-fcf4-4256-a0d3-1c76e4862947")
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/xml")
                         .WithBodyFromFile("WireMock.Net.xml", false)
                         );

            server
            .Given(Request.Create().WithHeader("ProxyThis", "true")
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithProxy("http://www.google.com")
                         );

            server
            .Given(Request.Create().WithPath("/bodyasbytes.png")
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "image/png")
                         .WithBody(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTczbp9jAAAAJ0lEQVQoU2NgUPuPD6Hz0RCEAtJoiAxpCCBXGgmRIo0TofORkdp/AMiMdRVnV6O0AAAAAElFTkSuQmCC"))
                         );

            server
            .Given(Request.Create().WithPath("/oauth2/access").UsingPost().WithBody("grant_type=password;username=u;password=p"))
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { access_token = "AT", refresh_token = "RT" }));

            server
            .Given(Request.Create().WithPath("/helloworld").UsingGet().WithHeader("Authorization", new RegexMatcher("^(?i)Bearer AT$")))
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithBody("hi"));

            server
            .Given(Request.Create().WithPath("/data").UsingPost().WithBody(b => b.Contains("e")))
            .AtPriority(999)
            .RespondWith(Response.Create()
                         .WithStatusCode(201)
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { result = "data posted with FUNC 201" }));

            server
            .Given(Request.Create().WithPath("/json").UsingPost().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")))
            .RespondWith(Response.Create()
                         .WithStatusCode(201)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody(@"{ ""result"": ""json posted with 201""}"));

            server
            .Given(Request.Create().WithPath("/json2").UsingPost().WithBody("x"))
            .RespondWith(Response.Create()
                         .WithStatusCode(201)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody(@"{ ""result"": ""json posted with x - 201""}"));

            server
            .Given(Request.Create().WithPath("/data").UsingDelete())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody(@"{ ""result"": ""data deleted with 200""}"));

            server
            .Given(Request.Create()
                   .WithPath("/needs-a-key")
                   .UsingGet()
                   .WithHeader("api-key", "*", MatchBehaviour.AcceptOnMatch)
                   .UsingAnyMethod())
            .RespondWith(Response.Create()
                         .WithStatusCode(HttpStatusCode.OK)
                         .WithBody(@"{ ""result"": ""api-key found""}"));

            server
            .Given(Request.Create()
                   .WithPath("/needs-a-key")
                   .UsingGet()
                   .WithHeader("api-key", "*", MatchBehaviour.RejectOnMatch)
                   .UsingAnyMethod())
            .RespondWith(Response.Create()
                         .WithStatusCode(HttpStatusCode.Unauthorized)
                         .WithBody(@"{ ""result"": ""api-key missing""}"));

            server
            .Given(Request.Create().WithPath("/nobody").UsingGet())
            .RespondWith(Response.Create().WithDelay(TimeSpan.FromSeconds(1))
                         .WithStatusCode(200));

            server
            .Given(Request.Create().WithPath("/partial").UsingPost().WithBody(new SimMetricsMatcher(new[] { "cat", "dog" })))
            .RespondWith(Response.Create().WithStatusCode(200).WithBody("partial = 200"));

            // http://localhost:8080/trans?start=1000&stop=1&stop=2
            server
            .Given(Request.Create().WithPath("/trans").UsingGet())
            .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "application/json")
                         .WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}")
                         .WithHeader("xyz_{{request.headers.Postman-Token}}", "token is {{request.headers.Postman-Token}}")
                         .WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }")
                         .WithTransformer()
                         .WithDelay(TimeSpan.FromMilliseconds(100))
                         );

            server
            .Given(Request.Create().WithPath("/jsonpathtestToken").UsingPost())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
                         .WithTransformer()
                         );

            server
            .Given(Request.Create().WithPath("/zubinix").UsingPost())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBody("{ \"result\": \"{{JsonPath.SelectToken request.bodyAsJson \"username\"}}\" }")
                         .WithTransformer()
                         );

            server
            .Given(Request.Create().WithPath("/zubinix2").UsingPost())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { path = "{{request.path}}", result = "{{JsonPath.SelectToken request.bodyAsJson \"username\"}}" })
                         .WithTransformer()
                         );

            server
            .Given(Request.Create().WithPath("/jsonpathtestTokenJson").UsingPost())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { status = "OK", url = "{{request.url}}", transformed = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" })
                         .WithTransformer()
                         );

            server
            .Given(Request.Create().WithPath("/jsonpathtestTokens").UsingPost())
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBody("[{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}} { \"idx\":{{id}}, \"value\":\"{{value}}\" }, {{/JsonPath.SelectTokens}} {} ]")
                         .WithTransformer()
                         );

            server
            .Given(Request.Create()
                   .WithPath("/state1")
                   .UsingGet())
            .InScenario("s1")
            .WillSetStateTo("Test state 1")
            .RespondWith(Response.Create()
                         .WithBody("No state msg 1"));

            server
            .Given(Request.Create()
                   .WithPath("/foostate1")
                   .UsingGet())
            .InScenario("s1")
            .WhenStateIs("Test state 1")
            .RespondWith(Response.Create()
                         .WithBody("Test state msg 1"));

            server
            .Given(Request.Create()
                   .WithPath("/state2")
                   .UsingGet())
            .InScenario("s2")
            .WillSetStateTo("Test state 2")
            .RespondWith(Response.Create()
                         .WithBody("No state msg 2"));

            server
            .Given(Request.Create()
                   .WithPath("/foostate2")
                   .UsingGet())
            .InScenario("s2")
            .WhenStateIs("Test state 2")
            .RespondWith(Response.Create()
                         .WithBody("Test state msg 2"));

            server
            .Given(Request.Create().WithPath("/encoded-test/a%20b"))
            .RespondWith(Response.Create()
                         .WithBody("EncodedTest 1 : Path={{request.path}}, Url={{request.url}}")
                         .WithTransformer()
                         );

            server
            .Given(Request.Create().WithPath("/encoded-test/a b"))
            .RespondWith(Response.Create()
                         .WithBody("EncodedTest 2 : Path={{request.path}}, Url={{request.url}}")
                         .WithTransformer()
                         );

            // https://stackoverflow.com/questions/51985089/wiremock-request-matching-with-comparison-between-two-query-parameters
            server
            .Given(Request.Create().WithPath("/linq")
                   .WithParam("from", new LinqMatcher("DateTime.Parse(it) > \"2018-03-01 00:00:00\"")))
            .RespondWith(Response.Create()
                         .WithBody("linq match !!!")
                         );

            server
            .Given(Request.Create().WithPath("/myendpoint").UsingAnyMethod())
            .RespondWith(Response.Create()
                         .WithStatusCode(500)
                         .WithBody(requestMessage =>
            {
                return(JsonConvert.SerializeObject(new
                {
                    Message = "Test error"
                }));
            })
                         );

            server
            .Given(Request.Create().WithPath("/random"))
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new
            {
                Xeger1            = "{{Xeger \"\\w{4}\\d{5}\"}}",
                Xeger2            = "{{Xeger \"\\d{5}\"}}",
                TextRegexPostcode = "{{Random Type=\"TextRegex\" Pattern=\"[1-9][0-9]{3}[A-Z]{2}\"}}",
                Text                = "{{Random Type=\"Text\" Min=8 Max=20}}",
                TextLipsum          = "{{Random Type=\"TextLipsum\"}}",
                IBAN                = "{{Random Type=\"IBAN\" CountryCode=\"NL\"}}",
                TimeSpan1           = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}",
                TimeSpan2           = "{{Random Type=\"TimeSpan\"}}",
                DateTime1           = "{{Random Type=\"DateTime\"}}",
                DateTimeNow         = DateTime.Now,
                DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
                Guid1               = "{{Random Type=\"Guid\" Uppercase=false}}",
                Guid2               = "{{Random Type=\"Guid\"}}",
                Guid3               = "{{Random Type=\"Guid\" Format=\"X\"}}",
                Boolean             = "{{Random Type=\"Boolean\"}}",
                Integer             = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
                Long                = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
                Double              = "{{Random Type=\"Double\" Min=10 Max=99}}",
                Float               = "{{Random Type=\"Float\" Min=100 Max=999}}",
                IP4Address          = "{{Random Type=\"IPv4Address\" Min=\"10.2.3.4\"}}",
                IP6Address          = "{{Random Type=\"IPv6Address\"}}",
                MACAddress          = "{{Random Type=\"MACAddress\" Separator=\"-\"}}",
                StringListValue     = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
            })
                         .WithTransformer()
                         );

            server
            .Given(Request.Create()
                   .UsingPost()
                   .WithPath("/xpathsoap")
                   .WithBody(new XPathMatcher("//*[local-name() = 'getMyData']"))
                   )
            .RespondWith(Response.Create()
                         .WithHeader("Content-Type", "application/xml")
                         .WithBody("<xml>ok</xml>")
                         );

            server
            .Given(Request.Create()
                   .UsingPost()
                   .WithPath("/post_with_query")
                   .WithHeader("PRIVATE-TOKEN", "t")
                   .WithParam("name", "stef")
                   .WithParam("path", "p")
                   .WithParam("visibility", "Private")
                   .WithParam("parent_id", "1")
                   )
            .RespondWith(Response.Create()
                         .WithBody("OK : post_with_query")
                         );

            server.Given(Request.Create()
                         .WithPath("/services/query/")
                         .WithParam("q", "SELECT Id from User where username='******'")
                         .UsingGet())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new { Id = "5bdf076c-5654-4b3e-842c-7caf1fabf8c9" }));
            server
            .Given(Request.Create().WithPath("/random200or505").UsingGet())
            .RespondWith(Response.Create().WithCallback(request => new ResponseMessage
            {
                StatusCode = new Random().Next(1, 100) == 1 ? 504 : 200
            }));

            System.Console.WriteLine(JsonConvert.SerializeObject(server.MappingModels, Formatting.Indented));

            System.Console.WriteLine("Press any key to stop the server");
            System.Console.ReadKey();
            server.Stop();

            System.Console.WriteLine("Displaying all requests");
            var allRequests = server.LogEntries;

            System.Console.WriteLine(JsonConvert.SerializeObject(allRequests, Formatting.Indented));

            System.Console.WriteLine("Press any key to quit");
            System.Console.ReadKey();
        }
コード例 #30
0
 public void SetUp()
 {
     _wireMock = WireMockServer.Start(_wireMockPort, true);
 }