Beispiel #1
0
        public void DeathTestRevive()
        {
            BaseEntity player = new MockEntity(Engine)
            {
                Name = "MOCK_PLAYER", Key = "MOCK_KEY"
            };

            player.Kill();
            player.Update();
            Assert.AreEqual(true, player.IsDead);
            player.Update();
            Assert.AreEqual(false, player.IsDead);
            ResourceInstance hp = player.GetResource(Entity.HP_KEY);

            Assert.AreEqual(hp.MaxAmount * hp.Modifier, hp.Value);
        }
        public void GetInstance_single()
        {
            MockEntity entity = new MockEntity()
            {
                id = 1
            };
            DbEntityDataBundle dataBundle = DbEntityDataBundle.GetInstance(1, 0, entity);

            Assert.AreEqual(typeof(MockEntity), dataBundle.Type);
            Assert.AreEqual(1, dataBundle.Parameters.Count);
            Assert.IsTrue(dataBundle.Contains <MockEntity>(DbEntityDataBundle.EntityParameterKey));
            Assert.IsFalse(dataBundle.Contains <string>(DbEntityDataBundle.EntityJsonParameterKey));
            Assert.IsFalse(dataBundle.Contains <List <MockEntity> >(DbEntityDataBundle.EntitiesParameterKey));
            Assert.IsFalse(dataBundle.Contains <string>(DbEntityDataBundle.EntitiesJsonParameterKey));
            Assert.AreEqual(entity, dataBundle.GetParameter <MockEntity>(DbEntityDataBundle.EntityParameterKey));
        }
        public void Equals_new_entities_true()
        {
            string     guid = Guid.NewGuid().ToString();
            MockEntity e1   = new MockEntity()
            {
                id = 0, Guid = guid
            };
            MockEntity e2 = new MockEntity()
            {
                id = 0, Guid = guid
            };

            IEqualityComparer <MockEntity> comparer = new DbEntitiesComparer <MockEntity>();

            Assert.IsTrue(comparer.Equals(e1, e2));
        }
Beispiel #4
0
            public void CustomMethodWithParams(MockEntity entity, long param1, IEnumerable <string> param2, Dictionary <byte, string> param3, Uri param4)
            {
                var parameters = new Dictionary <string, object>();

                parameters.Add("entity", entity);
                parameters.Add("param1", param1);
                parameters.Add("param2", param2);
                parameters.Add("param3", param3);
                parameters.Add("param4", param4);
                this.OnOperationInvoked("CustomMethodWithParams", parameters);

                if (entity.Name == "ThrowError")
                {
                    throw new ValidationException(entity.Name);
                }
            }
        public void MutationOperator_Mutate()
        {
            GeneticAlgorithm     algorithm = GetAlgorithm(.03);
            MockMutationOperator op        = new MockMutationOperator();

            op.Initialize(algorithm);
            GeneticEntity entity = new MockEntity();

            entity.Initialize(algorithm);
            entity.Age = 10;
            GeneticEntity mutant = op.Mutate(entity);

            Assert.NotSame(entity, mutant);
            Assert.Equal(entity.Age, mutant.Age);
            Assert.Equal(1, op.DoMutateCallCount);
        }
        public void GetHashCode_new_entities_equal()
        {
            string     guid = Guid.NewGuid().ToString();
            MockEntity e1   = new MockEntity()
            {
                id = 0, Guid = guid
            };
            MockEntity e2 = new MockEntity()
            {
                id = 0, Guid = guid
            };

            IEqualityComparer <MockEntity> comparer = new DbEntitiesComparer <MockEntity>();

            Assert.AreEqual(comparer.GetHashCode(e1), comparer.GetHashCode(e2));
        }
Beispiel #7
0
        public void ValidateTest()
        {
            AssertHelper.ExpectedException<ArgumentNullException>(() => DataErrorInfoExtensions.Validate(null));
            AssertHelper.ExpectedException<ArgumentNullException>(() => DataErrorInfoExtensions.Validate(null, "Name"));

            MockEntity entity = new MockEntity();
            entity.Error = "Test Error";
            Assert.AreEqual("Test Error", entity.Validate());
            entity.Error = null;
            Assert.AreEqual("", entity.Validate());

            entity.Errors.Add("Name", "Name Error");
            Assert.AreEqual("Name Error", entity.Validate("Name"));
            entity.Errors.Add("Address", null);
            Assert.AreEqual("", entity.Validate("Address"));
        }
        public void Get_deleted_entity()
        {
            MockEntity entity = new MockEntity()
            {
                id = int.MinValue
            };

            DbEntityAssociativeCollectionManager <MockEntity, MockEntity> manager = new DbEntityAssociativeCollectionManager <MockEntity, MockEntity>(1, entity, () => entity.RelationalEntities, null, null, (o, ae) => true, (e, ae) => true);

            entity.RelationalEntities.Add(new MockEntity()
            {
                IsDeleted = true
            });

            Assert.IsNull(manager.Get(new MockEntity()));
        }
        public void SerializeEntity_null_relational_entity()
        {
            MockEntity entity = new MockEntity()
            {
                RelationalEntity1 = new MockEntity(), StringProperty = "Original"
            };
            PropertyChangeTracker tracker = new PropertyChangeTracker(entity);

            tracker.Start();
            entity.StringProperty    = null;
            entity.RelationalEntity1 = null;

            string json = DbEntityJsonConvert.SerializeEntity(entity, tracker.DbEntityChanges());

            Assert.AreEqual("{\"$id\":\"" + entity.Guid + "\",\"Guid\":\"" + entity.Guid + "\",\"StringProperty\":null,\"RelationalEntity1\":null}", json);
        }
        public void MatchesAssociativeEntity_persisted_entity_false()
        {
            MockEntity existingEntity = new MockEntity()
            {
                id = int.MaxValue
            };

            existingEntity.MarkPersisted();
            MockEntity entityToMatch = new MockEntity()
            {
                id = int.MinValue
            };

            entityToMatch.MarkPersisted();
            Assert.IsFalse(U.MatchAssociativeEntities(existingEntity, existingEntity.id, entityToMatch, entityToMatch.id));
        }
        public void SerializeEntity_new_entity_flat_property_changes()
        {
            MockEntity            entity  = new MockEntity();
            PropertyChangeTracker tracker = new PropertyChangeTracker(entity);

            tracker.Start();
            entity.IntProperty = 1;

            string json = DbEntityJsonConvert.SerializeEntity(entity, tracker.DbEntityChanges());

            MockEntity deserialised = TypeExtensions.DeserializeObject <MockEntity>(json);

            Assert.AreEqual("{\"$id\":\"" + entity.Guid + "\",\"Guid\":\"" + entity.Guid + "\",\"IntProperty\":1}", json);
            Assert.AreEqual(entity.Guid, deserialised.Guid);
            Assert.AreEqual(entity.IntProperty, deserialised.IntProperty);
        }
        public void DbEntityUndeleted()
        {
            MockEntity entity = new MockEntity()
            {
                IsDeleted = true
            };
            bool eventRaised = false;

            entity.DbEntityUndeleted += (object sender, EventArgs e) =>
            {
                eventRaised = true;
            };
            entity.IsDeleted = false;

            Assert.IsTrue(eventRaised);
        }
Beispiel #13
0
        public void CastTestSkillUsingStats()
        {
            BaseEntity mob = new MockEntity(Engine);
            double     expectedMobHealth = mob.GetProperty(Entity.HP_KEY).Value - _testPlayer.GetProperty("STR").Value *10 - _testPlayer.GetProperty(BASE_VALUE).Value;

            _testPlayer.Cast(mob, _skillUsingStat.Key);
            foreach (MeNode node in _skillUsingStat.ByLevel[0].Formulas)
            {
                Console.WriteLine(node.ToString());
            }
            MockTimer timer = (MockTimer)Engine.GetTimer();

            timer.ForceTick();
            _testPlayer.Update();
            Assert.AreEqual(expectedMobHealth, mob.GetProperty(Entity.HP_KEY).Value);
        }
Beispiel #14
0
        public async Task EnsureUpdatesAreExecutedOneAfterTheOther()
        {
            // arrange
            var entityStore = new EntityStore();
            var entityId    = new EntityId(nameof(MockEntity), 1);

            List <string> updated = new();
            ulong         version = 0;

            entityStore.Watch().Subscribe(update =>
            {
                updated.Add(
                    entityStore.GetEntities <MockEntity>(update.UpdatedEntityIds).Single().Foo !);
                version = update.Version;
            });

            // act
            Task task1 = BeginUpdate(entityStore, "abc");
            Task task2 = BeginUpdate(entityStore, "def");
            await Task.WhenAll(task1, task2);

            // assert
            Assert.Collection(
                updated,
                item =>
            {
                Assert.Equal("abc", item);
            },
                item =>
            {
                Assert.Equal("def", item);
            });
            Assert.Equal(2ul, version);

            Task BeginUpdate(IEntityStore entityStore, string foo)
            {
                IEntityUpdateSession session = entityStore.BeginUpdate();

                return(Task.Run(async() =>
                {
                    await Task.Delay(50);
                    MockEntity entity = entityStore.GetOrCreate <MockEntity>(entityId);
                    entity.Foo = foo;
                    session.Dispose();
                }));
            }
        }
        public async Task Entity_BasicAsyncCrud([Values("sqlserver", "sqlite")] string databaseEngine)
        {
            using (var dataContext = this.BuildDataContext(databaseEngine))
            {
                Assert.AreEqual(TENANT_ID, dataContext.TenantId, "Wrong data context tenant id.");

                //insert

                dataContext.MockEntityRepository.Insert(new MockEntity
                {
                    //Id = 1,
                    Name = "Name"
                });

                await dataContext.SaveAsync();

                MockEntity mockEntity = await dataContext.MockEntityRepository.FindOneByAsync(x => x.Name == "Name");

                Assert.IsNotNull(mockEntity, "Entity is null.");
                Assert.AreEqual("Name", mockEntity.Name, "Wrong name.");

                //update

                mockEntity.Name = "NAME";

                dataContext.MockEntityRepository.Update(mockEntity);

                await dataContext.SaveAsync();

                mockEntity = (await dataContext.MockEntityRepository.FindManyByAsync(x => x.Name == "NAME")).FirstOrDefault();

                Assert.IsNotNull(mockEntity, "Entity is null.");
                Assert.AreEqual("NAME", mockEntity.Name, "Wrong name.");

                //delete

                dataContext.MockEntityRepository.DeleteBy(x => "NAME".Equals(x.Name));

                await dataContext.SaveAsync();

                mockEntity = await dataContext.MockEntityRepository.FindOneByAsync(x => x.Name == "NAME");

                Assert.IsNull(mockEntity, "Entity is not null.");

                await dataContext.RollbackAsync();
            }
        }
Beispiel #16
0
        public void UniformSelectionOperator_Select()
        {
            MockGeneticAlgorithm algorithm = new MockGeneticAlgorithm
            {
                FitnessEvaluator  = new MockFitnessEvaluator(),
                GeneticEntitySeed = new MockEntity(),
                PopulationSeed    = new SimplePopulation(),
                SelectionOperator = new UniformSelectionOperator
                {
                    SelectionBasedOnFitnessType = FitnessType.Scaled
                }
            };
            UniformSelectionOperator op = new UniformSelectionOperator();

            op.Initialize(algorithm);
            SimplePopulation population = new SimplePopulation();

            population.Initialize(algorithm);

            for (int i = 0; i < 4; i++)
            {
                MockEntity entity = new MockEntity();
                entity.Initialize(algorithm);
                population.Entities.Add(entity);
            }

            TestRandomUtil randomUtil = new TestRandomUtil();

            RandomNumberService.Instance = randomUtil;

            randomUtil.Value = 3;
            IList <GeneticEntity> selectedEntities = op.SelectEntities(1, population);

            Assert.Same(population.Entities[randomUtil.Value], selectedEntities[0]);

            randomUtil.Value = 2;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(population.Entities[randomUtil.Value], selectedEntities[0]);

            randomUtil.Value = 1;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(population.Entities[randomUtil.Value], selectedEntities[0]);

            randomUtil.Value = 0;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(population.Entities[randomUtil.Value], selectedEntities[0]);
        }
Beispiel #17
0
        public void FitnessScalingStrategy_Scale()
        {
            GeneticAlgorithm            algorithm = GetAlgorithm();
            FakeFitnessScalingStrategy2 strategy  = new FakeFitnessScalingStrategy2();

            strategy.Initialize(algorithm);
            MockPopulation population = new MockPopulation();

            population.Initialize(algorithm);
            MockEntity entity = new MockEntity();

            entity.Initialize(algorithm);
            population.Entities.Add(entity);
            strategy.Scale(population);

            Assert.True(strategy.OnScaleCalled, "ScaleCore was not called.");
        }
Beispiel #18
0
        public void InsertCallsRepositoryInsertWithinAUnitOfWorkAndReturnsId()
        {
            var entity = new MockEntity
            {
                Id             = this.fixture.MockEntities.Count + 1,
                StringProperty = "copied to service insert argument"
            };

            var result = this.service.Insert(entity);

            this.unitOfWorkMock.Verify(unitOfWork => unitOfWork.Start(), Times.Once());
            this.repositoryMock.Verify(repository => repository.Insert(
                                           It.Is <MockEntity>((e => e.Id == 0 && e.StringProperty == entity.StringProperty)
                                                              )), Times.Once());
            this.unitOfWorkMock.Verify(unitOfWork => unitOfWork.End(), Times.Once());
            Assert.Equal(entity.Id, result);
        }
Beispiel #19
0
        public void EntityConflict_ArgumentNullExceptions()
        {
            MockEntity           entity        = new MockEntity();
            IEnumerable <string> propertyNames = new[] { "Property1" };

            ExceptionHelper.ExpectArgumentNullException(
                () => new EntityConflict(entity, null, propertyNames, false),
                "storeEntity");

            ExceptionHelper.ExpectArgumentNullException(
                () => new EntityConflict(null, entity, propertyNames, false),
                "currentEntity");

            ExceptionHelper.ExpectArgumentNullException(
                () => new EntityConflict(entity, entity, null, false),
                "propertyNames");
        }
        public void Get_deleted_persisted_entity()
        {
            int        userId        = 1;
            MockEntity deletedEntity = new MockEntity()
            {
                id = int.MaxValue, IsDeleted = true
            };

            deletedEntity.MarkPersisted();
            MockEntity entity = new MockEntity();

            entity.RelationalEntities.Add(deletedEntity);

            ForeignEntityCollectionManager <MockEntity> manager = new ForeignEntityCollectionManager <MockEntity>(userId, entity, () => entity.RelationalEntities, null);

            Assert.IsNull(manager.Get(deletedEntity.PrimaryKeys));
        }
        public void Contains_persisted_entity_false()
        {
            int        userId          = 1;
            MockEntity persistedEntity = new MockEntity()
            {
                id = int.MaxValue
            };

            persistedEntity.MarkPersisted();
            MockEntity entity = new MockEntity();

            entity.RelationalEntities.Add(persistedEntity);

            ForeignEntityCollectionManager <MockEntity> manager = new ForeignEntityCollectionManager <MockEntity>(userId, entity, () => entity.RelationalEntities, null);

            Assert.IsFalse(manager.Contains(new MockEntity()));
        }
        public void Add_new_entity()
        {
            int        userId = 1;
            bool       isSetForeignKeysActionCalled = false;
            MockEntity entity = new MockEntity();

            Action <IDbEntity, MockEntity> setForeignKeys       = (o, e) => { isSetForeignKeysActionCalled = true; };
            ForeignEntityCollectionManager <MockEntity> manager = new ForeignEntityCollectionManager <MockEntity>(userId, entity, () => entity.RelationalEntities, setForeignKeys);

            MockEntity added = manager.Add();

            Assert.AreEqual(1, entity.RelationalEntities.Count);
            Assert.AreEqual(added, entity.RelationalEntities.First());
            Assert.IsTrue(isSetForeignKeysActionCalled);
            Assert.IsFalse(added.IsDeleted);
            Assert.AreEqual(userId, added.CreatedByID);
        }
        public void Equals_persisted_new_false()
        {
            MockEntity e1 = new MockEntity()
            {
                id = 1
            };
            MockEntity e2 = new MockEntity()
            {
                id = 1
            };

            e2.MarkPersisted();

            IEqualityComparer <MockEntity> comparer = new DbEntitiesComparer <MockEntity>();

            Assert.IsFalse(comparer.Equals(e2, e1));
        }
        public void Get_persisted_entity()
        {
            int        userId          = 1;
            MockEntity persistedEntity = new MockEntity()
            {
                id = int.MaxValue
            };

            persistedEntity.MarkPersisted();
            MockEntity entity = new MockEntity();

            entity.RelationalEntities.Add(persistedEntity);

            ForeignEntityCollectionManager <MockEntity> manager = new ForeignEntityCollectionManager <MockEntity>(userId, entity, () => entity.RelationalEntities, null);

            Assert.AreEqual(persistedEntity, manager.Get(persistedEntity.PrimaryKeys));
        }
Beispiel #25
0
        private static MockPopulation GetPopulation(GeneticAlgorithm algorithm)
        {
            MockPopulation population = new MockPopulation();

            population.Initialize(algorithm);
            MockEntity entity1 = new MockEntity();

            entity1.Initialize(algorithm);
            entity1.Identifier = "5";
            MockEntity entity2 = new MockEntity();

            entity2.Initialize(algorithm);
            entity2.Identifier = "2";
            population.Entities.Add(entity1);
            population.Entities.Add(entity2);
            return(population);
        }
        public void ValidateTest()
        {
            AssertHelper.ExpectedException <ArgumentNullException>(() => DataErrorInfoExtensions.Validate(null));
            AssertHelper.ExpectedException <ArgumentNullException>(() => DataErrorInfoExtensions.Validate(null, "Name"));

            var entity = new MockEntity();

            entity.Error = "Test Error";
            Assert.AreEqual("Test Error", entity.Validate());
            entity.Error = null;
            Assert.AreEqual("", entity.Validate());

            entity.Errors.Add("Name", "Name Error");
            Assert.AreEqual("Name Error", entity.Validate("Name"));
            entity.Errors.Add("Address", null);
            Assert.AreEqual("", entity.Validate("Address"));
        }
Beispiel #27
0
        public void MarkPersisted_flat_one_to_many_relation()
        {
            MockEntity entity = new MockEntity();

            entity.RelationalEntities.Add(new MockEntity());
            Assert.AreEqual(EntityState.New, entity.State);
            Assert.AreEqual(EntityState.New, entity.RelationalEntities.Single().State);

            Tuple <string, object>[] primaryKeys = new Tuple <string, object>[] { new Tuple <string, object>("Key", "Value") };
            Mock <IDataAccessLayer>  mockDal     = new Mock <IDataAccessLayer>();

            mockDal.Setup(m => m.GetEntity <MockEntity, IDbEntityProjection>(primaryKeys)).Returns(Task.FromResult(entity));
            DbEntityRepository.MarkPersisted(entity, entity.GetType());

            Assert.AreEqual(EntityState.Persisted, entity.State);
            Assert.AreEqual(EntityState.Persisted, entity.RelationalEntities.Single().State);
        }
Beispiel #28
0
        public void BoltzmannSelectionOperator_Select_Overflow()
        {
            double initialTemp = .0000001;
            MockGeneticAlgorithm           algorithm = GetMockAlgorithm(initialTemp);
            FakeBoltzmannSelectionOperator op        = new FakeBoltzmannSelectionOperator();

            op.Initialize(algorithm);
            MockPopulation population = new MockPopulation();

            population.Initialize(algorithm);
            MockEntity entity = new MockEntity();

            entity.Initialize(algorithm);
            entity.ScaledFitnessValue = 1;
            population.Entities.Add(entity);
            Assert.Throws <OverflowException>(() => op.SelectEntities(1, population));
        }
Beispiel #29
0
        private static SimplePopulation GetPopulation(GeneticAlgorithm algorithm, int populationSize)
        {
            SimplePopulation population = new SimplePopulation {
                MinimumPopulationSize = populationSize
            };

            population.Initialize(algorithm);

            for (int i = 0; i < population.MinimumPopulationSize; i++)
            {
                MockEntity entity = new MockEntity();
                entity.Initialize(algorithm);
                population.Entities.Add(entity);
            }

            return(population);
        }
        public void UndoAllEdit()
        {
            int        before = 1;
            int        after  = 2;
            MockEntity entity = new MockEntity()
            {
                IntProperty = before
            };

            entity.BeginEdit();

            entity.IntProperty = after;
            entity.UndoAllEdit();

            Assert.AreEqual(before, entity.IntProperty);
            Assert.IsTrue(entity.IsEditing);
        }
        public void DbEntityPropertyPath_entity_path_no_property_path_2()
        {
            MockEntity entity           = new MockEntity();
            MockEntity manyToManyEntity = new MockEntity();
            MockEntity oneToOneEntity   = new MockEntity();

            manyToManyEntity.RelationalEntities.Add(oneToOneEntity);
            MockEntity associativeEntity = new MockEntity()
            {
                RelationalEntity1 = manyToManyEntity
            };

            entity.RelationalEntities.Add(associativeEntity);
            string         entityPath = ".RelationalEntities[Guid=" + associativeEntity.Guid + "].RelationalEntity1.RelationalEntities[Guid=" + oneToOneEntity.Guid + "]";
            PropertyChange change     = new PropertyChange(entityPath, string.Empty, string.Empty, null, null);

            Assert.AreEqual(entityPath, change.DbEntityPropertyPath(entity));
        }
        public void ChangeTrackerTest()
        {
            var entity = new MockEntity();
            Assert.IsFalse(entity.HasChanges);
            var changesSnapshot1 = entity.GetChanges();
            Assert.IsFalse(changesSnapshot1.Any());

            AssertHelper.PropertyChangedEvent(entity, x => x.HasChanges, () => entity.Name = "Bill");
            Assert.IsTrue(entity.HasChanges);
            var changesSnapshot2 = entity.GetChanges();
            Assert.IsFalse(changesSnapshot1.Any());
            Assert.AreEqual("Name", changesSnapshot2.Single());

            AssertHelper.PropertyChangedEvent(entity, x => x.HasChanges, () => entity.ClearChanges());
            Assert.IsFalse(entity.HasChanges);
            var changesSnapshot3 = entity.GetChanges();
            Assert.IsFalse(changesSnapshot1.Any());
            Assert.AreEqual("Name", changesSnapshot2.Single());
            Assert.IsFalse(changesSnapshot3.Any());

            entity.Name = "Bill";
            Assert.IsFalse(entity.HasChanges);
        }
        public void ValidateTest()
        {
            MockEntity mockEntity = new MockEntity();
            DataErrorInfoSupport dataErrorInfoSupport = new DataErrorInfoSupport(mockEntity);

            Assert.AreEqual("The Firstname field is required.", dataErrorInfoSupport["Firstname"]);
            Assert.AreEqual("The Lastname field is required.", dataErrorInfoSupport["Lastname"]);
            Assert.AreEqual("", dataErrorInfoSupport["Email"]);
            Assert.AreEqual("The Firstname field is required." + Environment.NewLine + "The Lastname field is required.",
                dataErrorInfoSupport.Error);

            mockEntity.Firstname = "Harry";
            mockEntity.Lastname = "Potter";
            Assert.AreEqual("", dataErrorInfoSupport["Lastname"]);
            Assert.AreEqual("", dataErrorInfoSupport.Error);

            mockEntity.Email = "InvalidEmailAddress";
            Assert.AreEqual("", dataErrorInfoSupport["Lastname"]);
            Assert.AreEqual(@"The field Email must match the regular expression '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$'.",
                dataErrorInfoSupport["Email"]);
            Assert.AreEqual(@"The field Email must match the regular expression '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$'.",
                dataErrorInfoSupport.Error);
        }
Beispiel #34
0
 protected bool Equals(MockEntity other)
 {
     return Id == other.Id && string.Equals(Name, other.Name);
 }