protected AppendEntryBaseTest()
        {
            // Arrange  
            var mocker = new AutoMocker();

            ServerIdentifier = new ServerIdentifier();

            mocker.Use(ServerIdentifier);

            mocker.Setup<ISubject<AppendEntryMessage>>(p => p.Subscribe(It.IsAny<IObserver<AppendEntryMessage>>()))
                .Callback<IObserver<AppendEntryMessage>>((o) =>
                {
                    AppendEntryCallback = o;
                });
            AppendEntryCallback = mocker.Get<ISubject<AppendEntryMessage>>();

            AppendEntryResult = new Subject<AppendEntryResultMessage>();
            Election = new Election();
            LogReplication = new LogReplication();
            
            AppendEntry = new Rafting.AppendEntry(AppendEntryResult,
                mocker.Get<ISubject<AppendEntryMessage>>(),
                mocker.Get<IHartbeatTimer>(),
                LogReplication,
                Election,
                mocker.Get<ILoggerFactory>(),
                new RaftOptions(),
                mocker.Get<ServerIdentifier>(),
                null);
        }
        protected VoteReceivedBaseTests()
        {
            // Arrange
            var mocker = new AutoMocker();

            ServerIdentifier = new ServerIdentifier();

            mocker.Use(ServerIdentifier);

            mocker.Setup<ISubject<RequestVoteMessage>>(p => p.Subscribe(It.IsAny<IObserver<RequestVoteMessage>>()))
                .Callback<IObserver<RequestVoteMessage>>((o) =>
                {
                    RequestVoteCallback = o;
                });
            RequestVoteCallback = mocker.Get<ISubject<RequestVoteMessage>>();

            Election = new Election();

            Message = new RequestVoteResultMessage();

            mocker.Setup<ISubject<RequestVoteResultMessage>>(p => p.OnNext(It.IsAny<RequestVoteResultMessage>()))
                .Callback<RequestVoteResultMessage>((o) =>
                {
                    Message = o;
                });

            VoteReceived = new Rafting.VoteReceived(mocker.Get<ISubject<RequestVoteResultMessage>>(),
                mocker.Get<ServerIdentifier>(),
                mocker.Get<ISubject<RequestVoteMessage>>(),
                Election,
                mocker.Get<ILoggerFactory>(),
                new Nodes(),
                new RaftOptions(),
                mocker.Get<ILogReplication>());
        }
示例#3
0
        public void ChangeStates()
        {
            // Arrange
            var mocker = new AutoMocker();
            mocker.Setup<IHartbeatTimer>(p => p.Reset()).Callback(() =>
            {

            });

            var mockFollower = mocker.GetMock<Follower>();
            var mockCandidate = mocker.GetMock<Candidate>();
            var mockLeader = mocker.GetMock<Leader>();

            mocker.Setup<IObservableProvider>(p =>  p.GetObservable<Follower, ServerStateType>())
                .Returns(mockFollower.Object);

            mocker.Setup<IObservableProvider>(p => p.GetObservable<Candidate, ServerStateType>())
                .Returns(mockCandidate.Object);

            mocker.Setup<IObservableProvider>(p => p.GetObservable<Leader, ServerStateType>())
                .Returns(mockLeader.Object);

            Machine<ServerStateType, ServerStateType> machine = null;
            mocker.Setup<IHartbeatTimer>(p => p.Subscribe(It.IsAny<Machine<ServerStateType, ServerStateType>>()))
                .Returns(new Disposable())
                .Callback<Machine<ServerStateType, ServerStateType>>(m =>
                {
                    machine = m;
                });
            
            var node = new Node(mocker.Get<IVoteReceived>(),
                mocker.Get<IAppendEntry>(),
                mocker.Get<IHartbeatTimer>(),
                mocker.Get<ILoggerFactory>(),
                mocker.Get<IObservableProvider>(),
                mocker.Get<ILogReplication>(),
                mocker.Get<ServerIdentifier>());

            var mockHartbeat = mocker.GetMock<IHartbeatTimer>();

            // Assert
            Assert.Equal(ServerStateType.Follower, node.State);

            machine.OnNext(ServerStateType.Candidate);

            Assert.Equal(ServerStateType.Candidate, node.State);

            machine.OnNext(ServerStateType.Leader);
        }
示例#4
0
        public void TestMoqVersionRedirect()
        {
            var mocker = new AutoMocker();
            mocker.Setup<IMockableThing>(mock => mock.SayHello(It.IsAny<string>())).Returns("Hello Peter");

            var sut = mocker.CreateInstance<Fake>();

            Assert.That(sut.SayHello("Peter"), Is.EqualTo("Hello Peter"));
        }
        public async Task Handle_WhenNoTestResultIsFound_ReturnsNegativeResult()
        {
            var automocker = new AutoMocker();

            automocker
            .Setup <IMsisLookupService, Task <Option <PositiveTestResult> > >(x =>
                                                                              x.FindPositiveTestResult("01019098765"))
            .ReturnsAsync(Option.None <PositiveTestResult>());

            automocker.Setup <IOptions <VerifyIdentifiedUser.Config>, VerifyIdentifiedUser.Config>(x => x.Value)
            .Returns(new VerifyIdentifiedUser.Config
            {
                UseFixedTestCases = false
            });

            var target = automocker.CreateInstance <VerifyIdentifiedUser.Handler>();

            var result = await target.Handle(new VerifyIdentifiedUser.Command("01019098765", "pseudo-1"), new CancellationToken());

            result.HasVerifiedPostiveTest.Should().BeFalse();
            result.PositiveTestDate.Should().Be(Option.None <DateTime>());

            automocker.VerifyAll();
        }
示例#6
0
        public void SetAutomaticTemperatureRegulation()
        {
            var autoMocker = new AutoMocker();

            autoMocker.Setup <IOptionsMonitor <AppSettings>, AppSettings>(x => x.CurrentValue)
            .Returns(new AppSettings
            {
                RefreshMilliseconds = 1, UpperTemperatureThreshold = 40, LowerTemperatureThreshold = 30
            });
            var testee = autoMocker.CreateInstance <RaspiTemperatureController>();

            testee.SetAutomaticTemperatureRegulation();

            testee.RegulationMode.Should().Be(RegulationMode.Automatic);
        }
示例#7
0
        public void TestOpenNewTabCommand()
        {
            var tabsListViewModelMock = new Mock <ITabsListViewModel>();

            tabsListViewModelMock
            .Setup(m => m.CreateNewTab())
            .Verifiable();
            var filePanelViewModelMock = new Mock <IFilesPanelViewModel>();

            filePanelViewModelMock
            .SetupGet(m => m.TabsListViewModel)
            .Returns(tabsListViewModelMock.Object);
            _autoMocker
            .Setup <IFilesOperationsMediator, IFilesPanelViewModel>(m => m.ActiveFilesPanelViewModel)
            .Returns(filePanelViewModelMock.Object);

            var mainWindowViewModel = _autoMocker.CreateInstance <MainWindowViewModel>();

            Assert.True(mainWindowViewModel.CreateNewTabCommand.CanExecute(null));
            mainWindowViewModel.CreateNewTabCommand.Execute(null);

            tabsListViewModelMock
            .Verify(m => m.CreateNewTab(), Times.Once);
        }
        public async Task Login_GivenUnsuccessfulPinValidation_ReturnsViewResult()
        {
            var automocker = new AutoMocker();

            automocker.Setup <IAccountService, Task <Option <LoginOptions, string> > >(x =>
                                                                                       x.GetLoginOptions("/auth/?authRequest=123"))
            .ReturnsAsync(new LoginOptions
            {
                EnableLocalLogin  = true,
                ExternalProviders = new ExternalProvider[0]
            }.Some <LoginOptions, string>());

            automocker.Setup <IAccountService, Task <Option <LocalLoginResult, string> > >(x =>
                                                                                           x.AttemptLocalLogin("12345", "/auth/?authRequest=123"))
            .ReturnsAsync(Option.None <LocalLoginResult, string>("Not a valid pin"));

            var target = automocker.CreateInstance <AccountController>();

            var result = await target.Login(new LoginInputModel
            {
                ReturnUrl = "/auth/?authRequest=123",
                PinCode   = "12345"
            });

            result.Should().BeOfType <ViewResult>();
            var vResult = (ViewResult)result;

            vResult.ViewName.Should().BeNull();
            vResult.Model.Should().BeOfType <LoginViewModel>();
            var vm = (LoginViewModel)vResult.Model;

            vm.PinCode.Should().Be("12345");
            vm.ReturnUrl.Should().Be("/auth/?authRequest=123");
            vm.EnableLocalLogin.Should().BeTrue();
            vm.VisibleExternalProviders.Should().BeEmpty();
        }
        public async Task Handle_GivenPositiveTestLimitExceeded_ReturnsExceededAndConfig()
        {
            var automocker = new AutoMocker();

            var verLimitConfig = new Mock <IVerificationLimitConfig>();

            automocker
            .Setup <IVerificationLimit, bool>(x => x.HasReachedLimit(It.IsAny <IEnumerable <VerificationRecord> >()))
            .Returns(true);

            automocker
            .Setup <IVerificationLimit, IVerificationLimitConfig>(x => x.Config)
            .Returns(verLimitConfig.Object);

            var target = automocker.CreateInstance <VerifyPinUser.Handler>();

            var result = await target.Handle(new VerifyPinUser.Command("pseudo-1", true, false), new CancellationToken());

            result.HasVerifiedPostiveTest.Should().BeTrue();
            result.VerificationLimitExceeded.Should().BeTrue();
            result.VerificationLimitConfig.Should().Be(verLimitConfig.Object.Some());

            automocker.VerifyAll();
        }
示例#10
0
        public void TestNameExtraction(string fileName, string expectedFileName)
        {
            _autoMocker
            .Setup <IEnvironmentPathService, string>(m => m.GetFileNameWithoutExtension(It.IsAny <string>()))
            .Returns <string>(Path.GetFileNameWithoutExtension);
            var pathService    = _autoMocker.CreateInstance <PathService>();
            var actualFileName = pathService.GetFileNameWithoutExtension(fileName);

            Assert.Equal(expectedFileName, actualFileName);
        }
        public async Task FindPositiveTestResult_ResponseNoPositiveTest_ReturnsNone()
        {
            var automocker = new AutoMocker();

            automocker.Setup <IMsisClient, Task <Covid19Status> >(x => x.GetCovid19Status("01019012345"))
            .ReturnsAsync(new Covid19Status
            {
                HarPositivCovid19Prove = false
            });

            var target = automocker.CreateInstance <MsisLookupService>();

            var result = await target.FindPositiveTestResult("01019012345");

            result.Should().Be(Option.None <PositiveTestResult>());
        }
示例#12
0
        public void TrySetUpperTemperatureThreshold()
        {
            var autoMocker = new AutoMocker();

            autoMocker.Setup <IOptionsMonitor <AppSettings>, AppSettings>(x => x.CurrentValue)
            .Returns(new AppSettings
            {
                RefreshMilliseconds = 1, UpperTemperatureThreshold = 40, LowerTemperatureThreshold = 30
            });
            var testee = autoMocker.CreateInstance <RaspiTemperatureController>();

            var result = testee.TrySetUpperTemperatureThreshold(35);

            result.Should().BeTrue();
            testee.UpperTemperatureThreshold.Should().Be(35);
        }
示例#13
0
        public void IsPlatformSupported()
        {
            var autoMocker = new AutoMocker();

            autoMocker.Setup <IOptionsMonitor <AppSettings>, AppSettings>(x => x.CurrentValue)
            .Returns(new AppSettings
            {
                RefreshMilliseconds = 1, UpperTemperatureThreshold = 40, LowerTemperatureThreshold = 30
            });
            var testee = autoMocker.CreateInstance <RaspiTemperatureController>();

            // ReSharper disable once UnusedVariable - Reviewed: the result is not necessary, only the call is important
            var result = testee.IsPlatformSupported;

            autoMocker.Verify <ITemperatureProvider, bool>(x => x.IsPlatformSupported(), Times.Once);
        }
示例#14
0
    public void TestSearchCommand()
    {
        _autoMocker
        .Setup <IFilesOperationsMediator>(m => m.ToggleSearchPanelVisibility())
        .Verifiable();

        var mainWindowViewModel = _autoMocker.CreateInstance <MainWindowViewModel>();

        Assert.True(mainWindowViewModel.SearchCommand.CanExecute(null));
        mainWindowViewModel.SearchCommand.Execute(null);

        _autoMocker
        .Verify <IFilesOperationsMediator>(m => m.ToggleSearchPanelVisibility(), Times.Once);
    }
        public void Index_WhenHomePageDisabled_ReturnsNotFound()
        {
            var automocker = new AutoMocker();

            automocker.Setup <IOptions <InteractionConfig>, InteractionConfig>(x => x.Value)
            .Returns(new InteractionConfig
            {
                EnableHomePage = false
            });

            var target = automocker.CreateInstance <HomeController>();

            var result = target.Index();

            result.Should().BeOfType <NotFoundResult>();
        }
示例#16
0
        public void Init()
        {
            _mocker = new AutoMocker();

            _sampleAudioDramaProvider = new SampleAudioDramaProvider();
            _audioDramas = _sampleAudioDramaProvider.Get().ToList();

            _mocker.Use <IEnumerable <AudioDrama> >(_audioDramas);

            _mocker
            .Setup <ISource <IEnumerable <AudioDrama> >, IEnumerable <AudioDrama> >(x => x.Get())
            .Returns(_audioDramas);

            _sut = _mocker.CreateInstance <AudioDramaListPresenter>();
            _sut.SetModel(_audioDramas);
        }
示例#17
0
        public async Task TestReload()
        {
            _autoMocker.Use(new DriveServiceConfiguration {
                DrivesListRefreshIntervalMs = 10
            });

            var taskCompletionSource = new TaskCompletionSource <bool>();

            var callsCount = 0;

            _autoMocker
            .Setup <IUnmountedDriveService>(m => m.ReloadUnmountedDrivesAsync())
            .Callback(() =>
            {
                if (Interlocked.Increment(ref callsCount) == 1)
                {
                    taskCompletionSource.SetResult(true);
                }
            });

            var service = _autoMocker.CreateInstance <DrivesUpdateService>();

            await Task.Delay(1000);

            _autoMocker
            .Verify <IMountedDriveService>(m => m.ReloadMountedDrives(), Times.Never);
            _autoMocker
            .Verify <IUnmountedDriveService>(m => m.ReloadUnmountedDrivesAsync(), Times.Never);

            service.Start();

            var task = await Task.WhenAny(Task.Delay(2000), taskCompletionSource.Task);

            if (task != taskCompletionSource.Task)
            {
                taskCompletionSource.SetResult(false);
            }

            var result = await taskCompletionSource.Task;

            Assert.True(result);

            _autoMocker
            .Verify <IMountedDriveService>(m => m.ReloadMountedDrives(), Times.AtLeastOnce);
            _autoMocker
            .Verify <IUnmountedDriveService>(m => m.ReloadUnmountedDrivesAsync(), Times.AtLeastOnce);
        }
示例#18
0
    public async Task TestCopyCancel()
    {
        _autoMocker
        .Setup <IFileService, Task <bool> >(m => m.CopyAsync(SourceName, DestinationName,
                                                             It.IsAny <CancellationToken>(),
                                                             false))
        .Throws <TaskCanceledException>();

        var operation = new CopyOperation(
            _autoMocker.Get <IDirectoryService>(),
            _autoMocker.Get <IFileService>(),
            _autoMocker.Get <IPathService>(),
            SourceName,
            DestinationName
            );

        Task RunAsync() => operation.RunAsync(default);
示例#19
0
        public async Task GetCurrentImageUrl()
        {
            var imageFilePaths = new Collection <string> {
                "Path1", "Path2"
            };
            var autoMocker = new AutoMocker();

            autoMocker.Setup <IHttpClientFactory, HttpClient>(x => x.CreateClient()).Returns(new MockHttpMessageHandler().ToHttpClient());
            var testee = autoMocker.CreateInstance <Project>();

            testee.ProjectPath = "MyPath";
            await testee.AddImagesAsync(imageFilePaths);

            var result = testee.GetCurrentImageUrl();

            result.Should().MatchRegex("http:\\/\\/localhost:8001\\/api\\/images\\/\\S+");
        }
示例#20
0
        public async Task AddImages()
        {
            var imageFilePaths = new Collection <string> {
                "Path1", "Path2"
            };
            var autoMocker    = new AutoMocker();
            var httpMock      = new MockHttpMessageHandler();
            var mockedRequest = httpMock.When(HttpMethod.Post, "/api/images").Respond(HttpStatusCode.OK);

            autoMocker.Setup <IHttpClientFactory, HttpClient>(x => x.CreateClient()).Returns(httpMock.ToHttpClient);
            var testee = autoMocker.CreateInstance <Project>();

            await testee.AddImagesAsync(imageFilePaths);

            testee.NumberOfImages.Should().Be(2);
            httpMock.GetMatchCount(mockedRequest).Should().Be(2);
        }
示例#21
0
    public void TestProperties(string filePath, string extension, bool isDirectory, bool isImage)
    {
        _autoMocker
        .Setup <IFileSizeFormatter, string>(m => m.GetFormattedSize(Size))
        .Returns(FormattedSize);
        _autoMocker
        .Setup <IFileSizeFormatter, string>(m => m.GetSizeAsNumber(Size))
        .Returns(SizeAsNumber);
        _autoMocker
        .Setup <IPathService, string>(m => m.GetParentDirectory(filePath))
        .Returns(ParentDirectory);
        _autoMocker
        .Setup <IPathService, string>(m => m.GetFileName(filePath))
        .Returns(FileName);
        _autoMocker
        .Setup <IPathService, string>(m => m.GetExtension(filePath))
        .Returns(extension);
        _autoMocker
        .Setup <IBitmapFactory, IBitmap>(m => m.Create(filePath))
        .Returns(new Mock <IBitmap>().Object);

        var viewModel = _autoMocker.CreateInstance <MainNodeInfoTabViewModel>();
        var nodeModel = new NodeModelBase
        {
            FullPath             = filePath,
            CreatedDateTime      = DateTime.Now,
            LastAccessDateTime   = DateTime.Now.AddHours(1),
            LastModifiedDateTime = DateTime.Now.AddHours(2),
        };

        viewModel.Activate(nodeModel, isDirectory, InnerFilesCount, InnerDirectoriesCount);
        viewModel.SetSize(Size);

        Assert.Equal(nodeModel.CreatedDateTime, viewModel.CreatedDateTime);
        Assert.Equal(nodeModel.LastAccessDateTime, viewModel.LastAccessDateTime);
        Assert.Equal(nodeModel.LastModifiedDateTime, viewModel.LastWriteDateTime);
        Assert.Equal(FormattedSize, viewModel.FormattedSize);
        Assert.Equal(SizeAsNumber, viewModel.FormattedSizeAsNumber);
        Assert.Equal(FileName, viewModel.Name);
        Assert.Equal(ParentDirectory, viewModel.Path);
        Assert.Equal(isDirectory, viewModel.IsDirectory);
        Assert.Equal(InnerFilesCount, viewModel.InnerFilesCount);
        Assert.Equal(InnerDirectoriesCount, viewModel.InnerDirectoriesCount);

        if (isImage)
        {
            Assert.NotNull(viewModel.ImageBitmap);
        }
        else
        {
            Assert.Null(viewModel.ImageBitmap);
        }
    }
示例#22
0
    public async Task TestActivation()
    {
        var taskCompletionSource = new TaskCompletionSource <bool>();

        var directoryModel = new DirectoryModel {
            FullPath = Directory
        };

        _autoMocker
        .Setup <IDirectoryService, DirectoryModel>(m => m.GetDirectory(Directory))
        .Returns(directoryModel);
        _autoMocker
        .Setup <IDirectoryService, long>(m => m.CalculateSize(Directory))
        .Returns(Size);
        _autoMocker
        .Setup <IApplicationDispatcher>(m => m.Dispatch(It.IsAny <Action>()))
        .Callback <Action>(action =>
        {
            action();
            taskCompletionSource.SetResult(true);
        });
        _autoMocker
        .Setup <IDirectoryService, IReadOnlyList <DirectoryModel> >(m => m.GetChildDirectories(Directory, null))
        .Returns(Enumerable.Repeat(new DirectoryModel(), DirsCount).ToArray());
        _autoMocker
        .Setup <IFileService, IReadOnlyList <FileModel> >(m => m.GetFiles(Directory, null))
        .Returns(Enumerable.Repeat(new FileModel(), FilesCount).ToArray());
        _autoMocker
        .Setup <IMainNodeInfoTabViewModel>(m => m.SetSize(Size))
        .Verifiable();
        _autoMocker
        .Setup <IMainNodeInfoTabViewModel>(m => m.Activate(directoryModel, true, FilesCount, DirsCount))
        .Verifiable();

        var viewModel = _autoMocker.CreateInstance <DirectoryInformationDialogViewModel>();
        var parameter = new FileSystemNodeNavigationParameter(Directory);

        viewModel.Activate(parameter);

        await Task.WhenAny(taskCompletionSource.Task, Task.Delay(1000));

        _autoMocker
        .Verify <IMainNodeInfoTabViewModel>(m => m.SetSize(Size),
                                            Times.Once);
        _autoMocker
        .Verify <IMainNodeInfoTabViewModel>(m => m.Activate(directoryModel, true, FilesCount, DirsCount),
                                            Times.Once);
    }
        public async Task TestChangedAndRenamedEvents()
        {
            _autoMocker
            .Setup <IPathService, string>(m => m.GetParentDirectory(It.IsAny <string>()))
            .Returns(DirectoryPath);

            var decorator = _autoMocker.CreateInstance <AggregatingFileSystemWatcherDecorator>();

            var changedCallsCount = 0;
            var actualCallsCount  = 0;

            decorator.Changed += (sender, args) =>
            {
                Assert.Equal(WatcherChangeTypes.Changed, args.ChangeType);
                Assert.Equal(FileName, args.Name);
                Assert.Equal(0, actualCallsCount);

                changedCallsCount++;
            };
            decorator.Renamed += (sender, args) =>
            {
                Assert.Equal(WatcherChangeTypes.Renamed, args.ChangeType);
                Assert.Equal(FileName, args.OldName);
                Assert.Equal(NewFileName, args.Name);

                actualCallsCount++;
            };

            var fileSystemWatcherWrapperMock = _autoMocker.GetMock <IFileSystemWatcher>();

            var changedArgs = new FileSystemEventArgs(WatcherChangeTypes.Changed, DirectoryPath, FileName);

            fileSystemWatcherWrapperMock.Raise(m => m.Changed += null, changedArgs);

            var renamedArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, DirectoryPath, NewFileName, FileName);

            fileSystemWatcherWrapperMock.Raise(m => m.Renamed += null, renamedArgs);

            await Task.Delay(DelayIntervalMs);

            Assert.Equal(1, actualCallsCount);
            Assert.True(changedCallsCount <= 1);
        }
    public void TestProperties()
    {
        _autoMocker
        .Setup <IPathService, string>(m => m.GetFileName(NodePath))
        .Returns(NodeName);

        var dialog = _autoMocker.CreateInstance <RenameNodeDialogViewModel>();

        dialog.Activate(new RenameNodeNavigationParameter(NodePath));

        Assert.Equal(NodeName, dialog.NodeName);
    }
        public async Task Handle_DeletesExpiredAnonymousTokenIssueRecords()
        {
            var limitConfigMock = new Mock <IVerificationLimitConfig>();

            limitConfigMock.Setup(x => x.MaxLimitDuration).Returns(TimeSpan.FromHours(24));

            var automocker = new AutoMocker();

            automocker.Setup <IVerificationLimit, IVerificationLimitConfig>(x => x.Config)
            .Returns(limitConfigMock.Object);

            var target = automocker.CreateInstance <DeleteExpiredData.Handler>();

            await target.Handle(new DeleteExpiredData.Command(), new CancellationToken());

            automocker.Verify <IAnonymousTokenIssueRecordRepository>(x =>
                                                                     x.DeleteExpiredRecords());
        }
        public void Login_GivenInvalidModelStateAuthRequestRequiredMissing_ThrowsException()
        {
            var automocker = new AutoMocker();

            automocker.Setup <IAccountService, Task <Option <LoginOptions, string> > >(x =>
                                                                                       x.GetLoginOptions("/auth/?authRequest=123"))
            .ReturnsAsync(Option.None <LoginOptions, string>("rejected."));

            var target = automocker.CreateInstance <AccountController>();

            target.ModelState.AddModelError("PinCode", "PinCode is required");

            Assert.ThrowsAsync <Exception>(() => target.Login(new LoginInputModel
            {
                ReturnUrl = "/auth/?authRequest=123",
                PinCode   = null
            }));
        }
示例#27
0
        public void TestGetCloudantSecurityDocument_Should_Return_A_Valid_Document()
        {
            //SETUP
            var mocker = new AutoMocker();

            //connection returns base uri
            mocker.Setup<ICouchConnection>(c => c.BaseUri).Returns(new Uri("http://localhost"));

            //GetCouchResponse returns security doc as per Cloudant documentation
            const string responseString = "{ " +
                                          "\"_id\":\"_security\"," +
                                          "\"cloudant\":" +
                                          "{" +
                                          "  \"userwithreadonlyaccess\": [" +
                                          "    \"_reader\"" +
                                          "  ]," +
                                          "  \"userwithreadandwriteaccess\": [" +
                                          "    \"_reader\"," +
                                          "    \"_writer\"" +
                                          "  ]" +
                                          "}," +
                                          "\"ok\":true" +
                                          "}";
            mocker.Setup<ICouchResponse>(r => r.ResponseString).Returns(responseString);
            mocker.Setup<ICouchResponse, HttpStatusCode>(r => r.StatusCode).Returns(HttpStatusCode.OK);
            mocker.Setup<ICouchRequest>(r => r.GetCouchResponse()).Returns(mocker.Get<ICouchResponse>());

            //couchFactory returns request
            mocker.Setup<ICouchFactory>(f => f.GetRequest(It.IsAny<Uri>(), It.IsAny<ICouchConnection>()))
                .Returns(mocker.Get<ICouchRequest>());
            //Get request returns request
            mocker.Setup<ICouchRequest>(r => r.Get()).Returns(mocker.Get<ICouchRequest>());
            //Json content type returns request
            mocker.Setup<ICouchRequest>(r => r.Json()).Returns(mocker.Get<ICouchRequest>());

            //TEST
            var database = mocker.CreateInstance<CloudantDatabase>();

            var securityDocument = (CloudantSecurityDocument)database.GetSecurityDocument();

            securityDocument.Id.Should().Be("_security");
            securityDocument.CloudantSecuritySection.GetAssignment("userwithreadonlyaccess").Should().BeEquivalentTo("_reader");
            securityDocument.CloudantSecuritySection.GetAssignment("userwithreadandwriteaccess").Should().BeEquivalentTo("_reader", "_writer");
            securityDocument.Ok.Should().BeTrue();

            mocker.VerifyAll();
        }
示例#28
0
        public void TestGetDrives()
        {
            var drives = DriveInfo.GetDrives();

            _autoMocker
            .Setup <IEnvironmentDriveService, DriveInfo[]>(m => m.GetMountedDrives())
            .Returns(drives);

            var driveService = _autoMocker.CreateInstance <MountedDriveService>();

            Assert.NotNull(driveService.MountedDrives);
            Assert.NotEmpty(driveService.MountedDrives);
        }
        public void Index_WhenHomePageEnabled_ReturnsViewResult()
        {
            var automocker = new AutoMocker();

            automocker.Setup <IOptions <InteractionConfig>, InteractionConfig>(x => x.Value)
            .Returns(new InteractionConfig
            {
                EnableHomePage = true
            });

            var target = automocker.CreateInstance <HomeController>();

            var result = target.Index();

            result.Should().BeOfType <ViewResult>();
            var vResult = (ViewResult)result;

            vResult.ViewName.Should().BeNull();
        }
        public void ShouldReturnTemperature_WhenCommandIsExecutedSuccessfully()
        {
            // given
            const string content = "4b 01 4b 46 7f ff 05 10 e1 : crc=e1 YES\n" +
                                   "4b 01 4b 46 7f ff 05 10 e1 t=20687";

            var mocker = new AutoMocker();

            mocker.Setup <IShellHelper, Task <string> >(h => h.ExecuteCommandAsync(It.IsAny <string>()))
            .ReturnsAsync(content);

            var sensor = mocker.CreateInstance <DS18B20Thermometer>();

            // when
            var temperature = sensor.ReadValue();

            // then
            temperature.Should().Be(20.7m);
        }
        public void LoadMasterKeyBytes_MasterKeyCertNotFound_ThrowsException()
        {
            var options = new AnonymousTokensConfig
            {
                MasterKeyCertId = "key-id"
            };

            var automocker = new AutoMocker();

            automocker.SetupOptions(options);

            automocker
            .Setup <ICertificateLocator, Task <Option <X509Certificate2> > >(x => x.GetCertificateAsync("key-id"))
            .ReturnsAsync(Option.None <X509Certificate2>());

            var target = automocker.CreateInstance <AnonymousTokenMasterKeyLoader>();

            Assert.ThrowsAsync <AnonymousTokenMasterKeyLoaderException>(() => target.LoadMasterKeyBytes());
        }
示例#32
0
        public async Task Cancel_GivenNoTrustedReturnUrl_ReturnRedirectUrlToRoot()
        {
            var automocker = new AutoMocker();

            automocker.Setup <IAccountService, Task <CancelLoginResult> >(x => x.CancelLogin(null))
            .ReturnsAsync(new CancelLoginResult
            {
                UseNativeClientRedirect = false
            });

            var target = automocker.CreateInstance <AccountController>().AddTestControllerContext();

            var result = await target.Cancel(new CancelLoginInputModel());

            result.Should().BeOfType <RedirectResult>();
            var rResult = (RedirectResult)result;

            rResult.Url.Should().Be("~/");
        }
示例#33
0
    public void TestCreate()
    {
        _autoMocker
        .Setup <IDirectoryService, DirectoryModel>(m => m.GetDirectory(DirPath))
        .Returns(new DirectoryModel
        {
            Name = DirName
        });

        var factory = _autoMocker.CreateInstance <FavouriteDirectoryViewModelFactory>();

        var viewModel = factory.Create(DirPath);

        Assert.IsType <FavouriteDirectoryViewModel>(viewModel);

        var favDirViewModel = (FavouriteDirectoryViewModel)viewModel;

        Assert.Equal(DirName, favDirViewModel.DirectoryName);
    }
    public async Task TestLoadAssociatedApplicationsAsync(string output, int resultsCount)
    {
        var configuration = new UtiToExtensionsMappingConfiguration
        {
            UtiToExtensionsMapping = new Dictionary <string, List <string> >
            {
                ["public.text"] = new List <string>
                {
                    Extension
                }
            }
        };
        var apps = new[]
        {
            new ApplicationModel
            {
                ExecutePath = "/home/app"
            }
        };

        _autoMocker.Use(configuration);
        _autoMocker
        .Setup <IProcessService, Task <string> >(m =>
                                                 m.ExecuteAndGetOutputAsync(
                                                     "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister",
                                                     "-dump Bundle"))
        .ReturnsAsync(output);

        var service = _autoMocker.CreateInstance <MacApplicationsAssociationsLoader>();

        var associations = await service.LoadAssociatedApplicationsAsync(apps);

        Assert.NotNull(associations);
        Assert.Equal(resultsCount, associations.Count);

        if (resultsCount == 1)
        {
            Assert.True(associations.ContainsKey(Extension));
            Assert.Single(associations[Extension]);

            Assert.Equal(apps.Single(), associations[Extension].Single());
        }
    }
示例#35
0
        public async Task Save()
        {
            var imageFilePaths = new Collection <string> {
                "Path1", "Path2"
            };
            var projectPath = "MyPath";
            var autoMocker  = new AutoMocker();

            autoMocker.Setup <IHttpClientFactory, HttpClient>(x => x.CreateClient()).Returns(new MockHttpMessageHandler().ToHttpClient());
            var testee = autoMocker.CreateInstance <Project>();

            testee.ProjectPath = projectPath;
            await testee.AddImagesAsync(imageFilePaths);

            await testee.SaveAsync();

            autoMocker.GetMock <IFileHandler>()
            .Verify(x => x.WriteAsync(It.Is <ProjectDto>(d => d.Images.Count() == 2), projectPath), Times.Once);
        }
示例#36
0
        public void TestUpdateSecurityDoc_Should_Succeed_For_Valid_Document()
        {
            //SETUP
            var mocker = new AutoMocker();

            //connection returns base uri
            mocker.Setup<ICouchConnection>(c => c.BaseUri).Returns(new Uri("http://localhost"));

            //GetCouchResponse returns security doc as per Cloudant documentation
            const string responseString = "{ " +
                                          "\"ok\":true" +
                                          "}";
            mocker.Setup<ICouchResponse>(r => r.ResponseString).Returns(responseString);
            mocker.Setup<ICouchResponse, HttpStatusCode>(r => r.StatusCode).Returns(HttpStatusCode.OK);
            mocker.Setup<ICouchRequest>(r => r.GetCouchResponse()).Returns(mocker.Get<ICouchResponse>());

            //couchFactory returns request
            mocker.Setup<ICouchFactory>(f => f.GetRequest(It.IsAny<Uri>(), It.IsAny<ICouchConnection>()))
                .Returns(mocker.Get<ICouchRequest>());
            //Get request returns request
            mocker.Setup<ICouchRequest>(r => r.Put()).Returns(mocker.Get<ICouchRequest>());
            //Json content type returns request
            mocker.Setup<ICouchRequest>(r => r.Json()).Returns(mocker.Get<ICouchRequest>());
            //Data returns request
            mocker.Setup<ICouchRequest>(r => r.Data(It.IsAny<string>())).Returns(mocker.Get<ICouchRequest>());

            //security doc
            var securityDoc = new CloudantSecurityDocument();
            securityDoc.CloudantSecuritySection.AddUser("user1", "_reader");
            securityDoc.CloudantSecuritySection.AddUser("user2", "_reader","_writer");

            //TEST
            var database = mocker.CreateInstance<CloudantDatabase>();

            database.UpdateSecurityDocument(securityDoc);

            mocker.VerifyAll();
        }