public void FluentMockServer_Admin_ReadStaticMapping_WithNonGuidFilename()
        {
            var    guid  = Guid.Parse("04ee4872-9efd-4770-90d3-88d445265d0d");
            string title = "documentdb_root_title";

            var server = FluentMockServer.Start();

            string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");

            server.ReadStaticMappingAndAddOrUpdate(path);

            var mappings = server.Mappings.ToArray();

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

            Check.That(mappings.First().RequestMatcher).IsNotNull();
            Check.That(mappings.First().Provider).IsNotNull();
            Check.That(mappings.First().Guid).Equals(guid);
            Check.That(mappings.First().Title).Equals(title);
        }
Пример #2
0
        public void FluentMockServer_Should_reset_mappings()
        {
            // given
            string path   = $"/foo_{Guid.NewGuid()}";
            var    server = FluentMockServer.Start();

            server
            .Given(Request.Create()
                   .WithPath(path)
                   .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] + path)).ThrowsAny();
        }
Пример #3
0
        public async Task FluentMockServer_Should_delay_responses()
        {
            // given
            var 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);
        }
Пример #4
0
        static void Main(params string[] args)
        {
            XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

            string url = "http://localhost:9999/";

            var server = FluentMockServer.Start(new FluentMockServerSettings
            {
                Urls = new[] { url },
                StartAdminInterface = true,
                Logger = new WireMockConsoleLogger()
            });

            System.Console.WriteLine("FluentMockServer listening at {0}", string.Join(",", server.Urls));

            server.SetBasicAuthentication("a", "b");

            server.AllowPartialMapping();

            server
            .Given(Request.Create()
                   .UsingGet()
                   .WithHeader("Keep-Alive-Test", "stef")
                   )
            .RespondWith(Response.Create()
                         .WithHeader("Keep-Alive", "timeout=1, max=1")
                         .WithBody("Keep-Alive OK")
                         );

            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();
        }
        public async Task FluentMockServer_Should_find_a_request_satisfying_a_request_spec()
        {
            // Assign
            string path = $"/bar_{Guid.NewGuid()}";

            _server = FluentMockServer.Start();

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

            // then
            var result = _server.FindLogEntries(Request.Create().WithPath(new RegexMatcher("^/b.*"))).ToList();

            Check.That(result).HasSize(1);

            var requestLogged = result.First();

            Check.That(requestLogged.RequestMessage.Path).IsEqualTo(path);
            Check.That(requestLogged.RequestMessage.Url).IsEqualTo("http://localhost:" + _server.Ports[0] + path);
        }
        public void Should_Get_List_Of_Assets_NonRecursive(string assetDirectoryUri)
        {
            const string jsonList = @"[
            {
                ""name"": ""integration-tests"",
                ""type"": ""dir"",
                ""created"": ""2017-10-25T20:22:48.533Z"",
                ""modified"": ""2017-10-25T20:22:48.503Z""
            }
            ]";

            using (var server = FluentMockServer.Start())
            {
                server.Given(Request.Create().WithPath(assetDirectoryUri).UsingGet())
                .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK).WithBody(jsonList));

                var asset  = new ProGetAssetDirectoryLister(_config);
                var result = asset.ListDirectory($"http://localhost:{server.Ports[0]}{assetDirectoryUri}");
                Assert.Single(result);
            }
        }
        public void FluentMockServer_Admin_ReadStaticMappings_FolderDoesNotExist()
        {
            // Assign
            var loggerMock = new Mock <IWireMockLogger>();

            loggerMock.Setup(l => l.Info(It.IsAny <string>(), It.IsAny <object[]>()));
            var settings = new FluentMockServerSettings
            {
                Logger = loggerMock.Object
            };
            var server = FluentMockServer.Start(settings);

            // Act
            server.ReadStaticMappings(Guid.NewGuid().ToString());

            // Assert
            Check.That(server.Mappings).HasSize(0);

            // Verify
            loggerMock.Verify(l => l.Info(It.Is <string>(s => s.StartsWith("The Static Mapping folder")), It.IsAny <object[]>()), Times.Once);
        }
        /// <summary>
        /// This method causes the communication listener to be opened. Once the Open completes, the communication listener becomes usable - accepts and sends messages.
        /// </summary>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>A <see cref="Task">Task</see> that represents outstanding operation. The result of the Task is is endpoint string on which WireMock.Net is listening.</returns>
        public Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            string url = GetListenerUrl();

            ServiceEventSource.Current.ServiceMessage(_context, $"WireMock.Net Starting on {url}");

            _server = FluentMockServer.Start(new FluentMockServerSettings
            {
                Urls = new[] { url },
                StartAdminInterface        = true,
                ReadStaticMappings         = true,
                WatchStaticMappings        = true,
                PreWireMockMiddlewareInit  = app => { ServiceEventSource.Current.ServiceMessage(_context, $"PreWireMockMiddlewareInit : {app.GetType()}"); },
                PostWireMockMiddlewareInit = app => { ServiceEventSource.Current.ServiceMessage(_context, $"PostWireMockMiddlewareInit : {app.GetType()}"); },
                Logger = new WireMockServiceFabricLogger(_context),

                // FileSystemHandler = new WireMockServiceFabricFileSystemHandler(_reliableStateManager)
            });

            return(Task.FromResult(url));
        }
Пример #9
0
        public FakeZendesk()
        {
            var conf = new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json", optional: true)
                       .AddJsonFile("appsettings.local.json", optional: true)
                       .AddUserSecrets("ZendeskMonitorSecrets")
                       .Build();

            var instance       = conf.GetValue <string>("Zendesk:Instance");
            var user           = conf.GetValue <string>("Zendesk:ApiUser");
            var token          = conf.GetValue <string>("Zendesk:ApiKey");
            var useLiveZendesk = conf.GetValue <bool?>("Zendesk:UseLiveInstance") ?? false;

            server = FluentMockServer.Start(new FluentMockServerSettings
            {
                ReadStaticMappings     = !useLiveZendesk,
                FileSystemHandler      = new LocalFileSystemHandler(ProjectPath),
                ProxyAndRecordSettings = useLiveZendesk ? LiveZendeskProxySettings(instance) : null,
            });

            var url = server.Urls.First();

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri($"https://{instance}.zendesk.com/api/v2")
            };

            httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
            {
                NoCache = true
            };

            var byteArray = Encoding.ASCII.GetBytes($"{user}:{token}");

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            zendeskApi     = ApiFactory.CreateApi(httpClient);
            sharing        = new SharingTickets(zendeskApi);
            ticketFieldIds = new Lazy <Task <Dictionary <string, long> > >(LoadTicketFields);
        }
Пример #10
0
        public async Task Scenario_and_State_TodoList_Example()
        {
            // Assign
            var server = FluentMockServer.Start();

            server
            .Given(Request.Create().WithPath("/todo/items").UsingGet())
            .InScenario("To do list")
            .WillSetStateTo("TodoList State Started")
            .RespondWith(Response.Create().WithBody("Buy milk"));

            server
            .Given(Request.Create().WithPath("/todo/items").UsingPost())
            .InScenario("To do list")
            .WhenStateIs("TodoList State Started")
            .WillSetStateTo("Cancel newspaper item added")
            .RespondWith(Response.Create().WithStatusCode(201));

            server
            .Given(Request.Create().WithPath("/todo/items").UsingGet())
            .InScenario("To do list")
            .WhenStateIs("Cancel newspaper item added")
            .RespondWith(Response.Create().WithBody("Buy milk;Cancel newspaper subscription"));

            // Act and Assert
            string url          = "http://localhost:" + server.Ports[0];
            string getResponse1 = new HttpClient().GetStringAsync(url + "/todo/items").Result;

            Check.That(getResponse1).Equals("Buy milk");

            var postResponse = await new HttpClient().PostAsync(url + "/todo/items", new StringContent("Cancel newspaper subscription"));

            Check.That(postResponse.StatusCode).Equals(HttpStatusCode.Created);

            string getResponse2 = await new HttpClient().GetStringAsync(url + "/todo/items");

            Check.That(getResponse2).Equals("Buy milk;Cancel newspaper subscription");

            server.Dispose();
        }
Пример #11
0
        private static void Start()
        {
            if (IsRecordMode)
            {
                Server = FluentMockServer.Start(new FluentMockServerSettings
                {
                    StartAdminInterface    = true,
                    ProxyAndRecordSettings = new ProxyAndRecordSettings
                    {
                        Url                = "http://localhost:5001/",
                        SaveMapping        = true,
                        BlackListedHeaders = new[] { "X-ClientId", "Request-Id", "Authorization", "Host" },
                    },
                    Port = 8080
                });
            }
            else
            {
                Server = FluentMockServer.Start(new FluentMockServerSettings
                {
                    Urls = new[] { "http://localhost:8080/" }
                });

                var path = AppDomain.CurrentDomain.BaseDirectory;
                path = path.Remove(path.IndexOf("bin", StringComparison.Ordinal));

                Server.ReadStaticMappings(path + "SavedResponses");
                Server.ReadStaticMappings(path + "SavedResponses/Articles");
                Server.ReadStaticMappings(path + "SavedResponses/Atoz");
                Server.ReadStaticMappings(path + "SavedResponses/Events");
                Server.ReadStaticMappings(path + "SavedResponses/Footer");
                Server.ReadStaticMappings(path + "SavedResponses/Groups");
                Server.ReadStaticMappings(path + "SavedResponses/Homepage");
                Server.ReadStaticMappings(path + "SavedResponses/News");
                Server.ReadStaticMappings(path + "SavedResponses/Showcase");
                Server.ReadStaticMappings(path + "SavedResponses/Topics");
                Server.ReadStaticMappings(path + "SavedResponses/ContactUsArea");
            }
        }
        public async void FluentMockServer_LogEntriesChanged()
        {
            // Assign
            _server = FluentMockServer.Start();

            _server
            .Given(Request.Create()
                   .WithPath("/foo")
                   .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] + "/foo");

            // Assert
            Check.That(count).Equals(1);
        }
Пример #13
0
        public async Task IFluentMockServerAdmin_GetRequestsAsync()
        {
            // given
            _server = FluentMockServer.Start(new FluentMockServerSettings {
                StartAdminInterface = true, Logger = new WireMockNullLogger()
            });
            var serverUrl = "http://localhost:" + _server.Ports[0];

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

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

            // then
            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");
        }
Пример #14
0
        private static void StartMockServer()
        {
            var mockSrv = FluentMockServer.Start(new FluentMockServerSettings
            {
                Urls = new[] { "http://+:5001" },
                StartAdminInterface = true
            });

            mockSrv.Given(Request.Create()
                          .WithPath("/service1/api/users")
                          .UsingGet()
                          .WithBody(new { age = 30 }))
            .RespondWith(Response.Create()
                         .WithStatusCode(HttpStatusCode.OK)
                         .WithHeader("Content-Type", "application/json")
                         .WithBodyAsJson(new
            {
                name    = "joe doe",
                age     = 30,
                address = "1 rue de Paris"
            }));
        }
Пример #15
0
        public async void GetTrustedFromCacheAsync_TokenNotExistInCache_GetTokenFromCache()
        {
            using (var server = FluentMockServer.Start())
            {
                server
                .Given(Request.Create().WithPath("/pl/standard/user/oauth/authorize").UsingPost())
                .RespondWith(
                    Response.Create()
                    .WithStatusCode(200)
                    .WithBody(Json.ReadFromTestFiles("token.json"))
                    );
                ObjectCache cache = MemoryCache.Default;

                var result = await
                             cache.GetTokenFromCacheAsync <PayUToken>(new PayUClientSettings(string.Concat("http://*****:*****@test.com", "extCustomerId"), default(CancellationToken));

                Assert.Equal("fakeToken", result.AccessToken);
                Assert.Equal(999999, result.ExpireIn);
                Assert.Equal("type", result.TokenType);
                Assert.Equal("client_credentials", result.GrantType);
            }
        }
        public void FluentMockServer_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>())).Returns(new string[0]);

            var server = FluentMockServer.Start(new FluentMockServerSettings
            {
                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"), Times.Once);
        }
Пример #17
0
        public void FluentMockServer_Admin_Mappings_Add_SameGuid()
        {
            var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");

            _server = FluentMockServer.Start();

            _server.Given(Request.Create().WithPath("/1").UsingGet())
            .WithGuid(guid)
            .RespondWith(Response.Create().WithStatusCode(500));

            var mappings = _server.Mappings.ToArray();

            Check.That(mappings).HasSize(1);
            Check.That(mappings.First().Guid).Equals(guid);

            _server.Given(Request.Create().WithPath("/2").UsingGet())
            .WithGuid(guid)
            .RespondWith(Response.Create().WithStatusCode(500));

            Check.That(mappings).HasSize(1);
            Check.That(mappings.First().Guid).Equals(guid);
        }
Пример #18
0
 public void SetUp()
 {
     this.app_key        = "test_app_key";
     this.user_id        = "u1";
     this.app_version    = "v_test";
     this.ts             = 0;
     this.app_name       = "test_app";
     this.timezone       = 360000;
     this.event_name     = "test_event";
     this.event_id       = null;
     this.event_value    = null;
     this.ga_active      = false;
     this.anonymous_id   = null;
     this.trait_key      = null;
     this.trait_value    = null;
     this.api_key        = "test_api_key";
     this.GA_TRACKIND_ID = null;
     this.GA_CD_1        = 0;
     this.GA_CD_2        = 0;
     this.GA_CD_EVENT    = "group";
     _server             = FluentMockServer.Start();
 }
Пример #19
0
        public void HttpAuthorizerShouldRaiseExceptionIfUnauthorized()
        {
            string channelName   = "private-unauthorized-test";
            string socketId      = Guid.NewGuid().ToString("N");
            int    hostPort      = _HostPort++;
            string hostUrl       = "http://localhost:" + (hostPort).ToString();
            string FakeTokenAuth = "Forbidden";

            var server = FluentMockServer.Start(hostPort);

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

            ChannelUnauthorizedException exception = null;
            var testHttpAuthorizer = new PusherClient.HttpAuthorizer(hostUrl + "/unauthz");

            try
            {
                testHttpAuthorizer.Authorize(channelName, socketId);
            }
            catch (ChannelUnauthorizedException e)
            {
                exception = e;
            }

            Assert.IsNotNull(exception, $"Expecting a {nameof(ChannelUnauthorizedException)}");
            Assert.AreEqual(channelName, exception.ChannelName, nameof(ChannelUnauthorizedException.ChannelName));
            Assert.AreEqual(socketId, exception.SocketID, nameof(ChannelUnauthorizedException.SocketID));
            Assert.AreEqual(ErrorCodes.ChannelUnauthorized, exception.PusherCode);
        }
Пример #20
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();
        }
Пример #21
0
        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);
        }
Пример #22
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!""}");
        }
        public async void FluentMockServer_LogEntriesChanged()
        {
            // Assign
            string path   = $"/log_{Guid.NewGuid()}";
            var    server = FluentMockServer.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);
        }
Пример #24
0
        public async Task GivenAnExistingUser_WhenGettingTheirAccountInformation()
        {
            var fixture = new Fixture();

            _user = fixture.Build <User>()
                    .With(x => x.BankDetails, fixture.Build <BankDetails>()
                          .With(x => x.AccountNumber, "12345678")
                          .With(x => x.Name, "BizfiBank")
                          .Create())
                    .Create();

            _fluentMockServer = FluentMockServer.Start(Configuration.BizfiBankUrl);
            _fluentMockServer.Given(Request.Create().WithPath($"/accounts/{_user.BankDetails.AccountNumber}").UsingGet())
            .RespondWith(Response.Create()
                         .WithStatusCode(200)
                         .WithBody(_expectedResponse)
                         .WithHeader("Content-Type", "application/json"));


            await Database.Users.InsertOneAsync(_user);

            _result = await HttpClients.FairWayApi.GetAsync($"users/{_user.Id}/account");
        }
        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_Proxy_Should_change_absolute_location_header_in_proxied_response()
        {
            // Assign
            string path     = $"/prx_{Guid.NewGuid().ToString()}";
            var    settings = new FluentMockServerSettings {
                AllowPartialMapping = false
            };

            var serverForProxyForwarding = FluentMockServer.Start(settings);

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

            var server = FluentMockServer.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");
        }
Пример #27
0
        public async Task HttpAuthorizerShouldRaiseExceptionIfAuthorizerUrlNotFoundAsync()
        {
            string channelName   = "private-unauthorized-test";
            string socketId      = Guid.NewGuid().ToString("N");
            int    hostPort      = _HostPort++;
            string hostUrl       = "http://localhost:" + (hostPort).ToString();
            string FakeTokenAuth = "NotFound";

            var server = FluentMockServer.Start(hostPort);

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

            ChannelAuthorizationFailureException exception = null;
            var testHttpAuthorizer = new HttpAuthorizer(hostUrl + "/notfound");

            try
            {
                await testHttpAuthorizer.AuthorizeAsync(channelName, socketId).ConfigureAwait(false);
            }
            catch (ChannelAuthorizationFailureException e)
            {
                exception = e;
            }

            Assert.IsNotNull(exception, $"Expecting a {nameof(ChannelAuthorizationFailureException)}");
            Assert.IsTrue(exception.Message.Contains("404"));
            Assert.AreEqual(ErrorCodes.ChannelAuthorizationError, exception.PusherCode);
        }
Пример #28
0
        public async Task HttpAuthorizerShouldRaiseExceptionWhenRequestTimeoutAsync()
        {
            // 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(408)
                .WithHeader("Content-Type", "application/json")
                .WithBody(FakeTokenAuth)
                );

            ChannelAuthorizationFailureException channelException = null;

            // Act
            var testHttpAuthorizer = new HttpAuthorizer(hostUrl + "/authz");

            try
            {
                await testHttpAuthorizer.AuthorizeAsync("private-test", "fsfsdfsgsfs");
            }
            catch (Exception e)
            {
                channelException = e as ChannelAuthorizationFailureException;
            }

            // Assert
            AssertTimeoutError(channelException);
        }
        public async Task FluentMockServer_Should_respond_to_valid_matchers_when_sent_json()
        {
            // Assign
            var validMatchersForHelloServerJsonMessage = new List <object[]>
            {
                new object[] { new WildcardMatcher("*Hello server*"), "application/json" },
                new object[] { new WildcardMatcher("*Hello server*"), "text/plain" },
                new object[] { new ExactMatcher(jsonRequestMessage), "application/json" },
                new object[] { new ExactMatcher(jsonRequestMessage), "text/plain" },
                new object[] { new RegexMatcher("Hello server"), "application/json" },
                new object[] { new RegexMatcher("Hello server"), "text/plain" },
                new object[] { new JsonPathMatcher("$..[?(@.message == 'Hello server')]"), "application/json" },
                new object[] { new JsonPathMatcher("$..[?(@.message == 'Hello server')]"), "text/plain" }
            };

            var _server = FluentMockServer.Start();

            foreach (var item in validMatchersForHelloServerJsonMessage)
            {
                string path = $"/foo_{Guid.NewGuid()}";
                _server
                .Given(Request.Create().WithPath(path).WithBody((IMatcher)item[0]))
                .RespondWith(Response.Create().WithBody("Hello client"));

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

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

                Check.That(responseString).Equals("Hello client");

                _server.ResetMappings();
                _server.ResetLogEntries();
            }
        }
        public async Task FluentMockServer_LogEntriesChanged_Parallel()
        {
            int expectedCount = 10;

            // Assign
            string path   = $"/log_p_{Guid.NewGuid()}";
            var    server = FluentMockServer.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(10);
                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);
        }