예제 #1
0
        public async Task ServiceProxyRpcMessageShouldRemainSame()
        {
            const string serviceName = "DemoService";
            int          defaultPort = DisposablePort.GetPort().Port;
            var          dict        = new Dictionary <string, string>
            {
                { $"Discovery.Services.{serviceName}.Source", "Config" },
                { $"Discovery.Services.{serviceName}.Hosts", "host1" },
                { $"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString() }
            };

            Uri    uri            = null;
            string requestMessage = null;

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*").Respond(async req =>
                {
                    requestMessage = await req.Content.ReadAsStringAsync();
                    uri            = req.RequestUri;
                    return(HttpResponseFactory.GetResponse(HttpStatusCode.Accepted));
                });
                return(messageHandler);
            };

            using (var kernel = new TestingKernel <ConsoleLog>(k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            }, dict))
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();

                TracingContext.SetRequestID("g");

                var serviceProxy = providerFactory(serviceName);

                string expectedHost = "override-host";
                int    expectedPort = DisposablePort.GetPort().Port;

                TracingContext.SetHostOverride(serviceName, expectedHost, expectedPort);

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());
                await serviceProxy.Invoke(request, typeof(string));

                var body = requestMessage;
                Console.WriteLine($"error: {body}");

                JsonConvert.DeserializeObject <GigyaRequestProtocol>(body, new JsonSerializerSettings()
                {
                    MissingMemberHandling = MissingMemberHandling.Error
                });


                uri.Host.ShouldBe(expectedHost);
                uri.Port.ShouldBe(expectedPort);
            }
        }
예제 #2
0
        public async Task NotGigyaServerBadRequestTest()
        {
            var resMessage = HttpResponseFactory.GetResponse(HttpStatusCode.ServiceUnavailable, isGigyaHost: false);

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler.When("*").Respond(resMessage);

                return(messageHandler);
            };

            unitTesting.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);

            try
            {
                await CreateClient().ToUpper("aaaa");
            }
            catch (Exception)
            {
                var expected = DefaultExpected();

                expected.Counters.Add(new MetricDataEquatable {
                    Name = "HostFailure", Unit = Unit.Calls
                });

                GetMetricsData().AssertEquals(expected);
            }
        }
예제 #3
0
        public async Task SuccessTest()
        {
            var resMessage = HttpResponseFactory.GetResponse(content: "''");

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler.When("*").Respond(resMessage);

                return(messageHandler);
            };

            unitTesting.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);

            await CreateClient().ToUpper("aaaa");

            var expected = DefaultExpected();

            expected.Counters.Add(new MetricDataEquatable {
                Name = "Success", Unit = Unit.Calls
            });
            expected.Timers.Add(new MetricDataEquatable {
                Name = "Deserialization", Unit = Unit.Calls
            });

            GetMetricsData().AssertEquals(expected);
        }
예제 #4
0
        public async Task OneHostHasNetworkErrorShouldMoveToNextHost()
        {
            var dict = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "host1,host2" },
                { "Discovery.Services.DemoService.DefaultPort", "5555" }
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
            }, dict)
                   )
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");

                //Disable  TracingContext.SetRequestID("1");
                CallContext.FreeNamedDataSlot("#ORL_RC");

                int counter        = 0;
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req =>
                {
                    bool disableReachabilityChecker = req.Content == null;
                    if (disableReachabilityChecker)
                    {
                        throw new HttpRequestException();
                    }

                    counter++;

                    if (req.RequestUri.Host == "host1")
                    {
                        throw new HttpRequestException();
                    }
                    return(HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"));
                });

                serviceProxy.HttpMessageHandler = messageHandler;

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

                for (int i = 0; i < 3; i++)
                {
                    var server = await serviceProxy.Invoke(request, typeof(string));

                    server.ShouldBe("host2");
                }

                counter.ShouldBe(4);
            }
        }
예제 #5
0
        public async Task ToUpper_MethodCallSucceeds_ResultIsCorrect()
        {
            var expected       = "AAAA";
            var messageHandler = new MockHttpMessageHandler();

            messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(content: $"'{expected}'"));

            var actual = await CreateClient(messageHandler).ToUpper("aaaa");

            actual.ShouldBe(expected);
        }
예제 #6
0
        public async Task ToUpper_MethodCallFailsWithInvalidJson_CorrectExceptionIsThrown()
        {
            string badJson        = "not JSON!";
            var    messageHandler = new MockHttpMessageHandler();

            messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(HttpStatusCode.InternalServerError, content: badJson));

            var actual = CreateClient(messageHandler).ToUpper("aaaa").ShouldThrow <RemoteServiceException>();

            actual.EncryptedTags["responseContent"].ShouldBe(badJson);
            actual.InnerException.ShouldBeAssignableTo <JsonException>();
        }
예제 #7
0
        public async Task AllRequestsForSameCallID_SameHostSelected()
        {
            var port = DisposablePort.GetPort().Port;
            var dict = new Dictionary <string, string> {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "host1,host2" },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() }
            };

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req => HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"));
                return(messageHandler);
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            },
                           dict))
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;

                //If we set Request Id we would like always to select same Host
                TracingContext.SetRequestID("dumyId1");
                var request        = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());
                var hostOfFirstReq = (string)await serviceProxy.Invoke(request, typeof(string));

                string host;
                for (int i = 0; i < 50; i++)
                {
                    host = (string)await serviceProxy.Invoke(request, typeof(string));

                    host.ShouldBe(hostOfFirstReq);
                }

                TracingContext.SetRequestID("dumyId2");
                host = (string)await serviceProxy.Invoke(request, typeof(string));

                host.ShouldNotBe(hostOfFirstReq);
            }
        }
예제 #8
0
        public async Task RequestContextShouldOverrideHostOnly()
        {
            const string serviceName = "DemoService";
            int          defaultPort = DisposablePort.GetPort().Port;

            var dict = new Dictionary <string, string> {
                { $"Discovery.Services.{serviceName}.Source", "Config" },
                { $"Discovery.Services.{serviceName}.Hosts", "host1" },
                { $"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString() }
            };

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req =>
                {
                    if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https")
                    {
                        throw new HttpRequestException();
                    }

                    return(HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}:{req.RequestUri.Port}'"));
                });
                return(messageHandler);
            };

            var kernel = new TestingKernel <ConsoleLog>(k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            }, dict);
            var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
            var serviceProxy    = providerFactory(serviceName);

            string overrideHost = "override-host";


            TracingContext.SetHostOverride(serviceName, overrideHost);

            var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

            for (int i = 0; i < 50; i++)
            {
                var host = (string)await serviceProxy.Invoke(request, typeof(string));

                host.ShouldBe($"{overrideHost}:{defaultPort}");
            }
        }
예제 #9
0
        public async Task ToUpper_MethodCallSucceeds_ResultIsCorrect()
        {
            var expected = "AAAA";
            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(content: $"'{expected}'"));

                return(messageHandler);
            };

            unitTesting.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);

            var actual = await CreateClient().ToUpper("aaaa");

            actual.ShouldBe(expected);
        }
예제 #10
0
        public async Task RequestContextShouldOverridePortAndHost()
        {
            const string serviceName = "DemoService";
            const int    defaultPort = 5555;
            var          dict        = new Dictionary <string, string>
            {
                { $"Discovery.Services.{serviceName}.Source", "Config" },
                { $"Discovery.Services.{serviceName}.Hosts", "host1" },
                { $"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString() }
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k => k.Rebind <IDiscoverySourceLoader>().To <DiscoverySourceLoader>().InSingletonScope(), dict))
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory(serviceName);



                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req => HttpResponseFactory.GetResponse(
                             content: $"'{req.RequestUri.Host}:{req.RequestUri.Port}'"));

                serviceProxy.HttpMessageHandler = messageHandler;
                string overrideHost = "override-host";
                int    overridePort = 5318;

                TracingContext.SetHostOverride(serviceName, overrideHost, overridePort);

                var request = new HttpServiceRequest("testMethod", new Dictionary <string, object>());
                for (int i = 0; i < 50; i++)
                {
                    var host = (string)await serviceProxy.Invoke(request, typeof(string));

                    host.ShouldBe($"{overrideHost}:{overridePort}");
                }
            }
        }
예제 #11
0
        public async Task AllRequestsForSameCallID_SameHostSelected()
        {
            var dict = new Dictionary <string, string> {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "host1,host2" },
                { "Discovery.Services.DemoService.DefaultPort", "5555" }
            };

            var kernel          = new TestingKernel <ConsoleLog>(k => k.Rebind <IDiscoverySourceLoader>().To <DiscoverySourceLoader>().InSingletonScope(), dict);
            var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
            var serviceProxy    = providerFactory("DemoService");



            var messageHandler = new MockHttpMessageHandler();

            messageHandler
            .When("*")
            .Respond(req => HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"));

            serviceProxy.HttpMessageHandler = messageHandler;

            //If we set Request Id we would like always to select same Host
            TracingContext.SetRequestID("dumyId1");
            var request        = new HttpServiceRequest("testMethod", new Dictionary <string, object>());
            var hostOfFirstReq = (string)await serviceProxy.Invoke(request, typeof(string));

            string host;

            for (int i = 0; i < 50; i++)
            {
                host = (string)await serviceProxy.Invoke(request, typeof(string));

                host.ShouldBe(hostOfFirstReq);
            }

            TracingContext.SetRequestID("dumyId2");
            host = (string)await serviceProxy.Invoke(request, typeof(string));

            host.ShouldNotBe(hostOfFirstReq);
        }
예제 #12
0
        public async Task SuccessTest()
        {
            var resMessage = HttpResponseFactory.GetResponse(content: "''");

            var messageHandler = new MockHttpMessageHandler();

            messageHandler.When("*").Respond(resMessage);

            await CreateClient(messageHandler).ToUpper("aaaa");

            var expected = DefaultExpected();

            expected.Counters.Add(new MetricDataEquatable {
                Name = "Success", Unit = Unit.Calls
            });
            expected.Timers.Add(new MetricDataEquatable {
                Name = "Deserialization", Unit = Unit.Calls
            });

            GetMetricsData().AssertEquals(expected);
        }
예제 #13
0
        public async Task NotGigyaServerFailureTest()
        {
            var resMessage = HttpResponseFactory.GetResponse(isGigyaHost: false);

            var messageHandler = new MockHttpMessageHandler();

            messageHandler.When("*").Respond(resMessage);

            try
            {
                await CreateClient(messageHandler).ToUpper("aaaa");
            }
            catch (Exception)
            {
                var expected = DefaultExpected();

                expected.Counters.Add(new MetricDataEquatable {
                    Name = "HostFailure", Unit = Unit.Calls
                });

                GetMetricsData().AssertEquals(expected);
            }
        }
예제 #14
0
        public async Task HttpsDisabled_NoCertificate_CallSucceeds()
        {
            var host            = "host1";
            var httpsPortOffset = 5;
            var port            = DisposablePort.GetPort().Port;
            var dict            = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", host },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() },
                { "Discovery.Services.DemoService.UseHttpsOverride", "false" }
            };

            int  httpsTestCount    = 0;
            bool httpsMethodCalled = false;

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("https://*")
                .Respond(req =>
                         HttpResponseFactory.GetResponseWithException(ExceptionSerializer, new SocketException()));

                messageHandler
                .When("http://*")
                .Respond(req => HttpResponseFactory.GetResponse(content: "'some HTTP response'"));

                return(messageHandler);
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);

                var certificateLocator = Substitute.For <ICertificateLocator>();
                certificateLocator
                .When(cl => cl.GetCertificate(Arg.Any <string>()))
                .Do(x => throw new Exception());
                k.Rebind <ICertificateLocator>().ToConstant(certificateLocator);

                var httpsAuthenticator = Substitute.For <IHttpsAuthenticator>();
                httpsAuthenticator
                .When(a => a.AddHttpMessageHandlerAuthentication(Arg.Any <HttpClientHandler>(), Arg.Any <HttpClientConfiguration>()))
                .Do(x => throw new Exception());
                k.Rebind <IHttpsAuthenticator>().ToConstant(httpsAuthenticator);
            }, dict)
                   )
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;
                TracingContext.SetRequestID("1");

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

                await serviceProxy.Invoke(request, typeof(string));
            }
        }
예제 #15
0
        public async Task HttpsStoppedListening_FallbackToHttp()
        {
            var host            = "host1";
            var httpsPortOffset = 5;
            var port            = DisposablePort.GetPort().Port;
            var dict            = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", host },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() },
                { "Discovery.Services.DemoService.TryHttps", "true" }
            };

            int  httpsTestCount    = 0;
            bool httpsMethodCalled = false;

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("https://*")
                .Respond(req =>
                {
                    if (httpsMethodCalled)
                    {
                        throw new HttpRequestException("", new WebException("", WebExceptionStatus.ProtocolError));
                    }
                    if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/")
                    {
                        httpsTestCount++;
                        return(HttpResponseFactory.GetResponse(content: "'some HTTPS response'"));
                    }

                    if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/DemoService.testMethod")
                    {
                        httpsMethodCalled = true;
                        return(HttpResponseFactory.GetResponse(content: "'some HTTPS response'"));
                    }

                    throw new HttpRequestException("Invalid uri");
                });
                messageHandler
                .When("http://*")
                .Respond(req =>
                {
                    if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod")
                    {
                        return(HttpResponseFactory.GetResponse(content: "'some HTTP response'"));
                    }
                    if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/")
                    {
                        return(HttpResponseFactory.GetResponse(content: "'{X-Gigya-ServerHostname: someValue}'"));
                    }
                    throw new HttpRequestException("Invalid uri");
                });

                return(messageHandler);
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
                var getConfig = k.Get <Func <DiscoveryConfig> >();
                k.Rebind <Func <DiscoveryConfig> >().ToMethod(c =>
                {
                    var config = getConfig();
                    config.UseHttpsOverride = false;

                    return(() => config);
                });
            }, dict)
                   )
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;
                TracingContext.SetRequestID("1");

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

                var server = await serviceProxy.Invoke(request, typeof(string));

                server.ShouldBe("some HTTP response");

                Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds);

                server = await serviceProxy.Invoke(request, typeof(string));

                server.ShouldBe("some HTTPS response");

                server = await serviceProxy.Invoke(request, typeof(string));

                server.ShouldBe("some HTTP response");
            }
        }
예제 #16
0
        public async Task HttpsListening_CallHttpsAfterFirstHttpCall()
        {
            var host            = "host1";
            var httpsPortOffset = 5;
            var port            = DisposablePort.GetPort().Port;
            var dict            = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", host },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() }
            };

            int httpsTestCount = 0;

            Func <bool, string, HttpMessageHandler> messageHandlerFactory = (_, __) =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("https://*")
                .Respond(req =>
                {
                    if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/")
                    {
                        httpsTestCount++;
                        return(HttpResponseFactory.GetResponse(content: "'some HTTPS response'"));
                    }
                    if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/DemoService.testMethod")
                    {
                        return(HttpResponseFactory.GetResponse(content: "'some HTTPS response'"));
                    }
                    throw new HttpRequestException("Invalid uri");
                });
                messageHandler
                .When("http://*")
                .Respond(req =>
                {
                    if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod")
                    {
                        return(HttpResponseFactory.GetResponse(content: "'some HTTP response'"));
                    }
                    throw new HttpRequestException("Invalid uri");
                });

                return(messageHandler);
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <bool, string, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            }, dict)
                   )
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;
                TracingContext.SetRequestID("1");

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

                for (int i = 0; i < 10; i++)
                {
                    bool httpsTestFinished = httpsTestCount > 0;

                    var server = await serviceProxy.Invoke(request, typeof(string));

                    server.ShouldBe(httpsTestFinished ? "some HTTPS response" : "some HTTP response");
                }

                Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds);
            }
        }