public async Task ToUpper_MethodCallFailsWithProgrammaticException_CorrectExceptionIsThrown() { var expected = new ProgrammaticException("You code is invalid.").ThrowAndCatch(); Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ => { var messageHandler = new MockHttpMessageHandler(); messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); return(messageHandler); }; unitTesting.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory); var actual = CreateClient().ToUpper("aaaa").ShouldThrow <RemoteServiceException>(); actual.InnerException.ShouldBeOfType <ProgrammaticException>(); actual.InnerException.Message.ShouldBe(expected.Message); }
public async Task ToUpper_MethodCallFailsWithInvalidJson_CorrectExceptionIsThrown() { string badJson = "not JSON!"; Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ => { var messageHandler = new MockHttpMessageHandler(); messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(HttpStatusCode.InternalServerError, content: badJson)); return(messageHandler); }; unitTesting.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory); var actual = CreateClient().ToUpper("aaaa").ShouldThrow <RemoteServiceException>(); actual.EncryptedTags["responseContent"].ShouldBe(badJson); actual.InnerException.ShouldBeAssignableTo <JsonException>(); }
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 <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope(), dict)) { var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >(); var serviceProxy = providerFactory(serviceName); Uri uri = null; string requestMessage = null; var messageHandler = new MockHttpMessageHandler(); messageHandler .When("*").Respond(async req => { requestMessage = await req.Content.ReadAsStringAsync(); uri = req.RequestUri; return(HttpResponseFactory.GetResponse(HttpStatusCode.Accepted)); }); serviceProxy.HttpMessageHandler = messageHandler; string expectedHost = "override-host"; int expectedPort = 5318; TracingContext.SetHostOverride(serviceName, expectedHost, expectedPort); var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>()); await serviceProxy.Invoke(request, typeof(string)); var body = requestMessage; JsonConvert.DeserializeObject <GigyaRequestProtocol>(body, new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); uri.Host.ShouldBe(expectedHost); uri.Port.ShouldBe(expectedPort); } }
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" } }; using (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); } }
public async Task ToUpper_MethodCallFailsWithRemoteServiceException_CorrectExceptionIsThrown() { var expected = new RemoteServiceException("A service is invalid.", "someUri").ThrowAndCatch(); Func <bool, string, HttpMessageHandler> messageHandlerFactory = (_, __) => { var messageHandler = new MockHttpMessageHandler(); messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); return(messageHandler); }; unitTesting.Rebind <Func <bool, string, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory); var actual = CreateClient().ToUpper("aaaa").ShouldThrow <RemoteServiceException>(); actual.Message.ShouldBe(expected.Message); actual.RequestedUri.ShouldBe(expected.RequestedUri); actual.InnerException.ShouldBeNull(); }
public async Task ToUpper_MethodCallFailsWithCustomerFacingException_CorrectExceptionIsThrown() { var expected = new RequestException("You action is invalid, Mr. Customer.", 30000).ThrowAndCatch(); Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ => { var messageHandler = new MockHttpMessageHandler(); messageHandler.When("*").Respond(req => { return(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); }); return(messageHandler); }; unitTesting.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory); var actual = CreateClient().ToUpper("aaaa").ShouldThrow <RequestException>(); actual.Message.ShouldBe(expected.Message); actual.ErrorCode.ShouldBe(expected.ErrorCode); }
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}"); } } }
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); }
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); } }
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)); } }
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"); } }
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); } }
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>()); using (TracingContext.Tags.SetUnencryptedTag("test", 1)) using (TracingContext.SuppressCaching(CacheSuppress.RecursiveAllDownstreamServices)) 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); } }