예제 #1
0
        public void DeepNestedShouldWork()
        {
            var infraKernel = new TestingKernel <ConsoleLog>(mockConfig: new Dictionary <string, string>  {
                { "FirstLevel.NextLevel.NextLevel.ID", "ID" },
            });

            var extractor = infraKernel.Get <Func <FirstLevel> >();
            var deep      = extractor();

            deep?.NextLevel?.NextLevel?.ID?.ShouldBe("ID");

            infraKernel.Dispose();
        }
예제 #2
0
        public void ShouldThrowOnMissingInt()
        {
            var infraKernel = new TestingKernel <ConsoleLog>(mockConfig: new Dictionary <string, string>
            {
                { "BusSettings.TopicName", "il3-_env_func-infraTest" },
                { "BusSettings.MessageFormat", "Json" }
            });
            var extractor = infraKernel.Get <Func <BusSettings> >();

            Should.Throw <ConfigurationException>(() => extractor());

            infraKernel.Dispose();
        }
예제 #3
0
        public virtual void SetUp()
        {
            var kernel = new TestingKernel<ConsoleLog>();
            _insecureClient = kernel.Get<IDemoService>();
            _exceptionSerializer = kernel.Get<JsonExceptionSerializer>();

            Metric.ShutdownContext("Service");
            TracingContext.SetUpStorage();
            TracingContext.SetRequestID("1");

            _testinghost = new TestingHost<IDemoService>();
            _stopTask = _testinghost.RunAsync();
        }
        public void ShouldThrowOnValidateError()
        {
            var infraKernel = new TestingKernel <ConsoleLog>(mockConfig: new Dictionary <string, string>  {
                { "BusSettings.ConsumerSettings.ConsumerId", "consID" },
            });

            var extractor = infraKernel.Get <Func <BusSettings> >();

            var ex = Should.Throw <ConfigurationException>(() => extractor());

            ex.UnencryptedTags["ValidationErrors"].ShouldNotBeNullOrEmpty();
            infraKernel.Dispose();
        }
예제 #5
0
        public async Task RequestWithException_ShouldNotWrapWithUnhandledException()
        {
            var _kernel = new TestingKernel <ConsoleLog>();
            var _exceptionSerializer = _kernel.Get <JsonExceptionSerializer>();

            _testinghost.Host.Kernel.Get <IDemoService>().When(a => a.DoSomething()).Throw(x => new ArgumentException("MyEx"));
            var request = await GetRequestFor <IDemoService>(p => p.DoSomething());

            var responseJson      = await(await new HttpClient().SendAsync(request)).Content.ReadAsStringAsync();
            var responseException = _exceptionSerializer.Deserialize(responseJson);

            responseException.ShouldBeOfType <ArgumentException>();
        }
예제 #6
0
        public void SetupConsulListener()
        {
            _consulSimulator = new ConsulSimulator(ConsulPort);
            _testingKernel   = new TestingKernel <ConsoleLog>(k =>
            {
                _environment = Substitute.For <IEnvironment>();
                _environment.ConsulAddress.Returns($"{CurrentApplicationInfo.HostName}:{ConsulPort}");
                _environment.Zone.Returns(Zone);
                k.Rebind <IEnvironment>().ToMethod(_ => _environment);

                k.Rebind <Func <ConsulConfig> >().ToMethod(_ => () => _consulConfig);
            });
        }
예제 #7
0
        public async Task AllHostsAreHavingNetworkErrorsShouldTryEachOnce()
        {
            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() }
            };

            int counter = 0;
            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req =>
                {
                    bool disableReachabilityChecker = req.Content == null;
                    if (disableReachabilityChecker)
                    {
                        throw new HttpRequestException();
                    }

                    counter++;
                    throw new HttpRequestException();
                });

                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;

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

                Func <Task> act = () => serviceProxy.Invoke(request, typeof(string));
                await act.ShouldThrowAsync <ServiceUnreachableException>();

                counter.ShouldBe(2);
            }
        }
예제 #8
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() }
            };

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

                TracingContext.SetRequestID("g");

                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 = 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);
            }
        }
예제 #9
0
        public async Task RequestContextOverrideShouldFailOnFirstAttempt()
        {
            var port = DisposablePort.GetPort().Port;
            var dict = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "notImpotent" },
                { "Discovery.Services.DemoService.DefaultPort", port.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("DemoService");
                serviceProxy.DefaultPort = port;

                //Disable  TracingContext.SetRequestID("1");

                CallContext.FreeNamedDataSlot("#ORL_RC");

                int counter        = 0;
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req =>
                {
                    counter++;

                    throw new HttpRequestException();
                });


                string overrideHost = "override-host";
                int    overridePort = 5318;
                TracingContext.SetHostOverride("DemoService", overrideHost, overridePort);
                serviceProxy.HttpMessageHandler = messageHandler;

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

                for (int i = 0; i < 3; i++)
                {
                    Func <Task> act = () => serviceProxy.Invoke(request, typeof(string));

                    await act.ShouldThrowAsync <HttpRequestException>();
                }
                counter.ShouldBe(3);
            }
        }
예제 #10
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}");
            }
        }
예제 #11
0
        public void SetupKernel()
        {
            _kernel = new TestingKernel <ConsoleLog>(k =>
            {
                RebindKernelToSetCreatedNodeSourceBeforeCreatingIt <LocalNodeSource>(k);
                RebindKernelToSetCreatedNodeSourceBeforeCreatingIt <ConfigNodeSource>(k);

                k.Rebind <INodeSourceFactory>().ToMethod(c => _consulNodeSourceFactory);
                k.Bind <INodeSourceFactory>().ToMethod(c => _slowNodeSourceFactory);
                k.Rebind <Func <DiscoveryConfig> >().ToMethod(c => () => _discoveryConfig);
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InTransientScope(); // get a different instance for each test
                k.Rebind <IDateTime>().ToMethod(_ => _dateTimeFake);
            });
        }
예제 #12
0
 public void SetUp()
 {
     try
     {
         Environment.SetEnvironmentVariable("GIGYA_CONFIG_ROOT", AppDomain.CurrentDomain.BaseDirectory, EnvironmentVariableTarget.Process);
         kernel         = new TestingKernel <ConsoleLog>();
         ResolutionRoot = kernel;
     }
     catch (Exception ex)
     {
         Console.Write(ex);
         throw;
     }
 }
예제 #13
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);
            }
        }
예제 #14
0
        public async Task FailedHostShouldBeRemovedFromHostList()
        {
            var dict = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "local" },
                { "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");

                //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++;

                    throw new HttpRequestException();
                });


                serviceProxy.HttpMessageHandler = messageHandler;

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

                for (int i = 0; i < 10; i++)
                {
                    Func <Task> act = () => serviceProxy.Invoke(request, typeof(string));

                    await act.ShouldThrowAsync <MissingHostException>();
                }
                counter.ShouldBe(2);
            }
        }
예제 #15
0
        public async Task RequestWithException_ShouldNotWrap(Type exceptionType)
        {
            var _kernel = new TestingKernel <ConsoleLog>();
            var _exceptionSerializer = _kernel.Get <JsonExceptionSerializer>();

            _testinghost.Host.Instance.When(a => a.DoSomething()).Throw(i => (Exception)Activator.CreateInstance(exceptionType, "MyEx", null, null, null));

            var request = await GetRequestFor <IDemoService>(p => p.DoSomething());

            var responseJson      = await(await new HttpClient().SendAsync(request)).Content.ReadAsStringAsync();
            var responseException = _exceptionSerializer.Deserialize(responseJson);

            responseException.ShouldBeOfType(exceptionType);
        }
예제 #16
0
        public void CanReadWithReplacingPrefix()
        {
            var infraKernel = new TestingKernel <ConsoleLog>(mockConfig: new Dictionary <string, string>
            {
                { "Prefix1.Prefix2.GatorConfig.Name", "infraTest" },
            });
            var extractor = infraKernel.Get <Func <Gator> >();

            var busSettings = extractor();

            busSettings.ShouldNotBeNull();
            busSettings.Name.ShouldBe("infraTest");

            infraKernel.Dispose();
        }
예제 #17
0
        public async Task CanReplaceServiceProxy()
        {
            var kernel = new TestingKernel <ConsoleLog>(k =>
            {
                var demoService = Substitute.For <IDemoService>();
                demoService.IncrementInt(Arg.Any <int>()).Returns(100);
                k.Rebind <IDemoService>().ToConstant(demoService);
                var serviceProxy = Substitute.For <IServiceProxyProvider <IDemoService> >();
                serviceProxy.Client.Returns(demoService);
                k.Rebind <IServiceProxyProvider <IDemoService> >().ToConstant(serviceProxy);
            });
            var useServiceWithNoCache = kernel.Get <UseServiceWithNoCache>();

            (await useServiceWithNoCache.DemoService.IncrementInt(1)).Should().Be(100);
        }
예제 #18
0
        public void SetupConsulListener()
        {
            _consulSimulator = new ConsulSimulator(ConsulPort);

            _testingKernel = new TestingKernel <ConsoleLog>(k =>
            {
                _environmentVariableProvider = Substitute.For <IEnvironmentVariableProvider>();
                _environmentVariableProvider.ConsulAddress.Returns($"{CurrentApplicationInfo.HostName}:{ConsulPort}");
                _environmentVariableProvider.DataCenter.Returns(DataCenter);
                k.Rebind <IEnvironmentVariableProvider>().ToMethod(_ => _environmentVariableProvider);

                k.Rebind <IDateTime>().ToMethod(_ => _dateTimeFake);

                k.Rebind <Func <ConsulConfig> >().ToMethod(_ => () => _consulConfig);
            });
        }
        public void Setup()
        {
            _unitTestingKernel = new TestingKernel <ConsoleLog>();

            _dateTimeFake = new DateTimeFake {
                UtcNow = new DateTime(2016, 11, 11)
            };
            Kernel.Rebind <IDateTime>().ToConstant(_dateTimeFake);

            var environmentVarialbesMock = Substitute.For <IEnvironmentVariableProvider>();

            environmentVarialbesMock.DeploymentEnvironment.Returns(ENV);
            Kernel.Rebind <IEnvironmentVariableProvider>().ToConstant(environmentVarialbesMock);

            SetupConsulClientAdapter();
        }
예제 #20
0
        public async Task ShouldCallSelfHostServcie()
        {
            NonOrleansServiceTester <CalculatorServiceHost> serviceTester = null;
            var testingKernel = new TestingKernel <TraceLog>();

            try
            {
                serviceTester = testingKernel.GetServiceTesterForNonOrleansService <CalculatorServiceHost>(1111, TimeSpan.FromSeconds(10));
                (await serviceTester.GetServiceProxy <ICalculatorService>().Add(1, 2)).ShouldBe(3);
            }
            finally
            {
                serviceTester?.Dispose();
                testingKernel.Dispose();
            }
        }
예제 #21
0
        public async Task CallWeakRequestWith_NoParamsAndNoReturnTypeAndNoType()
        {
            var ukernel = new TestingKernel <ConsoleLog>();

            var providerFactory = ukernel.Get <Func <string, ServiceProxyProvider> >();
            var serviceProxy    = providerFactory("CalculatorService");
            var dict            = new Dictionary <string, object>();

            serviceProxy.DefaultPort = 6555;

            var res = await serviceProxy.Invoke(new HttpServiceRequest("Do", dict), typeof(JObject));

            var json = (JToken)res;

            json.ShouldBe(null);
        }
예제 #22
0
        public async Task CallWeakRequestWith_Int_ParamAndNoReturnType()
        {
            var ukernel = new TestingKernel <ConsoleLog>();

            var providerFactory = ukernel.Get <Func <string, ServiceProxyProvider> >();
            var serviceProxy    = providerFactory("CalculatorService");
            var dict            = new Dictionary <string, object> {
                { "a", "5" }
            };

            serviceProxy.DefaultPort = 6555;

            var res = await serviceProxy.Invoke(new HttpServiceRequest("DoInt", typeof(ICalculatorService).FullName, dict), typeof(JObject));

            ((JToken)res).Value <int>().ShouldBe(5);
        }
예제 #23
0
        public void SetUp()
        {
            var unitTesting = new TestingKernel <ConsoleLog>(k =>
                                                             k.Rebind <Func <StackTraceEnhancerSettings> >().ToConstant <Func <StackTraceEnhancerSettings> >(() => new StackTraceEnhancerSettings
            {
                RegexReplacements = new Dictionary <string, RegexReplace>
                {
                    ["TidyAsyncLocalFunctionNames"] = new RegexReplace
                    {
                        Pattern     = @"\.<>c__DisplayClass(?:\d+)_(?:\d+)(?:`\d)?\.<<(\w+)>g__(\w+)\|?\d>d.MoveNext\(\)",
                        Replacement = @".$1.$2(async)"
                    }
                }
            })
                                                             );

            ExceptionSerializer = unitTesting.Get <JsonExceptionSerializer>();
        }
        private async Task <HttpRequestMessage> GetRequestFor <T>(Func <T, Task> action)
        {
            HttpRequestMessage request        = null;
            string             requestContent = null;
            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var mockHandler = new MockHttpMessageHandler();
                mockHandler.When("*").Respond(async r =>
                {
                    if (r.Method != HttpMethod.Get)
                    {
                        request        = r;
                        requestContent = await r.Content.ReadAsStringAsync();
                    }

                    return(HttpResponseFactory.GetResponse(content: "''"));
                });

                return(mockHandler);
            };
            var kernel = new TestingKernel <ConsoleLog>();

            kernel.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            var client = kernel.Get <ServiceProxyProviderSpy <T> >();

            client.DefaultPort = _testinghost.BasePort;

            await action(client.Client);

            var contentClone = new StringContent(requestContent, Encoding.UTF8, "application/json");

            foreach (KeyValuePair <string, IEnumerable <string> > header in request.Content.Headers.Where(h =>
                                                                                                          h.Key.StartsWith("X")))
            {
                contentClone.Headers.Add(header.Key, header.Value);
            }

            kernel.Dispose();

            return(new HttpRequestMessage(request.Method, request.RequestUri)
            {
                Content = contentClone
            });
        }
        public async Task Setup()
        {
            _configDic         = new Dictionary <string, string>();
            _unitTestingKernel = new TestingKernel <ConsoleLog>(k =>
            {
                k.Rebind <IDiscoverySourceLoader>().To <DiscoverySourceLoader>().InSingletonScope();
                k.Rebind <IEnvironment>().ToConstant(new HostEnvironment(new TestHostEnvironmentSource()));
                _consulClientMock = new ConsulClientMock();
                _consulClientMock.SetResult(new EndPointsResult {
                    EndPoints = new[] { new ConsulEndPoint {
                                            HostName = "dumy", Version = ServiceVersion
                                        } }, ActiveVersion = ServiceVersion, IsQueryDefined = true
                });
                k.Rebind <Func <string, IConsulClient> >().ToMethod(c => s => _consulClientMock);
            }, _configDic);

            _configRefresh    = _unitTestingKernel.Get <ManualConfigurationEvents>();
            _serviceDiscovery = _unitTestingKernel.Get <Func <string, ReachabilityChecker, ServiceDiscovery.ServiceDiscovery> >()("ServiceName", x => Task.FromResult(true));
        }
예제 #26
0
 public void SetUp()
 {
     try
     {
         Environment.SetEnvironmentVariable("GIGYA_CONFIG_ROOT", AppDomain.CurrentDomain.BaseDirectory, EnvironmentVariableTarget.Process);
         kernel = new TestingKernel <ConsoleLog>((kernel) =>
         {
             var revokingManager = new FakeRevokingManager();
             kernel.Rebind <IRevokeListener>().ToConstant(revokingManager);
             kernel.Rebind <ICacheRevoker>().ToConstant(revokingManager);
         });
         ResolutionRoot = kernel;
     }
     catch (Exception ex)
     {
         Console.Write(ex);
         throw;
     }
 }
예제 #27
0
        public async Task AllHostsAreHavingNetworkErrorsShouldTryEachTwice()
        {
            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");

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

                    counter++;
                    //HttpRequestException
                    throw new HttpRequestException();
                });

                serviceProxy.HttpMessageHandler = messageHandler;

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

                Func <Task> act = () => serviceProxy.Invoke(request, typeof(string));
                await act.ShouldThrowAsync <MissingHostException>();

                counter.ShouldBe(4);
            }
        }
        public async Task Setup()
        {
            _configDic         = new Dictionary <string, string>();
            _unitTestingKernel = new TestingKernel <ConsoleLog>(k =>
            {
                k.Rebind <IDiscoverySourceLoader>().To <DiscoverySourceLoader>().InSingletonScope();
                k.Rebind <IEnvironmentVariableProvider>().To <EnvironmentVariableProvider>();
                _consulAdapterMock = Substitute.For <IConsulClient>();
                _consulAdapterMock.GetEndPoints(Arg.Any <string>()).Returns(Task.FromResult(new EndPointsResult {
                    EndPoints = new[] { new ConsulEndPoint {
                                            HostName = "dumy"
                                        } }
                }));
                k.Rebind <IConsulClient>().ToConstant(_consulAdapterMock);
            }, _configDic);

            _configRefresh    = _unitTestingKernel.Get <ManualConfigurationEvents>();
            _serviceDiscovery = _unitTestingKernel.Get <Func <string, ReachabilityChecker, ServiceDiscovery.ServiceDiscovery> >()("ServiceName", x => Task.FromResult(true));
        }
예제 #29
0
        public void Test_GetConfigObject()
        {
            var infraKernel = new TestingKernel <ConsoleLog>(mockConfig: new Dictionary <string, string>
            {
                { "BusSettings.TopicName", "il3-_env_func-infraTest" },
                { "BusSettings.MessageFormatNullable", "Json" },
                { "BusSettings.RequestTimeoutInMs", "30000" },
                { "BusSettings.RequestTimeoutInMsNullable", "30000" },
                { "BusSettings.MessageFormat", "Json" },
                { "BusSettings.Date", "2016/11/08" },
                { "BusSettings.DateTime", "2016-11-08 15:57:20" },
            });

            var kafkaSettings = infraKernel.Get <SomeGrain>();

            kafkaSettings.DoWork();

            infraKernel.Dispose();
        }
예제 #30
0
        public async Task Setup()
        {
            _consulSimulator.Reset();
            _testingKernel = new TestingKernel <ConsoleLog>(k =>
            {
                _environment = Substitute.For <IEnvironment>();
                _environment.ConsulAddress.Returns($"{CurrentApplicationInfo.HostName}:{ConsulPort}");
                _environment.Zone.Returns(Zone);
                k.Rebind <IEnvironment>().ToMethod(_ => _environment);
                k.Rebind <Func <ConsulConfig> >().ToMethod(_ => () => _consulConfig);
                k.Rebind <ConsulNodeSourceFactory>().ToSelf().InTransientScope();
            });
            _serviceName = $"MyService_{Guid.NewGuid().ToString().Substring(5)}";

            _deploymentIdentifier = new DeploymentIdentifier(_serviceName, "prod", Substitute.For <IEnvironment>());
            _consulConfig         = new ConsulConfig {
                ErrorRetryInterval = TimeSpan.FromMilliseconds(10)
            };
            _consulNodeSourceFactory = _testingKernel.Get <ConsulNodeSourceFactory>();
        }