Ejemplo n.º 1
0
        public void CanUpdate_should_throw_exception_if_pattern_exists()
        {
            var id1 = DomainId.NewGuid();
            var id2 = DomainId.NewGuid();

            var patterns_1 = patterns_0.Add(id1, "Pattern1", "[0-5]", "Message");
            var patterns_2 = patterns_1.Add(id2, "Pattern2", "[0-4]", "Message");

            var command = new UpdatePattern {
                PatternId = id2, Name = "Pattern2", Pattern = "[0-5]"
            };

            ValidationAssert.Throws(() => GuardAppPatterns.CanUpdate(patterns_2, command),
                                    new ValidationError("This pattern already exists but with another name."));
        }
Ejemplo n.º 2
0
        public async Task CanChangeStatus_should_throw_exception_if_due_date_in_past()
        {
            var schema = CreateSchema(false);

            var content = CreateContent(Status.Draft);
            var command = new ChangeContentStatus {
                Status = Status.Published, DueTime = dueTimeInPast, User = user
            };

            A.CallTo(() => contentWorkflow.CanMoveToAsync(content, content.Status, command.Status, user))
            .Returns(true);

            await ValidationAssert.ThrowsAsync(() => GuardContent.CanChangeStatus(schema, content, contentWorkflow, command),
                                               new ValidationError("Due time must be in the future.", "DueTime"));
        }
Ejemplo n.º 3
0
        public async Task CanAssign_should_throw_exception_if_contributor_max_reached()
        {
            A.CallTo(() => appPlan.MaxContributors)
            .Returns(2);

            var command = new AssignContributor {
                ContributorId = "3"
            };

            var contributors_1 = contributors_0.Assign("1", Role.Owner);
            var contributors_2 = contributors_1.Assign("2", Role.Editor);

            await ValidationAssert.ThrowsAsync(() => GuardAppContributors.CanAssign(command, App(contributors_2), users, appPlan),
                                               new ValidationError("You have reached the maximum number of contributors for your plan."));
        }
Ejemplo n.º 4
0
        public void Join_WhenResultsContainEqualErrors_DoesNotFiltersErrors()
        {
            var firstEqualError  = CreateValidationError("Equal error");
            var secondEqualError = CreateValidationError("Equal error");

            Assert.AreEqual(firstEqualError, secondEqualError, "Assumption failed");

            var s1 = CreateValidationResult(firstEqualError);
            var s2 = CreateValidationResult(secondEqualError);

            var joined   = ValidationResult.Join(s1, s2);
            var expected = new ValidationResult(new[] { firstEqualError, secondEqualError });

            ValidationAssert.AreEqual(expected, joined);
        }
Ejemplo n.º 5
0
        public async Task CanChangeStatus_should_throw_exception_if_status_flow_not_valid()
        {
            var schema = CreateSchema(false);

            var content = CreateContent(Status.Draft);
            var command = new ChangeContentStatus {
                Status = Status.Published, User = user
            };

            A.CallTo(() => contentWorkflow.CanMoveToAsync(content, content.Status, command.Status, user))
            .Returns(false);

            await ValidationAssert.ThrowsAsync(() => GuardContent.CanChangeStatus(schema, content, contentWorkflow, command),
                                               new ValidationError("Cannot change status from Draft to Published.", "Status"));
        }
Ejemplo n.º 6
0
        public async Task CanCreate_should_throw_exception_if_trigger_null()
        {
            var command = new CreateRule
            {
                Trigger = null !,
                Action  = new TestAction
                {
                    Url = validUrl
                },
                AppId = appId
            };

            await ValidationAssert.ThrowsAsync(() => GuardRule.CanCreate(command, appProvider),
                                               new ValidationError("Trigger is required.", "Trigger"));
        }
        public void Refresh_OfViewModelProperty_RevalidatesPropertyValue()
        {
            ParameterizedTest
            .TestCase("InstanceProperty", new Func <RootVMDescriptor, IVMPropertyDescriptor>(x => x.InstanceProperty))
            .TestCase("MappedProperty", x => x.WrapperProperty)
            .TestCase("DelegateProperty", x => x.DelegateProperty)
            .Run(propertySelector => {
                var property                  = propertySelector(VM.Descriptor);
                var expectedError             = "Validation error";
                VM.ValidationErrors[property] = expectedError;

                VM.Refresh(propertySelector);
                ValidationAssert.ErrorMessages(VM.GetValidationResult(property), expectedError);
            });
        }
Ejemplo n.º 8
0
        public void GetValueOfUnloadedGrandChild_WhenRevalidateLoadedDescendantsWasCalledBefore_ValidatesGrandchild()
        {
            VM.Revalidate(ValidationScope.SelfAndLoadedDescendants);

            VM.GetValue(x => x.UnloadedChild);
            VM.GetValue(x => x.UnloadedChild).GetValue(x => x.Items);

            ValidationAssert.ErrorMessages(
                VM.ValidationResult,
                LoadedChildError,
                LoadedGrandChildError,
                UnloadedChildError,
                UnloadedGrandChildError
                );
        }
Ejemplo n.º 9
0
        public async Task CanCreate_should_throw_exception_if_action_null()
        {
            var command = new CreateRule
            {
                Trigger = new ContentChangedTriggerV2
                {
                    Schemas = ReadOnlyCollection.Empty <ContentChangedTriggerSchemaV2>()
                },
                Action = null !,
                AppId  = appId
            };

            await ValidationAssert.ThrowsAsync(() => GuardRule.CanCreate(command, appProvider),
                                               new ValidationError("Action is required.", "Action"));
        }
Ejemplo n.º 10
0
        public void CanUpdate_should_throw_exception_if_name_exists()
        {
            var id1 = DomainId.NewGuid();
            var id2 = DomainId.NewGuid();

            var patterns_1 = patterns_0.Add(id1, "Pattern1", "[0-5]", "Message");
            var patterns_2 = patterns_1.Add(id2, "Pattern2", "[0-4]", "Message");

            var command = new UpdatePattern {
                PatternId = id2, Name = "Pattern1", Pattern = "[0-4]"
            };

            ValidationAssert.Throws(() => GuardAppPatterns.CanUpdate(command, App(patterns_2)),
                                    new ValidationError("A pattern with the same name already exists."));
        }
Ejemplo n.º 11
0
        public void OwnerResult_WhenDelegatedViewModelPropertyIsRefreshedAndReturnsNewInvalidViewModel_ContainsError()
        {
            Owner.DelegatedPropertyResultToReturn = new ItemVM();
            Owner.Load(x => x.DelegatedProperty);
            ValidationAssert.IsValid(Owner);

            var invalidChild = CreateInvalidItem();

            Owner.DelegatedPropertyResultToReturn = invalidChild;
            ValidationAssert.IsValid(Owner);

            Owner.Refresh(x => x.DelegatedProperty);
            Assert.IsFalse(Owner.DelegatedProperty.IsValid);

            ValidationAssert.ErrorMessages(Owner.ValidationResult, invalidChild.ErrorToReturn);
        }
        public void SetValue_ToNewChild_RevalidatesOldAndNewChild()
        {
            var vm       = new ParentVM();
            var oldChild = new ChildVM();
            var newChild = new ChildVM();

            vm.SetValue(x => x.Child, oldChild);

            oldChild.ChildPropertyErrorMessage = "Old validation error";
            newChild.ChildPropertyErrorMessage = "New validation error";

            vm.SetValue(x => x.Child, newChild);

            ValidationAssert.ErrorMessages(oldChild.ValidationResult, oldChild.ChildPropertyErrorMessage);
            ValidationAssert.ErrorMessages(newChild.ValidationResult, newChild.ChildPropertyErrorMessage);
        }
        public void SetValue_RemovesValidationErrorsOfAncestorValidatorsFromOldChild()
        {
            string parentErrorMessage = "Parent error";

            var vm       = new ParentVM();
            var oldChild = new ChildVM();
            var newChild = new ChildVM();

            vm.ChildPropertyErrorMessage = parentErrorMessage;

            vm.SetValue(x => x.Child, oldChild);
            ValidationAssert.ErrorMessages(oldChild.ValidationResult, parentErrorMessage);

            vm.SetValue(x => x.Child, newChild);

            ValidationAssert.IsValid(oldChild);
        }
Ejemplo n.º 14
0
        public void CanUpdate_should_throw_exception_if_text_not_defined()
        {
            var commentId = DomainId.NewGuid();
            var command   = new UpdateComment {
                CommentId = commentId, Actor = user1
            };

            var events = new List <Envelope <CommentsEvent> >
            {
                Envelope.Create <CommentsEvent>(new CommentCreated {
                    CommentId = commentId, Actor = user1
                }).To <CommentsEvent>()
            };

            ValidationAssert.Throws(() => GuardComments.CanUpdate(commentsId, events, command),
                                    new ValidationError("Text is required.", "Text"));
        }
        public void ViewModelValidationDefinedOnParent_IsPerformedIfChildOnlyCallsEnableParentValidation()
        {
            var error = "Parent added error";

            var parent = EmployeeVM.Create(b => {
                b.ValidateDescendant(x => x.SelectedProject)
                .CheckViewModel(args => args.AddError(error));
            });

            var child = ProjectVM.Create(b => {
                b.EnableParentViewModelValidation();
            });

            parent.SetValue(x => x.SelectedProject, child);

            parent.Revalidate(ValidationScope.SelfAndAllDescendants);
            ValidationAssert.ErrorMessages(child.ValidationResult, error);
        }
Ejemplo n.º 16
0
        public async Task CanMove_should_throw_exception_when_adding_to_its_own_child()
        {
            var id = Guid.NewGuid();

            var command = new MoveAssetFolder {
                ParentId = Guid.NewGuid()
            };

            A.CallTo(() => assetQuery.FindAssetFolderAsync(command.ParentId))
            .Returns(new List <IAssetFolderEntity>
            {
                CreateFolder(id),
                CreateFolder(command.ParentId)
            });

            await ValidationAssert.ThrowsAsync(() => GuardAssetFolder.CanMove(command, assetQuery, id, Guid.NewGuid()),
                                               new ValidationError("Cannot add folder to its own child.", "ParentId"));
        }
Ejemplo n.º 17
0
        public void GetValidationResult_Initially_ReturnsValidResults()
        {
            var vm = new TestVM();

            ParameterizedTest
            .TestCase(ValidationResultScope.PropertiesOnly)
            .TestCase(ValidationResultScope.ViewModelValidationsOnly)
            .TestCase(ValidationResultScope.Self)
            .TestCase(ValidationResultScope.Descendants)
            .TestCase(ValidationResultScope.All)
            .Run(scope => {
                var result = vm
                             .Behavior
                             .GetValidationResult(vm.GetContext(), scope);

                ValidationAssert.IsValid(result);
            });
        }
Ejemplo n.º 18
0
        public async Task CanMove_should_throw_exception_if_adding_to_its_own_child()
        {
            var id = DomainId.NewGuid();

            var command = new MoveAssetFolder {
                AppId = appId, ParentId = DomainId.NewGuid()
            };

            A.CallTo(() => assetQuery.FindAssetFolderAsync(appId.Id, command.ParentId, A <CancellationToken> ._))
            .Returns(new List <IAssetFolderEntity>
            {
                AssetFolder(id),
                AssetFolder(command.ParentId)
            });

            await ValidationAssert.ThrowsAsync(() => GuardAssetFolder.CanMove(command, AssetFolder(id), assetQuery),
                                               new ValidationError("Cannot add folder to its own child.", "ParentId"));
        }
        [TestMethod] // regression test
        public void SetValue_WhenOldAndNewChildGetInvalid_ParentResultContainsOnlyErrorOfNewChild()
        {
            var parent = new ParentVM();

            var oldChild = new ChildVM();
            var newChild = new ChildVM();

            parent.SetValue(x => x.Child, oldChild);

            oldChild.ChildPropertyErrorMessage = "Old validation error";
            newChild.ChildPropertyErrorMessage = "New validation error";
            parent.SetValue(x => x.Child, newChild);

            ValidationAssert.ErrorMessages(
                parent.ValidationResult,
                ParentVM.ChildInvalidMessage,
                newChild.ChildPropertyErrorMessage
                );
        }
        public void RefreshContainer_WhenItemIsAddedToSoureCollection_RevalidatesSelectionOfItemVMWhenLoaded()
        {
            Employee   emp   = new Employee();
            EmployeeVM empVM = new EmployeeVM();

            empVM.InitializeFrom(emp);

            empVM.Load(x => x.Projects);

            emp.AddProjekt();

            empVM.RefreshContainer(x => x.Projects);

            ProjectVM projectVM = empVM.GetValue(x => x.Projects).Single();

            projectVM.Load(x => x.Department);

            ValidationAssert.ErrorMessages(projectVM.GetValidationResult(ValidationResultScope.All), ProjectVM.ValidationError);
        }
Ejemplo n.º 21
0
        public void PropertyValidation_WhenConditionIsFalse_IsNotExecuted()
        {
            bool condition = true;

            EmployeeVM vm = CreateVM(b => b
                                     .When(args => condition)
                                     .Check(x => x.Name)
                                     .Custom(args => args.AddError("Test error"))
                                     );

            vm.Revalidate(ValidationScope.SelfAndAllDescendants);

            ValidationAssert.IsInvalid(vm);

            condition = false;
            vm.Revalidate(ValidationScope.SelfAndAllDescendants);

            ValidationAssert.IsValid(vm);
        }
Ejemplo n.º 22
0
        public void ViewModelCollectionValidation_WhenItemConditionIsFalse_IsNotExecuted()
        {
            ProjectVM project1 = new ProjectVM();
            ProjectVM project2 = new ProjectVM();

            EmployeeVM vm = CreateVM(b => b
                                     .ValidateDescendant(x => x.Projects)
                                     .When(args => args.Target == project2)
                                     .CheckViewModel(args => args.AddError("Test error"))
                                     );

            vm.Projects.Add(project1);
            vm.Projects.Add(project2);

            vm.Revalidate(ValidationScope.SelfAndAllDescendants);

            ValidationAssert.IsValid(project1);
            ValidationAssert.IsInvalid(project2);
        }
Ejemplo n.º 23
0
        public void CanCreate_should_throw_exception_if_field_name_invalid()
        {
            var command = CreateCommand(new CreateSchema
            {
                Fields = new[]
                {
                    new UpsertSchemaField
                    {
                        Name         = "invalid name",
                        Properties   = new StringFieldProperties(),
                        Partitioning = Partitioning.Invariant.Key
                    }
                },
                Name = "new-schema"
            });

            ValidationAssert.Throws(() => GuardSchema.CanCreate(command),
                                    new ValidationError("Name is not a Javascript property name.",
                                                        "Fields[0].Name"));
        }
        public void Revalidate_WhenDescendantAddsValidationError_AddsErrorToAncestorValidationResult()
        {
            Results.SetupFailing().PropertyValidation
            .Targeting(Child, x => x.ChildProperty)
            .On(Child);

            Results.SetupFailing().ViewModelValidation
            .Targeting(Child)
            .On(Child);

            Child.Revalidate(x => x.ChildProperty);

            Results.VerifySetupValidationResults();

            var expectedAncestorResult = new ValidationResult(
                Results.ValidatorSetups.SelectMany(x => x.Result.Errors)
                );

            ValidationAssert.AreEqual(expectedAncestorResult, Grandparent.ValidationResult);
        }
        public void Min_ExecutedSecondTime_ReturnsUpdatedErrorMessage()
        {
            int min          = 10;
            int currentValue = 100;

            var vm = CreateParent(b => b.Check(x => x.IntegerProperty).Min(x => min));

            vm.SetValue(x => x.IntegerProperty, currentValue);

            min = currentValue + 1;
            vm.Revalidate();

            min = currentValue + 2;
            vm.Revalidate();

            ValidationAssert.ErrorMessages(
                vm.ValidationResult,
                Localized.ValidationMin.FormatWith(min)
                );
        }
Ejemplo n.º 26
0
        public void SetIsSelectedProperty_WhenSelectedItemGetsInvalid_CorrectlyUpdatesIsSelectedOfAllItems()
        {
            var vm = CreateUserVM(
                allDepartments: new[] { Department1, Department2 },
                selectedDepartment: DepartmentNotInSource
                );

            vm.Department.Load(x => x.SelectedItem);
            ValidationAssert.IsInvalid(vm);

            Department[] areSelected = vm
                                       .Department
                                       .AllItems
                                       .Where(x => x.IsSelected)
                                       .Select(x => x.Source)
                                       .ToArray();

            CollectionAssert.AreEquivalent(new[] { DepartmentNotInSource }, areSelected);

            vm.Department.SelectedItem = vm
                                         .Department
                                         .AllItems
                                         .Single(x => x.Source == Department1);

            vm
            .Department
            .AllItems
            .Where(x => x.Source == DepartmentNotInSource)
            .Single()
            .IsSelected = true;

            areSelected = vm
                          .Department
                          .AllItems
                          .Where(x => x.IsSelected)
                          .Select(x => x.Source)
                          .ToArray();

            Assert.AreEqual(1, areSelected.Length);
            Assert.AreEqual(DepartmentNotInSource, areSelected[0]);
        }
Ejemplo n.º 27
0
        public void CanCreate_should_throw_exception_if_field_name_invalid()
        {
            var command = new CreateSchema
            {
                AppId  = appId,
                Fields = new List <UpsertSchemaField>
                {
                    new UpsertSchemaField
                    {
                        Name         = "invalid name",
                        Properties   = new StringFieldProperties(),
                        Partitioning = Partitioning.Invariant.Key
                    }
                },
                Name = "new-schema"
            };

            ValidationAssert.Throws(() => GuardSchema.CanCreate(command),
                                    new ValidationError("Field name must be a valid javascript property name.",
                                                        "Fields[1].Name"));
        }
Ejemplo n.º 28
0
        public Task CanCreate_should_throw_exception_if_field_properties_null()
        {
            var command = new CreateSchema
            {
                AppId  = appId,
                Fields = new List <CreateSchemaField>
                {
                    new CreateSchemaField
                    {
                        Name         = "field1",
                        Properties   = null,
                        Partitioning = Partitioning.Invariant.Key
                    }
                },
                Name = "new-schema"
            };

            return(ValidationAssert.ThrowsAsync(() => GuardSchema.CanCreate(command, appProvider),
                                                new ValidationError("Field properties is required.",
                                                                    "Fields[1].Properties")));
        }
Ejemplo n.º 29
0
        public Task CanCreate_should_throw_exception_if_field_partitioning_not_valid()
        {
            var command = new CreateSchema
            {
                AppId  = appId,
                Fields = new List <CreateSchemaField>
                {
                    new CreateSchemaField
                    {
                        Name         = "field1",
                        Properties   = new StringFieldProperties(),
                        Partitioning = "INVALID"
                    }
                },
                Name = "new-schema"
            };

            return(ValidationAssert.ThrowsAsync(() => GuardSchema.CanCreate(command, appProvider),
                                                new ValidationError("Field partitioning is not valid.",
                                                                    "Fields[1].Partitioning")));
        }
Ejemplo n.º 30
0
        public void CanCreate_should_throw_exception_if_field_partitioning_not_valid()
        {
            var command = new CreateSchema
            {
                AppId  = appId,
                Fields = new List <UpsertSchemaField>
                {
                    new UpsertSchemaField
                    {
                        Name         = "field1",
                        Properties   = new StringFieldProperties(),
                        Partitioning = "INVALID"
                    }
                },
                Name = "new-schema"
            };

            ValidationAssert.Throws(() => GuardSchema.CanCreate(command),
                                    new ValidationError("Partitioning is not a valid value.",
                                                        "Fields[1].Partitioning"));
        }