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); } }
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 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 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 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 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 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 ServerExceptionIsCaught_KeepResponse_Async(int status, string exceptionType, string exceptionMessage) { var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage); using (var fake = new AutoFake(callsDoNothing: true)) { this.CallAsync(status, exceptionType, exceptionMessage, fake, response, exposeRawResponse: true); } }
public void ByDefaultFakesAreNotStrict() { using (var fake = new AutoFake()) { var foo = fake.Resolve<Foo>(); Assert.DoesNotThrow(() => foo.Go()); } }
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 ServerExceptionIsCaught_DiscardResponse(int status, string exceptionType, string exceptionMessage) { var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage); using (var fake = new AutoFake(callsDoNothing: true)) { this.Call(status, exceptionType, exceptionMessage, fake, response); } }
public async void ServerExceptionIsCaught_DiscardResponse_Async(int status, string exceptionType, string exceptionMessage) { var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage); using (var fake = new AutoFake(callsDoNothing: true)) { var result = await this.CallAsync(status, exceptionType, exceptionMessage, fake, response); result.ResponseRaw.Should().BeNull(); } }
public void ServerExceptionIsCaught_KeepResponse(int status, string exceptionType, string exceptionMessage) { var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage); using (var fake = new AutoFake(callsDoNothing: true)) { var result = this.Call(status, exceptionType, exceptionMessage, fake, response, exposeRawResponse: true); result.ResponseRaw.Should().NotBeNull(); } }
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 ByDefaultConcreteTypesAreResolvedToTheSameSharedInstance() { using (var fake = new AutoFake()) { var baz1 = fake.Resolve<Baz>(); var baz2 = fake.Resolve<Baz>(); Assert.AreSame(baz1, baz2); } }
public void ByDefaultAbstractTypesAreResolvedToTheSameSharedInstance() { using (var fake = new AutoFake()) { var bar1 = fake.Resolve<IBar>(); var bar2 = fake.Resolve<IBar>(); Assert.AreSame(bar1, bar2); } }
public static ITransport ProvideDefaultTransport( AutoFake fake, IDateTimeProvider dateTimeProvider = null, IMemoryStreamProvider memoryStreamProvider = null ) { var dateTimeParam = new TypedParameter(typeof(IDateTimeProvider), dateTimeProvider); var memoryStreamParam = new TypedParameter(typeof(IMemoryStreamProvider), memoryStreamProvider); var serializerParam = new TypedParameter(typeof(IElasticsearchSerializer), null); return fake.Provide<ITransport, Transport>(dateTimeParam, serializerParam, memoryStreamParam); }
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 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 ShouldAllowLogLevelIn(string command, LogLevel level) { AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider()); var builder = AutoFake.Resolve <CommandLineBuilder>(); (builder as ICommandLineConventionContext).OnRun( state => (int)(state.GetLogLevel() ?? LogLevel.Information) ); var response = builder.Build(typeof(CommandLineBuilderTests).GetTypeInfo().Assembly); var result = (LogLevel)response.Execute(AutoFake.Resolve <IServiceProvider>(), command.Split(' ')); result.Should().Be(level); }
public void Constructs() { var configuration = AutoFake.Resolve <IConfiguration>(); var builder = AutoFake.Resolve <ConfigurationBuilder>(); builder.Logger.Should().NotBeNull(); builder.Configuration.Should().NotBeNull(); builder.Configuration.Should().BeSameAs(configuration); Action a = () => { builder.AppendConvention(A.Fake <IConfigurationConvention>()); }; a.Should().NotThrow(); a = () => { builder.AppendDelegate(delegate { }); }; a.Should().NotThrow(); }
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 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 Handle_Four_Fake_Item() { var fake1 = AutoFake.Provide(FakeItEasy.A.Fake <Item>()); var fake2 = AutoFake.Provide(FakeItEasy.A.Fake <Item>()); var fake3 = AutoFake.Provide(FakeItEasy.A.Fake <Item>()); var fake4 = AutoFake.Provide(FakeItEasy.A.Fake <Item>()); var result = AutoFake.Resolve <IEnumerable <Item> >().ToArray(); result.Should().HaveCount(4); result.Should().Contain(fake1); result.Should().Contain(fake2); result.Should().Contain(fake3); result.Should().Contain(fake4); }
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 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 ShouldAppendDelegates_AsAnEnumerable() { var scanner = AutoFake.Resolve <BasicConventionScanner>(); var convention = A.Fake <ServiceConventionDelegate>(x => x.Named("convention")); var convention2 = A.Fake <ServiceConventionDelegate>(x => x.Named("convention2")); var convention3 = A.Fake <ServiceConventionDelegate>(x => x.Named("convention3")); var conventions = new[] { convention3, convention, convention2 }.AsEnumerable(); scanner.AppendDelegate(conventions); var result = scanner.BuildProvider().Get <IServiceConvention, ServiceConventionDelegate>(); result.Should().HaveCount(3); result.Select(x => x.Delegate).Should().ContainInOrder(conventions); }
public void ShouldResolveConventionsUsingTheServiceProvider_And_Fail_IfTypeIsNotProvided() { var properties = new ServiceProviderDictionary(); AutoFake.Provide <IServiceProvider>(properties); var scanner = AutoFake.Resolve <Scanner>(); properties.Add(typeof(IConventionScanner), scanner); scanner.AppendConvention <F>(); Action a = () => scanner.BuildProvider().Get <IServiceConvention, ServiceConventionDelegate>(); a.Should().Throw <InvalidOperationException>(); }
public static IReturnValueConfiguration<Task<ElasticsearchResponse<Stream>>> SniffAsync( AutoFake fake, IConnectionConfigurationValues configurationValues = null, IList<Uri> nodes = null ) { var sniffCall = A.CallTo(() => fake.Resolve<IConnection>().Get( A<Uri>.That.Matches(IsSniffUrl()), A<IRequestConnectionConfiguration>._)); if (nodes == null) return sniffCall; var stream = SniffResponse(nodes); var response = FakeResponse.Ok(configurationValues, "GET", "/_nodes/_all/clear", stream); sniffCall.Returns(Task.FromResult(response)); return sniffCall; }
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 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 ShouldHandleExcludedConventions() { var scanner = AutoFake.Resolve <BasicConventionScanner>(); var convention = A.Fake <IServiceConvention>(); scanner.PrependConvention(convention); scanner.ExceptConvention(convention.GetType()); var provider = scanner.BuildProvider(); provider.Get <IServiceConvention, ServiceConventionDelegate>() .Select(x => x.Convention) .Should() .NotContain(convention); }
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 ShouldEnableHelpOnAllCommands() { AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider()); var builder = AutoFake.Resolve <CommandLineBuilder>(); builder.AddCommand <Remote>(); builder.AddCommand <Fetch>(); var response = builder.Build(); response.Application.OptionHelp.Should().NotBeNull(); response.Execute(AutoFake.Resolve <IServiceProvider>(), "remote", "add", "-v").Should().Be(1); Logger.LogInformation(response.Application.Commands.Find(x => x.Name == "remote") !.GetHelpText()); response.Application.Commands.Find(x => x.Name == "fetch") !.GetHelpText().Should().NotBeNullOrEmpty(); }
public void ShouldPrependDelegates_AsAnArray() { var scanner = AutoFake.Resolve <Scanner>(); var convention = A.Fake <ServiceConventionDelegate>(x => x.Named("convention")); var convention2 = A.Fake <ServiceConventionDelegate>(x => x.Named("convention2")); var convention3 = A.Fake <ServiceConventionDelegate>(x => x.Named("convention3")); var conventions = new[] { convention3, convention, convention2 }; scanner.PrependDelegate(conventions); var result = scanner.BuildProvider().Get <IServiceConvention, ServiceConventionDelegate>(); result.Count().Should().Be(3); result.Select(x => x.Delegate).Should().ContainInOrder(conventions); }
public 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>(); Assert.Throws <MaxRetryException>(async() => await client.InfoAsync()); getCall.MustHaveHappened(Repeated.Exactly.Times(_retries + 1)); } }
public void Constructs() { var assemblyProvider = AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider()); var builder = AutoFake.Resolve <LoggingBuilder>(); builder.AssemblyProvider.Should().BeSameAs(assemblyProvider); builder.AssemblyCandidateFinder.Should().NotBeNull(); builder.Services.Should().NotBeNull(); builder.Configuration.Should().NotBeNull(); builder.Environment.Should().NotBeNull(); Action a = () => { builder.PrependConvention(A.Fake <ILoggingConvention>()); }; a.Should().NotThrow(); a = () => { builder.PrependDelegate(delegate { }); }; a.Should().NotThrow(); }
public void ShouldNotRetryOn400() { using (var fake = new AutoFake(callsDoNothing: true)) { fake.Provide <IConnectionConfigurationValues>(_connectionConfig); FakeCalls.ProvideDefaultTransport(fake); var getCall = FakeCalls.GetSyncCall(fake); getCall.Returns(FakeResponse.Any(_connectionConfig, 400)); var client = fake.Resolve <ElasticsearchClient>(); Assert.DoesNotThrow(() => client.Info()); getCall.MustHaveHappened(Repeated.Exactly.Once); } }
public void ConstructTheContainerAndRegisterWithSystem_ServiceProvider() { AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider()); AutoFake.Provide <IServiceCollection>(new ServiceCollection()); var servicesBuilder = AutoFake.Resolve <ServicesBuilder>(); servicesBuilder.Services.AddSingleton(A.Fake <IAbc3>()); servicesBuilder.Services.AddSingleton(A.Fake <IAbc4>()); var sp = servicesBuilder.Build(); sp.GetService <IAbc>().Should().BeNull(); sp.GetService <IAbc2>().Should().BeNull(); sp.GetService <IAbc3>().Should().NotBeNull(); sp.GetService <IAbc4>().Should().NotBeNull(); }
public void Should_Call_Through_To_Delegate_Methods() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(x => { }) .ConfigureRocketSurgery( x => x .UseScanner(AutoFake.Resolve <IConventionScanner>()) .PrependDelegate(new Action(() => { })) .AppendDelegate(new Action(() => { })) ) .ConfigureServices((context, collection) => { }); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().PrependDelegate(A <Delegate> ._)) .MustHaveHappened(1, Times.Exactly); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().AppendDelegate(A <Delegate> ._)) .MustHaveHappened(1, Times.Exactly); }
public void Should_Call_Through_To_Delegate_Methods() { var startup = new Startup(); var builder = new WebJobsBuilder() .UseRocketBooster( startup, RocketBooster.For(DependencyContext.Load(typeof(RocketHostTests).Assembly)), rb => rb .UseScanner(AutoFake.Resolve <IConventionScanner>()) .PrependDelegate(new Action(() => { })) .AppendDelegate(new Action(() => { })) ); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().PrependDelegate(A <Delegate> ._)).MustHaveHappened(1, Times.Exactly); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().AppendDelegate(A <Delegate> ._)).MustHaveHappened(1, Times.Exactly); }
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 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 ChooseMatchViewModelTests() { Container.RegisterDependencies(); _fake = new AutoFake(); _scope = Container.ForTest_SetContainer(_fake.Container); MessagingCenter.Subscribe <ChooseMatchViewModel>(this, MessageKeys.CHOOSEMATCHLANDEDKEY, (sender) => { _iSAppLandedOn = true; }); MessagingCenter.Subscribe <PlayMatchViewModel>(this, MessageKeys.PLAYMATCHLANDEDKEY, (sender) => { _isNavigatedToPlayMatch = true; }); }
public void Should_ConfigureLogging() { var builder = Host.CreateDefaultBuilder() .ConfigureRocketSurgery( rb => rb .UseDependencyContext(DependencyContext.Default) .UseScanner(AutoFake.Resolve <IConventionScanner>()) .ConfigureLogging(x => { }) ); builder.Build(); A.CallTo( () => AutoFake.Resolve <IConventionScanner>().AppendDelegate( A <Delegate[]> .That.Matches(z => z[0].GetType() == typeof(LoggingConventionDelegate)) ) ).MustHaveHappened(); }
public void Should_Call_Through_To_Convention_Methods() { var convention = AutoFake.Resolve <IConvention>(); Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(x => { }) .ConfigureRocketSurgery( x => x .UseScanner(AutoFake.Resolve <IConventionScanner>()) .PrependConvention(convention) .AppendConvention(convention) ); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().PrependConvention(A <IConvention> ._)) .MustHaveHappened(1, Times.Exactly); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().AppendConvention(A <IConvention> ._)) .MustHaveHappened(1, Times.Exactly); }
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 ConstructTheContainerAndRegisterWithCore() { AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider()); AutoFake.Provide <IServiceCollection>(new ServiceCollection()); AutoFake.Provide(new ContainerBuilder()); var servicesBuilder = AutoFake.Resolve <AutofacBuilder>(); servicesBuilder.ConfigureContainer(c => c.RegisterInstance(A.Fake <IAbc>())); servicesBuilder.Services.AddSingleton(A.Fake <IAbc2>()); var items = servicesBuilder.Build(); items.ResolveOptional <IAbc>().Should().NotBeNull(); items.ResolveOptional <IAbc2>().Should().NotBeNull(); items.ResolveOptional <IAbc3>().Should().BeNull(); items.ResolveOptional <IAbc4>().Should().BeNull(); }
public void Should_Call_Through_To_Convention_Methods() { AutoFake.Provide(Array.Empty <string>()); var convention = AutoFake.Resolve <IConvention>(); Host.CreateDefaultBuilder() .ConfigureRocketSurgery( rb => rb .UseScanner(AutoFake.Resolve <IConventionScanner>()) .PrependConvention(convention) .AppendConvention(convention) ); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().PrependConvention(A <IConvention> ._)) .MustHaveHappened(1, Times.Exactly); A.CallTo(() => AutoFake.Resolve <IConventionScanner>().AppendConvention(A <IConvention> ._)) .MustHaveHappened(1, Times.Exactly); }
public void Constructs() { var assemblyProvider = AutoFake.Provide <IAssemblyProvider>(new TestAssemblyProvider()); var builder = AutoFake.Resolve <CommandLineBuilder>(); builder.AssemblyProvider.Should().BeSameAs(assemblyProvider); builder.AssemblyCandidateFinder.Should().NotBeNull(); Action a = () => { builder.PrependConvention(A.Fake <ICommandLineConvention>()); }; a.Should().NotThrow(); a = () => { builder.AppendConvention(A.Fake <ICommandLineConvention>()); }; a.Should().NotThrow(); a = () => { builder.PrependDelegate(delegate { }); }; a.Should().NotThrow(); a = () => { builder.AppendDelegate(delegate { }); }; a.Should().NotThrow(); }
public void ShouldNotRetryOn400() { using (var fake = new AutoFake(callsDoNothing: true)) { var settings = fake.Provide<IConnectionConfigurationValues>(_connectionConfig); this.ProvideTransport(fake); var getCall = A.CallTo(() => fake.Resolve<IConnection>().GetSync(A<Uri>._)); getCall.Returns(ElasticsearchResponse.Create(settings, 400, "GET", "/", null, null)); var client = fake.Resolve<ElasticsearchClient>(); Assert.DoesNotThrow(()=> client.Info()); getCall.MustHaveHappened(Repeated.Exactly.Once); } }
public void ShouldConstruct() { var properties = new ServiceProviderDictionary(); AutoFake.Provide <IServiceProviderDictionary>(properties); var builder = AutoFake.Resolve <CCBuilder>(); builder.Should().NotBeNull(); builder.Properties.Should().NotBeNull(); builder.Scanner.Should().NotBeNull(); builder.AssemblyProvider.Should().NotBeNull(); builder.AssemblyCandidateFinder.Should().NotBeNull(); builder["a"] = "b"; builder["a"].Should().Be("b"); }
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 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>(); 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.Once); nowCall.MustHaveHappened(Repeated.Exactly.Times(7)); //var nowCall = A.CallTo(() => fake.Resolve<IDateTimeProvider>().Sniff(A<Uri>._, A<int>._)); } }
public void ShouldNotRetryOn201() { using (var fake = new AutoFake(callsDoNothing: true)) { fake.Provide<IConnectionConfigurationValues>(_connectionConfig); FakeCalls.ProvideDefaultTransport(fake); var getCall = FakeCalls.GetSyncCall(fake); getCall.Returns(FakeResponse.Any(_connectionConfig, 201)); var client = fake.Resolve<ElasticsearchClient>(); Assert.DoesNotThrow(() => client.Info()); getCall.MustHaveHappened(Repeated.Exactly.Once); } }
public void MustRegisterListeners_Implicitly() { AutoFake.Provide <IServiceCollection>(new ServiceCollection()); var serviceProviderDictionary = new ServiceProviderDictionary(); AutoFake.Provide <IServiceProviderDictionary>(serviceProviderDictionary); AutoFake.Provide <IServiceProvider>(serviceProviderDictionary); AutoFake.Provide <IDictionary <object, object?> >(serviceProviderDictionary); var scanner = AutoFake.Resolve <SimpleConventionScanner>(); AutoFake.Provide <IConventionScanner>(scanner); serviceProviderDictionary.Set( new MartenOptions { SessionTracking = DocumentTracking.DirtyTracking, UseSession = true } ); var servicesBuilder = AutoFake.Resolve <ServicesBuilder>(); servicesBuilder.Scanner.AppendConvention <MartenConvention>(); servicesBuilder.Services.AddSingleton(A.Fake <IDocumentSessionListener>()); servicesBuilder.Services.AddTransient <MartenRegistry, MyMartenRegistry>(); servicesBuilder.Services.AddSingleton(LoggerFactory); servicesBuilder.Services.AddSingleton <IClock>( new FakeClock( Instant.FromDateTimeOffset(DateTimeOffset.Now), Duration.FromSeconds(1) ) ); servicesBuilder.Services.AddScoped <IMartenContext>( _ => new MartenContext { User = new MartenUser <string>(() => "abc123") } ); var serviceProvider = servicesBuilder.Build(); var options = serviceProvider.GetRequiredService <IOptions <StoreOptions> >().Value; options.Connection(() => new NpgsqlConnection()); var session = serviceProvider.GetService <IDocumentSession>(); session.Listeners.Count.Should().Be(1); }
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); } }
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 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); } }