public void Booking_confirm_should_take_two_different_payments_suggested_by_the_price_calculator() { // arrange using var fake = new AutoFake(); var booking = fake.Resolve <Booking>(); var priceCalculator = fake.Resolve <IPriceCalculator>(); var paymentGateway = fake.Resolve <IPaymentGateway>(); var price1 = new Price { Amount = 100, VatAmount = 5m }; var price2 = new Price { Amount = 50, VatAmount = 2.5m }; A.CallTo(() => priceCalculator.CalculatePrice()) .ReturnsNextFromSequence(price1, price2); // act booking.Confirm6(); // assert A.CallTo(() => paymentGateway.CapturePayment(price2.Amount, price2.VatAmount)).MustHaveHappenedOnceExactly(); A.CallTo(() => paymentGateway.CapturePayment(price1.Amount, price1.VatAmount)).MustHaveHappenedOnceExactly(); }
public void HardRetryLimitTakesPrecedenceOverNumberOfNodes() { using (var fake = new AutoFake(callsDoNothing: true)) { //setup config values with a hight retry count fake.Provide <IConnectionConfigurationValues>( new ConnectionConfiguration(_connectionPool) .MaximumRetries(7) ); var getCall = A.CallTo(() => fake.Resolve <IConnection>().GetSync(A <Uri> ._, A <IRequestConfiguration> ._)); getCall.Throws <Exception>(); var transport = this.ProvideTransport(fake); var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(_ok); var client = fake.Resolve <ElasticsearchClient>(); Assert.Throws <MaxRetryException>(() => client.Info()); //We want to see 8 attempt to do a GET on / //(original call + retry of 7 == 8) getCall.MustHaveHappened(Repeated.Exactly.Times(8)); } }
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)); } }
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 <MaxRetryException>(() => client.Info()); //make sure we've observed an attempt on all the nodes foreach (var call in calls) { call.MustHaveHappened(Repeated.Exactly.Once); } } }
public void Task2_CreateNewUserShouldCallUserRepository() { const string userName = "******"; const string email = "*****@*****.**"; const int age = 42; using var fake = new AutoFake(); var usersController = fake.Resolve <UsersController>(); var userCreateData = new UserCreate { Name = userName, Email = email, Age = age }; usersController.CreateNewUser(userCreateData); var fakeUsersRepository = fake.Resolve <IUsersRepository>(); var foundCall = TestUtilities.GetMethodCall(() => fakeUsersRepository.CreateNewUser("", "", 0)); Assert.IsNotNull(foundCall, CreateNewUserNotCalledError); Assert.That.All( () => Assert.AreEqual(userName, foundCall.Get <string>("name"), UserNameNotPassedError), () => Assert.AreEqual(email, foundCall.Get <string>("email"), UserEmailNotPassedError), () => Assert.AreEqual(42, foundCall.Get <int>("age"), UserAgeNotPassedError) ); }
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( _bad, _bad, _bad, _bad, _ok ); var transport = this.ProvideTransport(fake); var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(_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.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 InterceptTest(bool hasContext, string method, int initialDepth, bool proceedCalled, string durableInvocation) { using (var fake = new AutoFake()) { DurableInterceptor.Context.Value = hasContext ? new DurableContext { OrchestrationContext = fake.Resolve <IDurableOrchestrationContext>() } : null; var invocation = fake.Resolve <IInvocation>(); A.CallTo(() => invocation.Method).Returns(this.GetType().GetMethod(method)); var durableInterceptor = fake.Resolve <DurableInterceptor>(); (durableInterceptor.GetType() .GetMethod("get_Depth", BindingFlags.NonPublic | BindingFlags.Static) .Invoke(durableInterceptor, null) as AsyncLocal <int> ).Value = initialDepth; durableInterceptor.Intercept(invocation); A.CallTo(() => invocation.Proceed()).MustHaveHappened(proceedCalled ? 1 : 0, Times.Exactly); if (!string.IsNullOrWhiteSpace(durableInvocation)) { Fake.GetCalls(DurableInterceptor.Context.Value.OrchestrationContext) .Any(p => p.Method.Name == durableInvocation) .Should().BeTrue(); } } }
public void Task3_CreateNewUserShouldCallStoreWithUserData() { using var autoFake = new AutoFake(); var fakeDocumentStoreFactory = autoFake.Resolve <IDocumentStoreFactory>(); var fakeDocumentStore = A.Fake <IDocumentStore>(); A.CallTo(() => fakeDocumentStoreFactory.Store).Returns(fakeDocumentStore); var fakeDocumentSession = A.Fake <IDocumentSession>(); A.CallTo(() => fakeDocumentStore.OpenSession(A <DocumentTracking> ._, A <IsolationLevel> ._)) .Returns(fakeDocumentSession); var usersRepository = autoFake.Resolve <UsersRepository>(); usersRepository.CreateNewUser("user name", "*****@*****.**", 42); var methodCall = TestUtilities.GetMethodCall(() => fakeDocumentSession.Store(new User[0])); Assert.IsNotNull(methodCall, StoreNotCalledError); var users = methodCall.Get <User[]>("entities"); Assert.IsNotNull(users, UserWasNotPassedToStoreError); Assert.AreEqual(1, users.Length, UserWasNotPassedToStoreError); User createdUser = users[0]; Assert.That.All( () => Assert.AreEqual("user name", createdUser.Name, WrongUserArgumentsPassedToDbError), () => Assert.AreEqual("*****@*****.**", createdUser.Email, WrongUserArgumentsPassedToDbError), () => Assert.AreEqual(42, createdUser.Age, WrongUserArgumentsPassedToDbError) ); }
public void HelloWorld3_approve() { using (var fake = new AutoFake()) { var provider = fake.Resolve <IServiceLocator>(); var actionRepository = new InMemoryRepository <ActionDef>(new List <ActionDef>()); A.CallTo(() => provider.GetInstance <IRepository <ActionDef> >()).Returns(actionRepository); ServiceLocator.SetLocatorProvider(() => provider); ProcessDefinition processDefinition = ProcessDefinitionFactory.getHelloWorld3(); var delegationHelper = fake.Resolve <IDelegationHelper>(); Transition transition = processDefinition.Nodes.Single(s => s is Decision).LeavingTransitions.Single(l => l.To is EndState); A.CallTo(delegationHelper).WithReturnType <Transition>().Returns(transition); A.CallTo(() => provider.GetInstance <IDelegationHelper>()).Returns(delegationHelper); ExecutionContext executionContext = new ExecutionContext(new User("ae"), processDefinition); ProcessInstance processInstance = executionContext.StartProcess(); Assert.AreEqual(2, executionContext.Flow.AttributeInstances.Count); IDictionary <string, object> attributeValues = new Dictionary <string, object>(); attributeValues.Add("evaluation result", "approve"); executionContext.PerformActivity(attributeValues); var endState = processDefinition.Nodes.Single(q => q is EndState); Assert.AreEqual(endState, processInstance.RootFlow.Node); } }
public void Task4_GetUserByIdShouldCallLoad() { using var autoFake = new AutoFake(); var user = new User { Id = 1, Name = "user1", Age = 42, Email = "*****@*****.**" }; var fakeDocumentStoreFactory = autoFake.Resolve <IDocumentStoreFactory>(); var fakeDocumentStore = A.Fake <IDocumentStore>(); A.CallTo(() => fakeDocumentStoreFactory.Store).Returns(fakeDocumentStore); var fakeSession = A.Fake <IQuerySession>(); A.CallTo(() => fakeDocumentStore.QuerySession()).Returns(fakeSession); A.CallTo(() => fakeSession.Load <User>(1)).Returns(user); var usersRepository = autoFake.Resolve <UsersRepository>(); var userById = usersRepository.GetUserById(1); var fakeObjectCall = TestUtilities.GetMethodCall(() => fakeSession.Load <User>(0)); Assert.IsNotNull(fakeObjectCall, QuerySessionLoadNotCalledError); Assert.AreEqual(1, fakeObjectCall.Arguments.Get <int>(0), IdNotPassedToQueryError); Assert.AreEqual(user, userById, UserNotReturnedFromGetUserByIdError); }
private static IMppPresentatie PreparePresentation(AutoFake fakeScope, string fileName) { var app = fakeScope.Resolve<IMppApplication>(); A.CallTo(() => fakeScope.Resolve<IMppFactory>().GetApplication()).Returns(app); var pres = fakeScope.Resolve<IMppPresentatie>(); A.CallTo(() => app.Open(fileName, true)).Returns(pres); return pres; }
public void Setup() { var mapper = new AutoMapperConfig().RegisterMappings().CreateMapper(); _autoFakeContainer = new AutoFake(); _sut = new CustomerController(_autoFakeContainer.Resolve <ICustomerRepository>(), mapper, _autoFakeContainer.Resolve <HttpContextBase>()); }
public static AutoFake WithFakeHttpClient(this AutoFake autoFake, string baseAddress) { A.CallTo(() => autoFake.Resolve <ILocalhostAddressLocator>().BaseAddress) .Returns(baseAddress); autoFake.Provide <IHttpClientFactory>(new FakeHttpClientFactory(autoFake.Resolve <ILocalhostAddressLocator>())); return(autoFake); }
public void ByDefaultAbstractTypesAreResolvedToTheSameSharedInstance() { using (var fake = new AutoFake()) { var bar1 = fake.Resolve<IBar>(); var bar2 = fake.Resolve<IBar>(); Assert.AreSame(bar1, bar2); } }
public void ByDefaultAbstractTypesAreResolvedToTheSameSharedInstance() { using (var fake = new AutoFake()) { var bar1 = fake.Resolve <IBar>(); var bar2 = fake.Resolve <IBar>(); Assert.Same(bar1, bar2); } }
public void ByDefaultConcreteTypesAreResolvedToTheSameSharedInstance() { using (var fake = new AutoFake()) { var baz1 = fake.Resolve <Baz>(); var baz2 = fake.Resolve <Baz>(); Assert.Same(baz1, baz2); } }
public void ByDefaultConcreteTypesAreResolvedToTheSameSharedInstance() { using (var fake = new AutoFake()) { var baz1 = fake.Resolve<Baz>(); var baz2 = fake.Resolve<Baz>(); Assert.AreSame(baz1, baz2); } }
public void AllNodesWillBeMarkedDead() { using (var fake = new AutoFake(callsDoNothing: true)) { //set up a fake datetimeprovider var dateTimeProvider = fake.Resolve <IDateTimeProvider>(); fake.Provide(dateTimeProvider); //create a connectionpool that uses the fake datetimeprovider var connectionPool = new StaticConnectionPool( _uris, dateTimeProvider: dateTimeProvider ); var config = new ConnectionConfiguration(connectionPool); fake.Provide <IConnectionConfigurationValues>(config); //Now() on the fake still means Now() A.CallTo(() => dateTimeProvider.Now()).Returns(DateTime.UtcNow); //Set up individual mocks for each DeadTime(Uri uri,...) call //where uri matches one of the node ports var calls = _uris.Select(u => A.CallTo(() => dateTimeProvider.DeadTime( A <Uri> .That.Matches(uu => uu.Port == u.Port), A <int> ._, A <int?> ._, A <int?> ._ ))).ToList(); //all the fake mark dead calls return 60 seconds into the future foreach (var call in calls) { call.Returns(DateTime.UtcNow.AddSeconds(60)); } //When we do a GET on / we always recieve a 503 var getCall = A.CallTo(() => fake.Resolve <IConnection>().GetSync(A <Uri> ._, A <IRequestConfiguration> ._)); getCall.Returns(_bad); var transport = this.ProvideTransport(fake); var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(_ok); var client = fake.Resolve <ElasticsearchClient>(); //Since we always get a 503 we should see an out of nodes exception Assert.Throws <MaxRetryException>(() => client.Info()); pingCall.MustHaveHappened(Repeated.Exactly.Times(4)); //The call should be tried on all the nodes getCall.MustHaveHappened(Repeated.Exactly.Times(4)); //We should see each individual node being marked as dead foreach (var call in calls) { call.MustHaveHappened(Repeated.Exactly.Once); } } }
public static ITransport ProvideRealTranportInstance(AutoFake fake, IDateTimeProvider dateTimeProvider = null) { var connection = fake.Resolve <IConnection>(); var config = fake.Resolve <IConnectionConfigurationValues>(); var param = new TypedParameter(typeof(IDateTimeProvider), dateTimeProvider); var serializerParam = new TypedParameter(typeof(IElasticsearchSerializer), null); return(new Transport( config, connection, serializerParam.Value as IElasticsearchSerializer, param.Value as IDateTimeProvider)); }
public void IfAConnectionComesBackToLifeOnItsOwnItShouldBeMarked() { using (var fake = new AutoFake(callsDoNothing: true)) { //Setting up a datetime provider so that can track dead/alive marks var dateTimeProvider = fake.Resolve <IDateTimeProvider>(); A.CallTo(() => dateTimeProvider.Now()).Returns(DateTime.UtcNow); var markDeadCall = A.CallTo(() => dateTimeProvider.DeadTime(A <Uri> ._, A <int> ._, A <int?> ._, A <int?> ._)); var markAliveCall = A.CallTo(() => dateTimeProvider.AliveTime(A <Uri> ._, A <int> ._)); markDeadCall.Returns(DateTime.UtcNow.AddSeconds(60)); markAliveCall.Returns(new DateTime()); fake.Provide(dateTimeProvider); var connectionPool = new StaticConnectionPool( _uris, dateTimeProvider: dateTimeProvider); //set retries to 4 fake.Provide <IConnectionConfigurationValues>( new ConnectionConfiguration(connectionPool) .MaximumRetries(4) ); //fake getsync handler that return a 503 4 times and then a 200 //this will cause all 4 nodes to be marked dead on the first client call var getCall = FakeCalls.GetSyncCall(fake); getCall.ReturnsNextFromSequence( _bad, _bad, _bad, _bad, _ok ); //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>(); //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 is 5 getCall.MustHaveHappened(Repeated.Exactly.Times(5)); //4 nodes must be marked dead markDeadCall.MustHaveHappened(Repeated.Exactly.Times(4)); //atleast one of them sprung back to live so markAlive must be called once markAliveCall.MustHaveHappened(Repeated.Exactly.Times(1)); } }
public void SniffIsCalledAfterItHasGoneOutOfDate_NotWhenItSeesA503() { 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(10), //info call 4 DateTime.UtcNow.AddMinutes(12) //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)) .ExposeRawResponse(); fake.Provide <IConnectionConfigurationValues>(config); var transport = FakeCalls.ProvideDefaultTransport(fake, dateTimeProvider); var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(FakeResponse.Ok(config)); var sniffCall = FakeCalls.Sniff(fake, config, uris); 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), //sniff FakeResponse.Ok(config), //info 4 FakeResponse.Bad(config) //info 5 ); 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.Once); nowCall.MustHaveHappened(Repeated.Exactly.Times(7)); //var nowCall = A.CallTo(() => fake.Resolve<IDateTimeProvider>().Sniff(A<Uri>._, A<int>._)); } }
public async Task Should_FindAllYamlFiles() { // Arrange var fs = new MockFileSystem(new Dictionary <string, MockFileData> { { @"c:\root\shortcuts\vscode\shortcuts.yml", new MockFileData(TestData.OneContext1Shortcut()) }, { @"c:\root\shortcuts\vs\shortcuts.yml", new MockFileData(TestData.TwoContext2Shortcuts()) }, { @"c:\root\shortcuts\notyml\shortcuts.json", new MockFileData("") }, { @"c:\not-root\shortcuts\xy\shortcuts.yml", new MockFileData("") }, }); _auto.Provide <IFileSystem>(fs); var handler = _auto.Resolve <LoadRawShortcutsFromFilesRequestHandler>(); var request = new LoadRawShortcutsFromFiles() { SourceDirectory = @"C:\root\shortcuts\" }; // Act var result = await handler.Handle(request, CancellationToken.None); // Assert result.Should().HaveCount(2); }
public void Task2_CreateNewUserShouldReturnCreatedUserId() { using var fake = new AutoFake(); var fakeUsersRepository = fake.Resolve <IUsersRepository>(); A.CallTo(() => fakeUsersRepository.CreateNewUser(A <String> ._, A <string> ._, A <int> ._)) .Returns(123); var usersController = fake.Resolve <UsersController>(); var actual = usersController.CreateNewUser(new UserCreate()); Assert.AreEqual(123, actual, UserIdNotReturnedError); }
public void Task5_DeleteUserShouldCallUsersRepository() { using var fake = new AutoFake(); var usersController = fake.Resolve <UsersController>(); usersController.Delete(100); var fakeUsersRepository = fake.Resolve <IUsersRepository>(); var fakeObjectCall = TestUtilities.GetMethodCall(() => fakeUsersRepository.DeleteUser(0)); Assert.IsNotNull(fakeObjectCall, DeleteUserWasNotCalledError); Assert.AreEqual(100, fakeObjectCall.Arguments.Get <int>(0), DeleteCalledWithWrongIdError); }
public void Test() { // Arrange using var fake = new AutoFake(); A.CallTo(() => fake.Resolve <INameProvider>().GetName()).Returns("A Name"); // Act var sut = fake.Resolve <MyClassAuto>(); sut.DoGreeting(); // Assert A.CallTo(() => fake.Resolve <IGreetingService>().Greet("A Name")).MustHaveHappened(); }
public void SniffOnConnectionFaultCausesSniffOn503() { using (var fake = new AutoFake()) { var dateTimeProvider = fake.Resolve <IDateTimeProvider>(); var nowCall = A.CallTo(() => dateTimeProvider.Now()); nowCall.Invokes(() => { }); 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 sniffNewNodes = new[] { new Uri("http://localhost:9200"), new Uri("http://localhost:9201") }; var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(FakeResponse.Ok(config)); var sniffCall = FakeCalls.Sniff(fake, config, sniffNewNodes); 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(8)); } }
public void Application_Opened() { using (var fake = new AutoFake()) { var app = fake.Resolve<IMppApplication>(); A.CallTo(() => fake.Resolve<IMppFactory>().GetApplication()).Returns(app); var sut = fake.Resolve<mppt.PowerpointFunctions>(); var dependendFiles = A.Fake<IBuilderDependendFiles>(); A.CallTo(() => dependendFiles.FullTemplateTheme).Returns("\testbestand.ppt"); sut.PreparePresentation(GetEmptyLiturgie(), A.Fake<IBuilderBuildSettings>(), A.Fake<IBuilderBuildDefaults>(), dependendFiles, null); sut.GeneratePresentation(); A.CallTo(() => app.Open(dependendFiles.FullTemplateTheme, true)).MustHaveHappened(); } }
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 FailEarlyIfTimeoutIsExhausted_Async() { using (var fake = new AutoFake()) { var dateTimeProvider = ProvideDateTimeProvider(fake); var config = ProvideConfiguration(dateTimeProvider); var connection = ProvideConnection(fake, config, dateTimeProvider); var getCall = FakeCalls.GetCall(fake); var ok = Task.FromResult(FakeResponse.Ok(config)); var bad = Task.FromResult(FakeResponse.Bad(config)); getCall.ReturnsNextFromSequence( bad, bad, ok ); var seenNodes = new List<Uri>(); getCall.Invokes((Uri u, IRequestConfiguration o) => seenNodes.Add(u)); var pingCall = FakeCalls.PingAtConnectionLevelAsync(fake); pingCall.Returns(ok); var client1 = fake.Resolve<ElasticsearchClient>(); //event though the third node should have returned ok, the first 2 calls took a minute var e = Assert.Throws<MaxRetryException>(async () => await client1.InfoAsync()); e.Message.Should() .StartWith("Retry timeout 00:01:00 was hit after retrying 1 times:"); IElasticsearchResponse response = null; Assert.DoesNotThrow(async () => response = await client1.InfoAsync() ); response.Should().NotBeNull(); response.Success.Should().BeTrue(); } }
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)); } }
public void Should_Inject_LoggerFactory() { var test = AutoFake.Resolve <LoggerFactoryImpl>(); test.Write(); A.CallTo(() => AutoFake.Resolve <ITestOutputHelper>().WriteLine(A <string> ._)).MustHaveHappened(); }
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); } }
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); } }
public void MustCallDelegatesOnBuild() { 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); martenBuilder.UseDirtyTrackedSession(); var serviceProvider = servicesBuilder.Build(); var options = serviceProvider.GetRequiredService <IOptions <StoreOptions> >().Value; A.CallTo(() => configurationDelegate(options)) .MustHaveHappened(Repeated.Exactly.Once) .Then(A.CallTo(() => componentConfigurationDelegate(A <IServiceProvider> ._, options)) .MustHaveHappened(Repeated.Exactly.Once)); }
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); } }
public void Should_Fail_If_Container_Is_Touched_When_Building() { var access = AutoFake.Resolve <DoubleAccess>(); Action a = () => access.Self.Resolve <IContainer>(); a.Should().Throw <TestBootstrapException>(); }
public void IgnoreNonExistentItems() { AutoFake.Provide <IDictionary <object, object> >(new Dictionary <object, object>()); var servicesBuilder = AutoFake.Resolve <ServicesBuilder>(); servicesBuilder[string.Empty].Should().BeNull(); }
public void IfResponseIsKnowError_DoNotRetry_ThrowServerException(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.PingAtConnectionLevel(fake); pingCall.Returns(FakeResponse.Ok(connectionConfiguration)); var getCall = FakeCalls.GetSyncCall(fake); getCall.Returns(FakeResponse.Any(connectionConfiguration, status, response: response)); var client = fake.Resolve<ElasticsearchClient>(); var e = Assert.Throws<ElasticsearchServerException>(()=>client.Info()); 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); } }
public void SendsNotificationThrough_OnBuild_Observable_ForAutofac() { 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 observerContainer = A.Fake <IObserver <IContainer> >(); var observerApplication = A.Fake <IObserver <ILifetimeScope> >(); var observerSystem = A.Fake <IObserver <ILifetimeScope> >(); servicesBuilder.OnContainerBuild.Subscribe(observerContainer); servicesBuilder.OnBuild.Subscribe(observer); var container = servicesBuilder.Build(); A.CallTo(() => observer.OnNext(A <IServiceProvider> ._)).MustHaveHappenedOnceExactly(); A.CallTo(() => observerContainer.OnNext(container)).MustHaveHappenedOnceExactly(); }
public void ByDefaultFakesAreNotStrict() { using (var fake = new AutoFake()) { var foo = fake.Resolve<Foo>(); Assert.DoesNotThrow(() => foo.Go()); } }
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)); } }
public void TestContext() { using (var fake = new AutoFake(false, false, false, null, AutofacInstaller.Register())) { //var listValueModel = GetListDataInCsv(); var sawEditorPullService = fake.Resolve<ICornerstoneListsRepository>(); var result = sawEditorPullService.GetListCornerstoneLists(); Console.WriteLine("List WorkerId: {0}", string.Join(",", result.Select(x => x.Id))); } }
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)); } }
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 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 Application_Saved(string saveAsFileName) { using (var fake = new AutoFake()) { var dependendFiles = A.Fake<IBuilderDependendFiles>(); A.CallTo(() => dependendFiles.FullTemplateTheme).Returns("\testbestand.ppt"); var pres = PreparePresentation(fake, dependendFiles.FullTemplateTheme); var sut = fake.Resolve<mppt.PowerpointFunctions>(); sut.PreparePresentation(GetEmptyLiturgie(), A.Fake<IBuilderBuildSettings>(), A.Fake<IBuilderBuildDefaults>(), dependendFiles, saveAsFileName); sut.GeneratePresentation(); A.CallTo(() => pres.OpslaanAls(saveAsFileName)).MustHaveHappened(); } }
public void DeadNodesAreNotVisited_AndPingedAppropiately() { using (var fake = new AutoFake()) { var dateTimeProvider = ProvideDateTimeProvider(fake); var config = ProvideConfiguration(dateTimeProvider); var connection = ProvideConnection(fake, config); var getCall = FakeCalls.GetSyncCall(fake); var ok = FakeResponse.Ok(config); var bad = FakeResponse.Bad(config); getCall.ReturnsNextFromSequence( ok, //info 1 - 9204 bad, //info 2 - 9203 DEAD ok, //info 2 retry - 9202 ok, //info 3 - 9201 ok, //info 4 - 9204 ok, //info 5 - 9202 ok, //info 6 - 9201 ok, //info 7 - 9204 ok, //info 8 - 9203 (Now > Timeout) ok //info 9 - 9202 ); var seenNodes = new List<Uri>(); getCall.Invokes((Uri u, IRequestConnectionConfiguration o) => seenNodes.Add(u)); var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(ok); 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 AssertSeenNodesAreInExpectedOrder(seenNodes); //4 nodes first time usage + 1 time after the first time 9203 came back to live pingCall.MustHaveHappened(Repeated.Exactly.Times(5)); } }
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); } }
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 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); } }
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 static IReturnValueConfiguration<ElasticsearchResponse<Stream>> Sniff( AutoFake fake, IConnectionConfigurationValues configurationValues = null, IList<Uri> nodes = null) { var sniffCall = A.CallTo(() => fake.Resolve<IConnection>().GetSync( A<Uri>.That.Matches(IsSniffUrl()), A<IRequestConfiguration>._)); if (nodes == null) return sniffCall; sniffCall.ReturnsLazily(()=> { var stream = SniffResponse(nodes); var response = FakeResponse.Ok(configurationValues, "GET", "/_nodes/_all/clear", stream); return response; }); return sniffCall; }
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); } }
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 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); } }
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)); } }
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 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); } }