コード例 #1
0
        public FollowerRoleTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();

            builder.Provide <ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide <IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve <ISettings>();
            this.settings.ApplyEntriesOnFollowers.Returns(true);
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve <IRandom>();
            this.random.Next(Arg.Any <int>(), Arg.Any <int>()).Returns(RiggedRandomResult);

            this.coordinator  = builder.Resolve <IRoleCoordinator <int> >();
            this.stateMachine = builder.Resolve <IStateMachine <int> >();

            this.timers = new MockTimers();
            builder.Provide <RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf <InMemoryPersistentState>();
            builder.Provide <IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf <InMemoryLog <int> >();
            builder.Provide <IPersistentLog <int> >(this.journal);

            // After the container is configured, resolve required services.
            this.role = builder.Resolve <FollowerRole <int> >();
        }
コード例 #2
0
        public FollowerRoleTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();
            builder.Provide<ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide<IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve<ISettings>();
            this.settings.ApplyEntriesOnFollowers.Returns(true);
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve<IRandom>();
            this.random.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(RiggedRandomResult);

            this.coordinator = builder.Resolve<IRoleCoordinator<int>>();
            this.stateMachine = builder.Resolve<IStateMachine<int>>();

            this.timers = new MockTimers();
            builder.Provide<RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf<InMemoryLog<int>>();
            builder.Provide<IPersistentLog<int>>(this.journal);

            // After the container is configured, resolve required services.
            this.role = builder.Resolve<FollowerRole<int>>();
        }
コード例 #3
0
        public void CanSetUserSettings()
        {
            Logger.Debug("CanSetUserSettings");
            var autoResetEvent = new AutoResetEvent(false);

            var inMemoryBlobCache = new InMemoryBlobCache();

            _autoSub.Provide <IBlobCache>(inMemoryBlobCache);

            var dataCache = _autoSub.Resolve <DataCache>();

            dataCache.SetUserSettings(new UserSettings())
            .Subscribe(_ => autoResetEvent.Set());

            autoResetEvent.WaitOne();

            string[] keys = null;

            inMemoryBlobCache.GetAllKeys()
            .Subscribe(enumerable =>
            {
                keys = enumerable.ToArray();
                autoResetEvent.Set();
            });

            autoResetEvent.WaitOne();

            keys.Should().NotBeNull();
            keys.Should().Contain("UserSettings");
        }
コード例 #4
0
 public OctopusDeployTests()
 {
     _container = new AutoSubstitute();
     _config    = new ConfigSettings(s => string.Format("%{0}%", s), s => string.Format("c:\\{0}", s));
     _container.Provide(_config);
     _container.Provide(MachineName);
     _sut = _container.Resolve <OctopusDeploy.Infrastructure.OctopusDeploy>();
 }
コード例 #5
0
 public OctopusDeployTests()
 {
     _container = new AutoSubstitute();
     _config = new ConfigSettings(s => string.Format("%{0}%", s), s => string.Format("c:\\{0}", s));
     _container.Provide(_config);
     _container.Provide(MachineName);
     _sut = _container.Resolve<OctopusDeploy.Infrastructure.OctopusDeploy>();
 }
コード例 #6
0
        public CandidateRoleTests(ITestOutputHelper output)
        {
            var builder =
                new AutoSubstitute(cb => cb.Register(_ => Substitute.For<IRaftGrain<int>>()).InstancePerDependency());
            builder.Provide<ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide<IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve<ISettings>();
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve<IRandom>();
            this.random.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(RiggedRandomResult);

            this.coordinator = builder.Resolve<IRoleCoordinator<int>>();
            this.coordinator.StepDownIfGreaterTerm(Arg.Any<IMessage>())
                .Returns(
                    info => Task.FromResult(((IMessage)info[0]).Term > this.persistentState.CurrentTerm));
            var currentRole = builder.Resolve<IRaftRole<int>>();
            currentRole.RequestVote(Arg.Any<RequestVoteRequest>())
                .Returns(Task.FromResult(new RequestVoteResponse { Term = 1, VoteGranted = true }));
            currentRole.Append(Arg.Any<AppendRequest<int>>())
                .Returns(Task.FromResult(new AppendResponse { Term = 1, Success = true }));
            this.coordinator.Role.Returns(currentRole);

            this.timers = new MockTimers();
            builder.Provide<RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf<InMemoryLog<int>>();
            builder.Provide<IPersistentLog<int>>(this.journal);

            this.identity = Substitute.For<IServerIdentity>();
            this.identity.Id.Returns(Guid.NewGuid().ToString());
            builder.Provide(this.identity);

            this.members = builder.Resolve<StaticMembershipProvider>();
            this.members.SetServers(new[] { this.identity.Id, "other1", "other2", "other3", "other4" });
            builder.Provide<IMembershipProvider>(this.members);

            this.grainFactory = new FakeGrainFactory(builder.Container);
            builder.Provide<IGrainFactory>(this.grainFactory);
            this.OnRaftGrainCreated =
                (id, grain) =>
                grain.RequestVote(Arg.Any<RequestVoteRequest>())
                    .Returns(Task.FromResult(new RequestVoteResponse { VoteGranted = true }));

            // After the container is configured, resolve required services.
            this.role = builder.Resolve<CandidateRole<int>>();
            this.container = builder;
        }
        public void TestIEnumerableCorrectlyResolves()
        {
            using (var autosub = new AutoSubstitute())
            {
                var mockA     = autosub.Provide <IServiceItem, ServiceItemA>();
                var mockB     = autosub.Provide <IServiceItem, ServiceItemB>();
                var component = autosub.Resolve <TestIEnumerableComponent>();

                Assert.That(component.ServiceItems, Is.Not.Empty);
                Assert.That(component.ServiceItems.Contains(mockA), Is.True);
                Assert.That(component.ServiceItems.Contains(mockB), Is.True);
            }
        }
コード例 #8
0
        public void TestIListCorrectlyResolves()
        {
            using (var autosub = new AutoSubstitute())
            {
                var mockA     = autosub.Provide <IServiceItem, ServiceItemA>();
                var mockB     = autosub.Provide <IServiceItem, ServiceItemB>();
                var component = autosub.Resolve <TestIListComponent>();

                Assert.NotEmpty(component.ServiceItems);
                Assert.True(component.ServiceItems.Contains(mockA));
                Assert.True(component.ServiceItems.Contains(mockB));
            }
        }
コード例 #9
0
        public ImageManagementServiceTests(ITestOutputHelper testOutputHelper)
            : base(testOutputHelper)
        {
            _autoSubstitute = new AutoSubstitute();

            _testSchedulerProvider = new TestSchedulerProvider();
            _autoSubstitute.Provide <ISchedulerProvider>(_testSchedulerProvider);

            _unitOfWorkQueue = new Queue <IUnitOfWork>();
            _autoSubstitute.Provide <Func <IUnitOfWork> >(() => _unitOfWorkQueue.Dequeue());

            _mockFileSystem = new MockFileSystem();
            _autoSubstitute.Provide <IFileSystem>(_mockFileSystem);
        }
コード例 #10
0
        public RoleCoordinatorTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();
            builder.Provide<ILogger>(new TestLogger(output));

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            builder.ResolveAndSubstituteFor<FollowerRole<int>>();

            // After the container is configured, resolve required services.
            this.coordinator = builder.Resolve<RoleCoordinator<int>>();
            this.container = builder;
        }
コード例 #11
0
        public RoleCoordinatorTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();

            builder.Provide <ILogger>(new TestLogger(output));

            this.persistentState = Substitute.ForPartsOf <InMemoryPersistentState>();
            builder.Provide <IRaftPersistentState>(this.persistentState);

            builder.ResolveAndSubstituteFor <FollowerRole <int> >();

            // After the container is configured, resolve required services.
            this.coordinator = builder.Resolve <RoleCoordinator <int> >();
            this.container   = builder;
        }
コード例 #12
0
        public void CanGetImages()
        {
            Logger.Debug("CanGetImages");
            var directory = Faker.System.DirectoryPathWindows();

            var subDirectory = Path.Combine(directory, Faker.Random.Word());

            var mockFileSystem = new MockFileSystem();

            _autoSub.Provide <IFileSystem>(mockFileSystem);

            var files = new[] { "jpg", "jpeg", "png", "tiff", "tif", "bmp" }
            .Select(ext => Path.Combine(subDirectory, Faker.System.FileName(ext)))
            .ToArray();

            var otherFiles = new[] { "txt", "doc" }
            .Select(ext => Path.Combine(subDirectory, Faker.System.FileName(ext)))
            .ToArray();

            foreach (var file in files.Concat(otherFiles))
            {
                mockFileSystem.AddFile(file, new MockFileData(new byte[0]));
            }

            var autoResetEvent = new AutoResetEvent(false);

            string[] imagePaths = null;

            var testSchedulerProvider = new TestSchedulerProvider();

            _autoSub.Provide <ISchedulerProvider>(testSchedulerProvider);

            var imageLocationService = _autoSub.Resolve <ImageLocationService>();

            imageLocationService.GetImages(directory)
            .Subscribe(paths =>
            {
                imagePaths = paths;
                autoResetEvent.Set();
            });

            testSchedulerProvider.TaskPool.AdvanceBy(1);
            autoResetEvent.WaitOne();

            imagePaths.Should().NotBeNull();
            imagePaths.Select(fileInfo => fileInfo)
            .Should().BeEquivalentTo(files);
        }
        public void Should_Return_Did_Open_Text_Document_Handler_Descriptor_With_Sepcial_Character()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cshtml"), "csharp");
            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, Substitute.For <IResolverContext>(),
                                                         new LspHandlerTypeDescriptorProvider(new [] { typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly }))
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            // When
            var result = handlerMatcher.FindHandler(
                new DidOpenTextDocumentParams {
                TextDocument = new TextDocumentItem {
                    Uri = new Uri("file://c:/users/myøasdf/d.cshtml")
                }
            },
                collection.Where(x => x.Method == TextDocumentNames.DidOpen)
                );

            // Then
            result.Should().NotBeNullOrEmpty();
            result.Should().Contain(x => x.Method == TextDocumentNames.DidOpen);
        }
コード例 #14
0
        public void Should_Return_Did_Open_Text_Document_Handler_Descriptor()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider())
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            // When
            var result = handlerMatcher.FindHandler(
                new DidOpenTextDocumentParams {
                TextDocument = new TextDocumentItem {
                    Uri = new Uri("file:///abc/123/d.cs")
                }
            },
                collection.Where(x => x.Method == TextDocumentNames.DidOpen)
                );

            // Then
            result.Should().NotBeNullOrEmpty();
            result.Should().Contain(x => x.Method == TextDocumentNames.DidOpen);
        }
コード例 #15
0
        public void Should_Return_Did_Open_Text_Document_Handler_Descriptor_With_Sepcial_Character()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cshtml"));
            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue)
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            // When
            var result = handlerMatcher.FindHandler(new DidOpenTextDocumentParams()
            {
                TextDocument = new TextDocumentItem {
                    Uri = new Uri("file://c:/users/myøasdf/d.cshtml")
                }
            },
                                                    collection.Where(x => x.Method == DocumentNames.DidOpen));

            // Then
            result.Should().NotBeNullOrEmpty();
            result.Should().Contain(x => x.Method == DocumentNames.DidOpen);
        }
        public async Task ShouldHandle_Request_WithMissingParameters()
        {
            bool wasShutdown     = false;
            var  shutdownHandler = new ServerShutdownHandler();

            shutdownHandler.Shutdown.Subscribe(shutdownRequested =>
            {
                wasShutdown = true;
            });

            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers())
            {
                shutdownHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            JToken @params = null; // If the "params" property was missing entirely, this will be null.

            var id      = Guid.NewGuid().ToString();
            var request = new Request(id, GeneralNames.Shutdown, @params);

            await mediator.RouteRequest(mediator.GetDescriptor(request), request, CancellationToken.None);

            Assert.True(shutdownHandler.ShutdownRequested, "WasShutDown");
        }
コード例 #17
0
        public GetActiveIqAccountCommandHandlerTest()
        {
            AutoSubstitute = new AutoSubstitute();
            _connection    = AutoSubstitute.Resolve <IDbConnection>();

            AutoSubstitute.Provide <Func <IDbConnection> >(() => _connection);
        }
コード例 #18
0
        public void Should_Return_Did_Change_Text_Document_Descriptor()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"));
            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue)
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            // When
            var result = handlerMatcher.FindHandler(new DidChangeTextDocumentParams()
            {
                TextDocument = new VersionedTextDocumentIdentifier {
                    Uri = new Uri("file:///abc/123/d.cs"), Version = 1
                }
            },
                                                    collection.Where(x => x.Method == DocumentNames.DidChange));

            // Then
            result.Should().NotBeNullOrEmpty();
            result.Should().Contain(x => x.Method == DocumentNames.DidChange);
        }
コード例 #19
0
        public async Task ShouldHandle_Request_WithNullParameters()
        {
            bool wasShutDown = false;

            var shutdownHandler = new ShutdownHandler();

            shutdownHandler.Shutdown.Subscribe(shutdownRequested =>
            {
                wasShutDown = true;
            });

            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue)
            {
                shutdownHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            JToken @params = JValue.CreateNull(); // If the "params" property present but null, this will be JTokenType.Null.

            var id      = Guid.NewGuid().ToString();
            var request = new Request(id, GeneralNames.Shutdown, @params);

            await mediator.RouteRequest(mediator.GetDescriptor(request), request);

            Assert.True(wasShutDown, "WasShutDown");
        }
        public async Task ShouldRouteTo_CorrectRequestWhenGivenNullParams()
        {
            var handler = Substitute.For <IShutdownHandler>();

            handler
            .Handle(Arg.Any <ShutdownParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);

            var collection =
                new SharedHandlerCollection(
                    SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For <IResolverContext>(),
                    new LspHandlerTypeDescriptorProvider(
                        new[] {
                typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly,
                typeof(LspRequestRouter).Assembly
            }
                        )
                    )
            {
                handler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var request = new Request(id, GeneralNames.Shutdown, new JObject());

            await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None);

            await handler.Received(1).Handle(Arg.Any <ShutdownParams>(), Arg.Any <CancellationToken>());
        }
コード例 #21
0
        public void Does_Not_Auto_Substitute_Enumerable()
        {
            AutoSubstitute.Provide <Item>(new A());
            AutoSubstitute.Provide <Item>(new B());

            AutoSubstitute.Resolve <IEnumerable <Item> >().Should().HaveCount(2);
        }
コード例 #22
0
        public void Should_Return_Did_Close_Text_Document_Descriptor()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, Substitute.For <IResolverContext>(),
                                                         new LspHandlerTypeDescriptorProvider(new [] { typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly }))
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            // When
            var result = handlerMatcher.FindHandler(
                new DidCloseTextDocumentParams {
                TextDocument = new VersionedTextDocumentIdentifier {
                    Uri = new Uri("file:///abc/123/d.cs"), Version = 1
                }
            },
                collection.Where(x => x.Method == TextDocumentNames.DidClose)
                );

            // Then
            var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray();

            lspHandlerDescriptors.Should().NotBeNullOrEmpty();
            lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidClose);
        }
        public async Task RequestsCancellation()
        {
            var executeCommandHandler = Substitute.For <IExecuteCommandHandler>();

            executeCommandHandler
            .Handle(Arg.Any <ExecuteCommandParams>(), Arg.Any <CancellationToken>())
            .Returns(async(c) => {
                await Task.Delay(1000, c.Arg <CancellationToken>());
                throw new XunitException("Task was not cancelled in time!");
                return(Unit.Value);
            });

            var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers())
            {
                executeCommandHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new ExecuteCommandParams()
            {
                Command = "123"
            };
            var request = new Request(id, "workspace/executeCommand", JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)));
            var cts     = new CancellationTokenSource();

            cts.Cancel();

            var         response = ((IRequestRouter <ILspHandlerDescriptor>)mediator).RouteRequest(mediator.GetDescriptor(request), request, cts.Token);
            Func <Task> action   = () => ((IRequestRouter <ILspHandlerDescriptor>)mediator).RouteRequest(mediator.GetDescriptor(request), request, cts.Token);
            await action.Should().ThrowAsync <OperationCanceledException>();
        }
        public async Task ShouldRouteToCorrect_Notification()
        {
            var textDocumentSyncHandler = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>()).Returns(Unit.Value);

            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers())
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var @params = new DidSaveTextDocumentParams()
            {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs"))
            };

            var request = new Notification(DocumentNames.DidSave, JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)));

            await mediator.RouteNotification(mediator.GetDescriptor(request), request, CancellationToken.None);

            await textDocumentSyncHandler.Received(1).Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>());
        }
コード例 #25
0
        public async Task RequestsCancellation()
        {
            var executeCommandHandler = Substitute.For <IExecuteCommandHandler>();

            executeCommandHandler
            .Handle(Arg.Any <ExecuteCommandParams>(), Arg.Any <CancellationToken>())
            .Returns(async(c) => {
                await Task.Delay(1000, c.Arg <CancellationToken>());
                throw new XunitException("Task was not cancelled in time!");
                return(Unit.Value);
            });

            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue)
            {
                executeCommandHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new ExecuteCommandParams()
            {
                Command = "123"
            };
            var request = new Request(id, "workspace/executeCommand", JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)));

            var response = ((IRequestRouter)mediator).RouteRequest(request);

            mediator.CancelRequest(id);
            var result = await response;

            result.IsError.Should().BeTrue();
            result.Error.Should().BeEquivalentTo(new RequestCancelled());
        }
コード例 #26
0
        public void Should_Return_Code_Lens_Descriptor()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, Substitute.For <IResolverContext>(),
                                                         new LspHandlerTypeDescriptorProvider(new [] { typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly }))
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            var codeLensHandler = (ICodeLensHandler)Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]);

            codeLensHandler.GetRegistrationOptions(Arg.Any <CodeLensCapability>(), Arg.Any <ClientCapabilities>())
            .Returns(
                new CodeLensRegistrationOptions {
                DocumentSelector = new DocumentSelector(new DocumentFilter {
                    Pattern = "**/*.cs"
                })
            }
                );

            var codeLensHandler2 = (ICodeLensHandler)Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]);

            codeLensHandler2.GetRegistrationOptions(Arg.Any <CodeLensCapability>(), Arg.Any <ClientCapabilities>())
            .Returns(
                new CodeLensRegistrationOptions {
                DocumentSelector = new DocumentSelector(new DocumentFilter {
                    Pattern = "**/*.cake"
                })
            }
                );
            collection.Add(codeLensHandler, codeLensHandler2);
            collection.Initialize();

            // When
            var result = handlerMatcher.FindHandler(
                new CodeLensParams {
                TextDocument = new OptionalVersionedTextDocumentIdentifier {
                    Uri = new Uri("file:///abc/123/d.cs"), Version = 1
                }
            },
                collection.Where(x => x.Method == TextDocumentNames.CodeLens)
                );

            // Then
            var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray();

            lspHandlerDescriptors.Should().NotBeNullOrEmpty();
            lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.CodeLens);
            lspHandlerDescriptors.Should().Contain(x => ((LspHandlerDescriptor)x).Key == "[**/*.cs]");
        }
コード例 #27
0
        public GetIqAccountByIqAccountUserIdTest()
        {
            Mapper.Initialize(c => { c.AddProfiles(typeof(iqoption.data.AiOptionContext).Assembly); });
            Mapper.AssertConfigurationIsValid();

            AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Provide <IMapper>(Mapper.Instance);
        }
コード例 #28
0
 public void Should_Populate_Optional_Parameters_When_Provided()
 {
     AutoSubstitute.Provide <IItem>(new MyItem());
     AutoSubstitute.Resolve <Optional>()
     .Item
     .Should()
     .NotBeNull();
 }
        public async Task ShouldRouteToCorrect_Request_WithManyHandlers_CodeLensHandler()
        {
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentSyncHandler2 =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);
            textDocumentSyncHandler2.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);

            var codeActionHandler = Substitute.For <ICodeLensHandler>();

            codeActionHandler.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cs")
            });
            codeActionHandler
            .Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>())
            .Returns(new CodeLensContainer());

            var codeActionHandler2 = Substitute.For <ICodeLensHandler>();

            codeActionHandler2.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cake")
            });
            codeActionHandler2
            .Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>())
            .Returns(new CodeLensContainer());

            var tdi        = new TextDocumentIdentifiers();
            var collection =
                new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, tdi, new ServiceCollection().BuildServiceProvider())
            {
                textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler, codeActionHandler2
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            AutoSubstitute.Provide <IHandlerMatcher>(new TextDocumentMatcher(LoggerFactory.CreateLogger <TextDocumentMatcher>(), tdi));
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new CodeLensParams {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs"))
            };

            var request = new Request(
                id, TextDocumentNames.CodeLens,
                JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))
                );

            await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None);

            await codeActionHandler2.Received(0).Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>());

            await codeActionHandler.Received(1).Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>());
        }
        public async Task ShouldRouteToCorrect_Request_WithManyHandlers()
        {
            var textDocumentSyncHandler  = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentSyncHandler2 = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>()).Returns(Unit.Value);
            textDocumentSyncHandler2.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>()).Returns(Unit.Value);

            var codeActionHandler = Substitute.For <ICodeActionHandler>();

            codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions()
            {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cs")
            });
            codeActionHandler
            .Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>())
            .Returns(new CommandOrCodeActionContainer());

            var registry           = new TestLanguageServerRegistry();
            var codeActionDelegate = Substitute.For <Func <CodeActionParams, CancellationToken, Task <CommandOrCodeActionContainer> > >();

            codeActionDelegate.Invoke(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>())
            .Returns(new CommandOrCodeActionContainer());
            registry.OnCodeAction(
                codeActionDelegate,
                new CodeActionRegistrationOptions()
            {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cake")
            }
                );

            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var handlerCollection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers)
            {
                textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler
            };

            handlerCollection.Add(registry.Handlers);
            AutoSubstitute.Provide <IHandlerCollection>(handlerCollection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(handlerCollection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new CodeActionParams()
            {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cake"))
            };

            var request = new Request(id, DocumentNames.CodeAction, JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)));

            await mediator.RouteRequest(mediator.GetDescriptor(request), request, CancellationToken.None);

            await codeActionHandler.Received(0).Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>());

            await codeActionDelegate.Received(1).Invoke(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>());
        }
コード例 #31
0
        public LeaderRoleTests(ITestOutputHelper output)
        {
            var builder =
                new AutoSubstitute(cb => cb.Register(_ => Substitute.For <IRaftGrain <int> >()).InstancePerDependency());

            builder.Provide <ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide <IRaftVolatileState>(this.volatileState);

            this.coordinator = builder.Resolve <IRoleCoordinator <int> >();
            this.coordinator.StepDownIfGreaterTerm(Arg.Any <IMessage>())
            .Returns(
                info => Task.FromResult(((IMessage)info[0]).Term > this.persistentState.CurrentTerm));
            var currentRole = builder.Resolve <IRaftRole <int> >();

            currentRole.RequestVote(Arg.Any <RequestVoteRequest>())
            .Returns(Task.FromResult(new RequestVoteResponse {
                Term = 1, VoteGranted = true
            }));
            currentRole.Append(Arg.Any <AppendRequest <int> >())
            .Returns(Task.FromResult(new AppendResponse {
                Term = 1, Success = true
            }));
            this.coordinator.Role.Returns(currentRole);

            this.timers = new MockTimers();
            builder.Provide <RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf <InMemoryPersistentState>();
            builder.Provide <IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf <InMemoryLog <int> >();
            builder.Provide <IPersistentLog <int> >(this.journal);

            this.identity = Substitute.For <IServerIdentity>();
            this.identity.Id.Returns(Guid.NewGuid().ToString());
            builder.Provide(this.identity);

            this.members = builder.Resolve <StaticMembershipProvider>();
            this.members.SetServers(new[] { this.identity.Id, "other1", "other2", "other3", "other4" });
            builder.Provide <IMembershipProvider>(this.members);

            this.grainFactory = new FakeGrainFactory(builder.Container);
            builder.Provide <IGrainFactory>(this.grainFactory);
            this.OnRaftGrainCreated =
                (id, grain) =>
                grain.RequestVote(Arg.Any <RequestVoteRequest>())
                .Returns(Task.FromResult(new RequestVoteResponse {
                VoteGranted = true
            }));

            // After the container is configured, resolve required services.
            this.role = builder.Resolve <LeaderRole <int> >();
        }
コード例 #32
0
        public void Handle_One_Substitute_Item()
        {
            var fake1 = AutoSubstitute.Provide(Substitute.For <Item>());

            var result = AutoSubstitute.Resolve <IEnumerable <Item> >().ToArray();

            result.Should().HaveCount(1);
            result.Should().Contain(fake1);
        }
コード例 #33
0
        public void Should_Handle_Creating_A_Substitute_With_Logger()
        {
            Action a = () =>
            {
                var lt = AutoSubstitute.Resolve <LoggerTest>();
                AutoSubstitute.Provide <Item>(lt);
            };

            a.Should().NotThrow();
        }
コード例 #34
0
        public void ProvideImplementation()
        {
            using (var mock = new AutoSubstitute())
            {
                var serviceA = mock.Provide <IServiceA, ServiceA>();

                Assert.NotNull(serviceA);
                Assert.False(serviceA is ICallRouter);
            }
        }
        public static void ShouldAcceptProvidedIndexedDependency()
        {
            var autoSubstitute = new AutoSubstitute();
            var substitute = Substitute.For<IDependency2>();
            substitute.SomeOtherMethod().Returns(5);
            autoSubstitute.Provide(substitute, Switch.On);
            
            var target = autoSubstitute.Resolve<ClassWithKeyedDependencies>();

            Assert.That(target.OnDependency.SomeOtherMethod(), Is.EqualTo(5));
        }
コード例 #36
0
 public void SetUp()
 {
     const string payload = @"<link href='global.css' type='text/css' /><div>Hello World</div>";
     _account = 1470;
     _item = 7418569;
     _autoSubstitute = AutoSubstituteContainer.Create();
     _appSettingsService = _autoSubstitute.Resolve<IAppSettingsService>();
     _simpleWebRequestService = _autoSubstitute.Resolve<ISimpleWebRequestService>();
     _simpleWebRequestService.GetResponseText(Arg.Any<string>()).Returns(payload);
     var libGuideService = new LibGuideService(_simpleWebRequestService, _appSettingsService);
     _autoSubstitute.Provide<ILibGuideService>(libGuideService);
     _controller = _autoSubstitute.Resolve<LibGuideController>();
 }
コード例 #37
0
        public void Example_test_with_concrete_type_provided()
        {
            const int val = 3;
            var AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val); // This shouldn't do anything because of the next line
            AutoSubstitute.Provide<IDependency2, Dependency2>();
            AutoSubstitute.Resolve<IDependency1>().SomeMethod(Arg.Any<int>()).Returns(c => c.Arg<int>());

            var result = AutoSubstitute.Resolve<MyClass>().AMethod();

            Assert.That(result, Is.EqualTo(Dependency2.Value));
        }
コード例 #38
0
        public void Example_test_with_concrete_object_provided()
        {
            const int val1 = 3;
            const int val2 = 2;
            var AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val1);
            AutoSubstitute.Provide(new ConcreteClass(val2));

            var result = AutoSubstitute.Resolve<MyClassWithConcreteDependency>().AMethod();

            Assert.That(result, Is.EqualTo(val1 + val2));
        }