Exemplo n.º 1
0
        public static HtmlNode WaitForNode <TComponent>(this TestHost host, RenderedComponent <TComponent> component, string selector)
            where TComponent : IComponent
        {
            var node = component.Find(selector);

            while (node == null)
            {
                host.WaitForNextRender();
                node = component.Find(selector);
            }

            return(node);
        }
Exemplo n.º 2
0
        public static void DataValueAttributeShouldBePresentOnEachOption <T>(this RenderedComponent <MDCSelect <T> > sut, IEnumerable <T> expectedDataSource, bool includeEmpty)
        {
            var optionNodes = sut.FindListItemNodes();

            optionNodes
            .Where(r => r.Attributes["data-value"] != null)
            .Count()
            .ShouldBe(expectedDataSource.Count() + (includeEmpty ? 1 : 0));

            optionNodes
            .Select(r => r.Attributes["data-value"].Value)
            .ShouldBeUnique();
        }
Exemplo n.º 3
0
        public static string WaitForContains <TComponent>(this TestHost host, RenderedComponent <TComponent> component, string term)
            where TComponent : IComponent
        {
            var markup = component.GetMarkup();

            while (!markup.Contains(term))
            {
                host.WaitForNextRender();
                markup = component.GetMarkup();
            }

            return(markup);
        }
Exemplo n.º 4
0
        public static void CreateTestHost(string userName,
                                          IEnumerable <Claim> claims,
                                          string url,
                                          TestServer sut,
                                          ITestOutputHelper testOutputHelper,
                                          out TestHost host,
                                          out RenderedComponent <blazorApp.App> component,
                                          out MockHttpMessageHandler mockHttp)
        {
            CreateTestHost(userName, claims, url, sut, testOutputHelper, out host, out mockHttp);

            component = host.AddComponent <blazorApp.App>();
        }
Exemplo n.º 5
0
        public async Task CamperScheduleGrid_SelectCamper_CamperGroupRowsHilite()
        {
            // Arrange - run schedule with successful data set and load grid
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <ActivityDefinition> schedule;
            string scheduleId = "MySchedule";

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                List <CamperRequests> camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                schedule = _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }
            RenderedComponent <CamperScheduleGrid> component =
                _host.AddComponent <CamperScheduleGrid>();

            // Act - select a camper
            // Find a camper in a camper group
            List <HashSet <Camper> > camperGroups        = _schedulerService.GetCamperGroupsForScheduleId(scheduleId);
            HashSet <Camper>         selectedCamperGroup = camperGroups.First();
            // Pick a camper with a full name in the group
            Camper   selectedCamper = selectedCamperGroup.First(c => !string.IsNullOrEmpty(c.FirstName));
            HtmlNode nameCell       = component.FindAll("button")
                                      .First(node => node.InnerText.Equals(selectedCamper.FullName));
            await nameCell.ClickAsync();

            // Assert - load the row and verify it has the selected-camper-group class
            List <HtmlNode> selectedCamperGroupRows = component.FindAll("tr")
                                                      .Where(node => node.Attributes.AttributesWithName("class")
                                                             .Any(a => a.Value.Contains("selected-camper-group"))).ToList();

            // The selected camper does not get selected-camper-group, only his peers
            Assert.That(selectedCamperGroupRows, Has.Count.EqualTo(selectedCamperGroup.Count - 1),
                        "Selected camper group rows");
            // Check that each peer has a row in the set. Need to strip it down to the last names
            // because the group has incomplete names
            List <string> selectedCamperGroupLastNames = selectedCamperGroupRows.Select(g =>
                                                                                        g.Elements("td").First(n => n.Attributes.Any(a =>
                                                                                                                                     a.Name.Equals("data-name") && a.Value.Equals("FullName")))
                                                                                        .InnerText.Split(',')[0]).ToList();

            foreach (Camper camper in selectedCamperGroup.Where(c => c != selectedCamper))
            {
                Assert.That(selectedCamperGroupLastNames,
                            Has.One.EqualTo(camper.LastName), "Camper row name");
            }
        }
        public void ProductListPage_NotAuthenticated_CantSeeStock()
        {
            ParameterView parameterView = AuthenticationStateService.PageParametersCreator();

            RenderedComponent <ProductListWrapperTestComponent> component = _testHost.AddComponent <ProductListWrapperTestComponent>(parameterView);

            HtmlNode tableHeader = component.Find("#ProductTableHeaderQuantity");

            Assert.IsNull(tableHeader);

            IEnumerable <HtmlNode> tableNameCells = component.FindAll("#ProductRowQuantity");

            Assert.IsFalse(tableNameCells.Any());
        }
        public void ProductListPage_AuthenticatedAsStaff_CanSeeStockQuantity()
        {
            ParameterView parameterView = AuthenticationStateService.PageParametersCreator(null, new Claim(ClaimTypes.Role, "Staff"));

            RenderedComponent <ProductListWrapperTestComponent> component = _testHost.AddComponent <ProductListWrapperTestComponent>(parameterView);

            HtmlNode tableHeader = component.Find("#ProductTableHeaderQuantity");

            Assert.IsNotNull(tableHeader);

            IEnumerable <HtmlNode> tableNameCells = component.FindAll("#ProductRowQuantity");

            Assert.IsTrue(tableNameCells.All(tableNameCell => tableNameCell.InnerText.All(char.IsDigit)));
        }
        public void RunScheduler_InitializeFromLocalStorage_ShowsStoredActivitySet()
        {
            // Arrange / Act
            string activitySetName = "testy";

            _localStorage.GetItemAsync <string>(Arg.Any <string>())
            .Returns(Task.FromResult(activitySetName));
            RenderedComponent <RunScheduler> component =
                _host.AddComponent <RunScheduler>();

            // Assert
            // Verify activity set selector is initialized to default
            Assert.That(component.Instance.ActivitySet, Is.EqualTo(activitySetName),
                        "ActivitySet initial value");
        }
Exemplo n.º 9
0
        public void CamperScheduleGrid_ChangeCamperActivity_ScheduleIsUpdated(int camperIndex, int timeSlot)
        {
            // Arrange - run schedule with successful data set
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <ActivityDefinition> schedule;
            string scheduleId = "MySchedule";

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                List <CamperRequests> camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                schedule = _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }

            // Act - load the grid component and update a camper
            RenderedComponent <CamperScheduleGrid> component =
                _host.AddComponent <CamperScheduleGrid>();
            List <string> fullNames = component.FindAll("td")
                                      .Where(node => node.Attributes.AttributesWithName("data-name")
                                             .Any(a => a.Value.Equals("FullName")))
                                      .Select(node => node.InnerText).ToList();
            string          camperSlotId    = $"{fullNames[camperIndex]}-{timeSlot}";
            List <HtmlNode> camperSlotCells = component.FindAll("select")
                                              .Where(node => node.Attributes.AttributesWithName("id")
                                                     .Any(a => a.Value.Equals(camperSlotId))).ToList();
            List <HtmlAttribute> valueAttributes = camperSlotCells[0].Attributes
                                                   .AttributesWithName("value").ToList();
            string originalActivityName = valueAttributes[0].Value;
            string updatedActivityName  = schedule[0].Name == originalActivityName
                                ? schedule[1].Name : schedule[0].Name;

            camperSlotCells[0].Change(updatedActivityName);

            // Assert
            // Reload the schedule and verify the camper has changed the activity.
            List <ActivityDefinition> updatedSchedule = _schedulerService.GetSchedule(scheduleId);

            Assert.That(updatedSchedule.First(ad => ad.Name.Equals(originalActivityName))
                        .ScheduledBlocks[timeSlot].AssignedCampers.Select(c => c.FullName),
                        Has.None.EqualTo(fullNames[camperIndex]), "Source activity camper list");
            Assert.That(updatedSchedule.First(ad => ad.Name.Equals(updatedActivityName))
                        .ScheduledBlocks[timeSlot].AssignedCampers.Select(c => c.FullName),
                        Has.One.EqualTo(fullNames[camperIndex]), "Target activity camper list");
        }
        public void ProductDetailsPage_AuthenticatedAsCustomerOnPageWhereTheyHaveReview_CantSeeReviewForm()
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                ["ProductID"] = "1"
            };

            ParameterView parameterView = AuthenticationStateService.PageParametersCreator(parameters, new Claim(ClaimTypes.Name, "Bob"), new Claim(ClaimTypes.Role, "Customer"));

            RenderedComponent <ProductDetailsWrapperTestComponent> component = _testHost.AddComponent <ProductDetailsWrapperTestComponent>(parameterView);

            Assert.AreEqual("Bill", component.Find("#ReviewCustomerName").InnerText);

            HtmlNode reviewForm = component.Find("#ReviewForm");

            Assert.IsNull(reviewForm);
        }
        public async Task ActivityScheduleGrid_SelectCamperActivity_AllActivitiesForCamperHilited()
        {
            // Arrange - run schedule with successful data set
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <CamperRequests> camperRequests;
            string scheduleId = "MySchedule";

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }
            RenderedComponent <ActivityScheduleGrid> component =
                _host.AddComponent <ActivityScheduleGrid>();
            List <HtmlNode> camperActivityCells = component.FindAll("td")
                                                  .Where(node => node.Attributes.AttributesWithName("class")
                                                         .Any(a => a.Value.Contains("activity-camper-cell"))).ToList();

            Assert.That(camperActivityCells, Has.Count.EqualTo(camperRequests.Count() * 4),
                        "Number of camper activity cells");

            // Act - Click on the block 0 for the next activity
            HtmlNode clickTarget = camperActivityCells.First();
            await clickTarget.ClickAsync();

            // Assert - schedule has camper selected
            Assert.That(component.Instance.SelectedCamper?.FullName,
                        Is.EqualTo(clickTarget.Attributes["title"].Value),
                        "Selected Camper Name");

            // Verify that all activity cells for the camper are selected
            List <HtmlNode> selectedCamperActivityCells = component.FindAll("td")
                                                          .Where(node => node.Attributes.AttributesWithName("class")
                                                                 .Any(a => a.Value.Contains("selected-camper"))).ToList();

            Assert.That(selectedCamperActivityCells, Has.Count.EqualTo(4),
                        "Selected activity cells");
            Assert.That(selectedCamperActivityCells.Select(c => c.Attributes["title"].Value),
                        Has.All.EqualTo(component.Instance.SelectedCamper?.FullName),
                        "Selected cell camper names");
        }
        public void ActivityScheduleGrid_OverSubscribedSchedule_HasUnscheduledBlocks()
        {
            // Arrange - run schedule with successful data set
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));

            using (MemoryStream camperRequestStream = new MemoryStream(_overSubscribedCamperRequestsBuffer))
            {
                List <CamperRequests> camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                string scheduleId = "MySchedule";
                _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }

            // Act - load the grid component
            RenderedComponent <ActivityScheduleGrid> component =
                _host.AddComponent <ActivityScheduleGrid>();

            // Assert - activity definition has a new activity for unscheduled
            List <string> originalActivityNames = _activityDefinitionService.GetActivityDefinition(DefaultSetName)
                                                  .Select(ad => ad.Name).ToList();
            List <string> addedActivityNames = activityDefinitions.Select(ad => ad.Name)
                                               .Except(originalActivityNames).ToList();

            Assert.That(addedActivityNames, Has.Count.EqualTo(1),
                        "Number of activity definitions added by scheduling");
            Assert.That(addedActivityNames[0], Is.EqualTo(SchedulerService.UnscheduledActivityName),
                        "Name of activity added by scheduling");

            // Check that all of the activities included the added 1 are on the grid
            List <HtmlNode> gridCells = component.FindAll("td")
                                        .Where(node => node.Attributes.AttributesWithName("data-name")
                                               .Any(a => a.Value.Equals("ActivityDefinition.Name"))).ToList();

            Assert.That(gridCells, Has.Count.EqualTo(activityDefinitions.Count * 4),
                        "Number of activity rows");
            List <string> cellActivityNames = gridCells.Select(c =>
                                                               c.InnerText).Distinct().ToList();

            Assert.That(cellActivityNames, Is.EquivalentTo(activityDefinitions.Select(ad => ad.Name)),
                        "Activity row names");
        }
Exemplo n.º 13
0
 private void CreateTestHost(string userName,
                             string role,
                             out RenderedComponent <App> component)
 {
     TestUtils.CreateTestHost(userName,
                              new Claim[]
     {
         new Claim("role", SharedConstants.READER),
         new Claim("role", role)
     },
                              $"http://exemple.com/import",
                              Fixture.Sut,
                              Fixture.TestOutputHelper,
                              out TestHost host,
                              out component,
                              out MockHttpMessageHandler _,
                              true);
     _host = host;
 }
Exemplo n.º 14
0
        public void Setup()
        {
            IActivityDefinitionService service = Substitute.For <IActivityDefinitionService>();

            service.GetActivitySetNames().Returns(_activitySetNames);
            _host.AddService(service);

            EventCallbackFactory   eventCallbackFactory = new EventCallbackFactory();
            EventCallback <string> eventCallback        = eventCallbackFactory.Create <string>(this, x =>
            {
                _callBackValue = x;
            });
            IDictionary <string, object> parameters = new Dictionary <string, object>
            {
                { "CurrentActivitySetChanged", eventCallback }
            };

            _component = _host.AddComponent <ActivitySetSelector>(parameters);
        }
        public void ProductDetailsPage_AuthenticatedAsCustomer_CanSeeStockText()
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                ["ProductID"] = "1"
            };

            ParameterView parameterView = AuthenticationStateService.PageParametersCreator(parameters, new Claim(ClaimTypes.Name, "Bill"), new Claim(ClaimTypes.Role, "Customer"));

            RenderedComponent <ProductDetailsWrapperTestComponent> component = _testHost.AddComponent <ProductDetailsWrapperTestComponent>(parameterView);

            HtmlNode tableHeader = component.Find("#ProductHeaderQuantity");

            Assert.IsNotNull(tableHeader);

            IEnumerable <HtmlNode> tableNameCells = component.FindAll("#ProductQuantity");

            Assert.IsTrue(tableNameCells.All(tableNameCell => tableNameCell.InnerText.Contains("Stock")));
        }
        public void ProductDetailsPage_NotAuthenticated_CantSeeStock()
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                ["ProductID"] = "1"
            };

            ParameterView parameterView = AuthenticationStateService.PageParametersCreator(parameters);

            RenderedComponent <ProductDetailsWrapperTestComponent> component = _testHost.AddComponent <ProductDetailsWrapperTestComponent>(parameterView);

            HtmlNode tableHeader = component.Find("#ProductHeaderQuantity");

            Assert.IsNull(tableHeader);

            IEnumerable <HtmlNode> tableNameCells = component.FindAll("#ProductQuantity");

            Assert.IsFalse(tableNameCells.Any());
        }
        public void ProductDetailsPage_CustomerReviewsProductTheyHaveBought_ReviewIsAddedToList()
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                ["ProductID"] = "2"
            };

            ParameterView parameterView = AuthenticationStateService.PageParametersCreator(parameters, new Claim(ClaimTypes.Name, "Bill"), new Claim(ClaimTypes.Role, "Customer"));

            RenderedComponent <ProductDetailsWrapperTestComponent> component = _testHost.AddComponent <ProductDetailsWrapperTestComponent>(parameterView);

            component.Find("#ReviewFormRatingInput").Change("3");
            component.Find("#ReviewFormTextInput").Change("This is a test review.");
            component.Find("#ReviewForm").Submit();

            Assert.AreEqual("Bill", component.Find("#ReviewCustomerName").InnerText);
            Assert.AreEqual("3", component.Find("#ReviewRating").InnerText);
            Assert.AreEqual("This is a test review.", component.Find("#ReviewText").InnerText);
        }
        public void ProductDetailsPage_NotAuthenticated_CantSeeReviewFormOrDeleteButtons()
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                ["ProductID"] = "1"
            };

            ParameterView parameterView = AuthenticationStateService.PageParametersCreator(parameters);

            RenderedComponent <ProductDetailsWrapperTestComponent> component = _testHost.AddComponent <ProductDetailsWrapperTestComponent>(parameterView);

            HtmlNode reviewForm = component.Find("#ReviewForm");

            Assert.IsNull(reviewForm);

            HtmlNode reviewDeleteButton = component.Find("#ReviewDeleteButton");

            Assert.IsNull(reviewDeleteButton);
        }
        public void RunScheduler_InitializeEmptyLocalStorage_ShowDefaultActivitySet()
        {
            // Arrange / Act
            _localStorage.ClearReceivedCalls();
            _localStorage.GetItemAsync <string>(Arg.Any <string>())
            .Returns(Task.FromResult(string.Empty));
            RenderedComponent <RunScheduler> component =
                _host.AddComponent <RunScheduler>();

            // Assert
            // Verify activity set selector is initialized to default
            Assert.That(component.Instance.ActivitySet, Is.EqualTo(DefaultSetName),
                        "ActivitySet initial value");

            // Verify activity set is persisted.
            Received.InOrder(async() =>
            {
                await _localStorage.SetItemAsync(ActivitySetKey, DefaultSetName);
            });
        }
Exemplo n.º 20
0
        public static HtmlNode ShouldHaveLabelNode(this RenderedComponent <MDCTextField> source, MDCTextFieldStyle variant)
        {
            var root = source.GetDocumentNode();

            HtmlNode labelNode = null;

            switch (variant)
            {
            case MDCTextFieldStyle.Filled:
                labelNode = root.SelectNodes("//label/span[2]").ShouldHaveSingleItem();
                break;

            case MDCTextFieldStyle.Outlined:
                labelNode = root.SelectNodes("//label/span/span/span").ShouldHaveSingleItem();
                break;
            }

            labelNode.ShouldNotBeNull();
            return(labelNode);
        }
Exemplo n.º 21
0
 protected void CreateTestHost(string userName,
                               string role,
                               out TestHost host,
                               out RenderedComponent <App> component,
                               out MockHttpMessageHandler mockHttp)
 {
     TestUtils.CreateTestHost(userName,
                              new Claim[]
     {
         new Claim("role", SharedConstants.READER),
         new Claim("role", role)
     },
                              $"http://exemple.com/{Entities}",
                              _fixture.Sut,
                              _fixture.TestOutputHelper,
                              out host,
                              out component,
                              out mockHttp);
     _host = host;
 }
Exemplo n.º 22
0
        public void ItFetchesPriceAndSetsTheValue()
        {
            // Arrange
            _ = this.SetMockRuntime();
            _ = this.CreateMockHttpClientAsync();
            _ = this.CreateTimer();

            // Act
            RenderedComponent <Index> componentUnderTest = this.host.AddComponent <Index>();

            // Assert
            string       displayAmount = componentUnderTest.Find("p").InnerText.Split(new char[] { ' ' })[0];
            NumberStyles style         = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
            CultureInfo  provider      = new CultureInfo("de-DE");

            decimal resultAmount   = decimal.Parse(displayAmount, style, provider);
            decimal expectedAmount = decimal.Parse($"{this.testAmount:n2}");

            Assert.Equal(expectedAmount, resultAmount);

            Assert.Equal(2, MockBitcoinMessageHandler.requestCount);
        }
        public void RunSchedule_ScheduleOversubscribed_OutputsUnhappyCampers()
        {
            // Arrange
            RenderedComponent <RunScheduler> component =
                _host.AddComponent <RunScheduler>();
            MemoryStream   camperRequestStream = new MemoryStream(_overSubscribedCamperRequestsBuffer);
            IFileReference camperRequestFile   = Substitute.For <IFileReference>();

            camperRequestFile.OpenReadAsync().Returns(camperRequestStream);
            IFileReaderRef fileReaderRef = Substitute.For <IFileReaderRef>();

            fileReaderRef.EnumerateFilesAsync().Returns(new IFileReference[] { camperRequestFile });
            _fileReaderService.CreateReference(Arg.Any <ElementReference>()).Returns(fileReaderRef);

            // Act - execute scheduler
            HtmlAgilityPack.HtmlNode runSchedulerButton = component.Find("button");
            runSchedulerButton.Click();

            // Assert file is loaded
            Assert.That(component.Instance.Output, Contains.Substring("3 campers could not be scheduled"),
                        "Messages after scheduling");
        }
        public void RunSchedule_ScheduleMissingActivityFile_IndicatesUnknownActivity()
        {
            // Arrange
            RenderedComponent <RunScheduler> component =
                _host.AddComponent <RunScheduler>();
            MemoryStream   camperRequestStream = new MemoryStream(_missingActivityCamperRequestsBuffer);
            IFileReference camperRequestFile   = Substitute.For <IFileReference>();

            camperRequestFile.OpenReadAsync().Returns(camperRequestStream);
            IFileReaderRef fileReaderRef = Substitute.For <IFileReaderRef>();

            fileReaderRef.EnumerateFilesAsync().Returns(new IFileReference[] { camperRequestFile });
            _fileReaderService.CreateReference(Arg.Any <ElementReference>()).Returns(fileReaderRef);

            // Act - execute scheduler
            HtmlAgilityPack.HtmlNode runSchedulerButton = component.Find("button");
            runSchedulerButton.Click();

            // Assert error message
            Assert.That(component.Instance.Output,
                        Contains.Substring("requested unknown activity: 'Horseplay'"),
                        "Messages after scheduling");
        }
        public void ActivityScheduleGrid_PrebuiltValidSchedule_NoCapacityErrorStyles()
        {
            // Arrange - run schedule with successful data set
            _localStorage.GetItemAsync <string>(Arg.Any <string>())
            .Returns(Task.FromResult(PrebuiltScheduleId));

            // Act - load the grid component
            RenderedComponent <ActivityScheduleGrid> component =
                _host.AddComponent <ActivityScheduleGrid>();

            // Assert - none are marked over-subscribed or under-subscribed
            List <HtmlNode> countNodes = component.FindAll("td")
                                         .Where(node => node.Attributes.AttributesWithName("data-name")
                                                .Any(a => a.Value.Equals("AssignedCampers.Count"))).ToList();
            List <string> countClass = countNodes
                                       .Select(node => node.Attributes["class"].Value)
                                       .ToList();

            Assert.That(countClass, Has.None.Contains("capacity-over"),
                        "Activity block styles");
            Assert.That(countClass, Has.None.Contains("capacity-under"),
                        "Activity block styles");
        }
        public void ManageActivityDefinitions_InitializeFromLocalStorage_ShowsStoredActivitySet()
        {
            // Arrange / Act
            string activitySetName = _expectedActivitySets.Keys.Skip(1).First();

            _localStorage.GetItemAsync <string>(Arg.Any <string>())
            .Returns(Task.FromResult(activitySetName));
            RenderedComponent <ManageActivityDefinitions> component =
                _host.AddComponent <ManageActivityDefinitions>();

            // Assert
            // Verify activity set selector is initialized to default
            Assert.That(component.Instance.ActivitySet, Is.EqualTo(activitySetName),
                        "ActivitySet initial value");
            // Verify activity grid has correct number of rows.
            HtmlAgilityPack.HtmlNode gridCountSpan = component.FindAll("span")
                                                     .FirstOrDefault(s => s.Attributes
                                                                     .Any(a => a.Value.Equals("grid-itemscount-caption",
                                                                                              StringComparison.OrdinalIgnoreCase)));
            Assert.That(gridCountSpan?.InnerText,
                        Is.EqualTo(_expectedActivitySets[activitySetName].Count.ToString()),
                        "Reported number of activities in grid");
        }
        public void ActivityScheduleGrid_StartDragOfCamper_PayloadUpdated()
        {
            // Arrange - run schedule with successful data set
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <CamperRequests> camperRequests;

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                string scheduleId = "MySchedule";
                _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }
            RenderedComponent <ActivityScheduleGrid> component =
                _host.AddComponent <ActivityScheduleGrid>();

            // Act - Start a drag on a camper activity cell
            List <HtmlNode> camperActivityCells = component.FindAll("td")
                                                  .Where(node => node.Attributes.AttributesWithName("class")
                                                         .Any(a => a.Value.Contains("activity-camper-cell"))).ToList();

            Assert.That(camperActivityCells, Has.Count.EqualTo(camperRequests.Count() * 4),
                        "Number of camper activity cells");
            camperActivityCells[0].TriggerEventAsync("ondragstart", new DragEventArgs());

            // Assert - Grid pay load is set.
            // The first cell should be archery block 0
            Assert.That(component.Instance.DragPayload.ActivityName,
                        Is.EqualTo("Archery"), "Drag payload activity name");
            Assert.That(component.Instance.DragPayload.TimeSlot,
                        Is.EqualTo(0), "Drag pay load time slot");
            Assert.That(component.Instance.DragPayload.CamperName,
                        Is.Not.Null, "Drag pay load camper name");
        }
Exemplo n.º 28
0
        public async Task CamperScheduleGrid_SelectCamper_CamperRowHilite()
        {
            // Arrange - run schedule with successful data set and load grid
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <ActivityDefinition> schedule;

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                List <CamperRequests> camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                string scheduleId = "MySchedule";
                schedule = _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }
            RenderedComponent <CamperScheduleGrid> component =
                _host.AddComponent <CamperScheduleGrid>();

            // Act - select a camper
            Camper selectedCamper = schedule.First().ScheduledBlocks.First()
                                    .AssignedCampers.First();
            HtmlNode nameCell = component.FindAll("button")
                                .First(node => node.InnerText.Equals(selectedCamper.FullName));
            await nameCell.ClickAsync();

            // Assert - load the row and verify it has the selected-camper class
            List <HtmlNode> selectedCamperRows = component.FindAll("tr")
                                                 .Where(node => node.Attributes.AttributesWithName("class")
                                                        .Any(a => a.Value.Contains("selected-camper"))).ToList();

            Assert.That(selectedCamperRows, Has.Count.EqualTo(1), "Selected camper rows");
            Assert.That(selectedCamperRows[0].Elements("td").First(n =>
                                                                   n.Attributes.Any(a => a.Name.Equals("data-name") && a.Value.Equals("FullName"))).InnerText,
                        Is.EqualTo(selectedCamper.FullName), "Camper row name");
        }
        public void ActivityScheduleGrid_DropCamperInSameTimeSlot_CamperIsMoved()
        {
            // Arrange - run schedule with successful data set and start a drag
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <CamperRequests> camperRequests;
            string scheduleId = "MySchedule";

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }
            RenderedComponent <ActivityScheduleGrid> component =
                _host.AddComponent <ActivityScheduleGrid>();
            List <HtmlNode> camperActivityCells = component.FindAll("td")
                                                  .Where(node => node.Attributes.AttributesWithName("class")
                                                         .Any(a => a.Value.Contains("activity-camper-cell"))).ToList();

            Assert.That(camperActivityCells, Has.Count.EqualTo(camperRequests.Count() * 4),
                        "Number of camper activity cells");
            // Gather up the activity block drop zones.
            List <HtmlNode> activityBlockCampers = component.FindAll("tr")
                                                   .Where(node => node.Attributes.AttributesWithName("ondrop").Any())
                                                   .ToList();

            Assert.That(activityBlockCampers, Has.Count.EqualTo(activityDefinitions.Count * 4),
                        "Number of activity rows");
            // Start a drag on a camper in the first activity block
            HtmlNode sourceCamperActivity = camperActivityCells.First(
                node => node.ParentNode.GetAttributeValue("id", "") ==
                activityBlockCampers[0].GetAttributeValue("id", "NotDefined"));

            sourceCamperActivity.TriggerEventAsync("ondragstart", new DragEventArgs());
            string camperName = component.Instance.DragPayload.CamperName;

            // Act - Drop on the block 0 for the next activity
            HtmlNode dropTarget = activityBlockCampers.First(n =>
                                                             n.GetAttributeValue("id", "")
                                                             .Equals($"{activityDefinitions[1].Name}-0"));

            dropTarget.TriggerEventAsync("ondrop", new DragEventArgs());

            // Assert - Grid pay load is reset.
            Assert.That(component.Instance.DragPayload.ActivityName, Is.EqualTo(null),
                        "Drag payload activity");
            Assert.That(component.Instance.DragPayload.CamperName, Is.EqualTo(null),
                        "Drag payload camper");
            Assert.That(component.Instance.DragPayload.TimeSlot, Is.EqualTo(0),
                        "Drag payload time slot");

            // Verify camper activities have not changed
            List <ActivityDefinition> schedule              = _schedulerService.GetSchedule(scheduleId);
            ActivityDefinition        sourceActivity        = schedule.Find(ad => ad.Name.Equals(activityDefinitions[0].Name));
            List <string>             assignedCampersByName = sourceActivity.ScheduledBlocks[component.Instance.DragPayload.TimeSlot]
                                                              .AssignedCampers.Select(c => c.FullName).ToList();

            Assert.That(assignedCampersByName, Has.None.EqualTo(camperName),
                        "Assigned campers on drag source");
            ActivityDefinition targetActivity = schedule.Find(ad => ad.Name.Equals(activityDefinitions[1].Name));

            assignedCampersByName = targetActivity.ScheduledBlocks[component.Instance.DragPayload.TimeSlot]
                                    .AssignedCampers.Select(c => c.FullName).ToList();
            Assert.That(assignedCampersByName, Has.One.EqualTo(camperName),
                        "Assigned campers on drop target");
        }
Exemplo n.º 30
0
        public static ICollection <HtmlNode> WaitForAllNodes <TComponent>(this TestHost host, RenderedComponent <TComponent> component, string selector)
            where TComponent : IComponent
        {
            var nodes = component.FindAll(selector);

            while (nodes.Count == 0)
            {
                host.WaitForNextRender();
                nodes = component.FindAll(selector);
            }

            return(nodes);
        }