Beispiel #1
0
        public void Setup()
        {
            _profile = new ConversionProfile();

            _interactions       = new List <IInteraction>();
            _interactionInvoker = Substitute.For <IInteractionInvoker>();

            _interactionInvoker
            .When(x => x.Invoke(Arg.Any <PasswordInteraction>()))
            .Do(x =>
            {
                var interaction    = x.Arg <PasswordInteraction>();
                interaction.Result = PasswordResult.StorePassword;
            });

            _interactionInvoker
            .When(x => x.Invoke(Arg.Any <IInteraction>()))
            .Do(x =>
            {
                _interactions.Add(x.Arg <IInteraction>());
            });

            _file       = Substitute.For <IFile>();
            _path       = Substitute.For <IPath>();
            _smtpAction = Substitute.For <ISmtpMailAction>();
            _smtpAction.Check(_profile, Arg.Any <Accounts>()).Returns(x => new ActionResult());
            _smtpAction.ProcessJob(Arg.Any <Job>()).Returns(x => new ActionResult());
        }
        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>());
        }
Beispiel #3
0
        public void SetUp()
        {
            var bootstrapper = new IntegrationTestBootstrapper();
            var container    = bootstrapper.ConfigureContainer();

            _th = container.GetInstance <TestHelper>();
            _th.InitTempFolder("DevicesGeneralTests");

            _singleTempOutputfile    = new[] { @"output1.pdf" };
            _multipleTempOutputFiles = new[] { @"output1.png", @"output2.png", @"output3.png" };
            _multipleTempOutputFilesWithTwoDigits = new[]
            {
                @"output1.png", @"output2.png", @"output3.png",
                @"output4.png", @"output5.png", @"output6.png",
                @"output7.png", @"output8.png", @"output9.png",
                @"output10.png"
            };

            _countRetypeOutputFilename = 0;
            _cancelRetypeFilename      = false;

            _pathUtil = new PathUtil(new PathWrap(), new DirectoryWrap());

            _queryRetypeFileName = Substitute.For <IRetypeFileNameQuery>();
            _queryRetypeFileName.RetypeFileName(Arg.Any <string>(), Arg.Any <OutputFormat>()).Returns(RetypeOutputFilename);
        }
        public void Setup()
        {
            _smtpTestAccount           = new SmtpAccount();
            _smtpTestAccount.AccountId = "SmtpTestAccountId";

            _profile = new ConversionProfile();
            //Attention
            _profile.EmailSmtpSettings.AccountId = _smtpTestAccount.AccountId;
            //The AccountAssosiation is mocked below. The _smtpTestAccount is always used.

            _accounts = new Accounts();
            _accounts.SmtpAccounts.Add(_smtpTestAccount);

            _interactionRequest = new UnitTestInteractionRequest();
            _interactionInvoker = Substitute.For <IInteractionInvoker>();
            _interactionInvoker.Invoke(Arg.Do <PasswordOverlayInteraction>(i => i.Result = PasswordResult.StorePassword));

            _interactionRequest.RegisterInteractionHandler <PasswordOverlayInteraction>(interaction => interaction.Result = PasswordResult.StorePassword);

            _file       = Substitute.For <IFile>();
            _path       = Substitute.For <IPath>();
            _smtpAction = Substitute.For <ISmtpMailAction>();
            _smtpAction.Check(Arg.Any <ConversionProfile>(), _accounts, Arg.Any <CheckLevel>()).Returns(x => new ActionResult());
            _smtpAction.ProcessJob(Arg.Any <Job>()).Returns(x => new ActionResult());
            //_smtpAction.GetSmtpAccount(_profile, _accounts).Returns(_smtpTestAccount);

            _mailSignatureHelper = Substitute.For <IMailSignatureHelper>();
            _mailSignatureHelper.ComposeMailSignature().Returns(_mailSignature);

            _tokenReplacer        = new TokenReplacer();
            _tokenReplacerFactory = Substitute.For <ITokenReplacerFactory>();
            _tokenReplacerFactory.BuildTokenReplacerWithOutputfiles(Arg.Any <Job>()).Returns(_tokenReplacer);

            _translation = new SmtpTranslation();
        }
Beispiel #5
0
    public void Should_Inject_LoggerFactory()
    {
        var test = AutoSubstitute.Resolve <LoggerFactoryImpl>();

        test.Write();
        AutoSubstitute.Resolve <ITestOutputHelper>().Received().WriteLine(Arg.Any <string>());
    }
Beispiel #6
0
        public void CheckInTest_顧客1男2女_應回傳收費人數1人_使用NSubstitute物件()
        {
            //arrange準備受測物件、參數、預期結果
            ICheckInFee CheckInFee = Substitute.For <ICheckInFee>();
            Pub         pub        = new Pub(CheckInFee);

            CheckInFee.GetFee(Arg.Any <Customer>()).Returns(100);
            List <Customer> customers = new List <Customer>
            {
                new Customer {
                    IsMale = true
                },
                new Customer {
                    IsMale = false
                },
                new Customer {
                    IsMale = false
                },
            };

            decimal expected = 1;
            //act執行受測方法

            decimal actual = pub.CheckIn(customers);

            //assert驗證執行結果與預測結果是否一致
            Assert.AreEqual(expected, actual);
        }
Beispiel #7
0
        public static IEnumerable <object[]> Should_DealWithClassesThatImplementMultipleHandlers_WithoutConflictingRegistrations_Data()
        {
            var codeLensHandler = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]);

            ((ICodeLensHandler)codeLensHandler).GetRegistrationOptions(Arg.Any <CodeLensCapability>(), Arg.Any <ClientCapabilities>())
            .Returns(
                new CodeLensRegistrationOptions {
                DocumentSelector = new DocumentSelector()
            }
                );

            yield return(new[] { TextDocumentNames.CodeLensResolve, codeLensHandler });

            var documentLinkHandler = Substitute.For(new[] { typeof(IDocumentLinkHandler), typeof(IDocumentLinkResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]);

            ((IDocumentLinkHandler)documentLinkHandler).GetRegistrationOptions(Arg.Any <DocumentLinkCapability>(), Arg.Any <ClientCapabilities>())
            .Returns(
                new DocumentLinkRegistrationOptions {
                DocumentSelector = new DocumentSelector()
            }
                );

            yield return(new[] { TextDocumentNames.DocumentLinkResolve, documentLinkHandler });

            var completionHandler = Substitute.For(new[] { typeof(ICompletionHandler), typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]);

            ((ICompletionHandler)completionHandler).GetRegistrationOptions(Arg.Any <CompletionCapability>(), Arg.Any <ClientCapabilities>())
            .Returns(
                new CompletionRegistrationOptions {
                DocumentSelector = new DocumentSelector()
            }
                );

            yield return(new[] { TextDocumentNames.CompletionResolve, completionHandler });
        }
Beispiel #8
0
        public void Test_Income_顧客1男2女_應回傳收費人數1人_模擬每一人收費為100元_預期結果門票收入總數為100_使用NSubstitute物件()
        {
            //arrange準備受測物件、參數、預期結果
            ICheckInFee CheckInFee = Substitute.For <ICheckInFee>();
            Pub         pub        = new Pub(CheckInFee);

            CheckInFee.GetFee(Arg.Any <Customer>()).Returns(100);

            List <Customer> customers = new List <Customer>
            {
                new Customer {
                    IsMale = false
                },
                new Customer {
                    IsMale = true
                },
                new Customer {
                    IsMale = false
                },
            };

            var inComeBeforeCheckIn = pub.GetInCome();

            Assert.AreEqual(0, inComeBeforeCheckIn);

            decimal expectedIncome = 100;

            //act執行受測方法

            decimal chargeCustomerCount = pub.CheckIn(customers);
            decimal actualIncome        = pub.GetInCome();

            //assert驗證執行結果與預測結果是否一致
            Assert.AreEqual(expectedIncome, actualIncome);
        }
Beispiel #9
0
        public void Should_Contain_AllDefinedMethods_OnLanguageServer_WithDifferentKeys(Type requestHandler, Type type2, string key, string key2, int count)
        {
            var handler = 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.Initialize();

            handler.Initialize();
            var sub = (IJsonRpcHandler)Substitute.For(new[] { requestHandler, type2 }, new object[0]);

            if (sub is IRegistration <ITextDocumentRegistrationOptions> reg)
            {
                reg.GetRegistrationOptions(Arg.Any <ClientCapabilities>())
                .Returns(
                    new TextDocumentSyncRegistrationOptions {
                    DocumentSelector = new DocumentSelector()
                }
                    );
            }
            var sub2 = (IJsonRpcHandler)Substitute.For(new[] { requestHandler, type2 }, new object[0]);

            if (sub2 is IRegistration <ITextDocumentRegistrationOptions> reg2)
            {
                reg2.GetRegistrationOptions(Arg.Any <ClientCapabilities>())
                .Returns(
                    new TextDocumentSyncRegistrationOptions {
                    DocumentSelector = new DocumentSelector()
                }
                    );
            }
            handler.Add(sub);
            handler.Add(sub2);
            handler.Should().Contain(x => x.Method == key);
            handler.Should().Contain(x => x.Method == key2);
            handler.Should().HaveCount(count);
        }
        public void DuringPasswordInteraction_ShowsRecipientsWithReplacedTokens()
        {
            var recipientToWithToken  = "<username>@to.local";
            var recipientCcWithToken  = "<username>@cc.local";
            var recipientBccWithToken = "<username>@bcc.local";
            var expectedUserName      = Environment.UserName;

            _profile.EmailSmtpSettings.Recipients    = recipientToWithToken;
            _profile.EmailSmtpSettings.RecipientsCc  = recipientCcWithToken;
            _profile.EmailSmtpSettings.RecipientsBcc = recipientBccWithToken;
            _tokenReplacer.AddStringToken("username", expectedUserName);
            //_interactionRequest.RegisterInteractionHandler<PasswordOverlayInteraction>(interaction => interaction.Result = PasswordResult.Cancel);
            PasswordOverlayInteraction interaction = null;

            _interactionInvoker.Invoke(Arg.Do <PasswordOverlayInteraction>(i =>
            {
                interaction = i;
                i.Result    = PasswordResult.Cancel;
            }));

            var assistant = BuildAssistant();

            assistant.SendTestMail(_profile, _accounts);

            StringAssert.Contains(recipientToWithToken.Replace("<username>", expectedUserName), interaction.IntroText);
            StringAssert.Contains(recipientCcWithToken.Replace("<username>", expectedUserName), interaction.IntroText);
            StringAssert.Contains(recipientBccWithToken.Replace("<username>", expectedUserName), interaction.IntroText);
        }
        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 SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider())
            {
                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(
                TextDocumentNames.DidSave,
                JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))
                );

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

            await textDocumentSyncHandler.Received(1)
            .Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>());
        }
Beispiel #12
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]");
        }
Beispiel #13
0
        public void SendTestMail_CallsSmtpAction()
        {
            var assistant = BuildAssistant();

            assistant.SendTestMail(_profile, new Accounts());

            _smtpAction.Received().ProcessJob(Arg.Any <Job>());
        }
        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>());
        }
Beispiel #15
0
        public void RemoveInvalidFiles_InsertExistingFiles_ReturnsAllFiles()
        {
            var files    = new [] { "file1", "file2", "file3" };
            var fileStub = Substitute.For <IFile>();

            fileStub.Exists(Arg.Any <string>()).Returns(true);

            Assert.AreEqual(files, DragAndDropHelper.RemoveInvalidFiles(files, fileStub));
        }
        public void SendServiceStatistics_HttpHandlerPostAsyncRecivesOneCall()
        {
            var serviceUpTime = TimeSpan.MaxValue;

            _usageStatisticsManager.EnableUsageStatistics = true;
            _usageStatisticsManager.SendServiceStatistics(serviceUpTime);

            _usageStatisticsSender.Received(1).SendAsync(Arg.Any <IUsageMetric>());
        }
Beispiel #17
0
    public void Should_Inject_GenericLogger()
    {
        var test = AutoSubstitute.Resolve <GenericLoggerImpl>();

        test.Write();
        var testOutputHelper = AutoSubstitute.Resolve <ITestOutputHelper>();

        testOutputHelper.Received().WriteLine(Arg.Any <string>());
    }
Beispiel #18
0
        public void RemoveInvalidFiles_InsertNotExistingFiles_ReturnsEmptyList()
        {
            var files    = new[] { "file1", "file2", "file3" };
            var fileStub = Substitute.For <IFile>();

            fileStub.Exists(Arg.Any <string>()).Returns(false);

            Assert.IsEmpty(DragAndDropHelper.RemoveInvalidFiles(files, fileStub));
        }
        public void SendServiceStatistics_HttpHandlerPostAsyncDoesntReciveCall()
        {
            var serviceUpTime = TimeSpan.MaxValue;

            _usageStatisticsManager.EnableUsageStatistics = false;
            _usageStatisticsManager.SendServiceStatistics(serviceUpTime);

            _usageStatisticsSender.DidNotReceive().SendAsync(Arg.Any <IUsageMetric>());
        }
        public void SectionCanCoverWholeList()
        {
            listBuilderImpl.Capacity.Returns(10);
            listBuilderImpl.BuilderSettings.Returns(new BuilderSettings());
            listBuilderImpl.AddDeclaration(Arg.Any <IDeclaration <MyClass> >())
            .Returns(new MyDeclaration <MyClass>());

            ListBuilderExtensions.Section(listBuilderImpl, 0, 9);
        }
        public void WhenPasswordInteractionIsCancelled_DoesNotSendMail()
        {
            //_interactionRequest.RegisterInteractionHandler<PasswordOverlayInteraction>(interaction => interaction.Result = PasswordResult.Cancel);
            _interactionInvoker.Invoke(Arg.Do <PasswordOverlayInteraction>(i => i.Result = PasswordResult.Cancel));
            var assistant = BuildAssistant();

            assistant.SendTestMail(_profile, _accounts);

            _smtpAction.DidNotReceive().ProcessJob(Arg.Any <Job>());
        }
        public void WhenSmtpPasswordIsSet_UsesPasswordFromAccount()
        {
            var expectedPassword = "******";

            _smtpTestAccount.Password = expectedPassword;
            var assistant = BuildAssistant();

            assistant.SendTestMail(_profile, _accounts);

            _smtpAction.Received().ProcessJob(Arg.Is <Job>(x => x.Passwords.SmtpPassword == expectedPassword));
        }
Beispiel #23
0
        public async Task WhenUserIdentityHasWebConnectionInfo()
        {
            // Arrange
            var webConnectionInfo = new WebConnectionInfo
            {
                ServiceInstanceId = "1",
                PersonInfo        = new PersonInfo(),
                SessionCredential = new SessionCredential(),
                UserAuthToken     = "some"
            };

            // Mock HealthVaultIdentityProvider
            IHealthVaultIdentityProvider healthVaultIdentityProvider = Substitute.For <IHealthVaultIdentityProvider>();

            healthVaultIdentityProvider.TryGetIdentity().Returns(new HealthVaultIdentity
            {
                WebConnectionInfo = webConnectionInfo
            });
            Ioc.Container.Configure(c => c.ExportInstance(healthVaultIdentityProvider).As <IHealthVaultIdentityProvider>());

            // Mock HealthVaultConnection
            WebHealthVaultConfiguration webHealthVaultConfiguration = new WebHealthVaultConfiguration();

            webHealthVaultConfiguration.DefaultHealthVaultUrl      = new Uri("http://www.bing.com");
            webHealthVaultConfiguration.DefaultHealthVaultShellUrl = new Uri("http://www.bing.com");

            IServiceLocator serviceLocator = Substitute.For <IServiceLocator>();

            serviceLocator.GetInstance <WebHealthVaultConfiguration>().Returns(webHealthVaultConfiguration);
            serviceLocator.GetInstance <IHealthWebRequestClient>().Returns(Substitute.For <IHealthWebRequestClient>());
            serviceLocator
            .GetInstance <IHealthServiceResponseParser>()
            .Returns(Substitute.For <IHealthServiceResponseParser>());

            WebHealthVaultConnection webHealthVaultConnection = Substitute.For <WebHealthVaultConnection>(serviceLocator);

            Ioc.Container.Configure(c => c.ExportInstance(webHealthVaultConnection).As <IWebHealthVaultConnection>());

            // Mock ServiceInstanceProvider
            IServiceInstanceProvider serviceInstanceProvider = Substitute.For <IServiceInstanceProvider>();

            serviceInstanceProvider
            .GetHealthServiceInstanceAsync(Arg.Any <string>())
            .Returns(Task.FromResult(new HealthServiceInstance()));
            Ioc.Container.Configure(c => c.ExportInstance(serviceInstanceProvider).As <IServiceInstanceProvider>());

            WebHealthVaultFactory factory = new WebHealthVaultFactory();

            // Act
            IWebHealthVaultConnection resultWebHealthVaultConnection = await factory.CreateWebConnectionInternalAsync();

            // Assert
            Assert.AreEqual(webConnectionInfo.UserAuthToken, resultWebHealthVaultConnection.UserAuthToken);
        }
        public void SendUserStatistics_UsageStatisticsIsDisabled_HttpHandlerPostAsyncDoesntReciveCall()
        {
            var job      = BuildJob();
            var duration = TimeSpan.MaxValue;
            var status   = "test status";

            _usageStatisticsManager.EnableUsageStatistics = false;
            _usageStatisticsManager.SendUsageStatistics(duration, job, status);

            _usageStatisticsSender.DidNotReceive().SendAsync(Arg.Any <IUsageMetric>());
        }
Beispiel #25
0
        public void WhenCalled_UsesTheGivenProfile()
        {
            var expectedPassword = "******";

            _profile.EmailSmtpSettings.Password = expectedPassword;
            var assistant = BuildAssistant();

            assistant.SendTestMail(_profile, new Accounts());

            _smtpAction.Received().ProcessJob(Arg.Is <Job>(x => x.Profile.Equals(_profile)));
        }
        public void SendUserStatistics_HttpHandlerPostAsyncRecivesOneCall()
        {
            var job      = BuildJob();
            var duration = TimeSpan.MaxValue;
            var status   = "test status";

            _usageStatisticsManager.EnableUsageStatistics = true;
            _usageStatisticsManager.SendUsageStatistics(duration, job, status);

            _usageStatisticsSender.Received(1).SendAsync(Arg.Any <IUsageMetric>());
        }
Beispiel #27
0
        public void Should_Call_Register_Platform_Services()
        {
            // Given
            var registrar = Substitute.For <IPlatformRegistrar>();

            // When
            ApplicationMock sut = new ApplicationFixture().WithPlatformRegistration(registrar);

            // Then
            registrar.Received().RegisterPlatformServices(Arg.Any <IRegistrator>());
        }
        public void TheFirstShouldReturnARangeDeclaration()
        {
            var rangeDeclaration = new RangeDeclaration <MyClass>(listBuilderImpl, null, 0, 0);

            listBuilderImpl.Capacity.Returns(30);
            listBuilderImpl.CreateObjectBuilder().Returns((IObjectBuilder <MyClass>)null);
            listBuilderImpl.AddDeclaration(Arg.Is <RangeDeclaration <MyClass> >(y => y.Start == 0 && y.End == 9)).Returns(rangeDeclaration);

            var declaration = ListBuilderExtensions.TheFirst(listBuilderImpl, 10);

            Assert.That(declaration, Is.SameAs(rangeDeclaration));
        }
Beispiel #29
0
        public async Task ShouldRouteToCorrect_Notification_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 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, textDocumentSyncHandler2
            };

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

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

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

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

            await textDocumentSyncHandler.Received(0)
            .Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>());

            await textDocumentSyncHandler2.Received(1)
            .Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>());
        }
        public void SendTestMail_CallsSmtpAction()
        {
            var assistant = BuildAssistant();

            assistant.SendTestMail(_profile, _accounts);

            Received.InOrder(() =>
            {
                _smtpAction.Received().ApplyPreSpecifiedTokens(Arg.Any <Job>());
                _smtpAction.Check(_profile, _accounts, CheckLevel.Job);
                _smtpAction.Received().ProcessJob(Arg.Any <Job>());
            });
        }