public void TestInitializer()
        {
            // initialize fake context
            _fakeContext = InitializeFakeContext<FacilitiesController>();

            // explicitly create fake dependencies that need to be intercepted
            //  (all other fake dependencies will be implicitly created by _fakeContext.Resolve<>)
            _fakeBusinessFacade = A.Fake<IBusinessFacade>();
            _fakeLoadedSubscriber = A.Fake<ILoadedSubscriber>();
            _fakeCurrentLocation = A.Fake<ILoadedLocation>();
            _fakeCurrentUser = A.Fake<ILoggedInUser>();
            _fakePermissions = A.Fake<IPermissions>();

            // provide fake dependencies to context
            _fakeContext.Provide(_fakeBusinessFacade);
            _fakeContext.Provide(_fakeLoadedSubscriber);
            _fakeContext.Provide(_fakeCurrentLocation);
            _fakeContext.Provide(_fakeCurrentUser);
            _fakeContext.Provide(_fakePermissions);

            // create system-under-test instance
            _facilitiesControllerForTest = _fakeContext.Resolve<FacilitiesController>();

            // create fake data
            _usiForTest = TestDataRepository.GetUsiForTest();
            _locationIdForTest = TestDataRepository.GetLocationIdForTest();
            _serviceAddressControlNumberForTests = TestDataRepository.GetServiceAddressControlNumberForTest();
            _dpiRegionForTests = TestDataRepository.GetDpiRegionForTest();
        }
        public void CallInfo40000TimesOnMultipleThreads()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //set up connection configuration that holds a connection pool
                //with '_uris' (see the constructor)
                fake.Provide<IConnectionConfigurationValues>(_config);
                //we want to use our special concurrencytestconnection
                //this randonly throws on any node but 9200 and sniffing will represent a different
                //view of the cluster each time but always holding node 9200
                fake.Provide<IConnection>(new ConcurrencyTestConnection(this._config));
                //prove a real Transport with its unspecified dependencies
                //as fakes
                FakeCalls.ProvideDefaultTransport(fake);

                //create a real ElasticsearchClient with it unspecified dependencies as fakes
                var client = fake.Resolve<ElasticsearchClient>();
                int seen = 0;

                //We'll call Info() 10.000 times on 4 threads
                //This should not throw any exceptions even if connections sometime fail at a node level
                //because node 9200 is always up and running
                Assert.DoesNotThrow(()=>
                {
                    Action a = () =>
                    {
                        for(var i=0;i<10000;i++)
                        {
                            client.Info<VoidResponse>();
                            Interlocked.Increment(ref seen);
                        }
                    };
                    var thread1 = new Thread(()=>a());
                    var thread2 = new Thread(()=>a());
                    var thread3 = new Thread(()=>a());
                    var thread4 = new Thread(()=>a());
                    thread1.Start();
                    thread2.Start();
                    thread3.Start();
                    thread4.Start();
                    thread1.Join();
                    thread2.Join();
                    thread3.Join();
                    thread4.Join();

                });

                //we should have seen 40.000 increments
                //Sadly we can't use FakeItEasy's to ensure get is called 40.000 times
                //because it internally uses fixed arrays that will overflow :)
                seen.Should().Be(40000);
            }
        }
        public void ServerExceptionIsCaught_KeepResponse(int status, string exceptionType, string exceptionMessage)
        {
            var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                var connectionConfiguration = new ConnectionConfiguration()
                    .ExposeRawResponse(true);

                fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
                FakeCalls.ProvideDefaultTransport(fake);

                var getCall = FakeCalls.GetSyncCall(fake);
                getCall.Returns(FakeResponse.Bad(connectionConfiguration, response: response));

                var client = fake.Resolve<ElasticsearchClient>();

                var result = client.Info();
                result.Success.Should().BeFalse();
                AssertServerErrorsOnResponse(result, status, exceptionType, exceptionMessage);

                result.ResponseRaw.Should().NotBeNull();

                getCall.MustHaveHappened(Repeated.Exactly.Once);

            }
        }
		private ITransport ProvideTransport(AutoFake fake)
		{
			var dateTimeParam = new TypedParameter(typeof(IDateTimeProvider), null);
			var memoryStreamParam = new TypedParameter(typeof(IMemoryStreamProvider), null);
			var serializerParam = new TypedParameter(typeof(IElasticsearchSerializer), null);
			return fake.Provide<ITransport, Transport>(dateTimeParam, serializerParam, memoryStreamParam);
		}
		public void IfResponseIsKnowError_DoNotRetry_ThrowServerException_Async(int status, string exceptionType, string exceptionMessage)
		{
			var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				var connectionPool = new StaticConnectionPool(new[]
				{
					new Uri("http://localhost:9200"),
					new Uri("http://localhost:9201"),
				});
				var connectionConfiguration = new ConnectionConfiguration(connectionPool)
					.ThrowOnElasticsearchServerExceptions()
					.ExposeRawResponse(false);

				fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
				FakeCalls.ProvideDefaultTransport(fake);

				var pingCall = FakeCalls.PingAtConnectionLevelAsync(fake);
				pingCall.Returns(FakeResponse.OkAsync(connectionConfiguration));

				var getCall = FakeCalls.GetCall(fake);
				getCall.Returns(FakeResponse.AnyAsync(connectionConfiguration, status, response: response));

				var client = fake.Resolve<ElasticsearchClient>();

				var e = Assert.Throws<ElasticsearchServerException>(async ()=>await client.InfoAsync());
				AssertServerErrorsOnResponse(e, status, exceptionType, exceptionMessage);

				//make sure a know ElasticsearchServerException does not cause a retry
				//In this case we want to fail early

				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
Ejemplo n.º 6
0
		public async void ThrowsOutOfNodesException_AndRetriesTheSpecifiedTimes_Async()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				this.ProvideTransport(fake);
				var getCall = A.CallTo(() => fake.Resolve<IConnection>().Get(A<Uri>._));
				Func<ElasticsearchResponse> badTask = () => { throw new Exception(); };
				var t = new Task<ElasticsearchResponse>(badTask);
				t.Start();
				getCall.Returns(t);
				
				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().Be(_retries);
				try
				{
					var result = await client.InfoAsync();
				}
				catch (Exception e)
				{
					Assert.AreEqual(e.GetType(), typeof(OutOfNodesException));
				}
				getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));

			}
		}
Ejemplo n.º 7
0
		public async void ThrowsOutOfNodesException_AndRetriesTheSpecifiedTimes_Async()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake); 

				//return a started task that throws
				Func<ElasticsearchResponse<Dictionary<string, object>>> badTask = () => { throw new Exception(); };
				var t = new Task<ElasticsearchResponse<Dictionary<string, object>>>(badTask);
				t.Start();
				getCall.Returns(t);
				
				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().Be(_retries);
				try
				{
					var result = await client.InfoAsync();
				}
				catch (AggregateException ae)
				{
					Assert.AreEqual(typeof(MaxRetryException), ae.InnerException.GetType());
				}
				catch (Exception e)
				{
					Assert.AreEqual(typeof(MaxRetryException), e.GetType());
				}
				getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));

			}
		}
Ejemplo n.º 8
0
        public void CallInfo40000TimesOnMultipleThreads()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //set up connection configuration that holds a connection pool
                //with '_uris' (see the constructor)
                fake.Provide<IConnectionConfigurationValues>(_config);
                //prove a real HttpTransport with its unspecified dependencies
                //as fakes

                var connection = fake.Provide<IConnection>(new ConcurrencyTestConnection(this._config));
                this.ProvideTransport(fake);
                //create a real ElasticsearchClient with it unspecified dependencies as fakes
                var client = fake.Resolve<ElasticsearchClient>();
                int seen = 0;
                Assert.DoesNotThrow(()=>
                {
                    Action a = () =>
                    {
                        for(var i=0;i<10000;i++)
                        {
                            client.Info();
                            Interlocked.Increment(ref seen);
                        }
                    };
                    var thread1 = new Thread(()=>a());
                    var thread2 = new Thread(()=>a());
                    var thread3 = new Thread(()=>a());
                    var thread4 = new Thread(()=>a());
                    thread1.Start();
                    thread2.Start();
                    thread3.Start();
                    thread4.Start();
                    thread1.Join();
                    thread2.Join();
                    thread3.Join();
                    thread4.Join();

                });
                seen.Should().Be(40000);
            }
        }
		public void SniffCalledOnceAndEachEnpointPingedOnce()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				//It's recommended to only have on instance of your connection pool
				//Be sure to register it as Singleton in your IOC
				var uris = new[] { new Uri("http://localhost:9200"), new Uri("http://localhost:9201") };
				var connectionPool = new SniffingConnectionPool(uris);
				var config = new ConnectionConfiguration(connectionPool)
					.SniffOnStartup();
				fake.Provide<IConnectionConfigurationValues>(config);

				var pingCall = FakeCalls.PingAtConnectionLevel(fake);
				pingCall.Returns(FakeResponse.Ok(config));
				var sniffCall = FakeCalls.Sniff(fake, config, uris);
				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Returns(FakeResponse.Ok(config));

				var transport1 = FakeCalls.ProvideRealTranportInstance(fake);
				var transport2 = FakeCalls.ProvideRealTranportInstance(fake);
				var transport3 = FakeCalls.ProvideRealTranportInstance(fake);
				var transport4 = FakeCalls.ProvideRealTranportInstance(fake);

				transport1.Should().NotBe(transport2);

				var client1 = new ElasticsearchClient(config, transport: transport1);
				client1.Info();
				client1.Info();
				client1.Info();
				client1.Info();
				var client2 = new ElasticsearchClient(config, transport: transport2); 
				client2.Info();
				client2.Info();
				client2.Info();
				client2.Info();
				var client3 = new ElasticsearchClient(config, transport: transport3); 
				client3.Info();
				client3.Info();
				client3.Info();
				client3.Info();
				var client4 = new ElasticsearchClient(config, transport: transport4); 
				client4.Info();
				client4.Info();
				client4.Info();
				client4.Info();

				sniffCall.MustHaveHappened(Repeated.Exactly.Once);
				//sniff validates first node, one new node should be pinged before usage.
				pingCall.MustHaveHappened(Repeated.Exactly.Once);
			}
		}
		public void ShouldNotRetryOn500()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);

				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Returns(FakeResponse.Any(_connectionConfig, 500));

				var client = fake.Resolve<ElasticsearchClient>();

				Assert.DoesNotThrow(() => client.Info());
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
Ejemplo n.º 11
0
        public void ThrowsException()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
                FakeCalls.ProvideDefaultTransport(fake);

                var getCall = FakeCalls.GetSyncCall(fake);
                getCall.Throws<Exception>();

                var client = fake.Resolve<ElasticsearchClient>();

                Assert.Throws<Exception>(() => client.Info());
                getCall.MustHaveHappened(Repeated.Exactly.Once);

            }
        }
		public async void ShouldNotRetryOn400_Async()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);

				var getCall = FakeCalls.GetCall(fake);
				var task = Task.FromResult(FakeResponse.Any(_connectionConfig, 400));
				getCall.Returns(task);

				var client = fake.Resolve<ElasticsearchClient>();

				var result = await client.InfoAsync();
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
		private void Call(int status, string exceptionType, string exceptionMessage, AutoFake fake, MemoryStream response, bool exposeRawResponse = false)
		{
			var connectionConfiguration = new ConnectionConfiguration()
				.ThrowOnElasticsearchServerExceptions()
				.ExposeRawResponse(exposeRawResponse);

			fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
			FakeCalls.ProvideDefaultTransport(fake);

			var getCall = FakeCalls.GetSyncCall(fake);
			getCall.Returns(FakeResponse.Bad(connectionConfiguration, response: response));

			var client = fake.Resolve<ElasticsearchClient>();
			
			var e = Assert.Throws<ElasticsearchServerException>(()=>client.Info());
			AssertServerErrorsException(e, status, exceptionType, exceptionMessage);
			getCall.MustHaveHappened(Repeated.Exactly.Once);
		}
		public void ShouldNotRetryWhenMaxRetriesIs0_Async()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				var connectionConfiguration = new ConnectionConfiguration().MaximumRetries(0);
				fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
				FakeCalls.ProvideDefaultTransport(fake);

				var getCall = FakeCalls.GetCall(fake);
				getCall.Returns(FakeResponse.Bad(connectionConfiguration));

				var client = fake.Resolve<ElasticsearchClient>();

				Assert.DoesNotThrow(async () => await client.InfoAsync());
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
Ejemplo n.º 15
0
		public void ThrowsOutOfNodesException_AndRetriesTheSpecifiedTimes()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				this.ProvideTransport(fake);
				var getCall = A.CallTo(() => fake.Resolve<IConnection>().GetSync(A<Uri>._));
				getCall.Throws<Exception>();
				
				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().Be(_retries);

				Assert.Throws<OutOfNodesException>(()=> client.Info());
				getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));

			}
		}
Ejemplo n.º 16
0
		public void ThrowsMaxRetryException_AndRetriesTheSpecifiedTimes_HardIConnectionException_Async()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake);

				//return a started task that throws
				getCall.Throws<Exception>();

				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().Be(_retries);

				Assert.Throws<MaxRetryException>(async () => await client.InfoAsync());
				getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));
			}
		}
		public void OnConnectionException_WithoutPooling_Retires()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);

				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Throws((o)=> new Exception("inner"));

				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().NotHaveValue();

				var e = Assert.Throws<Exception>(() => client.Info());
				e.Message.Should().Be("inner");
				getCall.MustHaveHappened(Repeated.Exactly.Once);
			}
		}
		private ElasticsearchResponse<DynamicDictionary> Call(int status, string exceptionType, string exceptionMessage, AutoFake fake, MemoryStream response, bool exposeRawResponse = false)
		{
			var connectionConfiguration = new ConnectionConfiguration()
				.ExposeRawResponse(exposeRawResponse);

			fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
			FakeCalls.ProvideDefaultTransport(fake);

			var getCall = FakeCalls.GetSyncCall(fake);
			getCall.Returns(FakeResponse.Bad(connectionConfiguration, response: response));

			var client = fake.Resolve<ElasticsearchClient>();

			var result = client.Info();
			result.Success.Should().BeFalse();
			AssertServerErrorsOnResponse(result, status, exceptionType, exceptionMessage);
			getCall.MustHaveHappened(Repeated.Exactly.Once);
			return result;
		}
		public void SniffIsCalledAfterItHasGoneOutOfDate()
		{
			using (var fake = new AutoFake())
			{
				var dateTimeProvider = fake.Resolve<IDateTimeProvider>();
				var nowCall = A.CallTo(()=>dateTimeProvider.Now());
				nowCall.ReturnsNextFromSequence(
					DateTime.UtcNow, //initial sniff time (set even if not sniff_on_startup
					DateTime.UtcNow, //info call 1
					DateTime.UtcNow, //info call 2
					DateTime.UtcNow.AddMinutes(10), //info call 3
					DateTime.UtcNow.AddMinutes(10), //set now after sniff 3
					DateTime.UtcNow.AddMinutes(20), //info call 4
					DateTime.UtcNow.AddMinutes(20), //set now after sniff 4
					DateTime.UtcNow.AddMinutes(22) //info call 5
				);
				var uris = new[] { new Uri("http://localhost:9200") };
				var connectionPool = new SniffingConnectionPool(uris);
				var config = new ConnectionConfiguration(connectionPool)
					.SniffLifeSpan(TimeSpan.FromMinutes(4));
				fake.Provide<IConnectionConfigurationValues>(config);
				var transport = FakeCalls.ProvideDefaultTransport(fake, dateTimeProvider);
				var connection = fake.Resolve<IConnection>();
				var sniffCall = FakeCalls.Sniff(fake, config, uris);
				
				var pingCall = FakeCalls.PingAtConnectionLevel(fake);
				pingCall.Returns(FakeResponse.Ok(config));

				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Returns(FakeResponse.Ok(config));

				var client1 = fake.Resolve<ElasticsearchClient>();
				var result = client1.Info(); //info call 1
				result = client1.Info(); //info call 2
				result = client1.Info(); //info call 3
				result = client1.Info(); //info call 4
				result = client1.Info(); //info call 5

				sniffCall.MustHaveHappened(Repeated.Exactly.Twice);
				nowCall.MustHaveHappened(Repeated.Exactly.Times(8));
			}
		}
Ejemplo n.º 20
0
		public void Hard_IConnectionException_AsyncCall_WithoutPooling_DoesNot_Retry_AndRethrows()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake);

				//return a started task that throws
				getCall.Throws((o)=> new Exception("inner"));

				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().Be(_retries);

				var e = Assert.Throws<Exception>(async () => await client.InfoAsync());
				e.Message.Should().Be("inner");
				getCall.MustHaveHappened(Repeated.Exactly.Once);
			}
		}
Ejemplo n.º 21
0
		public void ThrowsException_Async()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake);

				//return a started task that throws
				Func<ElasticsearchResponse<Stream>> badTask = () => { throw new Exception(); };
				var t = new Task<ElasticsearchResponse<Stream>>(badTask);
				t.Start();
				getCall.Returns(t);

				var client = fake.Resolve<ElasticsearchClient>();

				Assert.Throws<Exception>(async () => await client.InfoAsync());
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
Ejemplo n.º 22
0
        public void StopsForHelp(string command)
        {
            AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider());
            var builder = AutoFake.Resolve <CommandLineBuilder>();

            builder
            .AddCommand <Cmd>("cmd1");
            builder
            .AddCommand <Cmd>("cmd2");
            builder
            .AddCommand <Cmd>("cmd3");
            builder
            .AddCommand <Cmd>("cmd4");
            builder
            .AddCommand <Cmd>("cmd5");

            var response = builder
                           .Build(typeof(CommandLineBuilderTests).GetTypeInfo().Assembly);
            var result = response.Execute(AutoFake.Resolve <IServiceProvider>(), command.Split(' '));

            result.Should().BeGreaterOrEqualTo(0);
        }
Ejemplo n.º 23
0
        public void SniffOnStartupCallsSniffOnlyOnce()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //It's recommended to only have on instance of your connection pool
                //Be sure to register it as Singleton in your IOC
                var uris           = new[] { new Uri("http://localhost:9200") };
                var connectionPool = new SniffingConnectionPool(uris);
                var config         = new ConnectionConfiguration(connectionPool)
                                     .DisablePing()
                                     .SniffOnStartup();
                fake.Provide <IConnectionConfigurationValues>(config);
                var sniffCall = FakeCalls.Sniff(fake, config, uris);
                var transport = FakeCalls.ProvideDefaultTransport(fake);
                var client1   = new ElasticsearchClient(config, transport: transport);
                var client2   = new ElasticsearchClient(config, transport: transport);
                var client3   = new ElasticsearchClient(config, transport: transport);
                var client4   = new ElasticsearchClient(config, transport: transport);

                sniffCall.MustHaveHappened(Repeated.Exactly.Once);
            }
        }
Ejemplo n.º 24
0
        public void SniffIsCalledAfterItHasGoneOutOfDate()
        {
            using (var fake = new AutoFake())
            {
                var dateTimeProvider = fake.Resolve <IDateTimeProvider>();
                var nowCall          = A.CallTo(() => dateTimeProvider.Now());
                nowCall.ReturnsNextFromSequence(
                    DateTime.UtcNow,                     //initial sniff time (set even if not sniff_on_startup
                    DateTime.UtcNow,                     //info call 1
                    DateTime.UtcNow,                     //info call 2
                    DateTime.UtcNow.AddMinutes(10),      //info call 3
                    DateTime.UtcNow.AddMinutes(10),      //set now after sniff 3
                    DateTime.UtcNow.AddMinutes(20),      //info call 4
                    DateTime.UtcNow.AddMinutes(20),      //set now after sniff 4
                    DateTime.UtcNow.AddMinutes(22)       //info call 5
                    );
                var uris           = new[] { new Uri("http://localhost:9200") };
                var connectionPool = new SniffingConnectionPool(uris);
                var config         = new ConnectionConfiguration(connectionPool)
                                     .SniffLifeSpan(TimeSpan.FromMinutes(4));
                fake.Provide <IConnectionConfigurationValues>(config);
                var transport  = FakeCalls.ProvideDefaultTransport(fake, dateTimeProvider);
                var connection = fake.Resolve <IConnection>();
                var sniffCall  = FakeCalls.Sniff(fake, config, uris);

                var getCall = FakeCalls.GetSyncCall(fake);
                getCall.Returns(FakeResponse.Ok(config));

                var client1 = fake.Resolve <ElasticsearchClient>();
                client1.Info();                 //info call 1
                client1.Info();                 //info call 2
                client1.Info();                 //info call 3
                client1.Info();                 //info call 4
                client1.Info();                 //info call 5

                sniffCall.MustHaveHappened(Repeated.Exactly.Twice);
                nowCall.MustHaveHappened(Repeated.Exactly.Times(8));
            }
        }
Ejemplo n.º 25
0
        public void ThrowsMaxRetryException_AndRetriesTheSpecifiedTimes_Async()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                fake.Provide <IConnectionConfigurationValues>(_connectionConfig);
                FakeCalls.ProvideDefaultTransport(fake);
                var getCall = FakeCalls.GetCall(fake);

                //return a started task that throws
                Func <ElasticsearchResponse <Stream> > badTask = () => { throw new Exception(); };
                var t = new Task <ElasticsearchResponse <Stream> >(badTask);
                t.Start();
                getCall.Returns(t);

                var client = fake.Resolve <ElasticsearchClient>();

                client.Settings.MaxRetries.Should().Be(_retries);

                Assert.Throws <MaxRetryException>(async() => await client.InfoAsync());
                getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));
            }
        }
		public void SniffOnStartupCallsSniffOnlyOnce()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				//It's recommended to only have on instance of your connection pool
				//Be sure to register it as Singleton in your IOC
				var uris = new[] { new Uri("http://localhost:9200") };
				var connectionPool = new SniffingConnectionPool(uris);
				var config = new ConnectionConfiguration(connectionPool)
					.DisablePing()
					.SniffOnStartup();
				fake.Provide<IConnectionConfigurationValues>(config);
				var sniffCall = FakeCalls.Sniff(fake, config, uris);
				var transport = FakeCalls.ProvideDefaultTransport(fake);
				var client1 = new ElasticsearchClient(config, transport: transport); 
				var client2 = new ElasticsearchClient(config, transport: transport); 
				var client3 = new ElasticsearchClient(config, transport: transport); 
				var client4 = new ElasticsearchClient(config, transport: transport); 

				sniffCall.MustHaveHappened(Repeated.Exactly.Once);
			}
		}
Ejemplo n.º 27
0
        public async void ShouldRetryOn503_Async()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                fake.Provide <IConnectionConfigurationValues>(_connectionConfig);
                FakeCalls.ProvideDefaultTransport(fake);

                var getCall = FakeCalls.GetCall(fake);
                getCall.Returns(Task.FromResult(FakeResponse.Bad(_connectionConfig)));

                var client = fake.Resolve <ElasticsearchClient>();
                try
                {
                    var result = await client.InfoAsync();
                }
                catch (MaxRetryException e)
                {
                    Assert.AreEqual(e.GetType(), typeof(MaxRetryException));
                }
                getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));
            }
        }
Ejemplo n.º 28
0
        public void MustRegisterListeners_Explicitly()
        {
            var configurationDelegate          = A.Fake <MartenConfigurationDelegate>();
            var componentConfigurationDelegate = A.Fake <MartenComponentConfigurationDelegate>();

            AutoFake.Provide <IServiceCollection>(new ServiceCollection());
            var servicesBuilder = AutoFake.Resolve <ServicesBuilder>();

            servicesBuilder.Services.AddTransient <MartenRegistry, MyMartenRegistry>();
            servicesBuilder.Services.AddSingleton <ILoggerFactory>(LoggerFactory);
            servicesBuilder.Services.AddSingleton <IClock>(
                new FakeClock(Instant.FromDateTimeOffset(DateTimeOffset.Now),
                              Duration.FromSeconds(1))
                );
            var martenBuilder = servicesBuilder
                                .WithMarten()
                                .AddStartupFilter()
                                .Configure(configurationDelegate)
                                .Configure(componentConfigurationDelegate);

            servicesBuilder.Services.AddScoped <IMartenContext>(_ => new MartenContext()
            {
                User = new MartenUser <string>(() => "abc123")
            });

            martenBuilder.UseDirtyTrackedSession();

            var serviceProvider = servicesBuilder.Build();
            var options         = serviceProvider.GetRequiredService <IOptions <StoreOptions> >().Value;

            options.Connection(() => new NpgsqlConnection());

            using (var scope = serviceProvider.GetService <IServiceScopeFactory>().CreateScope())
            {
                var session = scope.ServiceProvider.GetService <IDocumentStore>().LightweightSession();
                session.Listeners.Count.Should().Be(1);
            }
        }
		public void ShouldNotThrowAndNotRetrySniffOnConnectionFault403()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				var uris = new[]
				{
					new Uri("http://localhost:9200"),
					new Uri("http://localhost:9201"),
					new Uri("http://localhost:9202")
				};
				var connectionPool = new SniffingConnectionPool(uris, randomizeOnStartup: false);
				var config = new ConnectionConfiguration(connectionPool)
					.SniffOnConnectionFault();

				fake.Provide<IConnectionConfigurationValues>(config);
				FakeCalls.ProvideDefaultTransport(fake);

				var pingCall = FakeCalls.PingAtConnectionLevel(fake);
				pingCall.Returns(FakeResponse.Ok(config));

				var sniffCall = FakeCalls.Sniff(fake);
				var seenPorts = new List<int>();
				sniffCall.ReturnsLazily((Uri u, IRequestConfiguration c) =>
				{
					seenPorts.Add(u.Port);
					return FakeResponse.Any(config, 403);
				});

				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Returns(FakeResponse.Bad(config));

				var client = fake.Resolve<ElasticsearchClient>();

				Assert.DoesNotThrow(() => client.Info());
				sniffCall.MustHaveHappened(Repeated.Exactly.Once);
				getCall.MustHaveHappened(Repeated.Exactly.Once);
			}
		}
Ejemplo n.º 30
0
        public void ShouldNotThrowAndNotRetrySniffOnConnectionFault401()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                var uris = new[]
                {
                    new Uri("http://localhost:9200"),
                    new Uri("http://localhost:9201"),
                    new Uri("http://localhost:9202")
                };
                var connectionPool = new SniffingConnectionPool(uris, randomizeOnStartup: false);
                var config         = new ConnectionConfiguration(connectionPool)
                                     .SniffOnConnectionFault();

                fake.Provide <IConnectionConfigurationValues>(config);
                FakeCalls.ProvideDefaultTransport(fake);

                var pingCall = FakeCalls.PingAtConnectionLevel(fake);
                pingCall.Returns(FakeResponse.Ok(config));

                var sniffCall = FakeCalls.Sniff(fake);
                var seenPorts = new List <int>();
                sniffCall.ReturnsLazily((Uri u, IRequestConfiguration c) =>
                {
                    seenPorts.Add(u.Port);
                    return(FakeResponse.Any(config, 401));
                });

                var getCall = FakeCalls.GetSyncCall(fake);
                getCall.Returns(FakeResponse.Bad(config));

                var client = fake.Resolve <ElasticsearchClient>();

                Assert.DoesNotThrow(() => client.Info());
                sniffCall.MustHaveHappened(Repeated.Exactly.Once);
                getCall.MustHaveHappened(Repeated.Exactly.Once);
            }
        }
Ejemplo n.º 31
0
        public void Soft_IConnectionException_AsyncCall_WithoutPooling_DoesNot_Retry_AndRethrows()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                fake.Provide <IConnectionConfigurationValues>(_connectionConfig);
                FakeCalls.ProvideDefaultTransport(fake);
                var getCall = FakeCalls.GetCall(fake);

                //return a started task that throws
                Func <ElasticsearchResponse <Stream> > badTask = () => { throw new Exception("inner"); };
                var t = new Task <ElasticsearchResponse <Stream> >(badTask);
                t.Start();
                getCall.Returns(t);

                var client = fake.Resolve <ElasticsearchClient>();

                client.Settings.MaxRetries.Should().Be(_retries);

                var e = Assert.Throws <Exception>(async() => await client.InfoAsync());
                e.Message.Should().Be("inner");
                getCall.MustHaveHappened(Repeated.Exactly.Once);
            }
        }
Ejemplo n.º 32
0
        public void ShouldResolveConventionsUsingTheServiceProvider()
        {
            var properties = new ServiceProviderDictionary();

            AutoFake.Provide <IServiceProvider>(properties);
            var scanner = AutoFake.Resolve <Scanner>();

            properties.Add(typeof(IConventionScanner), scanner);
            var fakeService = A.Fake <IService>();

            properties.Add(typeof(IService), fakeService);

            scanner.AppendConvention <F>();

            var result = scanner.BuildProvider().Get <IServiceConvention, ServiceConventionDelegate>();

            var item = result.First().Convention;

            item.Should().BeOfType <F>();
            ((F)item !).Scanner.Should().NotBeNull();
            ((F)item !).Scanner.Should().BeSameAs(scanner);
            ((F)item !).Service.Should().BeSameAs(fakeService);
        }
Ejemplo n.º 33
0
        public void AddsLogging()
        {
            var properties = new ServiceProviderDictionary();

            AutoFake.Provide <IServiceProviderDictionary>(properties);
            AutoFake.Provide <IDictionary <object, object?> >(properties);
            AutoFake.Provide <IServiceProvider>(properties);
            var configuration = new ConfigurationBuilder().Build();

            AutoFake.Provide <IConfiguration>(configuration);

            properties[typeof(ILogger)] = Logger;
            var scanner = AutoFake.Resolve <SimpleConventionScanner>();

            AutoFake.Provide <IConventionScanner>(scanner);
            var services = new ServiceCollection();

            AutoFake.Provide <IServiceCollection>(services);

            var builder = AutoFake.Resolve <HostBuilder>();
            var sb      = AutoFake.Resolve <ServicesBuilder>();

            sb.Services.AddLogging(x => x.AddConsole().AddDebug());
Ejemplo n.º 34
0
        public void SupportsInjection_Creating_On_Construction()
        {
            AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider());
            var builder = AutoFake.Resolve <CommandLineBuilder>();

            builder
            .AddCommand <InjectionConstructor>("constructor");
            builder
            .AddCommand <InjectionExecute>("execute");

            builder.OnParse(state => { state.IsDefaultCommand.Should().BeFalse(); });

            var service = AutoFake.Resolve <IService>();

            A.CallTo(() => service.ReturnCode).Returns(1000);

            var response = builder.Build(typeof(CommandLineBuilderTests).GetTypeInfo().Assembly);

            var result = response.Execute(ServiceProvider, "constructor");

            result.Should().Be(1000);
            A.CallTo(() => service.ReturnCode).MustHaveHappened(1, Times.Exactly);
        }
Ejemplo n.º 35
0
        public void ConstructTheContainerAndRegisterWithApplication()
        {
            AutoFake.Provide <IServiceCollection>(new ServiceCollection());
            AutoFake.Provide <IContainer>(new Container());
            AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider());
            AutoFake.Provide <IConventionScanner, BasicConventionScanner>();
            var servicesBuilder = AutoFake.Resolve <DryIocBuilder>();

            servicesBuilder.ConfigureContainer(
                c => c.RegisterInstance(A.Fake <IAbc>())
                );
            servicesBuilder.Services.AddSingleton(A.Fake <IAbc2>());
            servicesBuilder.ConfigureContainer(
                c => c.RegisterInstance(A.Fake <IAbc4>())
                );

            var items = servicesBuilder.Build();

            items.Resolve <IAbc>(IfUnresolved.ReturnDefault).Should().NotBeNull();
            items.Resolve <IAbc2>(IfUnresolved.ReturnDefault).Should().NotBeNull();
            items.Resolve <IAbc3>(IfUnresolved.ReturnDefault).Should().BeNull();
            items.Resolve <IAbc4>(IfUnresolved.ReturnDefault).Should().NotBeNull();
        }
		public void Soft_IConnectionException_AsyncCall_WithoutPooling_Retries_AndThrows()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake);

				//return a started task that throws
				Func<ElasticsearchResponse<Stream>> badTask = () => { throw new Exception("inner"); };
				var t = new Task<ElasticsearchResponse<Stream>>(badTask);
				t.Start();
				getCall.Returns(t);

				var client = fake.Resolve<ElasticsearchClient>();

				client.Settings.MaxRetries.Should().NotHaveValue();

				var e = Assert.Throws<Exception>(async () => await client.InfoAsync());
				e.Message.Should().Be("inner");
				getCall.MustHaveHappened(Repeated.Exactly.Once);
			}
		}
        public void SendsNotificationThrough_OnBuild_Observable_ForMicrosoftExtensions()
        {
            var assemblyProvider = AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider());

            AutoFake.Provide <IServiceCollection>(new ServiceCollection());
            AutoFake.Provide(new ContainerBuilder());
            var servicesBuilder = AutoFake.Resolve <AutofacBuilder>();

            A.CallTo(
                () => AutoFake.Resolve <IAssemblyCandidateFinder>().GetCandidateAssemblies(A <IEnumerable <string> > ._)
                )
            .Returns(assemblyProvider.GetAssemblies());

            var observer            = A.Fake <IObserver <IServiceProvider> >();
            var observerApplication = A.Fake <IObserver <IServiceProvider> >();
            var observerSystem      = A.Fake <IObserver <IServiceProvider> >();

            ((IServiceConventionContext)servicesBuilder).OnBuild.Subscribe(observer);

            var items = servicesBuilder.Build();

            A.CallTo(() => observer.OnNext(A <IServiceProvider> .Ignored)).MustHaveHappenedOnceExactly();
        }
        public void AConnectionMustBeMadeEvenIfAllNodesAreDead()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //make sure we retry one more time then we have nodes
                //original call + 4 retries == 5
                fake.Provide<IConnectionConfigurationValues>(
                    new ConnectionConfiguration(_connectionPool)
                        .MaximumRetries(4)
                );
                //set up our GET to / to return 4 503's followed by a 200
                var getCall = A.CallTo(() =>
                    fake.Resolve<IConnection>().GetSync<Dictionary<string, object>>(A<Uri>._, A<object>._));
                getCall.ReturnsNextFromSequence(
                    ElasticsearchResponse<Dictionary<string, object>>.Create(_config, 503, "GET", "/", null),
                    ElasticsearchResponse<Dictionary<string, object>>.Create(_config, 503, "GET", "/", null),
                    ElasticsearchResponse<Dictionary<string, object>>.Create(_config, 503, "GET", "/", null),
                    ElasticsearchResponse<Dictionary<string, object>>.Create(_config, 503, "GET", "/", null),
                    ElasticsearchResponse<Dictionary<string, object>>.Create(_config, 200, "GET", "/", null)
                );
                var pingCall = A.CallTo(() => fake.Resolve<IConnection>().Ping(A<Uri>._));
                pingCall.Returns(true);
                //setup client
                this.ProvideTransport(fake);
                var client = fake.Resolve<ElasticsearchClient>();

                //Do not throw because by miracle the 4th retry manages to give back a 200
                //even if all nodes have been marked dead.
                Assert.DoesNotThrow(()=> client.Info());

                //original call + 4 retries == 5
                getCall.MustHaveHappened(Repeated.Exactly.Times(5));
                //ping must have been send out 4 times to the 4 nodes being used for the first time
                pingCall.MustHaveHappened(Repeated.Exactly.Times(4));

            }
        }
        public void Should_Work_With_CanBeAssigned_Document()
        {
            AutoFake.Provide <IServiceCollection>(new ServiceCollection());
            var servicesBuilder = AutoFake.Resolve <ServicesBuilder>();

            servicesBuilder.Services.AddTransient <MartenRegistry, MyMartenRegistry>();
            servicesBuilder.Services.AddSingleton <ILoggerFactory>(LoggerFactory);
            servicesBuilder.Services.AddSingleton <IClock>(
                new FakeClock(Instant.FromDateTimeOffset(DateTimeOffset.Now),
                              Duration.FromSeconds(1))
                );
            var martenBuilder = servicesBuilder.WithMarten();

            servicesBuilder.Services.AddScoped <IMartenContext>(_ => new MartenContext()
            {
                User = new MartenUser <long>(() => 123456)
            });

            martenBuilder.UseDirtyTrackedSession();

            var serviceProvider = servicesBuilder.Build();
            var options         = serviceProvider.GetRequiredService <IOptions <StoreOptions> >().Value;

            options.Connection(() => new NpgsqlConnection(_fixture.ConnectionString.ToString()));

            using (var scope = serviceProvider.CreateScope())
            {
                using (var session = scope.ServiceProvider.GetService <ISecureQuerySession>())
                {
                    var c = session.Query <CanBeAssigned>()
                            .ToCommand();

                    c.CommandText.Should().Be("select d.data, d.id, d.mt_version from public.mt_doc_securityqueryprovidertests_canbeassigned as d where d.data @> :arg0");
                }
            }
        }
		public void Should_Not_Retry_On_IConnection_Exception()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				//set up connection configuration that holds a connection pool
				//with '_uris' (see the constructor)
				fake.Provide<IConnectionConfigurationValues>(_config);
				//prove a real HttpTransport with its unspecified dependencies
				//as fakes
				this.ProvideTransport(fake);

				//set up fake for a call on IConnection.GetSync so that it always throws 
				//an exception
				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Returns(FakeResponse.AnyWithException(_config, -1, innerException: new Exception("inner")));
				var pingCall = FakeCalls.PingAtConnectionLevel(fake);
				pingCall.Returns(_ok);
				
				//create a real ElasticsearchClient with it unspecified dependencies
				//as fakes
				var client = fake.Resolve<ElasticsearchClient>();

				//our settings dictate retrying 2 times
				client.Settings.MaxRetries.Should().Be(2);
				
				//the single node connection pool always reports 0 for maxretries
				client.Settings.ConnectionPool.MaxRetries.Should().Be(0);

				//
				var exception = Assert.Throws<Exception>(()=> client.Info());
				exception.Message.Should().Be("inner");
				//the GetSync method must in total have been called the number of nodes times.
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
		public void ShouldThrowAndNotRetrySniffOnStartup403()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				var uris = new[]
				{
					new Uri("http://localhost:9200"),
					new Uri("http://localhost:9201"),
					new Uri("http://localhost:9202")
				};
				var connectionPool = new SniffingConnectionPool(uris, randomizeOnStartup: false);
				var config = new ConnectionConfiguration(connectionPool)
					.SniffOnStartup();

				var pingCall = FakeCalls.PingAtConnectionLevel(fake);
				pingCall.Returns(FakeResponse.Ok(config));

				var sniffCall = FakeCalls.Sniff(fake);
				var seenPorts = new List<int>();
				sniffCall.ReturnsLazily((Uri u, IRequestConfiguration c) =>
				{
					seenPorts.Add(u.Port);
					return FakeResponse.Any(config, 403);
				});

				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Returns(FakeResponse.Bad(config));

				fake.Provide<IConnectionConfigurationValues>(config);

				var e = Assert.Throws<ElasticsearchAuthorizationException>(() => FakeCalls.ProvideRealTranportInstance(fake));

				sniffCall.MustHaveHappened(Repeated.Exactly.Once);
				getCall.MustNotHaveHappened();
			}
		}
        public void AConnectionMustBeMadeEvenIfAllNodesAreDead()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //make sure we retry one more time then we have nodes
                //original call + 4 retries == 5
                fake.Provide <IConnectionConfigurationValues>(
                    new ConnectionConfiguration(_connectionPool)
                    .MaximumRetries(4)
                    );
                //set up our GET to / to return 4 503's followed by a 200
                var getCall = A.CallTo(() => fake.Resolve <IConnection>().GetSync(A <Uri> ._, A <IRequestConfiguration> ._));
                getCall.ReturnsNextFromSequence(
                    _ok
                    );
                var transport = this.ProvideTransport(fake);
                var pingCall  = FakeCalls.PingAtConnectionLevel(fake);
                pingCall.ReturnsNextFromSequence(
                    _bad,
                    _bad,
                    _bad,
                    _ok
                    );
                //setup client
                var client = fake.Resolve <ElasticsearchClient>();

                //Do not throw because by miracle the 4th retry manages to give back a 200
                //even if all nodes have been marked dead.
                Assert.DoesNotThrow(() => client.Info());

                //original call + 4 retries == 5
                getCall.MustHaveHappened(Repeated.Exactly.Once);
                //ping must have been send out 4 times to the 4 nodes being used for the first time
                pingCall.MustHaveHappened(Repeated.Exactly.Times(4));
            }
        }
		public void ThrowsOutOfNodesException_AndRetriesTheSpecifiedTimes()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				//set up connection configuration that holds a connection pool
				//with '_uris' (see the constructor)
				fake.Provide<IConnectionConfigurationValues>(_config);
				//prove a real HttpTransport with its unspecified dependencies
				//as fakes
				this.ProvideTransport(fake);

				//set up fake for a call on IConnection.GetSync so that it always throws 
				//an exception
				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Throws<Exception>();
				var pingCall = FakeCalls.PingAtConnectionLevel(fake);
				pingCall.Returns(_ok);
				
				//create a real ElasticsearchClient with it unspecified dependencies
				//as fakes
				var client = fake.Resolve<ElasticsearchClient>();

				//we don't specify our own value so it should be up to the connection pool
				client.Settings.MaxRetries.Should().Be(null);
				
				//the default for the connection pool should be the number of nodes - 1;
				client.Settings.ConnectionPool.MaxRetries.Should().Be(_retries);

				//calling GET / should throw an OutOfNodesException because our fake
				//will always throw an exception
				Assert.Throws<MaxRetryException>(()=> client.Info());
				//the GetSync method must in total have been called the number of nodes times.
				getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1));

			}
		}
Ejemplo n.º 44
0
        public void SniffOnConnectionFaultCausesSniffOn503()
        {
            using (var fake = new AutoFake())
            {
                var dateTimeProvider = fake.Resolve <IDateTimeProvider>();
                var nowCall          = A.CallTo(() => dateTimeProvider.Now());
                nowCall.Returns(DateTime.UtcNow);
                var nodes          = new[] { new Uri("http://localhost:9200") };
                var connectionPool = new SniffingConnectionPool(nodes);
                var config         = new ConnectionConfiguration(connectionPool)
                                     .SniffOnConnectionFault();
                fake.Provide <IConnectionConfigurationValues>(config);
                var transport  = FakeCalls.ProvideDefaultTransport(fake, dateTimeProvider);
                var connection = fake.Resolve <IConnection>();
                var sniffCall  = FakeCalls.Sniff(fake, config, nodes);
                var getCall    = FakeCalls.GetSyncCall(fake);
                getCall.ReturnsNextFromSequence(

                    FakeResponse.Ok(config),                     //info 1
                    FakeResponse.Ok(config),                     //info 2
                    FakeResponse.Ok(config),                     //info 3
                    FakeResponse.Ok(config),                     //info 4
                    FakeResponse.Bad(config)                     //info 5
                    );

                var client1 = fake.Resolve <ElasticsearchClient>();
                client1.Info();                                          //info call 1
                client1.Info();                                          //info call 2
                client1.Info();                                          //info call 3
                client1.Info();                                          //info call 4
                Assert.Throws <MaxRetryException>(() => client1.Info()); //info call 5

                sniffCall.MustHaveHappened(Repeated.Exactly.Once);
                nowCall.MustHaveHappened(Repeated.Exactly.Times(7));
            }
        }
Ejemplo n.º 45
0
        public void ShouldThrowAndNotRetrySniffOnStartup401()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                var uris = new[]
                {
                    new Uri("http://localhost:9200"),
                    new Uri("http://localhost:9201"),
                    new Uri("http://localhost:9202")
                };
                var connectionPool = new SniffingConnectionPool(uris, randomizeOnStartup: false);
                var config         = new ConnectionConfiguration(connectionPool)
                                     .SniffOnStartup();

                var pingCall = FakeCalls.PingAtConnectionLevel(fake);
                pingCall.Returns(FakeResponse.Ok(config));

                var sniffCall = FakeCalls.Sniff(fake);
                var seenPorts = new List <int>();
                sniffCall.ReturnsLazily((Uri u, IRequestConfiguration c) =>
                {
                    seenPorts.Add(u.Port);
                    return(FakeResponse.Any(config, 401));
                });

                var getCall = FakeCalls.GetSyncCall(fake);
                getCall.Returns(FakeResponse.Bad(config));

                fake.Provide <IConnectionConfigurationValues>(config);

                var e = Assert.Throws <ElasticsearchAuthenticationException>(() => FakeCalls.ProvideRealTranportInstance(fake));

                sniffCall.MustHaveHappened(Repeated.Exactly.Once);
                getCall.MustNotHaveHappened();
            }
        }
Ejemplo n.º 46
0
        private ITransport ProvideTransport(AutoFake fake)
        {
            var param = new TypedParameter(typeof(IDateTimeProvider), null);

            return(fake.Provide <ITransport, Transport>(param));
        }
Ejemplo n.º 47
0
        public void Setup()
        {
            AutoFake = new AutoFake();

            var configurationParams = new Dictionary <string, string>
            {
                { "MarvelComicsAPI:BaseURL", "http://gateway.marvel.com/v1/public/" },
                { "MarvelComicsAPI:PublicKey", "f72ecc981b3848b2d7ae9973d0454131" },
                { "MarvelComicsAPI:PrivateKey", "8614298176bdfa2ecff7a712cfdcb6e73bf1d4f9" },
            };

            config = new ConfigurationBuilder()
                     .AddInMemoryCollection(configurationParams)
                     .Build();

            AutoFake.Provide(config);

            AutoFake.Provide(new Configuracao(new Uri(config.GetSection("MarvelComicsAPI:BaseURL").Value), config.GetSection("MarvelComicsAPI:PublicKey").Value, config.GetSection("MarvelComicsAPI:PrivateKey").Value));

            relogio = A.Fake <Relogio>();
            A.CallTo(() => relogio.DataAtual).Returns(DateTime.Now);
            A.CallTo(() => relogio.ObterStringTicks()).Returns(DateTime.Now.Ticks.ToString());

            AutoFake.Provide(relogio);

            // o GetAsync precisa de uma resposta mockada do persogame
            // pra isso preciso cirar uma url no teste e mandar ela pro controller
            string ts        = relogio.ObterStringTicks();
            string publicKey = config.GetSection("MarvelComicsAPI:PublicKey").Value;
            string hash      = GerarHash(ts, publicKey, config.GetSection("MarvelComicsAPI:PrivateKey").Value);

            nome = "Captain America";

            url = config.GetSection("MarvelComicsAPI:BaseURL").Value +
                  $"characters?ts={ts}&apikey={publicKey}&hash={hash}&" +
                  $"name={Uri.EscapeUriString(nome)}";

            // temos que saber o objeto de retorno da api pra poder mockar o retorno do objeto fake na implementacao concreta
            var conteudo = new StringContent(JsonSerializer.Serialize(
                                                 new
            {
                data = new
                {
                    results = new List <dynamic> {
                        new {
                            name        = nome,
                            description = Faker.Random.Words(20),
                            thumbnail   = new { path = Faker.Internet.Url(), extension = Faker.Random.String(3) },
                            urls        = new List <dynamic> {
                                new { url = Faker.Internet.Url() }, new { url = Faker.Internet.Url() }
                            }
                        }
                    }
                }
            }
                                                 ));

            // a resposta vem como um objeto serializado
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = conteudo
            };

            A.CallTo(() => AutoFake.Resolve <IHttpClient>().GetAsync(new Uri(url))).Returns(response);

            service = AutoFake.Resolve <PersonagemService>();
        }
Ejemplo n.º 48
0
    public void Should_Provide_Values()
    {
        var item = AutoFake.Provide(new MyItem());

        ServiceProvider.GetRequiredService <MyItem>().Should().BeSameAs(item);
    }
Ejemplo n.º 49
0
 public void Should_Populate_Optional_Parameters_When_Provided()
 {
     AutoFake.Provide <IItem>(new MyItem());
     AutoFake.Resolve <Optional>().Item.Should().NotBeNull()
     .And.Match(z => !FakeItEasy.Fake.IsFake(z));
 }
        public void IfAllButOneConnectionDiesSubsequentRequestsMustUseTheOneAliveConnection()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //Setting up a datetime provider so that we can measure which
                //nodes have been marked alive and dead.
                //we provide a different fake for the method call with the last node
                //as argument.
                var dateTimeProvider = fake.Resolve <IDateTimeProvider>();
                A.CallTo(() => dateTimeProvider.Now()).Returns(DateTime.UtcNow);
                var markOthersDeadCall = A.CallTo(() => dateTimeProvider
                                                  .DeadTime(A <Uri> .That.Not.Matches(u => u.Port == 9203), A <int> ._, A <int?> ._, A <int?> ._));
                var markLastDead = A.CallTo(() => dateTimeProvider
                                            .DeadTime(A <Uri> .That.Matches(u => u.Port == 9203), A <int> ._, A <int?> ._, A <int?> ._));
                var markOthersAliveCall = A.CallTo(() => dateTimeProvider
                                                   .AliveTime(A <Uri> .That.Not.Matches(u => u.Port == 9203), A <int> ._));
                var markLastAlive = A.CallTo(() => dateTimeProvider
                                             .AliveTime(A <Uri> .That.Matches(u => u.Port == 9203), A <int> ._));
                markOthersDeadCall.Returns(DateTime.UtcNow.AddSeconds(60));
                markLastAlive.Returns(new DateTime());
                fake.Provide(dateTimeProvider);

                //Creating the connection pool making sure nodes are not randomized
                //So we are sure 9203 is that last node in the pool
                var connectionPool = new StaticConnectionPool(
                    _uris,
                    randomizeOnStartup: false,
                    dateTimeProvider: dateTimeProvider
                    );
                var config = new ConnectionConfiguration(connectionPool);
                fake.Provide <IConnectionConfigurationValues>(config);

                // provide a simple fake for synchronous get
                var getCall = FakeCalls.GetSyncCall(fake);

                //The first three tries get a 503 causing the first 3 nodes to be marked dead
                //all the subsequent requests should be handled by 9203 which gives a 200 4 times
                getCall.ReturnsNextFromSequence(
                    FakeResponse.Bad(config),
                    FakeResponse.Bad(config),
                    FakeResponse.Bad(config),
                    FakeResponse.Ok(config),
                    FakeResponse.Ok(config),
                    FakeResponse.Ok(config),
                    FakeResponse.Ok(config)
                    );
                //provide a transport with all the dependencies resolved
                var transport = this.ProvideTransport(fake);
                var pingCall  = FakeCalls.PingAtConnectionLevel(fake);
                pingCall.Returns(_ok);

                //instantiate connection with faked dependencies
                var client = fake.Resolve <ElasticsearchClient>();

                //We call the root for each node 4 times, eventhough the first 3 nodes
                //give back a timeout the default ammount of retries is 4 (each provided node)
                //and the last retry will hit our 9203 node.
                Assert.DoesNotThrow(() => client.Info());
                //These calls should not hit the dead nodes and go straight to the active 9203
                Assert.DoesNotThrow(() => client.Info());
                Assert.DoesNotThrow(() => client.Info());
                Assert.DoesNotThrow(() => client.Info());

                //The last node should never be marked dead
                markLastDead.MustNotHaveHappened();
                //the other nodes should never be marked alive
                markOthersAliveCall.MustNotHaveHappened();
                //marking the other 3 nodes dead should only happen once for each
                markOthersDeadCall.MustHaveHappened(Repeated.Exactly.Times(3));
                //every time a connection succeeds on a node it will be marked
                //alive therefor the last node should be marked alive 4 times
                markLastAlive.MustHaveHappened(Repeated.Exactly.Times(4));
            }
        }
Ejemplo n.º 51
0
        public async Task InProcess_SyncCommand(bool left)
        {
            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    Infrastructure.TestDirectory.CreateDirectory(leftDirectory.CreateDirectory("Dir1"), "Dir2");
                    Infrastructure.TestDirectory.CreateDirectory(rightDirectory.CreateDirectory("Dir1"), "Dir2");
                    leftDirectory.CreateDirectory("Dir3");
                    rightDirectory.CreateDirectory("Dir3");

                    var containerBuilder = new ContainerBuilder();
                    containerBuilder.RegisterModule <TestAutofacRegisterModule>();
                    containerBuilder.RegisterType <SettingsRow>().As <ISettingsRow>();
                    containerBuilder.RegisterType <SynchronizedItems>().As <ISynchronizedItems>();

                    using (var fake = new AutoFake(builder: containerBuilder))
                    {
                        var fakeItemFactory = A.Fake <IItemFactory>();
                        A.CallTo(() => fakeItemFactory.CreateDirectory(A <string> .Ignored, A <string[]> .Ignored))
                        .ReturnsLazily((string directoryPath, string[] excludedExtensions) =>
                        {
                            return(new TestDirectory(directoryPath, fakeItemFactory, 1));
                        });

                        var fakeSettingsRow = A.Fake <ISettingsRow>();
                        A.CallTo(() => fakeSettingsRow.LeftDirectory).Returns(new SettingsDirectory(leftDirectory.FullPath));
                        A.CallTo(() => fakeSettingsRow.RightDirectory).Returns(new SettingsDirectory(rightDirectory.FullPath));

                        var fakeSynchronizedItemsStatusAndCommandsUpdater = A.Fake <ISynchronizedItemsStatusAndCommandsUpdater>();
                        A.CallTo(() => fakeSynchronizedItemsStatusAndCommandsUpdater
                                 .UpdateStatusesAndCommands(A <ISynchronizedItem> .Ignored, A <ISynchronizedItem> .Ignored))
                        .Invokes((ISynchronizedItem item1, ISynchronizedItem item2) =>
                        {
                            item1.UpdateStatus(ItemStatusEnum.Equally);
                            item2.UpdateStatus(ItemStatusEnum.Equally);
                        });

                        fake.Provide(fakeSettingsRow);
                        fake.Provide(fakeItemFactory);
                        fake.Provide(fakeSynchronizedItemsStatusAndCommandsUpdater);

                        var synchronizedItems = fake.Resolve <ISynchronizedItems>();
                        await synchronizedItems.Load(); // Загрузим, чтобы построилось дерево элементов.

                        // А теперь запустим синхронизацию одного из элементов и проверим изменение признака InProcess.
                        var childLevel1SynchronizedItems1 = synchronizedItems.ChildItems[0];
                        var processItem = left ? childLevel1SynchronizedItems1.LeftItem : childLevel1SynchronizedItems1.RightItem;
                        processItem.SyncCommand.SetCommandAction(() =>
                                                                 Task.Delay(4));
                        var syncTask = Task.Run(() => processItem.SyncCommand.Process());

                        await Task.Delay(2); // Чтобы признаки успели поменять значения.

                        Assert.True(childLevel1SynchronizedItems1.InProcess);
                        Assert.True(synchronizedItems.InProcess);                           // И процесс родителя должен обозначиться.
                        Assert.True(childLevel1SynchronizedItems1.ChildItems[0].InProcess); // И процесс дочерних элементом.

                        Assert.False(synchronizedItems.ChildItems[1].InProcess);            // А эти элементы не при чём.

                        syncTask.Wait();                                                    // Ждём, пока завершится синхронизация.

                        // А теперь всё обратно в false.
                        Assert.False(childLevel1SynchronizedItems1.InProcess);
                        Assert.False(synchronizedItems.InProcess);
                        Assert.False(childLevel1SynchronizedItems1.ChildItems[0].InProcess);
                    }
                }
        }
Ejemplo n.º 52
0
        public void HostsReturnedBySniffAreVisited()
        {
            using (var fake = new AutoFake())
            {
                var dateTimeProvider = fake.Resolve <IDateTimeProvider>();
                var nowCall          = A.CallTo(() => dateTimeProvider.Now());
                nowCall.Returns(DateTime.UtcNow);

                var connectionPool = new SniffingConnectionPool(new[]
                {
                    new Uri("http://localhost:9200"),
                    new Uri("http://localhost:9201")
                }, randomizeOnStartup: false);
                var config = new ConnectionConfiguration(connectionPool)
                             .SniffOnConnectionFault();
                fake.Provide <IConnectionConfigurationValues>(config);
                FakeCalls.ProvideDefaultTransport(fake);
                FakeCalls.PingAtConnectionLevel(fake)
                .Returns(FakeResponse.Ok(config));

                var sniffCall = FakeCalls.Sniff(fake, config, new List <Uri>()
                {
                    new Uri("http://localhost:9204"),
                    new Uri("http://localhost:9203"),
                    new Uri("http://localhost:9202"),
                    new Uri("http://localhost:9201")
                });

                var connection = fake.Resolve <IConnection>();
                var seenNodes  = new List <Uri>();
                //var getCall =  FakeResponse.GetSyncCall(fake);
                var getCall = A.CallTo(() => connection.GetSync(
                                           A <Uri> .That.Not.Matches(u => u.AbsolutePath.StartsWith("/_nodes")),
                                           A <IRequestConfiguration> ._));
                getCall.ReturnsNextFromSequence(
                    FakeResponse.Ok(config),                    //info 1
                    FakeResponse.Bad(config),                   //info 2
                    FakeResponse.Ok(config),                    //info 2 retry
                    FakeResponse.Ok(config),                    //info 3
                    FakeResponse.Ok(config),                    //info 4
                    FakeResponse.Ok(config),                    //info 5
                    FakeResponse.Ok(config),                    //info 6
                    FakeResponse.Ok(config),                    //info 7
                    FakeResponse.Ok(config),                    //info 8
                    FakeResponse.Ok(config)                     //info 9
                    );
                getCall.Invokes((Uri u, IRequestConfiguration o) => seenNodes.Add(u));

                var client1 = fake.Resolve <ElasticsearchClient>();
                client1.Info();                 //info call 1
                client1.Info();                 //info call 2
                client1.Info();                 //info call 3
                client1.Info();                 //info call 4
                client1.Info();                 //info call 5
                client1.Info();                 //info call 6
                client1.Info();                 //info call 7
                client1.Info();                 //info call 8
                client1.Info();                 //info call 9

                sniffCall.MustHaveHappened(Repeated.Exactly.Once);
                seenNodes.Should().NotBeEmpty().And.HaveCount(10);
                seenNodes[0].Port.Should().Be(9200);
                seenNodes[1].Port.Should().Be(9201);
                //after sniff
                seenNodes[2].Port.Should().Be(9202, string.Join(",", seenNodes.Select(n => n.Port)));
                seenNodes[3].Port.Should().Be(9204);
                seenNodes[4].Port.Should().Be(9203);
                seenNodes[5].Port.Should().Be(9202);
                seenNodes[6].Port.Should().Be(9201);
            }
        }
Ejemplo n.º 53
0
 protected TService The <TService, TImplementation>()
 {
     return(FakeResolver.Provide <TService, TImplementation>());
 }
Ejemplo n.º 54
0
 public DryIocBuilderTests(ITestOutputHelper outputHelper) : base(outputHelper)
 {
     AutoFake.Provide <IDictionary <object, object?> >(new ServiceProviderDictionary());
 }
        public void AllNodesMustBeTriedOnce()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //set up client with fakes
                fake.Provide<IConnectionConfigurationValues>(_config);
                var connection = fake.Resolve<NoopConnection>();
                fake.Provide<IConnection>(connection);
                this.ProvideTransport(fake);

                //provide a unique fake for each node.
                var calls = _uris.Select(u =>
                    A.CallTo(()=> fake.Resolve<IUriObserver>()
                        .Observe(A<Uri>.That.Matches(uu=>uu.Port == u.Port)))
                ).ToList();

                //all of our fakes throw an exception
                foreach (var c in calls)
                    c.Throws<Exception>();

                var client = fake.Resolve<ElasticsearchClient>();

                Assert.Throws<OutOfNodesException>(()=> client.Info());

                //make sure we've observed an attempt on all the nodes
                foreach (var call in calls)
                    call.MustHaveHappened(Repeated.Exactly.Once);

            }
        }
 private void ProvideTransport(AutoFake fake)
 {
     var param = new TypedParameter(typeof(IDateTimeProvider), null);
     fake.Provide<ITransport, Transport>(param);
 }