示例#1
0
 public async void Should_respond_404_for_unexpected_request()
 {
     // given
     _server = FluentMockServer.Start();
     // when
     var response
         = await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/foo");
     // then
     Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
     Check.That((int)response.StatusCode).IsEqualTo(404);
 }
示例#2
0
        public async void Should_record_requests_in_the_requestlogs()
        {
            // given
            _server = FluentMockServer.Start();
            // when
            await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/foo");
            // then
            Check.That(_server.RequestLogs).HasSize(1);
            var requestLogged = _server.RequestLogs.First();
            Check.That(requestLogged.Verb).IsEqualTo("get");
            Check.That(requestLogged.Body).IsEmpty();

        }
示例#3
0
        public async void Should_find_a_request_satisfying_a_request_spec()
        {
            // given
            _server = FluentMockServer.Start();
            // when
            await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/foo");
            await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/bar");
            // then
            var result = _server.SearchLogsFor(Requests.WithUrl("/b*")); 
            Check.That(result).HasSize(1);
            var requestLogged = result.First();
            Check.That(requestLogged.Url).IsEqualTo("/bar");

        }
        private void SetupUnStableServer(FluentMockServer fluentMockServer, string response)
        {
            fluentMockServer.Given(Request.Create().UsingGet())
            .InScenario("UnstableServer")
            .WillSetStateTo("FIRSTCALLDONE")
            .RespondWith(Response.Create().WithBody(response, encoding: Encoding.UTF8)
                         .WithStatusCode(HttpStatusCode.InternalServerError));

            fluentMockServer.Given(Request.Create().UsingGet())
            .InScenario("UnstableServer")
            .WhenStateIs("FIRSTCALLDONE")
            .RespondWith(Response.Create().WithBody(response, encoding: Encoding.UTF8)
                         .WithStatusCode(HttpStatusCode.OK));
        }
        public async Task FluentMockServer_Should_respond_404_for_unexpected_request()
        {
            // given
            string path = $"/foo{Guid.NewGuid()}";

            _server = FluentMockServer.Start();

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

            // then
            Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
            Check.That((int)response.StatusCode).IsEqualTo(404);
        }
        public void FluentMockServer_Admin_StartStop()
        {
            var server1 = FluentMockServer.Start("http://localhost:9091");

            Check.That(server1.Urls[0]).Equals("http://localhost:9091");

            server1.Stop();

            var server2 = FluentMockServer.Start("http://localhost:9091/");

            Check.That(server2.Urls[0]).Equals("http://localhost:9091/");

            server2.Stop();
        }
示例#7
0
        static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLineParser.CommandLineParser();

            parser.ExtractArgumentAttributes(options);

            try
            {
                parser.ParseCommandLine(args);

                if (!options.Urls.Any())
                {
                    options.Urls.Add("http://localhost:9090/");
                }

                var settings = new FluentMockServerSettings
                {
                    Urls = options.Urls.ToArray(),
                    StartAdminInterface = options.StartAdminInterface,
                    ReadStaticMappings  = options.ReadStaticMappings,
                };

                if (!string.IsNullOrEmpty(options.ProxyURL))
                {
                    settings.ProxyAndRecordSettings = new ProxyAndRecordSettings
                    {
                        Url         = options.ProxyURL,
                        SaveMapping = options.SaveMapping
                    };
                }

                var server = FluentMockServer.Start(settings);
                if (options.AllowPartialMapping)
                {
                    server.AllowPartialMapping();
                }

                Console.WriteLine("WireMock.Net server listening at {0}", string.Join(" and ", server.Urls));
            }
            catch (CommandLineException e)
            {
                Console.WriteLine(e.Message);
                parser.ShowUsage();
            }

            Console.WriteLine("Press any key to stop the server");
            Console.ReadKey();
        }
示例#8
0
        // [Fact]
        public async Task Should_process_request_if_equals_state_and_multiple_state_defined()
        {
            // Assign
            var server = FluentMockServer.Start();

            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("/fooX").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("/fooX").UsingGet())
            .InScenario("s2")
            .WhenStateIs("Test state 2")
            .RespondWith(Response.Create().WithBody("Test state msg 2"));

            // Act and Assert
            string url = "http://localhost:" + server.Ports[0];
            var    responseNoState1 = await new HttpClient().GetStringAsync(url + "/state1");

            Check.That(responseNoState1).Equals("No state msg 1");

            var responseNoState2 = await new HttpClient().GetStringAsync(url + "/state2");

            Check.That(responseNoState2).Equals("No state msg 2");

            var responseWithState1 = await new HttpClient().GetStringAsync(url + "/fooX");

            Check.That(responseWithState1).Equals("Test state msg 1");

            var responseWithState2 = await new HttpClient().GetStringAsync(url + "/fooX");

            Check.That(responseWithState2).Equals("Test state msg 2");

            server.Dispose();
        }
示例#9
0
        public async Task HttpAuthorizerShouldRaiseExceptionWhenTimingOutAsync()
        {
            // Arrange
            int    hostPort      = _HostPort++;
            string hostUrl       = "http://localhost:" + (hostPort).ToString();
            string FakeTokenAuth = "{auth: 'b928ab800c5c554a47ad:f41b9934520700d8474928d03ea7d808cab0cc7fcec082676f6b73ca0d9ab2b'}";

            var server = FluentMockServer.Start(hostPort);

            server
            .Given(
                Requests.WithUrl("/authz").UsingPost()
                )
            .RespondWith(
                Responses
                .WithStatusCode(200)
                .WithHeader("Content-Type", "application/json")
                .WithBody(FakeTokenAuth)
                );

            ChannelAuthorizationFailureException channelException = null;

            // Act
            var testHttpAuthorizer = new HttpAuthorizer(hostUrl + "/authz")
            {
                Timeout = TimeSpan.FromTicks(1),
            };

            // Try to generate the error multiple times as it does not always error the first time
            for (int attempt = 0; attempt < TimeoutRetryAttempts; attempt++)
            {
                try
                {
                    await testHttpAuthorizer.AuthorizeAsync("private-test", "fsfsdfsgsfs");
                }
                catch (Exception e)
                {
                    channelException = e as ChannelAuthorizationFailureException;
                }

                if (channelException != null && channelException.PusherCode == ErrorCodes.ChannelAuthorizationTimeout)
                {
                    break;
                }
            }

            // Assert
            AssertTimeoutError(channelException);
        }
示例#10
0
        public async void Should_find_a_request_satisfying_a_request_spec()
        {
            // given
            _server = FluentMockServer.Start();
            // when
            await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/foo");
            await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/bar");
            // then
            var result = _server.SearchLogsFor(Requests.WithUrl("/b*"));

            Check.That(result).HasSize(1);
            var requestLogged = result.First();

            Check.That(requestLogged.Url).IsEqualTo("/bar");
        }
示例#11
0
        public MockMiddleware()
        {
            server = FluentMockServer.Start(new FluentMockServerSettings
            {
                StartAdminInterface = true,
            });

            server
            .Given(Request.Create().WithPath("/event").UsingAnyMethod())
            .RespondWith(Response.Create().WithSuccess());

            client = RestClient.For <Middleware.IApi>(server.Urls[0]);

            admin = RestClient.For <IFluentMockServerAdmin>(server.Urls[0]);
        }
示例#12
0
        public LinnworksApiMock()
        {
            this.server = FluentMockServer.Start();

            Categories = JsonConvert
                         .DeserializeObject <List <TestCategory> >(
                EmbeddedResourceHelpers.ReadFile("Linnworks.CodingTests.Part1.Server.API.Client.UnitTests.Responses.GetAllCategories.json"));
            ProductCategoryCount = JsonConvert
                                   .DeserializeObject <ExecuteCustomScriptResult <ProductCategoryCount> >(
                EmbeddedResourceHelpers.ReadFile("Linnworks.CodingTests.Part1.Server.API.Client.UnitTests.Responses.ProductsCategorieCount.json"));

            SetCategoriesEndpoint();
            SetExecuteCustomScript();
            SetUpAddCategory();
        }
        public void FluentMockServer_Authentication_RemoveBasicAuthentication()
        {
            // Assign
            var server = FluentMockServer.Start();

            server.SetBasicAuthentication("x", "y");

            // Act
            server.RemoveBasicAuthentication();

            // Assert
            var options = server.GetPrivateFieldValue <IWireMockMiddlewareOptions>("_options");

            Check.That(options.AuthorizationMatcher).IsNull();
        }
        public void FluentMockServer_Authentication_SetBasicAuthentication()
        {
            // Assign
            var server = FluentMockServer.Start();

            // Act
            server.SetBasicAuthentication("x", "y");

            // Assert
            var options = server.GetPrivateFieldValue <IWireMockMiddlewareOptions>("_options");

            Check.That(options.AuthorizationMatcher.Name).IsEqualTo("RegexMatcher");
            Check.That(options.AuthorizationMatcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch);
            Check.That(options.AuthorizationMatcher.GetPatterns()).ContainsExactly("^(?i)BASIC eDp5$");
        }
示例#15
0
        public DiFixture()
        {
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .Enrich.FromLogContext()
                         .CreateLogger();

            Server = FluentMockServer.Start(8081);

            var serviceCollection = new ServiceCollection()
                                    .AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true))
                                    .AddSingleton(typeof(IHelloWorldApi), new HelloWorldApi(Server));

            ServiceProvider = serviceCollection.BuildServiceProvider();
        }
示例#16
0
        public async Task FluentMockServer_Proxy_Should_proxy_responses()
        {
            // given
            _server = FluentMockServer.Start();
            _server
            .Given(Request.Create().WithPath("/*"))
            .RespondWith(Response.Create().WithProxy("http://www.google.com"));

            // when
            var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/search?q=test");

            // then
            Check.That(_server.Mappings).HasSize(1);
            Check.That(result).Contains("google");
        }
示例#17
0
        protected FluentMockServer MakeServer()
        {
            // currently we don't need to customize any server settings
            var server = FluentMockServer.Start();

            // Perform an initial request to make sure the server has warmed up. On Android in particular, startup
            // of the very first server instance in the test run seems to be very slow, which may cause the first
            // request made by unit tests to time out.
            using (var client = new HttpClient())
            {
                AsyncUtils.WaitSafely(() => client.GetAsync(server.Urls[0]));
            }
            server.ResetLogEntries(); // so the initial request doesn't interfere with test postconditions
            return(server);
        }
示例#18
0
        public static void Init()
        {
            DotNetEnv.Env.Load("../../../.env");

            if (server == null)
            {
                server = FluentMockServer.Start(new FluentMockServerSettings
                {
                    Urls = new[] { "http://localhost:9191" }
                });
            }

            apiKey = System.Environment.GetEnvironmentVariable("TAXJAR_API_KEY") ?? "foo123";
            client = new TaxjarApi(apiKey, new { apiUrl = "http://localhost:9191" });
        }
        public void FluentMockServer_Admin_Mappings_WithGuid_Get()
        {
            Guid guid   = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
            var  server = FluentMockServer.Start();

            server.Given(Request.Create().WithPath("/foo1").UsingGet()).WithGuid(guid)
            .RespondWith(Response.Create().WithStatusCode(201).WithBody("1"));

            server.Given(Request.Create().WithPath("/foo2").UsingGet())
            .RespondWith(Response.Create().WithStatusCode(202).WithBody("2"));

            var mappings = server.Mappings.ToArray();

            Check.That(mappings).HasSize(2);
        }
        public async Task FluentMockServer_Should_exclude_restrictedResponseHeader_for_IOwinResponse()
        {
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create().WithPath("/foo").UsingGet())
            .RespondWith(Response.Create().WithHeader("Keep-Alive", "").WithHeader("test", ""));

            // Act
            var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");

            // Assert
            Check.That(response.Headers.Contains("test")).IsTrue();
            Check.That(response.Headers.Contains("Keep-Alive")).IsFalse();
        }
        public async Task FluentMockServer_Admin_Requests_Get()
        {
            // given
            _server = FluentMockServer.Start();

            // when
            await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");

            // then
            Check.That(_server.LogEntries).HasSize(1);
            var requestLogged = _server.LogEntries.First();

            Check.That(requestLogged.RequestMessage.Method).IsEqualTo("get");
            Check.That(requestLogged.RequestMessage.BodyAsBytes).IsNull();
        }
        public async Task FluentMockServer_Should_respond_to_request_BodyAsJson_Indented()
        {
            // Assign
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create().UsingAnyMethod())
            .RespondWith(Response.Create().WithBodyAsJson(new { message = "Hello" }, true));

            // Act
            var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0]);

            // Assert
            Check.That(response).IsEqualTo("{\r\n  \"message\": \"Hello\"\r\n}");
        }
        public async Task FluentMockServer_Should_respond_to_request_bodyAsBytes()
        {
            // given
            _server = FluentMockServer.Start();

            _server.Given(Request.Create().WithPath("/foo").UsingGet()).RespondWith(Response.Create().WithBody(new byte[] { 48, 49 }));

            // when
            var responseAsString = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
            var responseAsBytes  = await new HttpClient().GetByteArrayAsync("http://localhost:" + _server.Ports[0] + "/foo");

            // then
            Check.That(responseAsString).IsEqualTo("01");
            Check.That(responseAsBytes).ContainsExactly(new byte[] { 48, 49 });
        }
示例#24
0
        public static void Init()
        {
            if (server == null)
            {
                server = FluentMockServer.Start(new FluentMockServerSettings
                {
                    Urls = new[] { "http://localhost:9191" }
                });
            }

            var options = GetTestOptions();

            apiKey = options.ApiToken;
            client = new TaxjarApi(apiKey, new { apiUrl = "http://localhost:9191" });
        }
示例#25
0
        public void FluentMockServer_FluentMockServerSettings_StartAdminInterfaceFalse_BasicAuthenticationIsNotSet()
        {
            // Assign and Act
            var server = FluentMockServer.Start(new FluentMockServerSettings
            {
                StartAdminInterface = false,
                AdminUsername       = "******",
                AdminPassword       = "******"
            });

            // Assert
            var options = server.GetPrivateFieldValue <IWireMockMiddlewareOptions>("_options");

            Check.That(options.AuthorizationMatcher).IsNull();
        }
        public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request()
        {
            // Assign
            string path = $"/prx_{Guid.NewGuid().ToString()}";
            var    serverForProxyForwarding = FluentMockServer.Start();

            serverForProxyForwarding
            .Given(Request.Create().WithPath(path))
            .RespondWith(Response.Create());

            var settings = new FluentMockServerSettings
            {
                ProxyAndRecordSettings = new ProxyAndRecordSettings
                {
                    Url               = serverForProxyForwarding.Urls[0],
                    SaveMapping       = true,
                    SaveMappingToFile = false
                }
            };
            var server = FluentMockServer.Start(settings);

            // Act
            var requestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"{server.Urls[0]}{path}"),
                Content    = new StringContent("stringContent", Encoding.ASCII)
            };

            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
            requestMessage.Content.Headers.Add("bbb", "test");
            await new HttpClient().SendAsync(requestMessage);

            // Assert
            var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;

            Check.That(receivedRequest.BodyData.BodyAsString).IsEqualTo("stringContent");
            Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
            Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
            Check.That(receivedRequest.Headers).ContainsKey("bbb");

            // check that new proxied mapping is added
            Check.That(server.Mappings).HasSize(2);

            //var newMapping = _server.Mappings.First(m => m.Guid != guid);
            //var matcher = ((Request)newMapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().FirstOrDefault(m => m.Name == "bbb");
            //Check.That(matcher).IsNotNull();
        }
        public async Task FluentMockServer_Proxy_Should_Not_overrule_AdminMappings()
        {
            // Assign
            string path = $"/prx_{Guid.NewGuid().ToString()}";
            var    serverForProxyForwarding = FluentMockServer.Start();

            serverForProxyForwarding
            .Given(Request.Create().WithPath(path))
            .RespondWith(Response.Create().WithBody("ok"));

            var server = FluentMockServer.Start(new FluentMockServerSettings
            {
                StartAdminInterface    = true,
                ReadStaticMappings     = false,
                ProxyAndRecordSettings = new ProxyAndRecordSettings
                {
                    Url               = serverForProxyForwarding.Urls[0],
                    SaveMapping       = false,
                    SaveMappingToFile = false
                }
            });

            // Act 1
            var requestMessage1 = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"{server.Urls[0]}{path}")
            };
            var response1 = await new HttpClient().SendAsync(requestMessage1);

            // Assert 1
            string content1 = await response1.Content.ReadAsStringAsync();

            Check.That(content1).IsEqualTo("ok");

            // Act 2
            var requestMessage2 = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"{server.Urls[0]}/__admin/mappings")
            };
            var response2 = await new HttpClient().SendAsync(requestMessage2);

            // Assert 2
            string content2 = await response2.Content.ReadAsStringAsync();

            Check.That(content2).IsEqualTo("[]");
        }
示例#28
0
        public void Print(string mazeId)
        {
            var          server      = FluentMockServer.Start(null, false);
            var          client      = new RestfulClient(server.Urls.Select(u => string.Concat(new Uri(u))).First() + $"pony-challenge/maze", true);
            IGameService gameService = new GameService(client);

            server.Given(Request.Create().UsingGet())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithHeader("content-type", "application/json; charset=utf-8")
                         .WithBody("+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n|   |                           |               |           |\n+   +---+   +   +---+---+---+   +   +---+---+   +---+---+   +\n|       |   |   |           |       |                       |\n+---+   +---+   +---+---+   +---+---+   +---+---+---+---+---+\n|   |       |           |               |       |           |\n+   +---+   +   +---+   +   +---+---+---+   +   +   +---+   +\n|       |   |       |   |   |               |       |       |\n+   +---+   +---+   +   +---+   +---+---+---+---+---+   +   +\n|           |   |   | P     |   |       | D         |   |   |\n+   +---+---+   +   +---+   +   +   +---+   +---+   +   +   +\n|   |                   |       |   |       |   |   |   |   |\n+   +---+   +---+---+   +---+---+   +   +---+   +   +   +---+\n|       |   |       |       |       |   |           |       |\n+---+   +---+   +   +---+   +   +   +   +   +---+---+   +   +\n|   |   |       |       |       |   |   |   |       |   |   |\n+   +   +   +---+---+   +---+---+   +   +   +   +   +---+   +\n|   |   |           |       |       |   |       |           |\n+   +   +---+---+   +---+   +---+   +   +---+---+---+---+   +\n|       |           |   |       |   |   |               |   |\n+   +---+   +---+---+   +---+   +   +   +---+---+   +   +   +\n|           |                   |   |           |   |   |   |\n+---+---+---+   +---+---+---+---+   +---+---+   +   +   +   +\n|   |       |           |                   |   |   |       |\n+   +   +   +---+---+   +---+---+---+---+---+   +---+---+---+\n|       |               |                   |               |\n+   +---+---+---+---+---+   +---+---+---+   +   +---+---+   +\n|   |       |       |           |       |   |   |       |   |\n+   +   +   +   +   +---+---+   +   +---+   +---+   +   +   +\n|       |       |               | E                 |       |\n+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+"));

            var gameServiceobj = gameService.Print(mazeId);

            Assert.IsTrue(gameServiceobj.Contains("+"));
        }
        private void VerifyRequest(FluentMockServer server, UpdateMode mode)
        {
            var req = server.GetLastRequest();

            Assert.Equal("GET", req.Method);

            // Note, we don't check for an exact match of the encoded user string in Req.Path because it is not determinate - the
            // SDK may add custom attributes to the user ("os" etc.) and since we don't canonicalize the JSON representation,
            // properties could be serialized in any order causing the encoding to vary. Also, we don't test REPORT mode here
            // because it is already covered in FeatureFlagRequestorTest.
            Assert.Matches(mode.FlagsPathRegex, req.Path);

            Assert.Equal("", req.RawQuery);
            Assert.Equal(_mobileKey, req.Headers["Authorization"][0]);
            Assert.Null(req.Body);
        }
        public void FluentMockServer_Admin_ResetMappings()
        {
            var server = FluentMockServer.Start();

            string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings");

            server.ReadStaticMappings(folder);

            Check.That(server.Mappings).HasSize(5);

            // Act
            server.ResetMappings();

            // Assert
            Check.That(server.Mappings).HasSize(0);
        }
        public async Task FluentMockServer_Should_IgnoreRestrictedHeader()
        {
            // Assign
            _server = FluentMockServer.Start();
            _server
            .Given(Request.Create().WithPath("/head").UsingHead())
            .RespondWith(Response.Create().WithHeader("Content-Length", "1024"));

            var request = new HttpRequestMessage(HttpMethod.Head, "http://localhost:" + _server.Ports[0] + "/head");

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

            // Assert
            Check.That(response.Content.Headers.GetValues("Content-Length")).ContainsExactly("0");
        }
示例#32
0
        public static void InitializeServer(TestContext context)
        {
            System.Environment.SetEnvironmentVariable("NULLAFI_API_URL", "http://localhost:5000/");
            Server = FluentMockServer.Start(5000);

            Server.Given(Request.Create().WithPath("/authentication/token").UsingPost())
            .RespondWith(
                Response.Create()
                .WithStatusCode(HttpStatusCode.OK)
                .WithBody(JsonConvert.SerializeObject(new
            {
                Token   = "some-token",
                HashKey = HASH_KEY
            }))
                );
        }
示例#33
0
        internal static void Start(int?portOkResponse = null, int?portBadResponse = null)
        {
            if (portOkResponse != null)
            {
                ServerOkResponse = FluentMockServer.Start(portOkResponse.Value);
            }
            if (portBadResponse != null)
            {
                ServerBadResponse = FluentMockServer.Start(portBadResponse.Value);
            }

            AddNewRouter("/createAccount", ResponseString.AccountResultResponse);
            AddNewRouter("/createPage", ResponseString.PageResultResponse);

            AddNewRouter("/", ResponseString.CommonBadResponse, ServerBadResponse, 401);
        }
示例#34
0
        public async void Should_respond_to_request()
        {
            // given
            _server = FluentMockServer.Start();

            _server
                .Given(
                    Requests
                        .WithUrl("/foo")
                        .UsingGet())
                .RespondWith(
                    Responses
                        .WithStatusCode(200)
                        .WithBody(@"{ msg: ""Hello world!""}")
                    );

            // when
            var response 
                = await new HttpClient().GetStringAsync("http://*****:*****@"{ msg: ""Hello world!""}");
        }
示例#35
0
        public async void Should_delay_responses()
        {
            // given
            _server = FluentMockServer.Start();
            _server.AddRequestProcessingDelay(TimeSpan.FromMilliseconds(2000));
            _server
                .Given(
                    Requests
                        .WithUrl("/*")
                    )
                .RespondWith(
                    Responses
                        .WithStatusCode(200)
                        .WithBody(@"{ msg: ""Hello world!""}")
                    );

            // when
            var watch = new Stopwatch();
            watch.Start();
            var response
                = await new HttpClient().GetStringAsync("http://localhost:" + _server.Port + "/foo");
            watch.Stop();

            // then
            Check.That(watch.ElapsedMilliseconds).IsGreaterThan(2000);
        }
示例#36
0
        public async void Should_respond_a_redirect_without_body()
        {
            // given
            _server = FluentMockServer.Start();

            _server
                .Given(
                    Requests
                        .WithUrl("/foo")
                        .UsingGet())
                .RespondWith(
                    Responses
                        .WithStatusCode(307)
                        .WithHeader("Location", "/bar")
                    );
            _server
                .Given(
                    Requests
                        .WithUrl("/bar")
                        .UsingGet())
                .RespondWith(
                    Responses
                        .WithStatusCode(200)
                        .WithBody("REDIRECT SUCCESSFUL")
                    );


            // when
            var response
                = await new HttpClient().GetStringAsync("http://localhost:" + _server.Port + "/foo");
            // then
            Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL");
        }
示例#37
0
        public async void Should_reset_requestlogs()
        {
            // given
            _server = FluentMockServer.Start();
            // when
            await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/foo");
            _server.Reset();
            // then
            Check.That(_server.RequestLogs).IsEmpty();

        }
示例#38
0
        public async void Should_reset_routes()
        {
            // given
            _server = FluentMockServer.Start();

            _server
                .Given(
                    Requests
                        .WithUrl("/foo")
                        .UsingGet())
                .RespondWith(
                    Responses
                        .WithStatusCode(200)
                        .WithBody(@"{ msg: ""Hello world!""}")
                    );

            // when
            _server.Reset();

            // then
            Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + _server.Port + "/foo"))
                .ThrowsAny();
        }