public void Should_validate()
		{
			var testEntity = new TestEntity();
			repository.Expect(x => x.GetById(3)).Return(testEntity);
			binder.BindModel(controllerContext, context);
			validatingBinder.AssertWasCalled(x => x.UpdateFrom(testEntity, controllerContext.HttpContext.Request.Form, context.ModelState, "foo"));
		}
        public void Test_UpperCase_BulkInsert()
        {
            // Use Upper Case Schema Name:
            subject = new PostgreSQLCopyHelper<TestEntity>("SAMPLE", "UNIT_TEST")
                .MapSmallInt("col_smallint", x => x.SmallInt);

            // Try to work with the Bulk Inserter:
            var entity0 = new TestEntity()
            {
                SmallInt = Int16.MinValue
            };

            var entity1 = new TestEntity()
            {
                SmallInt = Int16.MaxValue
            };

            subject.SaveAll(connection, new[] { entity0, entity1 });

            var result = connection.GetAll("sample", "unit_test");

            // Check if we have the amount of rows:
            Assert.AreEqual(2, result.Count);

            Assert.IsNotNull(result[0][0]);
            Assert.IsNotNull(result[1][0]);

            Assert.AreEqual(Int16.MinValue, (Int16)result[0][0]);
            Assert.AreEqual(Int16.MaxValue, (Int16)result[1][0]);
        }
        public void EntitiesWithDifferentIdShouldNotBeEqual()
        {
            var entity1 = new TestEntity(Guid.NewGuid());
            var entity2 = new TestEntity(Guid.NewGuid());

            Assert.IsFalse(entity1.Equals(entity2));
        }
 public ComparisonAttributeTest()
 {
     _validEntity = new TestEntity { FirstProperty = 10, SecondProperty = 10 };
     _invalidEntity = new TestEntity {FirstProperty = 10, SecondProperty = 20};
     _attribute = new ComparisonAttribute("SecondProperty", ComparisonAttribute.ComparisonCondition.Equal);
     _attribute.ErrorMessage = _errorMessage;
 }
 private static void SetEntityId(TestEntity entity, long id)
 {
     var idProperty = entity.GetType()
                            .GetProperty("Id", BindingFlags.Instance | BindingFlags.Public);
     var setter = idProperty.SetMethod;
     setter.Invoke(entity, new object[] { id });
 }
        public void When_include_has_no_conflicts_happy_path()
        {
            var entity1 = new TestEntity("INV-0001");
            var entity2 = new TestEntity("INV-0002");

            EventData[] events =
            {
                CreateEvent("e1", Include.Insert(entity1)), 
                CreateEvent("e2", Include.Insert(entity2))
            };

            var result = Stream.Write(new Stream(partition), events);

            var stored = RetrieveTestEntity(entity1.RowKey);
            Assert.That(stored, Is.Not.Null);

            stored = RetrieveTestEntity(entity2.RowKey);
            Assert.That(stored, Is.Not.Null);

            Assert.That(result.Includes.Length, Is.EqualTo(2));
            Assert.That(result.Includes[0], Is.SameAs(entity1));
            Assert.That(result.Includes[0].ETag, Is.Not.Null.Or.Empty);
            Assert.That(result.Includes[1], Is.SameAs(entity2));
            Assert.That(result.Includes[1].ETag, Is.Not.Null.Or.Empty);            
        }
        public void GivenValueDoesNotMatchInvalidValue_AndValidationContext_WhenValidate_ThenSucceed()
        {
            TestEntity toValidate = new TestEntity { Value = "not invalid" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };

            Target.Validate(toValidate.Value, validationContext);
        }
Beispiel #8
0
        public void Entity_ConstructorAssignsValues()
        {
            var guid = Guid.NewGuid();
            var entity = new TestEntity(guid);

            entity.Id.Should().Be(guid);
        }
        public void Castle()
        {
            SystemConfig.ConfigFilesAssemblyName = "CodeSharp.Framework.Castles.Test";
            SystemConfig.Configure("ConfigFiles")
                .Castle()
                .BusinessDependency(Assembly.GetExecutingAssembly());

            Assert.AreEqual("abc", SystemConfig.Settings["key1"]);

            Assert.DoesNotThrow(() => DependencyResolver.Resolve<ILoggerFactory>().Create(this.GetType()).Info("hi"));

            Assert.DoesNotThrow(() => DependencyResolver.Resolve<ITestService>());

            Assert.DoesNotThrow(() => DependencyResolver.Resolve<NHibernate.ISessionFactory>());

            //NH Tests
            var e = new TestEntity("abc");
            var s = DependencyResolver.Resolve<ITestService>();
            s.Create(e);
            DependencyResolver.Resolve<Castle.Facilities.NHibernateIntegration.ISessionManager>().OpenSession().Evict(e);
            var e2= s.Get(e.ID);
            //private setter?
            Assert.AreEqual(e.Name, e2.Name);
            Assert.AreEqual("abc", e2.Name);

            Assert.DoesNotThrow(() => SystemConfig.Cleanup());
        }
 public virtual void Context()
 {
     Entity = new TestEntity();
     Session = Mock<ISession>();
     var unitOfWork = CreateUnitOfWorkWithStartedTransaction();
     Repository = new NhibernateRepository<TestEntity>(unitOfWork);
 }
Beispiel #11
0
 public void GetHashCode_returns_hash_code_of_Id()
 {
     var entity = new TestEntity();
     long id = 2;
     SetEntityId(entity, id);
     Assert.AreEqual(id.GetHashCode(), entity.GetHashCode());
 }
Beispiel #12
0
 public void GetHashCode_uses_hash_code_that_was_generated_pre_id_set()
 {
     var entity = new TestEntity();
     var hash = entity.GetHashCode();
     SetEntityId(entity, 1);
     Assert.AreEqual(hash, entity.GetHashCode());
 }
Beispiel #13
0
        public void EqualsWithNewObjectsUsesReferenceEquals()
        {
            // Arrange
            var ent1 = new TestEntity();
            var ent2 = new TestEntity();

            // Act
            bool different = ent1.Equals( ent2 );
            bool different2 = ent2.Equals( ent1 );
            bool different3 = ent1 == ent2;
            bool equal3 = ent1 != ent2;

            var ent3 = ent1;
            bool equal = ent1.Equals( ent3 );
            bool equal2 = ent3.Equals( ent1 );
            bool equal4 = ent1 == ent3;
            bool different4 = ent1 != ent3;

            // Assert
            Assert.IsFalse( different );
            Assert.IsFalse( different2 );
            Assert.IsFalse( different3 );
            Assert.IsFalse( different4 );
            Assert.IsTrue( equal );
            Assert.IsTrue( equal2 );
            Assert.IsTrue( equal3 );
            Assert.IsTrue( equal4 );
        }
Beispiel #14
0
        public void IntersectTest()
        {
            var a = new TestEntity(Vector2.Zero, new Vector2(10, 10));
            var b = new TestEntity(Vector2.Zero, new Vector2(10, 10));

            Assert.IsTrue(a.Intersects(b));

            a.Position = new Vector2(9, 9);
            Assert.IsTrue(a.Intersects(b));

            a.Position = new Vector2(-9, -9);
            Assert.IsTrue(a.Intersects(b));

            a.Position = new Vector2(-9, 0);
            Assert.IsTrue(a.Intersects(b));

            a.Position = new Vector2(0, -9);
            Assert.IsTrue(a.Intersects(b));

            a.Position = new Vector2(-11, -11);
            Assert.IsFalse(a.Intersects(b));

            a.Position = new Vector2(-11, 0);
            Assert.IsFalse(a.Intersects(b));

            a.Position = new Vector2(0, -11);
            Assert.IsFalse(a.Intersects(b));

            a.Position = new Vector2(11, 11);
            Assert.IsFalse(a.Intersects(b));
        }
Beispiel #15
0
 public void EntityID_Can_Init()
 {
     var entity = new TestEntity();
     Assert.IsTrue(entity.Id == Guid.Empty);
     var id = Guid.NewGuid();
     entity.Id = id;
     Assert.IsTrue(entity.Id == id);
 }
        public void EntitiesWithSameIdShouldBeEqual()
        {
            var guid = Guid.NewGuid();
            var entity1 = new TestEntity(guid);
            var entity2 = new TestEntity(guid);

            Assert.IsTrue(entity1.Equals(entity2));
        }
Beispiel #17
0
 public void Equals_should_return_true_if_both_entities_have_same_Id()
 {
     var entity = new TestEntity();
     var entity2 = new TestEntity();
     SetEntityId(entity, 1);
     SetEntityId(entity2, 1);
     Assert.True(entity.Equals(entity2));
 }
        public void GivenNumbersEqual_AndAllowEquality_AndValidationContext_WhenValidate_ThenSucceed()
        {
            TestEntity toValidate = new TestEntity { Value = "10" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };
            var target = new NumericGreaterThanAttribute("Value") { AllowEquality = true };

            target.Validate("10", validationContext);
        }
Beispiel #19
0
 public void Equals_should_return_false_if_entities_have_different_Id()
 {
     var entity = new TestEntity();
     var entity2 = new TestEntity();
     SetEntityId(entity, 1);
     SetEntityId(entity2, 2);
     Assert.False(entity.Equals(entity2));
 }
        public void GivenValueContainsTerm_AndValidationContext_WhenValidate_ThenThrowException()
        {
            TestEntity toValidate = new TestEntity { Value = "mcblah" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };
            var target = new DoesNotContainAttribute("blah");

            target.ExpectException<ValidationException>(() => target.Validate(toValidate.Value, validationContext));
        }
        public void GivenValueDoesntContainTerm_AndValidationContext_WhenValidate_ThenSucceed()
        {
            TestEntity toValidate = new TestEntity { Value = "test" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };
            var target = new DoesNotContainAttribute("blah");

            target.Validate(toValidate.Value, validationContext);
        }
        public void GetValue_ShouldReturnFieldValue()
        {
            var expected = "expected";
            var entity = new TestEntity() { PublicField = expected };

            var setter = new FieldPropertySetter(typeof (TestEntity).GetField("PublicField"));
            Assert.Equal(expected, setter.GetValue(entity));
        }
		public void Should_fetch_from_primary_key()
		{
			var testEntity = new TestEntity();
			repository.Expect(x => x.GetById(3)).Return(testEntity);
			
			var result = binder.BindModel(controllerContext, context);
			result.ShouldBeTheSameAs(testEntity);
		}
 public void EntityRemovedEventShouldBeTriggeredWhenEntityAddedTest()
 {
     var serviceEntity = new TestEntity { Name = "name" };
     Context.Service.AddEntity(serviceEntity);
     Assert.IsTrue(Context.WaitFor(() => Context.Entities.Count() == 1, Context.WaitingPeriod));
     Context.Service.RemoveEntity(serviceEntity);
     Assert.IsTrue(Context.WaitFor(() => !Context.Entities.Any(), Context.WaitingPeriod));
 }
Beispiel #25
0
 public void AddTest()
 {
     foreach (var spatial in GetSpatials())
     {
         var entity = new TestEntity();
         spatial.Add(entity);
         Assert.IsTrue(spatial.CollectionContains(entity), "Current spatial: " + spatial);
     }
 }
 public void WithTestEntity()
 {
     Entity = new TestEntity
                 {
                     Description = "This is it",
                     Name = "THENAME",
                     Enabled = true
                 };
 }
        public void Can_changetracker_manipulatecollection()
        {
            var tracker = new ObservableChangeTracker();
            var entity = new TestEntity();

            tracker.Add(entity);
            tracker.Remove(entity);
            tracker.Add(entity);
        }
        public void GivenInvalidValue_AndValidationContext_WhenValidate_ThenThrowException()
        {
            TestEntity toValidate = new TestEntity { Value = "blah" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };
            var target = new NumericGreaterThanAttribute("Value");

            ValidationException actual = target.ExpectException<ValidationException>(() => target.Validate("10", validationContext));
            Assert.AreEqual("Value is not a numeric value.", actual.Message);
        }
        public void GivenPropertyIsEqual_AndDontAllowEquality_AndValidationContext_WhenValidate_ThenThrowException()
        {
            TestEntity toValidate = new TestEntity { Value = "10" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };
            var target = new NumericGreaterThanAttribute("Value") { AllowEquality = false };

            ValidationException actual = target.ExpectException<ValidationException>(() => target.Validate("10", validationContext));
            Assert.AreEqual("AllowEquality has been set to false so values cannot be equal.", actual.Message);
        }
        public void GivenInvalidProperty_AndValidationContext_WhenValidate_ThenThrowException()
        {
            TestEntity toValidate = new TestEntity { Value = "10" };
            ValidationContext validationContext = new ValidationContext(toValidate) { DisplayName = "Test Entity Value", MemberName = "Value" };
            var target = new NumericLessThanAttribute("blah");

            ValidationException actual = target.ExpectException<ValidationException>(() => target.Validate("10", validationContext));
            Assert.AreEqual("Could not find a property named blah.", actual.Message);
        }
        public void ListEntityBase_Remove()
        {
            TestEntity entity = new TestEntity();

            entity.InnerList.AddRange(Enumerable.Range(3, 3).Cast <object>());
            entity.InnerList.Add(3);

            entity.Remove(3);

            Assert.Equal(3, entity.InnerList.Count);
            Assert.Equal(4, entity.InnerList[0]);
            Assert.Equal(5, entity.InnerList[1]);
            Assert.Equal(3, entity.InnerList[2]);

            entity.Remove(0);
            entity.Remove("test");
            Assert.Equal(3, entity.InnerList.Count);

            entity.Remove(3);
            entity.Remove(4);
            entity.Remove(5);
            Assert.Empty(entity.InnerList);
        }
Beispiel #32
0
        public void MatchAction_with_keyFunc()
        {
            Func <TestItem, string, bool> matchKey = (model, key) => model.Key == Guid.Parse(key);

            var map = new MapTask <TestEntity>()
                      .MatchAction((x, y) =>
            {
                x.List = y.ToList();
            }, "items", matchKey);

            var modelMap = map.ModelMaps.First();
            var entity   = new TestEntity();
            var items    = new List <TestItem> {
                new TestItem()
            };

            Assert.That(map.ModelMaps.Count, Is.EqualTo(1));
            Assert.That(modelMap.Alias, Is.EqualTo("items"));
            Assert.That(modelMap.IsMatch, Is.Not.EqualTo(matchKey));
            Assert.That(modelMap.IsMany);
            modelMap.SetModel(entity, items);
            Assert.That(entity.List, Is.EqualTo(items));
        }
Beispiel #33
0
        public void CanPersistLinqWhereIEnumerable()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var entity = new TestEntity
                    {
                        Property = new[] { "one", "two" }.Where(s => s.Length > 1)
                    };

                    session.Store(entity);
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var loadedEntity = session.Load <TestEntity>("TestEntities/1-A");
                    Assert.Contains("one", loadedEntity.Property);
                    Assert.Contains("two", loadedEntity.Property);
                }
            }
        }
Beispiel #34
0
        public void EFCoreDataContextTest()
        {
            using (var connection = new SqliteConnection("DataSource=:memory:")) {
                connection.Open();

                var builder = new DbContextOptionsBuilder();
                var options = builder.UseSqlite(connection).Options;

                var testEntity = new TestEntity {
                    Key = 10, Value = "Sample Value"
                };

                using (var dc = new EFCoreTestDataContext(options)) {
                    dc.Database.EnsureCreated();
                    dc.Set <TestEntity> ().Add(testEntity);
                    dc.SaveChanges();
                }

                using (var dc = new EFCoreTestDataContext(options)) {
                    Assert.Equal(1, dc.Set <TestEntity> ().Count());
                }
            }
        }
Beispiel #35
0
    public void ReusabilitySucceeds()
    {
        const string dbName = "MyDatabase";
        const string value  = "prop";

        using (var context = InMemoryContextBuilder.Build <TestDataContext>(dbName))
        {
            var entity = new TestEntity
            {
                Property = value
            };
            context.Add(entity);
            context.SaveChanges();
        }

        TestEntity res;

        using (var context = InMemoryContextBuilder.Build <TestDataContext>(dbName))
        {
            res = context.TestEntities.First(e => e.Property == value);
        }
        Assert.NotNull(res);
    }
        public when_saving_entity()
        {
            this.eventStore = new Mock <IEventStore>();
            this.publisher  = new Mock <IEventStoreBusPublisher>();
            var sut = new AzureEventSourcedRepository <TestEntity>(eventStore.Object, publisher.Object, new JsonTextSerializer(), new StandardMetadataProvider(), null);

            this.id = Guid.NewGuid();
            var entity = new TestEntity
            {
                Id     = id,
                Events =
                {
                    new TestEvent {
                        SourceId = id, Version = 1, Foo = "Bar"
                    },
                    new TestEvent {
                        SourceId = id, Version = 2, Foo = "Baz"
                    }
                }
            };

            sut.Save(entity, "correlation");
        }
    void assertHasComponentA(TestEntity e, IComponent componentA = null)
    {
        if (componentA == null)
        {
            componentA = Component.A;
        }

        e.GetComponentA().should_be_same(componentA);

        var components = e.GetComponents();

        components.Length.should_be(1);
        components.should_contain(componentA);

        var indices = e.GetComponentIndices();

        indices.Length.should_be(1);
        indices.should_contain(CID.ComponentA);

        e.HasComponentA().should_be_true();
        e.HasComponents(_indicesA).should_be_true();
        e.HasAnyComponent(_indicesA).should_be_true();
    }
Beispiel #38
0
    public async Task WithFileAndNoDb()
    {
        new SqlInstance <TestDbContext>(
            constructInstance: builder => new TestDbContext(builder.Options),
            instanceSuffix: "EfWithFileAndNoDb");
        LocalDbApi.StopAndDelete("TestDbContext_EfWithFileAndNoDb");

        var instance = new SqlInstance <TestDbContext>(
            constructInstance: builder => new TestDbContext(builder.Options),
            instanceSuffix: "EfWithFileAndNoDb");

        var entity = new TestEntity
        {
            Property = "prop"
        };

        using (var database = await instance.Build(new List <object> {
            entity
        }))
        {
            Assert.NotNull(database.Context.TestEntities.FindAsync(entity.Id));
        }
    }
Beispiel #39
0
        public void When_including_unconditional_replace()
        {
            var entity = new TestEntity(EntityRowKey)
            {
                Data = "123"
            };

            InsertTestEntity(entity);

            entity = new TestEntity(EntityRowKey)
            {
                Data = "456",
                ETag = "*"
            };

            Assert.DoesNotThrow(() =>
                                Stream.Write(stream, CreateEvent(Include.Replace(entity))),
                                "Will be always executed and will fully replace contents");

            var stored = RetrieveTestEntity(EntityRowKey);

            Assert.That(stored.Data, Is.EqualTo("456"));
        }
        public void ShouldDetectMostRecentChangesForAdded()
        {
            var detector = new TestEntityChangeDetector();
            EntityChangeTracker <TestEntity> tracker = new EntityChangeTracker <TestEntity>(detector);

            TestEntity entity = new TestEntity()
            {
                IntValue = 123
            };

            tracker.Add(entity);

            entity.IntValue = 234;

            var after = tracker.DetectChanges(entity);

            Assert.AreEqual(EntityState.Added, after.State, "The entity should have remained Added.");
            Assert.IsTrue(after.HasChange(x => x.IntValue), "The IntValue should have changed.");
            var change = after.GetChange(x => x.IntValue);

            Assert.IsNotNull(change, "The change was null after detecting its prescence.");
            Assert.AreEqual(234, change.UpdatedValue, "The latest value was not returned.");
        }
Beispiel #41
0
        public void SortBy_Should_Sort_Collection_Successfully()
        {
            //Arrange
            var numberSortedList = new int[] { 1, 2, 3, 4, 5, 6 };
            var testEntity2      = new TestEntity {
                Id = 2, Name = "test2"
            };
            var testEntity3 = new TestEntity {
                Id = 3, Name = "test3"
            };
            var testEntity1 = new TestEntity {
                Id = 1, Name = "test1"
            };
            var entityCollection = new TestEntity[] { testEntity2, testEntity3, testEntity1 };

            //Act
            var sortedEntityCollection = entityCollection.SortBy(numberSortedList, x => x.Id);

            //Assert
            Assert.AreEqual(sortedEntityCollection.First().Id, 1);
            Assert.AreEqual(sortedEntityCollection.ElementAt(1).Id, 2);
            Assert.AreEqual(sortedEntityCollection.Last().Id, 3);
        }
        public void MainTest()
        {
            Require.ProviderIs(StorageProvider.SqlServer, "Uses multiple databases and native SQL");

            long id;

            var domain1 = BuildDomain(MultidatabaseTest.Database1Name);

            using (var session = domain1.OpenSession())
                using (var tx = session.OpenTransaction()) {
                    id = new TestEntity().Id;
                    tx.Complete();
                }

            var domain2 = BuildDomain(MultidatabaseTest.Database2Name);

            using (var session = domain2.OpenSession())
                using (var tx = session.OpenTransaction()) {
                    session.Services.Demand <DirectSqlAccessor>().RegisterInitializationSql(GetUseDatabaseScript(MultidatabaseTest.Database1Name));
                    var entity = session.Query.Single <TestEntity>(id);
                    Assert.That(entity.Id, Is.EqualTo(id));
                }
        }
        public void UpdateCommenters_OnValidCall_ExecuteNonQuery()
        {
            // Arrange
            SetupShimsForSqlClient();
            ShimSqlCommand.AllInstances.ExecuteScalar = _ => UserRole.Assignee;

            // Act
            TestEntity.UpdateCommenters(new Thread
            {
                Users = new[]
                {
                    new User {
                        Id = DummyInt, Role = UserRole.Commenter
                    },
                    new User {
                        Id = DummyInt, Role = UserRole.Assignee
                    }
                }
            });

            // Assert
            _executeNonQueryInvoked.ShouldBeTrue();
        }
        public void ListEntityBaseOfT_CompareTo_LongerLength()
        {
            TestEntity <string> entity1 = new TestEntity <string>
            {
                "a",
                null,
                "b",
                null,
                "c"
            };

            TestEntity <string> entity2 = new TestEntity <string>
            {
                "a",
                null,
                "b",
                null
            };

            int result = entity1.CompareTo(entity2);

            Assert.Equal(1, result);
        }
Beispiel #45
0
        public void EscapeNetworkTest()
        {
            var tt = new Timetable(TimetableType.Network);
            var e  = new TestEntity("test", tt);

            e.SetAttribute("rvctest", "0:foo:bar;;baz::;;;;;1:test;2:;");

            var rvc = new RouteValueCollection <string>(e, tt, "rvctest", "default;:test", s => s, s => s, false);

            rvc.TestForErrors(); // Should do nothing

            Assert.AreEqual("foo:bar;baz::;;", rvc.GetValue(0));
            Assert.AreEqual("test", rvc.GetValue(1));
            Assert.AreEqual("default;:test", rvc.GetValue(2));

            Assert.AreEqual("default;:test", rvc.GetValue(3)); // test default value

            rvc.SetValue(0, "");
            rvc.SetValue(1, "test;:test");
            rvc.Write();

            Assert.AreEqual("0:;1:test;;:test;2:default;;:test", e.GetAttribute <string>("rvctest"));
        }
        public void CanDocumentCreationWithExplicitMetadata_CreationDateOnly()
        {
            var          createdDate   = new DateTime(2000, 1, 1);
            const string createdByUser = null;

            var entity = new TestEntity
            {
                CreatedDate   = createdDate,
                CreatedByUser = createdByUser,
            };

            object[] values = CreateValues(entity);
            EntityMetadataUtils.DocumentCreation(entity, values, _properties);

            Assert.AreEqual(createdDate, entity.CreatedDate);
            Assert.AreEqual(GetUserName(), entity.CreatedByUser);

            // the LastChanged information will be set to the Creation information if missing
            Assert.AreEqual(createdDate, entity.LastChangedDate);
            Assert.AreEqual(GetUserName(), entity.LastChangedByUser);

            AssertEqualState(entity, values);
        }
        public void CanDocumentCreationWithExplicitMetadata_LastChangedOnly()
        {
            var          lastChangedDate   = new DateTime(2010, 1, 1);
            const string lastChangedByUser = "******";

            var entity = new TestEntity
            {
                LastChangedDate   = lastChangedDate,
                LastChangedByUser = lastChangedByUser,
            };

            object[] values = CreateValues(entity);
            EntityMetadataUtils.DocumentCreation(entity, values, _properties);

            Assert.AreEqual(lastChangedDate, entity.LastChangedDate);
            Assert.AreEqual(lastChangedByUser, entity.LastChangedByUser);

            // the Created information will be set to the LastChanged information if missing
            Assert.AreEqual(lastChangedDate, entity.CreatedDate);
            Assert.AreEqual(lastChangedByUser, entity.CreatedByUser);

            AssertEqualState(entity, values);
        }
        public void Test_NullableTimeSpan()
        {
            var entity0 = new TestEntity()
            {
                TimeSpan = TimeSpan.FromDays(1)
            };

            var entity1 = new TestEntity()
            {
                TimeSpan = TimeSpan.FromDays(2)
            };


            subject.SaveAll(connection, new[] { entity0, entity1 });

            var result = GetAll();

            // Check if we have the amount of rows:
            Assert.AreEqual(2, result.Count);

            Assert.AreEqual(entity0.TimeSpan, (TimeSpan)result[0][13]);
            Assert.AreEqual(entity1.TimeSpan, (TimeSpan)result[1][13]);
        }
Beispiel #49
0
 public void UpdateMultipleSameEntity()
 {
     using (var context = InMemoryContextBuilder.Build <TestDataContext>())
     {
         var entity1 = new TestEntity
         {
             Id1      = 1,
             Id2      = 1,
             Property = "prop"
         };
         var entity2 = new TestEntity
         {
             Id1      = 1,
             Id2      = 2,
             Property = "prop"
         };
         context.AddRange(entity1, entity2);
         context.SaveChanges();
         entity1.Property = "Something new";
         entity2.Property = "Something new";
         context.SaveChanges();
     }
 }
        public void SelectByIdTest()
        {
            var repository = RepositoryManager.GetRepository <ITestRepository>();

            Assert.IsNotNull(repository);

            var entity = new TestEntity()
            {
                Name = TestHelper.RandomizeString(), UpdateDate = DateTime.Now
            };

            Assert.AreEqual(0, entity.Id);
            var result = repository.Save(entity);

            Assert.IsTrue(result);
            Assert.IsTrue(0 < entity.Id);

            var dbEntity = repository.FindById(entity.Id);

            Assert.AreEqual(entity.Id, dbEntity.Id);
            Assert.AreEqual(entity.Name, dbEntity.Name);
            Assert.AreEqual(0, (entity.UpdateDate - dbEntity.UpdateDate).Minutes);
        }
        public void ListEntityBase_CompareTo_LongerLength()
        {
            TestEntity entity1 = new TestEntity
            {
                1,
                null,
                2,
                null,
                3
            };

            TestEntity entity2 = new TestEntity
            {
                1,
                null,
                2,
                null
            };

            int result = entity1.CompareTo(entity2);

            Assert.Equal(1, result);
        }
        public void SerializeToString_WhenVersionedMessage_ExpectCorrectString()
        {
            // Arrange
            var serializerSettings = new SerializerSettings {
                SerializerType = SerializerType.Json
            };
            var messageSerializer = new MessageSerializer(serializerSettings);

            var testEntity = new TestEntity {
                Data = "val"
            }.SerializeToVersionedMessage(SerializerType.Json);

            // Act
            var stopwatch         = Stopwatch.StartNew();
            var serializeToString = messageSerializer.SerializeToString(testEntity);

            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(serializeToString, Is.EqualTo("{\"v\":{\"T\":\"TestEntity\",\"Ma\":1,\"Mi\":0,\"P\":0,\"VT\":0,\"VTV\":0},\"d\":\"{\\\"Data\\\":\\\"val\\\"}\"}"));
        }
        public async Task DeleteByIdTest_Should_Delete_Entity()
        {
            // Arrange
            var testEntity1 = new TestEntity
            {
                Id = Guid.NewGuid()
            };

            var testEntity2 = new TestEntity
            {
                Id = Guid.NewGuid()
            };

            SeedDatabase(new List <TestEntity> {
                testEntity1, testEntity2
            });

            using (var testDbContextBeforeDelete = new TestDbContext(ContextOptions))
            {
                Assert.AreEqual(2, testDbContextBeforeDelete.TestEntities.Count());
            }

            // Act
            var result = await _testBaseController.DeleteByIdTest(testEntity1.Id);

            // Assert
            var noContentResult = result as NoContentResult;

            Assert.IsNotNull(noContentResult);

            using var testDbContext = new TestDbContext(ContextOptions);
            Assert.AreEqual(1, testDbContext.TestEntities.Count());

            var remainingEntity = testDbContext.TestEntities.First();

            Assert.AreEqual(testEntity2.Id, remainingEntity.Id);
        }
        public void CanDoCrud()
        {
            using (var session = factory.OpenSession()) {
                var entity = new TestEntity {
                    Name       = "Test 1",
                    Tags       = new string[] { "hello", "world" },
                    JsonField  = "{ \"val\": 1 }",
                    JsonbField = "{ \"val\": 1 }",
                    UpdateTime = DateTime.Now,
                    Int16Arr   = new short[] { 1, 2, 3 },
                    Int32Arr   = new int[] { 1, 2, 3 },
                    Int64Arr   = new long[] { 1L, 2L, 3L },
                    FloatArr   = new float[] { 1.1F, 2.2F, 3.3F },
                    DoubleArr  = new double[] { 1.1, 2.2, 3.3 },
                    BooleanArr = new bool[] { true, false }
                };

                session.Save(entity);
                session.Flush();
                session.Clear();

                Assert.True(entity.Id == 0);

                Console.WriteLine($"entity id: {entity.Id}");

                var query    = session.Query <TestEntity>();
                var entities = query.ToList();
                Assert.NotNull(entities);

                foreach (var e in entities)
                {
                    session.Delete(e);
                }

                session.Flush();
            }
        }
Beispiel #55
0
        public async Task Should_insert_specified_properties_only()
        {
            var testEntity = new TestEntity
            {
                Id    = new Guid("40B5CA93-5C02-48AD-B8A1-12BC13313866"),
                Name  = "Name",
                Count = 42
            };
            var testEntities = new[] { testEntity };

            var idProperty               = typeof(TestEntity).GetProperty(nameof(TestEntity.Id)) ?? throw new Exception($"Property {nameof(TestEntity.Id)} not found.");
            var countProperty            = typeof(TestEntity).GetProperty(nameof(TestEntity.Count)) ?? throw new Exception($"Property {nameof(TestEntity.Count)} not found.");
            var propertyWithBackingField = typeof(TestEntity).GetProperty(nameof(TestEntity.PropertyWithBackingField)) ?? throw new Exception($"Property {nameof(TestEntity.PropertyWithBackingField)} not found.");
            var privateField             = typeof(TestEntity).GetField("_privateField", BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new Exception($"Field _privateField not found.");

            await ActDbContext.BulkInsertAsync(testEntities, new SqlServerBulkInsertOptions
            {
                MembersToInsert = new EntityMembersProvider(new MemberInfo[]
                {
                    idProperty,
                    countProperty,
                    propertyWithBackingField,
                    privateField
                })
            });

            var loadedEntities = await AssertDbContext.TestEntities.ToListAsync();

            loadedEntities.Should().HaveCount(1);
            var loadedEntity = loadedEntities[0];

            loadedEntity.Should().BeEquivalentTo(new TestEntity
            {
                Id    = new Guid("40B5CA93-5C02-48AD-B8A1-12BC13313866"),
                Count = 42
            });
        }
Beispiel #56
0
        public async Task GeneticEntityCollectionExtensions_GetEntitiesSortedByFitness_SortRawMinimize()
        {
            TestEntity testEntity1 = new TestEntity {
                TestFitnessValue = 1
            };
            TestEntity testEntity2 = new TestEntity {
                TestFitnessValue = 3
            };
            TestEntity testEntity3 = new TestEntity {
                TestFitnessValue = 2
            };

            List <GeneticEntity> entities = new List <GeneticEntity>
            {
                testEntity1,
                testEntity2,
                testEntity3,
            };

            MockGeneticAlgorithm algorithm = new MockGeneticAlgorithm
            {
                FitnessEvaluator = new TestFitnessEvalutor()
            };

            foreach (GeneticEntity entity in entities)
            {
                entity.Initialize(algorithm);
                await entity.EvaluateFitnessAsync();
            }

            List <GeneticEntity> results = GeneticEntityCollectionExtensions.GetEntitiesSortedByFitness(entities, FitnessType.Raw, FitnessEvaluationMode.Minimize).ToList();

            Assert.Equal(3, results.Count);
            Assert.Same(testEntity2, results[0]);
            Assert.Same(testEntity3, results[1]);
            Assert.Same(testEntity1, results[2]);
        }
Beispiel #57
0
        public async Task WithPrematureAbortCallInNestedScope_ShouldPerformOperationsAndThenRollBack(Overload overload)
        {
            await this.Execute(overload, this.Provider, async (scope, ct) =>
            {
                await this.Execute(overload, this.Provider, (scope, ct) =>
                {
                    // Doing this early is just fine
                    // It will only take effect once the current execution scope ends
                    scope.Abort();

                    var entityToInsert = new TestEntity()
                    {
                        Id = 1
                    };
                    scope.DbContext.Add(entityToInsert);
                    scope.DbContext.SaveChanges();

                    var uncommittedEntityCount = ((TestDbContext)scope.DbContext).TestEntities.Count();
                    Assert.Equal(1, uncommittedEntityCount);

                    return(Task.FromResult(true));
                });

                // We should have rolled back when the inner scope was disposed
                {
                    using var dbContext = this.TestDbContextFactory.CreateDbContext();

                    dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);                     // By reading even uncommitted changes, we can confirm that the change was rolled back

                    var entityCount = dbContext.TestEntities.Count();

                    Assert.Equal(0, entityCount);
                }

                return(Task.FromResult(true));
            });
        }
        public async Task Should_create_draft_version()
        {
            TestEntity content = null;

            try
            {
                // STEP 1: Create a new item.
                content = await _.Contents.CreateAsync(new TestEntityData { Number = 1 }, true);


                // STEP 2: Create draft.
                content = await _.Contents.CreateDraftAsync(content.Id);


                // STEP 3: Update the item and ensure that the data has not changed.
                await _.Contents.PatchAsync(content.Id, new TestEntityData { Number = 2 });

                var updated = await _.Contents.GetAsync(content.Id);

                Assert.Equal(1, updated.Data.Number);
                Assert.Null(updated.NewStatus);


                // STEP 4: Get the unpublished version
                var unpublished = await _.Contents.GetAsync(content.Id, QueryContext.Default.Unpublished());

                Assert.Equal(2, unpublished.Data.Number);
                Assert.Equal("Draft", unpublished.NewStatus);
            }
            finally
            {
                if (content != null)
                {
                    await _.Contents.DeleteAsync(content.Id);
                }
            }
        }
        public void Test_FilterGroup_Or()
        {
            using (LogGroup logGroup = LogGroup.Start("Testing a filter group query with the OR operator.", NLog.LogLevel.Debug))
            {
                TestEntity e1 = new TestEntity();
                e1.Name = "Test E1";

                FilterGroup filterGroup = new FilterGroup();
                filterGroup.Operator = FilterGroupOperator.Or;

                PropertyFilter filter1 = (PropertyFilter)DataAccess.Data.CreateFilter(typeof(PropertyFilter));
                filter1.PropertyName  = "Name";
                filter1.PropertyValue = e1.Name;
                filter1.AddType(typeof(TestEntity));

                PropertyFilter filter2 = (PropertyFilter)DataAccess.Data.CreateFilter(typeof(PropertyFilter));
                filter2.PropertyName  = "Name";
                filter2.PropertyValue = "Another value";
                filter2.AddType(typeof(TestEntity));

                filterGroup.Filters = new BaseFilter[] { filter1, filter2 };

                DataAccess.Data.Stores[typeof(TestEntity)].Saver.Save(e1);

                IEntity[] found = (IEntity[])DataAccess.Data.Indexer.GetEntities(filterGroup);

                Assert.IsNotNull(found, "Null value returned.");

                if (found != null)
                {
                    Assert.IsTrue(found.Length > 0, "No results found.");
                }


                DataAccess.Data.Deleter.Delete(e1);
            }
        }
        public async Task UpdateFieldsAsync_WithProperties_ShouldUpdateSpecifiedEntityProperty()
        {
            // Arrange
            var testEntity = new TestEntity
            {
                Id     = Guid.NewGuid(),
                Name   = "Kylo Ren",
                Number = 1
            };

            DbContextOptions <TestDbContext> options = new DbContextOptionsBuilder <TestDbContext>()
                                                       .UseInMemoryDatabase(databaseName: "InMemory_TestDb")
                                                       .Options;

            using (var dbContext = new TestDbContext(options))
            {
                dbContext.Add(testEntity);
                await dbContext.SaveChangesAsync();
            }

            testEntity.Name = "Rey Skywalker";
            TestEntity updatedTeamMember = null;

            using (var dbContext = new TestDbContext(options))
            {
                var repository = new ReadWriteRepository <TestEntity, Guid>(() => dbContext);

                // Act
                await repository.UpdateFieldsAsync(testEntity, te => te.Name);

                // Assert
                updatedTeamMember = await repository.GetByIdAsync(testEntity.Id);
            }

            // Assert
            updatedTeamMember.Name.Should().Be("Rey Skywalker");
        }