Beispiel #1
0
    public async Task Step_Validate_Postcode_And_()
    {
        const string postcode  = "mk 4 2 8 y u";
        const string expected  = "MK42 8YU";
        const double latitude  = 50.0123;
        const double longitude = 1.987;
        const bool   isValid   = true;

        var expectedPostcodeLocation = new PostcodeLocation
        {
            Postcode  = expected,
            Latitude  = latitude,
            Longitude = longitude
        };

        var viewModel = new FindViewModel
        {
            Postcode = postcode
        };

        var context = new SearchContext(viewModel);

        _providerSearchService.IsSearchPostcodeValid(Arg.Is <string>(p => p == postcode)).Returns((isValid, expectedPostcodeLocation));

        await _searchStep.Execute(context);

        context.ViewModel.Postcode.Should().Be(expected);
        context.Continue.Should().BeTrue();
        await _providerSearchService.Received(1).IsSearchPostcodeValid(Arg.Is <string>(p => p == postcode));
    }
        /// <summary>
        ///		Abre la ventana de búsqueda
        /// </summary>
        private void OpenSearchWindow()
        {
            // Crea el viewModel de las ventanas de búsqueda si no existía
            if (FindViewModel == null)
            {
                FindViewModel = new Views.Tools.FindViewModel(this);
            }
            // Muestra el cuadro de búsqueda
            if (!FindViewModel.IsOpened && dckManager.ActiveDocument?.UserControl is FileDetailsView fileView)
            {
                Views.Tools.FindView view = new Views.Tools.FindView(FindViewModel);

                // Muestra el formulario activo
                view.Owner                 = this;
                view.ShowActivated         = true;
                view.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                view.WindowStyle           = WindowStyle.ToolWindow;
                view.ShowInTaskbar         = false;
                view.ResizeMode            = ResizeMode.NoResize;
                view.Top  = Top;
                view.Left = Left + Width - view.Height;
                // view.IsActive = true;
                // Muestra la venta
                view.Show();
                // Inicializa el viewModel
                FindViewModel.Open(fileView);
            }
        }
Beispiel #3
0
        public ActionResult <object> Find([FromBody] FindViewModel viewModel)
        {
            var path          = viewModel.Path;
            var search        = $"*{ viewModel.Search }*";
            var searchOptions = new EnumerationOptions()
            {
                MatchCasing           = viewModel.CaseSensitive ? MatchCasing.CaseSensitive : MatchCasing.CaseInsensitive,
                RecurseSubdirectories = viewModel.Recursive
            };

            var folders = Directory.GetDirectories(path, search, searchOptions);

            folders = folders.Select(x => x.Substring(path.Length)).ToArray();

            var files = Directory.GetFiles(path, search, searchOptions);

            files = files.Select(x => x.Substring(path.Length)).ToArray();

            var result = new
            {
                path          = viewModel.Path,
                search        = viewModel.Search,
                caseSensitive = viewModel.CaseSensitive,
                recursive     = viewModel.Recursive,
                folders,
                files
            };

            return(result);
        }
    public async Task MergeAvailableDeliveryYears_After_Available_Returns_Expected_Result()
    {
        var dateTimeService = Substitute.For <IDateTimeService>();

        dateTimeService.Today.Returns(DateTime.Parse("2021-09-01"));

        var providerLocations = new ProviderLocationViewModelListBuilder()
                                .Add()
                                .Build();

        var viewModel = new FindViewModel
        {
            ProviderLocations = providerLocations
        };

        var context = new SearchContext(viewModel);

        var searchStep = new MergeAvailableDeliveryYearsStep(dateTimeService);

        await searchStep.Execute(context);

        providerLocations[0].DeliveryYears.Count.Should().Be(1);
        providerLocations[0].DeliveryYears[0].IsAvailableNow.Should().BeTrue();
        providerLocations[0].DeliveryYears[0].Qualifications.Count.Should().Be(2);

        var qualifications = providerLocations[0].DeliveryYears[0].Qualifications.ToList();

        qualifications[0].Id.Should().Be(1);
        qualifications[0].Name.Should().Be("Test Qualification 1");
        qualifications[1].Id.Should().Be(2);
        qualifications[1].Name.Should().Be("Test Qualification 2");
    }
Beispiel #5
0
    public async Task Search_Will_Not_Execute_SearchSteps_When_SearchContext_Continue_Is_False()
    {
        var viewModel = new FindViewModel();
        var context   = new SearchContext(viewModel)
        {
            Continue = false
        };

        _searchPipelineFactory.GetSearchContext(Arg.Is(viewModel)).Returns(context);
        var searchStep1 = Substitute.For <ISearchStep>();
        var searchStep2 = Substitute.For <ISearchStep>();
        var searchStep3 = Substitute.For <ISearchStep>();
        var steps       = new List <ISearchStep>
        {
            searchStep1,
            searchStep2,
            searchStep3
        };

        _searchPipelineFactory.GetSearchSteps(_providerSearchService, _mapper).Returns(steps);

        await _providerSearchEngine.Search(viewModel);

        await searchStep1.Received(1).Execute(context);

        await searchStep2.Received(0).Execute(context);

        await searchStep3.Received(0).Execute(context);
    }
Beispiel #6
0
    public async Task Step_Validate_Wrong_Postcode()
    {
        const string postcode  = "dddfd";
        const double latitude  = 50.0123;
        const double longitude = 1.987;
        const bool   isValid   = false;

        var postcodeLocation = new PostcodeLocation
        {
            Postcode  = postcode,
            Latitude  = latitude,
            Longitude = longitude
        };

        var viewModel = new FindViewModel
        {
            Postcode = postcode
        };

        var context = new SearchContext(viewModel);

        _providerSearchService.IsSearchPostcodeValid(Arg.Is <string>(p => p == postcode)).Returns((isValid, postcodeLocation));

        await _searchStep.Execute(context);

        context.ViewModel.ValidationStyle.Should().Be(AppConstants.ValidationStyle);
        context.ViewModel.PostcodeValidationMessage.Should().Be(AppConstants.RealPostcodeValidationMessage);
        context.Continue.Should().BeFalse();
        await _providerSearchService.Received(1).IsSearchPostcodeValid(Arg.Is <string>(p => p == postcode));
    }
        public async Task Search_Execute_All_SearchSteps()
        {
            // Arrange
            var viewModel = new FindViewModel();
            var context   = new SearchContext(viewModel);

            _searchPipelineFactory.GetSearchContext(Arg.Is(viewModel)).Returns(context);
            var searchStep1 = Substitute.For <ISearchStep>();
            var searchStep2 = Substitute.For <ISearchStep>();
            var searchStep3 = Substitute.For <ISearchStep>();
            var steps       = new List <ISearchStep>
            {
                searchStep1,
                searchStep2,
                searchStep3
            };

            _searchPipelineFactory.GetSearchSteps(_providerSearchService, _mapper).Returns(steps);

            // Act
            await _providerSearchEngine.Search(viewModel);

            // Assert
            await searchStep1.Received(1).Execute(context);

            await searchStep2.Received(1).Execute(context);

            await searchStep3.Received(1).Execute(context);
        }
        public void FindViewModel_Default_Collections_Are_Not_Null()
        {
            var viewModel = new FindViewModel();

            viewModel.ProviderLocations.Should().NotBeNull();
            viewModel.Qualifications.Should().NotBeNull();
        }
Beispiel #9
0
        public async Task FindNext_finds_valid_positions_in_document()
        {
            var phrase   = "Lorem";
            var document = new TextDocument(
                @"Lorem ipsum abs xddd work or noe iavb Lorem back down weug
. This is Lorem or not Lor working and not.");

            var indexes      = new int[] { 0, 38, 70, 0 };
            var currentIndex = 0;

            var engine = new SearchEngine();
            var sut    = new FindViewModel(engine);

            sut.ChangeDocument(document);
            sut.SearchedText            = phrase;
            sut.OnCaretPositionChanged += (s, e) =>
            {
                Assert.Less(currentIndex, indexes.Length);
                Assert.AreEqual(indexes[currentIndex], e.NewPosition);
                currentIndex++;
            };

            for (int i = 0; i < indexes.Length; i++)
            {
                await sut.FindNext();
            }

            Assert.AreEqual(indexes.Length - 1, currentIndex);
        }
Beispiel #10
0
        public FindPage(Visitor visitor, VisitorListViewModel visitorListVm)
        {
            InitializeComponent();
            var findViewModel = new FindViewModel(visitor, visitorListVm);

            BindingContext = findViewModel;
        }
        public IActionResult Find(string place)
        {
            List <Window> windowList = new List <Window>();

            if (string.IsNullOrEmpty(place) || place == "Danmark")
            {
                ViewData["SearchWord"] = "Danmark";
                windowList             = _context.Window
                                         .Include(x => x.Address)
                                         .Include(x => x.WindowImages)
                                         .Include(x => x.WindowMeasures)
                                         .Where(x => x.WindowStatusId == 1).ToList();
            }
            else
            {
                ViewData["SearchWord"] = place;
                windowList             = _context.Window
                                         .Include(x => x.Address)
                                         .Include(x => x.WindowImages)
                                         .Include(x => x.WindowMeasures)
                                         .Where(x => x.WindowStatusId == 1)
                                         .Where(x => x.Address.City.ToLower() == place.ToLower() || x.Address.Zipcode.ToString() == place).ToList();
            }

            var model = new FindViewModel()
            {
                WindowList  = windowList,
                WindowCount = windowList.Count
            };

            return(View(model));
        }
        public ActionResult Index()
        {
            var fullPath = Path.GetFullPath(MissingImageLocation);
            var model    = new FindViewModel {
                FileList = Directory.EnumerateFiles(fullPath).Select(Path.GetFileNameWithoutExtension)
            };

            return(View(model));
        }
Beispiel #13
0
        public void FindCommand()
        {
            DispatcherHelper.Initialize();
            var segmentPool     = new SegmentPool();
            var projectService  = Substitute.For <IProjectService>();
            var dialogService   = Substitute.For <IDialogService>();
            var busyService     = Substitute.For <IBusyService>();
            var analysisService = new AnalysisService(_spanFactory, segmentPool, projectService, dialogService, busyService);
            var exportService   = Substitute.For <IExportService>();

            WordsViewModel.Factory wordsFactory = words => new WordsViewModel(busyService, words);
            WordViewModel.Factory  wordFactory  = word => new WordViewModel(busyService, analysisService, word);

            var segments = new SegmentsViewModel(projectService, dialogService, busyService, exportService, wordsFactory, wordFactory);

            CogProject project = TestHelpers.GetTestProject(_spanFactory, segmentPool);

            project.Meanings.AddRange(new[] { new Meaning("gloss1", "cat1"), new Meaning("gloss2", "cat2"), new Meaning("gloss3", "cat3") });
            project.Varieties.AddRange(new[] { new Variety("variety1"), new Variety("variety2") });
            project.Varieties[0].Words.AddRange(new[] { new Word("hɛ.loʊ", project.Meanings[0]), new Word("gʊd", project.Meanings[1]), new Word("bæd", project.Meanings[2]) });
            project.Varieties[1].Words.AddRange(new[] { new Word("hɛlp", project.Meanings[0]), new Word("gu.gəl", project.Meanings[1]), new Word("gu.fi", project.Meanings[2]) });
            projectService.Project.Returns(project);
            analysisService.SegmentAll();
            projectService.ProjectOpened += Raise.Event();

            WordsViewModel observedWords = segments.ObservedWords;

            observedWords.WordsView = new ListCollectionView(observedWords.Words);

            FindViewModel findViewModel = null;
            Action        closeCallback = null;

            dialogService.ShowModelessDialog(segments, Arg.Do <FindViewModel>(vm => findViewModel = vm), Arg.Do <Action>(callback => closeCallback = callback));
            segments.FindCommand.Execute(null);
            Assert.That(findViewModel, Is.Not.Null);
            Assert.That(closeCallback, Is.Not.Null);

            // already open, shouldn't get opened twice
            dialogService.ClearReceivedCalls();
            segments.FindCommand.Execute(null);
            dialogService.DidNotReceive().ShowModelessDialog(segments, Arg.Any <FindViewModel>(), Arg.Any <Action>());

            // nothing selected, no match
            findViewModel.Field  = FindField.Form;
            findViewModel.String = "nothing";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(observedWords.SelectedWords, Is.Empty);

            // nothing selected, matches
            segments.SelectedSegment = segments.Varieties[1].Segments[3];
            WordViewModel[] wordsViewArray = observedWords.WordsView.Cast <WordViewModel>().ToArray();
            findViewModel.String = "fi";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(observedWords.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(observedWords.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
        }
        public IActionResult Find(FindViewModel viewModel)
        {
            if (!string.IsNullOrEmpty(viewModel.Postcode))
            {
                viewModel.ShouldSearch = true;
            }

            return(View(viewModel));
        }
        public ActionResult FindLeague(FindViewModel viewModel)
        {
            ICollection <LeaguePreviewViewModel> model;

            using (var dbContext = new ManagementDataContext())
            {
                model = dbContext.Leagues.FindLeaguesByCity(viewModel.Input);
            }

            return(View("Leagues", model));
        }
        public ActionResult FindTeam(FindViewModel viewModel)
        {
            TeamPreviewViewModel model;

            using (var dbContext = new ManagementDataContext())
            {
                model = dbContext.Teams.FindTeamByName(viewModel.Input);
            }

            return(View("Team", model));
        }
Beispiel #17
0
        public async Task Step_Perform_Search_Returns_Expected_Results()
        {
            const string postcode          = "MK35 8UK";
            const int    numberOfItems     = 9;
            const int    qualificationId   = 5;
            const int    selectedItemIndex = 3;

            var viewModel = new FindViewModel
            {
                Postcode                = postcode,
                NumberOfItemsToShow     = numberOfItems,
                SelectedQualificationId = qualificationId,
                SelectedItemIndex       = selectedItemIndex
            };

            var context = new SearchContext(viewModel);

            var providerLocations = new List <ProviderLocation>
            {
                new ProviderLocation(),
                new ProviderLocation(),
                new ProviderLocation(),
                new ProviderLocation(),
                new ProviderLocation()
            };

            _providerSearchService.Search(Arg.Is <SearchRequest>(sr => sr.Postcode == postcode &&
                                                                 sr.NumberOfItems == numberOfItems &&
                                                                 sr.QualificationId == qualificationId))
            .Returns((providerLocations.Count, providerLocations));

            var providerLocationViewModels = new List <ProviderLocationViewModel>
            {
                new ProviderLocationViewModel(),
                new ProviderLocationViewModel(),
                new ProviderLocationViewModel(),
                new ProviderLocationViewModel(),
                new ProviderLocationViewModel()
            };

            _mapper.Map <IEnumerable <ProviderLocationViewModel> >(Arg.Is(providerLocations)).Returns(providerLocationViewModels);

            await _searchStep.Execute(context);

            context.ViewModel.TotalRecordCount.Should().Be(providerLocationViewModels.Count);
            providerLocationViewModels[context.ViewModel.SelectedItemIndex].HasFocus.Should().BeTrue();
            context.ViewModel.SearchedQualificationId.Should().Be(qualificationId);
            context.ViewModel.ProviderLocations.Should().Equal(providerLocationViewModels);

            await _providerSearchService.Received(1).Search(Arg.Is <SearchRequest>(sr => sr.Postcode == postcode && sr.NumberOfItems == numberOfItems && sr.QualificationId == qualificationId));

            _mapper.Received(1).Map <IEnumerable <ProviderLocationViewModel> >(Arg.Is(providerLocations));
        }
        public void FindViewModel_ShowNext_Should_Be_True_When_NumberOfItemsToShow_Is_Less_Than_TotalRecordCount()
        {
            var viewModel = new FindViewModel
            {
                ProviderLocations = new ProviderLocationViewModelListBuilder()
                                    .Add(5)
                                    .Build(),
                NumberOfItemsToShow = 15,
                TotalRecordCount    = 20
            };

            viewModel.ShowNext.Should().BeTrue();
        }
        public void FindViewModel_ShowNext_Should_Be_False_When_TotalRecordCount_Is_Equal_To_ProviderLocations_Count()
        {
            var viewModel = new FindViewModel
            {
                ProviderLocations = new ProviderLocationViewModelListBuilder()
                                    .Add(5)
                                    .Build(),
                NumberOfItemsToShow = 5,
                TotalRecordCount    = 5
            };

            viewModel.ShowNext.Should().BeFalse();
        }
Beispiel #20
0
        public IActionResult Find(FindViewModel find)
        {
            var list = db.TblBoots.Where(b => b.ColorId == find.ColorId || b.SizeId == find.SizeId).Select(x => new BootViewModel
            {
                Id      = x.Id,
                Name    = x.Name,
                Picture = x.Picture,
                Price   = x.Price,
                Sex     = x.Sex,
                Sale    = x.Sale,
            });

            return(View(list));
        }
Beispiel #21
0
    public async Task Step_Validate_Empty_Postcode()
    {
        var viewModel = new FindViewModel
        {
            Postcode = string.Empty
        };

        var context = new SearchContext(viewModel);

        await _searchStep.Execute(context);

        context.ViewModel.ValidationStyle.Should().Be(AppConstants.ValidationStyle);
        context.ViewModel.PostcodeValidationMessage.Should().Be(AppConstants.PostcodeValidationMessage);
        context.Continue.Should().BeFalse();
    }
        public async Task Step_Sets_QualificationId_For_Search(int?qualificationId, int expected)
        {
            // Arrange
            var viewModel = new FindViewModel
            {
                SelectedQualificationId = qualificationId
            };
            var context = new SearchContext(viewModel);

            // Act
            await _searchStep.Execute(context);

            // Assert
            context.ViewModel.SelectedQualificationId.Should().Be(expected);
        }
Beispiel #23
0
    public async Task Step_Load_Find_Page_And_Make_Page_Ready_For_Search()
    {
        const bool shouldSearch = false;
        var        viewModel    = new FindViewModel
        {
            ShouldSearch = shouldSearch
        };

        var context = new SearchContext(viewModel);

        await _searchStep.Execute(context);

        context.ViewModel.ShouldSearch.Should().BeTrue();
        context.Continue.Should().BeFalse();
    }
Beispiel #24
0
    public async Task <FindViewModel> Search(FindViewModel viewModel)
    {
        var context     = _searchPipelineFactory.GetSearchContext(viewModel);
        var searchSteps = _searchPipelineFactory.GetSearchSteps(_providerSearchService, _mapper);

        foreach (var searchStep in searchSteps)
        {
            await searchStep.Execute(context);

            if (!context.Continue)
            {
                break;
            }
        }

        return(context.ViewModel);
    }
Beispiel #25
0
        public async Task Changing_parameters_triggers_search_cancelation()
        {
            var  searchCancelled = false;
            Task verifier        = null;

            var engine = new Mock <ISearchEngine>();

            engine.Setup(x =>
                         x.FindInDocument(
                             It.IsAny <TextReader>(),
                             It.IsAny <string>(),
                             It.IsAny <SearchModeEnum>(),
                             It.IsAny <CancellationToken>(),
                             It.IsAny <Action <int> >()))
            .Callback <TextReader, string, SearchModeEnum, CancellationToken, Action <int> >(async(a, b, v, ct, e) =>
            {
                verifier = new Task(async() =>
                {
                    while (true)
                    {
                        await Task.Delay(100);
                        if (ct.IsCancellationRequested)
                        {
                            searchCancelled = true;
                            ct.ThrowIfCancellationRequested();
                        }
                    }
                }, ct);

                await Task.Run(() => verifier);
            });

            var sut = new FindViewModel(engine.Object);

            sut.ChangeDocument(new TextDocument());

            await sut.FindNext();

            sut.IgnoreCase = !sut.IgnoreCase;
            await Task.Delay(150);

            Assert.NotNull(verifier);
            Assert.IsTrue(verifier.IsCanceled);
            Assert.IsTrue(searchCancelled);
        }
Beispiel #26
0
        public IActionResult Find(IFormCollection form)
        {
            var model = new FindViewModel();

            if (!String.IsNullOrEmpty(form["search_param"]))
            {
                var sParam = form["search_param"];
                var query  = new Search
                {
                    Searchstring = form["search_query"]
                };

                model.SearchParam = sParam;

                var eApi = new EventApi(_apiSettings.ApiBaseUrl);
                model.Events = eApi.FindEvents(query);
                var edApi = new EventDateApi(_apiSettings.ApiBaseUrl);
                model.EventDates = edApi.FindEventDates(query);
                var vApi = new VenueApi(_apiSettings.ApiBaseUrl);
                model.Venues = vApi.FindVenues(query);

                if (sParam == "eventdate")
                {
                    model.PartialView = "_FindEventDatesPartial";
                    ViewData["Title"] = "Event Dates";
                }
                else if (sParam == "venue")
                {
                    model.PartialView = "_FindVenuesPartial";
                    ViewData["Title"] = "Venues";
                }
                else // sParam == events or something else
                {
                    model.PartialView = "_FindEventsPartial";
                    ViewData["Title"] = "Events";
                }
            }
            return(View("Find", model));
        }
Beispiel #27
0
    public async Task Student_Controller_Find_Get_Returns_Expected_Value()
    {
        var providerSearchEngine = Substitute.For <IProviderSearchEngine>();

        providerSearchEngine.Search(
            Arg.Any <FindViewModel>())
        .Returns(args => (FindViewModel)args[0]);

        var controller = new StudentControllerBuilder().BuildStudentController(providerSearchEngine: providerSearchEngine);

        var viewModel = new FindViewModel();
        var result    = await controller.Find(viewModel);

        var viewResult = result as ViewResult;

        viewResult.Should().NotBeNull();
        viewResult.Model.Should().BeOfType(typeof(FindViewModel));

        await providerSearchEngine
        .Received(1)
        //.Search(Arg.Is<FindViewModel>(x => x != null));
        .Search(viewModel);
    }
        public async Task Step_Returns_SelectListItems_For_All_Qualifications_With_A_Selected_Qualification()
        {
            // Arrange
            int?selectedQualificationId = 3;

            var viewModel = new FindViewModel
            {
                SelectedQualificationId = selectedQualificationId
            };

            var context = new SearchContext(viewModel);

            var qualifications = new List <Qualification>
            {
                new Qualification {
                    Id = 1, Name = "Qualification 1"
                },
                new Qualification {
                    Id = 2, Name = "Qualification 2"
                },
                new Qualification {
                    Id = 3, Name = "Qualification 3"
                },
                new Qualification {
                    Id = 4, Name = "Qualification 4"
                },
                new Qualification {
                    Id = 5, Name = "Qualification 5"
                }
            };

            _providerSearchService.GetQualifications().Returns(qualifications);

            // Act
            await _searchStep.Execute(context);

            // Assert
            _providerSearchService.Received(1).GetQualifications();
            context.ViewModel.Qualifications.Count().Should().Be(qualifications.Count);
            context.ViewModel.Qualifications
            .Any(q => q.Value == selectedQualificationId.ToString() && q.Selected)
            .Should().BeTrue();

            context.ViewModel.Qualifications
            .Count(q => q.Value == selectedQualificationId.ToString() && q.Selected)
            .Should()
            .Be(1);

            var qualificationsSelectList = context.ViewModel.Qualifications.OrderBy(q => q.Value).ToList();

            qualificationsSelectList[0].Value.Should().Be("1");
            qualificationsSelectList[0].Text.Should().Be("Qualification 1");
            qualificationsSelectList[0].Selected.Should().BeFalse();

            qualificationsSelectList[1].Value.Should().Be("2");
            qualificationsSelectList[1].Text.Should().Be("Qualification 2");
            qualificationsSelectList[1].Selected.Should().BeFalse();

            qualificationsSelectList[2].Value.Should().Be("3");
            qualificationsSelectList[2].Text.Should().Be("Qualification 3");
            qualificationsSelectList[2].Selected.Should().BeTrue();

            qualificationsSelectList[3].Value.Should().Be("4");
            qualificationsSelectList[3].Text.Should().Be("Qualification 4");
            qualificationsSelectList[3].Selected.Should().BeFalse();

            qualificationsSelectList[4].Value.Should().Be("5");
            qualificationsSelectList[4].Text.Should().Be("Qualification 5");
            qualificationsSelectList[4].Selected.Should().BeFalse();



            context.ViewModel.SelectedQualificationId.Should().Be(selectedQualificationId);
        }
        public void FindCommand()
        {
            DispatcherHelper.Initialize();
            var segmentPool     = new SegmentPool();
            var projectService  = Substitute.For <IProjectService>();
            var dialogService   = Substitute.For <IDialogService>();
            var busyService     = Substitute.For <IBusyService>();
            var exportService   = Substitute.For <IExportService>();
            var analysisService = new AnalysisService(_spanFactory, segmentPool, projectService, dialogService, busyService);

            WordPairsViewModel.Factory   wordPairsFactory   = () => new WordPairsViewModel(busyService);
            VarietyPairViewModel.Factory varietyPairFactory = (vp, order) => new VarietyPairViewModel(segmentPool, projectService, wordPairsFactory, vp, order);

            var varietyPairs = new VarietyPairsViewModel(projectService, busyService, dialogService, exportService, analysisService, varietyPairFactory);

            CogProject project = TestHelpers.GetTestProject(_spanFactory, segmentPool);

            project.Meanings.AddRange(new[] { new Meaning("gloss1", "cat1"), new Meaning("gloss2", "cat2"), new Meaning("gloss3", "cat3") });
            project.Varieties.AddRange(new[] { new Variety("variety1"), new Variety("variety2"), new Variety("variety3") });
            project.Varieties[0].Words.AddRange(new[] { new Word("hɛ.loʊ", project.Meanings[0]), new Word("gʊd", project.Meanings[1]), new Word("bæd", project.Meanings[2]) });
            project.Varieties[1].Words.AddRange(new[] { new Word("hɛlp", project.Meanings[0]), new Word("gu.gəl", project.Meanings[1]), new Word("gu.fi", project.Meanings[2]) });
            project.Varieties[2].Words.AddRange(new[] { new Word("wɜrd", project.Meanings[0]), new Word("kɑr", project.Meanings[1]), new Word("fʊt.bɔl", project.Meanings[2]) });
            projectService.Project.Returns(project);
            analysisService.SegmentAll();
            var varietyPairGenerator = new VarietyPairGenerator();

            varietyPairGenerator.Process(project);
            var wordPairGenerator = new SimpleWordPairGenerator(segmentPool, project, 0.3, ComponentIdentifiers.PrimaryWordAligner);

            foreach (VarietyPair vp in project.VarietyPairs)
            {
                wordPairGenerator.Process(vp);
                vp.SoundChangeFrequencyDistribution   = new ConditionalFrequencyDistribution <SoundContext, Ngram <Segment> >();
                vp.SoundChangeProbabilityDistribution = new ConditionalProbabilityDistribution <SoundContext, Ngram <Segment> >(vp.SoundChangeFrequencyDistribution, (sc, fd) => new MaxLikelihoodProbabilityDistribution <Ngram <Segment> >(fd));
            }

            int i = 0;

            foreach (WordPair wp in project.VarietyPairs[0].WordPairs)
            {
                wp.PhoneticSimilarityScore = (1.0 / project.VarietyPairs[0].WordPairs.Count) * (project.VarietyPairs[0].WordPairs.Count - i);
                wp.AreCognatePredicted     = wp.Meaning.Gloss.IsOneOf("gloss1", "gloss3");
                i++;
            }

            i = 0;
            foreach (WordPair wp in project.VarietyPairs[1].WordPairs)
            {
                wp.PhoneticSimilarityScore = (1.0 / project.VarietyPairs[1].WordPairs.Count) * (project.VarietyPairs[1].WordPairs.Count - i);
                i++;
            }

            projectService.ProjectOpened += Raise.Event();

            varietyPairs.VarietiesView1 = new ListCollectionView(varietyPairs.Varieties);
            varietyPairs.VarietiesView2 = new ListCollectionView(varietyPairs.Varieties);

            WordPairsViewModel cognates = varietyPairs.SelectedVarietyPair.Cognates;

            cognates.WordPairsView = new ListCollectionView(cognates.WordPairs);
            WordPairViewModel[] cognatesArray = cognates.WordPairsView.Cast <WordPairViewModel>().ToArray();
            WordPairsViewModel  noncognates   = varietyPairs.SelectedVarietyPair.Noncognates;

            noncognates.WordPairsView = new ListCollectionView(noncognates.WordPairs);
            WordPairViewModel[] noncognatesArray = noncognates.WordPairsView.Cast <WordPairViewModel>().ToArray();

            FindViewModel findViewModel = null;
            Action        closeCallback = null;

            dialogService.ShowModelessDialog(varietyPairs, Arg.Do <FindViewModel>(vm => findViewModel = vm), Arg.Do <Action>(callback => closeCallback = callback));
            varietyPairs.FindCommand.Execute(null);
            Assert.That(findViewModel, Is.Not.Null);
            Assert.That(closeCallback, Is.Not.Null);

            // already open, shouldn't get opened twice
            dialogService.ClearReceivedCalls();
            varietyPairs.FindCommand.Execute(null);
            dialogService.DidNotReceive().ShowModelessDialog(varietyPairs, Arg.Any <FindViewModel>(), Arg.Any <Action>());

            // form searches
            findViewModel.Field = FindField.Form;

            // nothing selected, no match
            findViewModel.String = "nothing";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.Empty);

            // nothing selected, matches
            findViewModel.String = "g";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[1].ToEnumerable()));
            Assert.That(noncognates.SelectedWordPairs, Is.Empty);
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));

            // first word selected, matches
            noncognates.SelectedWordPairs.Clear();
            cognates.SelectedWordPairs.Add(cognatesArray[0]);
            findViewModel.String = "ʊ";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[0].ToEnumerable()));
            Assert.That(noncognates.SelectedWordPairs, Is.Empty);
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[0].ToEnumerable()));
            Assert.That(noncognates.SelectedWordPairs, Is.Empty);
            // start over
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));

            // last word selected, matches
            cognates.SelectedWordPairs.Clear();
            noncognates.SelectedWordPairs.Add(noncognatesArray[0]);
            findViewModel.String = "h";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[0].ToEnumerable()));
            Assert.That(noncognates.SelectedWordPairs, Is.Empty);
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[0].ToEnumerable()));
            Assert.That(noncognates.SelectedWordPairs, Is.Empty);

            // switch variety pair, nothing selected, no cognates, matches, change selected word
            varietyPairs.SelectedVariety2 = varietyPairs.Varieties[2];
            cognates = varietyPairs.SelectedVarietyPair.Cognates;
            cognates.WordPairsView    = new ListCollectionView(cognates.WordPairs);
            noncognates               = varietyPairs.SelectedVarietyPair.Noncognates;
            noncognates.WordPairsView = new ListCollectionView(noncognates.WordPairs);
            noncognatesArray          = noncognates.WordPairsView.Cast <WordPairViewModel>().ToArray();

            findViewModel.String = "l";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[2].ToEnumerable()));
            noncognates.SelectedWordPairs.Clear();
            noncognates.SelectedWordPairs.Add(noncognatesArray[1]);
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[2].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));

            // gloss searches
            findViewModel.Field  = FindField.Gloss;
            findViewModel.String = "gloss2";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[1].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(cognates.SelectedWordPairs, Is.Empty);
            Assert.That(noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[1].ToEnumerable()));
        }
Beispiel #30
0
        public void FindCommand()
        {
            DispatcherHelper.Initialize();
            var projectService  = Substitute.For <IProjectService>();
            var dialogService   = Substitute.For <IDialogService>();
            var busyService     = Substitute.For <IBusyService>();
            var analysisService = Substitute.For <IAnalysisService>();

            WordsViewModel.Factory            wordsFactory   = words => new WordsViewModel(busyService, words);
            WordViewModel.Factory             wordFactory    = word => new WordViewModel(busyService, analysisService, word);
            VarietiesVarietyViewModel.Factory varietyFactory = variety => new VarietiesVarietyViewModel(projectService, dialogService, wordsFactory, wordFactory, variety);

            var varieties = new VarietiesViewModel(projectService, dialogService, analysisService, varietyFactory);

            var project = new CogProject(_spanFactory)
            {
                Meanings  = { new Meaning("gloss1", "cat1"), new Meaning("gloss2", "cat2"), new Meaning("gloss3", "cat3") },
                Varieties = { new Variety("variety1"), new Variety("variety2") }
            };

            project.Varieties[0].Words.AddRange(new[] { new Word("hello", project.Meanings[0]), new Word("good", project.Meanings[1]), new Word("bad", project.Meanings[2]) });
            project.Varieties[1].Words.AddRange(new[] { new Word("help", project.Meanings[0]), new Word("google", project.Meanings[1]), new Word("goofy", project.Meanings[2]) });
            projectService.Project.Returns(project);
            projectService.ProjectOpened += Raise.Event();

            varieties.VarietiesView = new ListCollectionView(varieties.Varieties);
            WordsViewModel wordsViewModel = varieties.SelectedVariety.Words;

            wordsViewModel.WordsView = new ListCollectionView(wordsViewModel.Words);
            WordViewModel[] wordsViewArray = wordsViewModel.WordsView.Cast <WordViewModel>().ToArray();

            FindViewModel findViewModel = null;
            Action        closeCallback = null;

            dialogService.ShowModelessDialog(varieties, Arg.Do <FindViewModel>(vm => findViewModel = vm), Arg.Do <Action>(callback => closeCallback = callback));
            varieties.FindCommand.Execute(null);
            Assert.That(findViewModel, Is.Not.Null);
            Assert.That(closeCallback, Is.Not.Null);

            // already open, shouldn't get opened twice
            dialogService.ClearReceivedCalls();
            varieties.FindCommand.Execute(null);
            dialogService.DidNotReceive().ShowModelessDialog(varieties, Arg.Any <FindViewModel>(), Arg.Any <Action>());

            // form searches
            findViewModel.Field = FindField.Form;

            // nothing selected, no match
            findViewModel.String = "fall";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.Empty);

            // nothing selected, matches
            findViewModel.String = "he";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[0].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[0].ToEnumerable()));

            // first word selected, matches
            findViewModel.String = "o";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[0].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[0].ToEnumerable()));
            // start search over
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));

            // last word selected, matches
            wordsViewModel.SelectedWords.Clear();
            wordsViewModel.SelectedWords.Add(wordsViewArray[2]);
            findViewModel.String = "ba";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[2].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[2].ToEnumerable()));

            // switch variety, nothing selected, matches, change selected word
            varieties.SelectedVariety = varieties.Varieties[1];
            wordsViewModel            = varieties.SelectedVariety.Words;
            wordsViewModel.WordsView  = new ListCollectionView(wordsViewModel.Words);
            wordsViewArray            = wordsViewModel.WordsView.Cast <WordViewModel>().ToArray();
            findViewModel.String      = "go";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
            wordsViewModel.SelectedWords.Clear();
            wordsViewModel.SelectedWords.Add(wordsViewArray[0]);
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[2].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[2].ToEnumerable()));

            // gloss searches
            findViewModel.Field  = FindField.Gloss;
            findViewModel.String = "gloss2";
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
            findViewModel.FindNextCommand.Execute(null);
            Assert.That(wordsViewModel.SelectedWords, Is.EquivalentTo(wordsViewArray[1].ToEnumerable()));
        }