Esempio n. 1
0
 protected void GenerarUrlVirtuales(string Path, string Body)
 {
     helperMock
     .Given(
         Request.Create()
         .WithPath(Path)
         .UsingAnyMethod()
         )
     .RespondWith(
         Response.Create()
         .WithStatusCode(200)
         .WithBody(Body)
         );
 }
        public void FluentMockServer_Admin_Mappings_Get()
        {
            var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");

            _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);

            Check.That(mappings.First().RequestMatcher).IsNotNull();
            Check.That(mappings.First().Provider).IsNotNull();
            Check.That(mappings.First().Guid).Equals(guid);

            Check.That(mappings[1].Guid).Not.Equals(guid);
        }
 public static void CrearURLSinArchivo(string Respuesta, string MetodoHTTP, FluentMockServer serviceMock)
 {
     if (MetodoHTTP == "GET")
     {
         serviceMock
         .Given(Request.Create().UsingGet())
         .RespondWith(
             Response.Create()
             .WithStatusCode(200)
             .WithBody(Respuesta)
             );
     }
     else if (MetodoHTTP == "POST")
     {
         serviceMock
         .Given(Request.Create().UsingPost())
         .RespondWith(
             Response.Create()
             .WithStatusCode(200)
             .WithBody(Respuesta)
             );
     }
 }
Esempio n. 4
0
        public async Task FluentMockServer_Admin_Mappings_AtPriority()
        {
            _server = FluentMockServer.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);
        }
        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_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}");
        }
Esempio n. 7
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]);
        }
        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 });
        }
        private void SetupHackerNewsServerResponse(string fileName, int page)
        {
            var fileContent = GetResourceFileContents(fileName);

            _fakeHackerNewsServer
            .Given(Request
                   .Create()
                   .WithPath($"/news")
                   .WithParam("p", page.ToString())
                   .UsingGet())
            .RespondWith(Response
                         .Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "text/html")
                         .WithBody(fileContent));
        }
Esempio n. 10
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
            }))
                );
        }
        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");
        }
Esempio n. 12
0
        public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request()
        {
            // given
            _serverForProxyForwarding = FluentMockServer.Start();
            _serverForProxyForwarding
            .Given(Request.Create().WithPath("/*"))
            .RespondWith(Response.Create());

            var settings = new FluentMockServerSettings
            {
                ProxyAndRecordSettings = new ProxyAndRecordSettings
                {
                    Url               = _serverForProxyForwarding.Urls[0],
                    SaveMapping       = true,
                    SaveMappingToFile = false
                }
            };

            _server = FluentMockServer.Start(settings);

            // when
            var requestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(_server.Urls[0]),
                Content    = new StringContent("stringContent")
            };

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

            // then
            var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage;

            Check.That(receivedRequest.Body).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();
        }
 protected void GivenEmailSendIsSuccessful()
 {
     _mockServer
     .Given(
         Requests
         .WithUrl("/messages/emails")
         .UsingPost())
     .RespondWith(
         Responses
         .WithStatusCode(200));
 }
Esempio n. 14
0
        public TubeAnagramsTest()
        {
            _mockServer = FluentMockServer.Start();

            _mockServer.Given(
                Request.Create()
                .WithPath("/line/central/stoppoints")
                .UsingGet())
            .RespondWith(
                Response.Create()
                .WithStatusCode(200)
                .WithHeader("Content-Type", "application/json")
                .WithBody(_responseBody)
                );

            _tflApi = new TflApi(_mockServer.Urls[0]);
        }
        public async Task When_the_product_is_not_licensed()
        {
            mockServer
            .Given(Request.Create().WithPath("/v2/contentConverters").UsingPost())
            .RespondWith(Response.Create()
                         .WithStatusCode(480)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody("{\"errorCode\":\"LicenseCouldNotBeVerified\"}"));

            var dummyInput = new ConversionSourceDocument(new RemoteWorkFile(null, null, null, null));

            await UtilAssert.ThrowsExceptionWithMessageAsync <RestApiErrorException>(
                async() =>
            {
                await prizmDocServer.ConvertAsync(dummyInput, new DestinationOptions(DestinationFileFormat.Pdf));
            }, "Remote server does not have a valid license.");
        }
Esempio n. 16
0
        public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_header_in_mapping()
        {
            // given
            _serverForProxyForwarding = FluentMockServer.Start();
            _serverForProxyForwarding
            .Given(Request.Create().WithPath("/*"))
            .RespondWith(Response.Create());

            var settings = new FluentMockServerSettings
            {
                ProxyAndRecordSettings = new ProxyAndRecordSettings
                {
                    Url                = _serverForProxyForwarding.Urls[0],
                    SaveMapping        = true,
                    SaveMappingToFile  = false,
                    BlackListedHeaders = new[] { "blacklisted" }
                }
            };

            _server = FluentMockServer.Start(settings);
            //_server
            //    .Given(Request.Create().WithPath("/*"))
            //    .RespondWith(Response.Create());

            // when
            var requestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(_server.Urls[0]),
                Content    = new StringContent("stringContent")
            };

            requestMessage.Headers.Add("blacklisted", "test");
            requestMessage.Headers.Add("ok", "ok-value");
            await new HttpClient().SendAsync(requestMessage);

            // then
            var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage;

            Check.That(receivedRequest.Headers).Not.ContainsKey("bbb");
            Check.That(receivedRequest.Headers).ContainsKey("ok");

            //var mapping = _server.Mappings.Last();
            //var matcher = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().FirstOrDefault(m => m.Name == "bbb");
            //Check.That(matcher).IsNull();
        }
Esempio n. 17
0
        public async Task GetAllUsesCorrectUriAndParsesResponseAsync()
        {
            _server.Given(Request.Create().UsingGet())
            .RespondWith(Response.Create().WithStatusCode(200).WithBody(AllDataJson));
            var result = await _requestor.GetAllDataAsync();

            var req = GetLastRequest();

            Assert.Equal("/sdk/latest-all", req.Path);

            Assert.Equal(1, result.Flags.Count);
            Assert.Equal(1, result.Flags["flag1"].Version);
            Assert.Equal(1, result.Segments.Count);
            Assert.Equal(2, result.Segments["seg1"].Version);
        }
        public async Task FluentMockServer_Should_respond_to_request_callback()
        {
            // Assign
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create().WithPath("/foo").UsingGet())
            .RespondWith(Response.Create().WithCallback(req => new ResponseMessage {
                Body = req.Path + "Bar"
            }));

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

            // Assert
            Check.That(response).IsEqualTo("/fooBar");
        }
        public void GetOfTReturnsExpectedData(string path, MockResponsePayload payload)
        {
            var fullpath = $"/{path}";

            var body = ToDomainResponse(payload);

            _server
            .Given(
                Request.Create().WithPath(fullpath).UsingGet())
            .RespondWith(
                Response.Create().WithStatusCode(200).WithBodyAsJson(body, true));

            var result = _sut.Get <MockResponsePayload>(fullpath);

            Assert.Equal(payload?.Data, result.Data);
        }
        private void SetUpFakeTimeTaskServer()
        {
            server = FluentMockServer.Start(new FluentMockServerSettings()
            {
                Port = 9998
            });
            var responseProvider = new FakeResponseProvider(HttpStatusCode.OK);

            responseProvider.Callback = message =>
            {
                var res = JsonConvert.DeserializeObject <TimeTaskRequest <AuctionEndTimeTaskValues> >(message.Body);
                called[res.Values.AuctionId] = true;
            };
            server.Given(Request.Create()
                         .WithPath("/test")
                         .UsingPost())
            .RespondWith(responseProvider);
        }
Esempio n. 21
0
        public async Task FluentMockServer_Should_respond_to_valid_matchers_when_sent_json(IMatcher matcher, string contentType)
        {
            // Assign
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create().WithPath("/foo").WithBody(matcher))
            .RespondWith(Response.Create().WithBody("Hello client"));

            // Act
            var content  = new StringContent(jsonRequestMessage, Encoding.UTF8, contentType);
            var response = await new HttpClient().PostAsync("http://localhost:" + _server.Ports[0] + "/foo", content);

            // Assert
            var responseString = await response.Content.ReadAsStringAsync();

            Check.That(responseString).Equals("Hello client");
        }
        public async Task Should_skip_non_relevant_states()
        {
            // given
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create()
                   .WithPath("/foo")
                   .UsingGet())
            .InScenario("s")
            .WhenStateIs("Test state")
            .RespondWith(Response.Create());

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

            // then
            Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
        }
        public async Task FluentMockServer_Should_delay_responses()
        {
            // given
            _server = FluentMockServer.Start();
            _server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200));
            _server
            .Given(Request.Create().WithPath("/*"))
            .RespondWith(Response.Create().WithBody(@"{ msg: ""Hello world!""}"));

            // 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);
        }
        public async Task FluentMockServer_Should_respond_to_request_bodyAsCallback()
        {
            // given
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create()
                   .WithPath("/foo")
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithBody(req => $"{{ path: '{req.Path}' }}"));

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

            // then
            Check.That(response).IsEqualTo("{ path: '/foo' }");
        }
        public async Task Should_respond_to_request()
        {
            // given
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create()
                   .WithPath("/foo")
                   .UsingGet())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithBody(@"{ msg: ""Hello world!""}"));

            // when
            var response = await new HttpClient().GetStringAsync("http://*****:*****@"{ msg: ""Hello world!""}");
        }
        public async Task InitializeAndSubmitGoodResponse()
        {
            FluentMockServer server = null;

            try
            {
                server = FluentMockServer.Start(new FluentMockServerSettings {
                    Urls = new[] { "http://+:5010" }
                });

                server
                .Given(Request.Create().WithPath("/Query").UsingPost())
                .RespondWith(
                    Response.Create()
                    .WithStatusCode(200)
                    .WithBody(@"{
                              ""guid"": ""00000000-0000-0000-0000-000000000000"",
                              ""status"": ""SUBMITTED"",
                              ""mD5Hash"": ""12345"",
                              ""errorMessage"": null,
                              ""isMalicious"": false
                            }")
                    );

                var handler = new PostHandler("http://localhost:5010/");

                var file = Path.GetTempFileName();

                var result = await handler.SubmitQueryHashAsync(file);

                Assert.IsNotNull(result);
                Assert.AreEqual(ResponseStatus.SUBMITTED, result.Status);
                Assert.AreEqual("12345", result.MD5Hash);
                Assert.AreEqual(false, result.IsMalicious);
                Assert.AreEqual(Guid.Empty, result.Guid);
                Assert.IsNull(result.ErrorMessage);
            }
            finally
            {
                server?.Stop();
            }
        }
        public void FluentMockServer_Should_reset_mappings()
        {
            // given
            _server = FluentMockServer.Start();

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

            // when
            _server.ResetMappings();

            // then
            Check.That(_server.Mappings).IsEmpty();
            Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo"))
            .ThrowsAny();
        }
Esempio n. 28
0
        internal static void AddNewRouter(string url, string responseString, FluentMockServer server = null, int?statusCode = null)
        {
            if (statusCode == null)
            {
                statusCode = 200;
            }

            if (server == null)
            {
                server = ServerOkResponse;
            }

            server.Given(
                Requests.WithUrl(url).UsingPost()
                )
            .RespondWith(
                Responses
                .WithStatusCode((int)statusCode)
                .WithBody(responseString)
                );
        }
Esempio n. 29
0
        public async Task Unknown_error_on_POST()
        {
            mockServer
            .Given(Request.Create().WithPath("/v2/contentConverters").UsingPost())
            .RespondWith(Response.Create()
                         .WithStatusCode(418)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody("{\"errorCode\":\"BoilingOver\",\"errorDetails\":{\"in\":\"body\",\"at\":\"input.admin.enableTurboMode\"}}"));

            var dummyInput = new ConversionSourceDocument(new RemoteWorkFile(null, null, null, null));

            string expectedMessage = @"Remote server returned an error: I'm a teapot BoilingOver {
  ""in"": ""body"",
  ""at"": ""input.admin.enableTurboMode""
}";

            await UtilAssert.ThrowsExceptionWithMessageAsync <RestApiErrorException>(
                async() => { await prizmDocServer.ConvertAsync(dummyInput, new DestinationOptions(DestinationFileFormat.Pdf)); },
                expectedMessage,
                ignoreCase : true);
        }
Esempio n. 30
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!""}");
        }
Esempio n. 31
0
        private void SetupBankResponse(Guid id, bool wasSuccessful, string error)
        {
            _fakeBankServer.ResetMappings();

            var response = new
            {
                id,
                wasSuccessful,
                error
            };

            _fakeBankServer
            .Given(Request
                   .Create()
                   .WithPath("/payments/process")
                   .UsingPost())
            .RespondWith(Response
                         .Create()
                         .WithStatusCode(200)
                         .WithHeader("Content-Type", "application/json")
                         .WithBody(JsonConvert.SerializeObject(response)));
        }
Esempio n. 32
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();
        }
Esempio n. 33
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");
        }
Esempio n. 34
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);
        }