Пример #1
0
        public void Delete_Localizable_Entity_In_NonDefault_Language_Delete_Only_Specific_Localizations()
        {
            using (var db = new TestDataContext())
            {
                db.ReCreate();
                var entity = new LocalizedEntity {
                    NotLocalizedText = "NotLocalizedText", LocalizedText = "LocalizedText"
                };
                db.LocalizedEntities.Add(entity);
                db.SaveChanges();
                entity = db.LocalizedEntities.First();
                entity.LanguageCode  = "cs";
                entity.LocalizedText = "new localized text";
                db.SaveChanges();
            }
            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.First();
                entity.LanguageCode  = "cs";
                entity.ArchivedOnUtc = DateTime.Now;
                db.LocalizedEntities.Remove(entity);
                db.SaveChanges();
            }

            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.First();

                Assert.AreEqual(1, entity.Id);
                Assert.AreEqual("NotLocalizedText", entity.NotLocalizedText);
                Assert.AreEqual("LocalizedText", entity.LocalizedText);
                Assert.IsTrue(!db.Localizations.Any());
            }
        }
Пример #2
0
        public void Delete_Localizable_Entity_In_Default_Language_Delete_AllLocalizations_And_Entity()
        {
            using (var db = new TestDataContext())
            {
                db.ReCreate();
                var entity = new LocalizedEntity {
                    NotLocalizedText = "NotLocalizedText", LocalizedText = "LocalizedText"
                };
                db.LocalizedEntities.Add(entity);
                db.SaveChanges();
                entity = db.LocalizedEntities.First();
                entity.LanguageCode  = "cs";
                entity.LocalizedText = "new localized text";
                db.SaveChanges();
            }
            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.First();
                entity.ArchivedOnUtc = DateTime.Now;                 // force delete
                db.LocalizedEntities.Remove(entity);
                db.SaveChanges();
            }

            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.FirstOrDefault();

                Assert.IsNull(entity);
                Assert.IsTrue(!db.Localizations.Any());
            }
        }
Пример #3
0
        public void Add_Localizable_Entity_Preserve_Original_And_Loads_Localized()
        {
            using (var db = new TestDataContext())
            {
                db.ReCreate();
                var entity = new LocalizedEntity {
                    NotLocalizedText = "NotLocalizedText", LocalizedText = "LocalizedText"
                };

                db.LocalizedEntities.Add(entity);
                db.SaveChanges();
            }

            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.First();
                entity.LanguageCode  = "cs";
                entity.LocalizedText = "new localized text";
                db.SaveChanges();
            }

            using (var db = new TestDataContext())
            {
                var entity = db.LocalizeEntity(db.LocalizedEntities.First(), "cs");

                Assert.AreEqual(1, entity.Id);
                Assert.AreEqual("NotLocalizedText", entity.NotLocalizedText);
                Assert.AreEqual("new localized text", entity.LocalizedText);
            }
        }
Пример #4
0
        public void Add_Localizable_Entity_Does_Add_Localizations()
        {
            using (var db = new TestDataContext())
            {
                db.ReCreate();
                var entity = new LocalizedEntity {
                    NotLocalizedText = "NotLocalizedText", LocalizedText = "LocalizedText"
                };

                db.LocalizedEntities.Add(entity);
                db.SaveChanges();
            }

            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.First();
                entity.LanguageCode  = "cs";
                entity.LocalizedText = "new localized text";
                db.SaveChanges();
            }

            using (var db = new TestDataContext())
            {
                var entity = db.LocalizedEntities.First();

                Assert.IsTrue(db.LocalizedEntities.Count() == 1);
                Assert.IsTrue(db.Localizations.Count() == 1);
                Assert.IsTrue(db.Localizations.Count(x => x.EntityName == typeof(LocalizedEntity).FullName && x.EntityPkValue == entity.Id) == 1);
                Assert.IsTrue(db.Localizations.Single(x => x.EntityName == typeof(LocalizedEntity).FullName && x.EntityPkValue == entity.Id && x.EntityPropertyName == "LocalizedText").Text == "new localized text");
                Assert.AreEqual("NotLocalizedText", entity.NotLocalizedText);
                Assert.AreEqual("LocalizedText", entity.LocalizedText);
                Assert.AreEqual(1, entity.Id);
            }
        }
Пример #5
0
 private void CreateBaseData()
 {
     CreateUser();
     CreateGame();
     CreateRound();
     TestDataContext.SaveChanges();
 }
Пример #6
0
        public void GetAllCommentsCreatedInTimeRange_SomeAreOutOfRange_CorrectDataReturned()
        {
            // Arrange
            var until = DateTime.Now;
            var from  = until.AddDays(-5);

            var outOfRangeComment = RandomDataEntityGenerator.CreateCommentWithRandomData();

            outOfRangeComment.CreatedDateTime = until.AddMinutes(1);
            var comment2 = RandomDataEntityGenerator.CreateCommentWithRandomData();

            comment2.CreatedDateTime = from.AddDays(2);
            var outOfRangeComment1 = RandomDataEntityGenerator.CreateCommentWithRandomData();

            outOfRangeComment1.CreatedDateTime = from.AddMinutes(-1);

            TestDataContext.Comments.AddRange(new[] { outOfRangeComment, comment2, outOfRangeComment1 });
            TestDataContext.SaveChanges();

            // Act
            var result = _SUT.GetCommentsCreatedInRange(from, until);

            // Assert
            Assert.AreEqual(1, result.Count);
        }
Пример #7
0
        public void GetAllCommentsCreatedInTimeRange_WhenAllInInclusiveRange_CorrectDataReturned()
        {
            // Arrange
            var until = DateTime.Now;
            var from  = until.AddDays(-5);

            var comment1 = RandomDataEntityGenerator.CreateCommentWithRandomData();

            comment1.CreatedDateTime = until;
            var comment2 = RandomDataEntityGenerator.CreateCommentWithRandomData();

            comment2.CreatedDateTime = from.AddDays(2);
            var comment3 = RandomDataEntityGenerator.CreateCommentWithRandomData();

            comment3.CreatedDateTime = from;

            TestDataContext.Comments.AddRange(new[] { comment1, comment2, comment3 });
            TestDataContext.SaveChanges();

            // Act
            var result = _SUT.GetCommentsCreatedInRange(from, until);

            // Assert
            Assert.AreEqual(3, result.Count);
        }
Пример #8
0
        public void ParallelQueries_Always_Crash()
        {
            // Arrange

            var user = RandomDataEntityGenerator.CreateUserWithRandomData();

            for (int postIndex = 0; postIndex < 10; postIndex++)
            {
                var post = RandomDataEntityGenerator.CreatePostWithRandomData(false);

                user.Posts.Add(post);
            }

            TestDataContext.Add(user);
            TestDataContext.SaveChanges();

            // Act / Assert
            using (var dbContext = CreateTestDataContext())
            {
                var postsQuery = dbContext.Posts;

                foreach (var post in postsQuery)
                {
                    // throws an error because same transaction is used = command is already in progress
                    Assert.ThrowsException <NpgsqlOperationInProgressException>(() =>
                    {
                        var firstName = post.User.FirstName;
                    });
                    var posText = post.Text;
                }
            }
        }
Пример #9
0
        public void GetPostsWithCommentsCreatedInRange_WhenMultipleCommentsPerPost_CorrectAmountReturned()
        {
            // Arrange
            var until = DateTime.Now.AddDays(-1);
            var from  = until.AddDays(-5);

            var user = RandomDataEntityGenerator.CreateUserWithRandomData();
            var post = RandomDataEntityGenerator.CreatePostWithRandomData(false);

            post.User        = user;
            post.CreatedTime = from.AddDays(1);

            var comment1 = RandomDataEntityGenerator.CreateCommentWithRandomData(false);

            comment1.User = user;
            comment1.Post = post;

            var comment2 = RandomDataEntityGenerator.CreateCommentWithRandomData(false);

            comment2.User = user;
            comment2.Post = post;

            TestDataContext.Comments.AddRange(new[] { comment1, comment2 });
            TestDataContext.SaveChanges();

            // Act
            var result = _SUT.GetPostsWithCommentsCreatedInRange(from, until);

            // Assert
            Assert.AreEqual(1, result.Count());
        }
Пример #10
0
        public void ParallelQueries_OtherContext_ShouldBeOK()
        {
            // Arrange
            var user = RandomDataEntityGenerator.CreateUserWithRandomData();

            for (int postIndex = 0; postIndex < 10; postIndex++)
            {
                var post = RandomDataEntityGenerator.CreatePostWithRandomData(false);

                user.Posts.Add(post);
            }

            TestDataContext.Add(user);
            TestDataContext.SaveChanges();

            // Act / Assert
            using (DataContext context = CreateTestDataContext()
                   , context2 = CreateTestDataContext())
            {
                var postsQuery = context.Posts;

                foreach (var post in postsQuery)
                {
                    context2.Attach(post).Reference(x => x.User).Load();
                    var firstName = post.User.FirstName;
                    var postText  = post.Text;
                }
            }
        }
Пример #11
0
        public async Task DeveAtualizarPessoa()
        {
            var pessoa = new Pessoa
            {
                Nome    = "nova pessoa",
                Twitter = "novo twitter"
            };

            TestDataContext.Add(pessoa);
            TestDataContext.SaveChanges();

            var data = TestDataContext.Pessoas.Where(c => c.Nome == pessoa.Nome && c.Twitter == pessoa.Twitter).FirstOrDefault();

            data.Nome    = "pessoa alterada";
            data.Twitter = "twitter alterado";

            var strPessoa   = JsonConvert.SerializeObject(data);
            var httpContent = new StringContent(strPessoa, Encoding.UTF8, "application/json");

            var response = await Client.PutAsync(BaseUrl, httpContent);

            response.EnsureSuccessStatusCode();

            Assert.Equal("OK", response.StatusCode.ToString());

            var pessoaAlterada = TestDataContext.Pessoas.Where(c => c.Nome == data.Nome && c.Twitter == data.Twitter).FirstOrDefault();

            Assert.NotNull(pessoaAlterada);
        }
Пример #12
0
 /// <summary>
 /// Check to see if the database exists. If not, create it and load
 /// the test data.
 /// </summary>
 /// <param name="dataContext">The <see cref="TestDataContext"/>/.</param>
 public void CheckAndSeed(TestDataContext dataContext)
 {
     if (dataContext.Database.EnsureCreated())
     {
         var data = GenerateSeed();
         dataContext.TestAssemblies.AddRange(data);
         dataContext.SaveChanges();
     }
 }
Пример #13
0
        public void InsertBigData()
        {
            var dbUser = db.Set <User>();

            for (int i = 0; i < 200000; i++)
            {
                dbUser.Add(new User()
                {
                    LastLoginDate = DateTime.Now,
                    Password      = "******",
                    Username      = "******",
                    CreateTime    = DateTime.Now,
                    IsEnabled     = false,
                    Status        = T.A
                });
            }
            db.SaveChanges();
        }
Пример #14
0
        public void AddData()
        {
            var testItem = new TestData
            {
                Name   = "testName",
                Number = 42,
                IsTrue = true
            };

            testDataContext.TestDatas.Add(testItem);
            testDataContext.SaveChanges();
        }
Пример #15
0
        public void Add_Localizable_Entity_In_NonDefault_Language_Throws_NotSupportedException()
        {
            using (var db = new TestDataContext())
            {
                db.ReCreate();
                var entity = new LocalizedEntity {
                    NotLocalizedText = "NotLocalizedText", LocalizedText = "LocalizedText", LanguageCode = "cs"
                };

                db.LocalizedEntities.Add(entity);
                db.SaveChanges();                 // -> shoud throw exception...
            }
        }
        /// <summary>
        /// Creates a test context
        /// </summary>
        /// <returns>The test context</returns>
        private TestDataContext CreateContext()
        {
            var name           = Guid.NewGuid().ToString("N");
            var optionsBuilder = new DbContextOptionsBuilder <TestDataContext>();

            optionsBuilder.UseInMemoryDatabase(name);

            var context = new TestDataContext(optionsBuilder.Options);

            // context.Database.Delete();
            var users =
                Enumerable.Range(1, 100).Select(n => new User {
                Login = $"user{n:####}", Uid = Guid.NewGuid(), Roles = new List <RoleUser>()
            }).ToList();
            var roles =
                Enumerable.Range(1, 10).Select(n => new Role {
                Name = $"role{n:###}", Uid = Guid.NewGuid(), Users = new List <RoleUser>()
            }).ToList();

            for (var roleNum = 1; roleNum <= roles.Count; roleNum++)
            {
                var role = roles[roleNum - 1];
                for (var userNum = 1; userNum <= users.Count; userNum++)
                {
                    var user = users[userNum - 1];
                    if (userNum % roleNum == 0)
                    {
                        role.Users.Add(new RoleUser {
                            User = user
                        });
                    }

                    context.Users.Add(user);
                }

                context.Roles.Add(role);
            }

            context.SaveChanges();
            return(new TestDataContext(optionsBuilder.Options));
        }
Пример #17
0
        public void GetPostsWithCommentsCreatedInRange_WhenAllInExclusiveRange_CorrectDataReturned()
        {
            // Arrange
            var until = DateTime.Now.AddDays(-1);
            var from  = until.AddDays(-5);

            var comment1 = RandomDataEntityGenerator.CreateCommentWithRandomData();
            var comment2 = RandomDataEntityGenerator.CreateCommentWithRandomData();
            var comment3 = RandomDataEntityGenerator.CreateCommentWithRandomData();

            TestDataContext.Comments.AddRange(new[] { comment1, comment2, comment3 });
            TestDataContext.SaveChanges();

            // Act
            var result = _SUT.GetPostsWithCommentsCreatedInRange(from, until);

            // Assert
            Assert.IsNotNull(result.FirstOrDefault(c => c.Id == comment1.PostId));
            Assert.IsNotNull(result.FirstOrDefault(c => c.Id == comment2.PostId));
            Assert.IsNotNull(result.FirstOrDefault(c => c.Id == comment3.PostId));
        }
Пример #18
0
 public void Add(Category category)
 {
     context.Categories.Add(category);
     context.SaveChanges();
 }
Пример #19
0
        public void TestMethod1()
        {
            var options = new DbContextOptionsBuilder <TestDataContext>()
                          .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
                          .Options;

            using (var context = new TestDataContext(options))
            {
                var streamingUser = new StreamingUser()
                {
                    UserName     = "******",
                    PasswordSalt = "testUser" + Guid.NewGuid().ToString(),
                };

                var streamingUser1 = new StreamingUser()
                {
                    UserName     = "******",
                    PasswordSalt = "testUser1" + Guid.NewGuid().ToString(),
                };

                var streamingUser2 = new StreamingUser()
                {
                    UserName     = "******",
                    PasswordSalt = "testUser2" + Guid.NewGuid().ToString(),
                };

                // Add new entity.
                context.Add(streamingUser);
                context.AddRange(new[] { streamingUser1, streamingUser2 }.ToList <StreamingUser>());
                context.SaveChanges();

                var q = from su in context.Get <StreamingUser>()
                        where su.Id == streamingUser.Id ||
                        su.Id == streamingUser1.Id ||
                        su.Id == streamingUser2.Id
                        select su;

                Console.WriteLine("IDataContext addnew test");
                Assert.IsTrue(q.Count() == 3);

                // Update entity.
                streamingUser.UserName = "******";
                context.Update(streamingUser);

                streamingUser1.UserName = "******";
                context.UpdateRange(new[] { streamingUser1 }.ToList <StreamingUser>());
                context.Update <StreamingUser>(x => x.Id == streamingUser2.Id, x => { x.UserName = "******"; });
                context.SaveChanges();

                var qUpdateCheck = from su in context.Get <StreamingUser>()
                                   where   su.UserName == "1" ||
                                   su.UserName == "2" ||
                                   su.UserName == "3"
                                   select su;
                Console.WriteLine("IDataContext update test");
                Assert.IsTrue(qUpdateCheck.Count() == 3);

                // Delete entry test.
                context.Delete(streamingUser);
                context.DeleteRange(new[] { streamingUser1 }.ToList <StreamingUser>());
                context.Delete <StreamingUser>(x => x.UserName == "3");
                context.SaveChanges();

                Console.WriteLine("IDataContext delete test");
                Assert.IsTrue(!context.Get <StreamingUser>().Any());
            }
        }
        public void Test_RoomBookingsForAccount()
        {
            // -- Arrange --
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            // We are using  TestDataContext to prevent database seeding
            var options = new DbContextOptionsBuilder <DataContext>().UseSqlite(connection).Options;

            var context = new TestDataContext(options);

            context.Database.EnsureCreated();

            // Add some test accounts
            context.Accounts.AddRange(_testAccounts);
            context.SaveChanges();

            // Add some test rooms
            context.Rooms.AddRange(_testRooms);
            context.SaveChanges();

            // Add some test bookings
            List <RoomBooking> testRoomBookings = new List <RoomBooking>
            {
                new RoomBooking {
                    RoomBookingId = 1, AccountId = 1, RoomId = 2, StartDate = DateTime.MinValue, EndDate = DateTime.MinValue, PersonCount = 2, CalculatedPrice = 0
                },
                new RoomBooking {
                    RoomBookingId = 2, AccountId = 1, RoomId = 3, StartDate = DateTime.MinValue, EndDate = DateTime.MinValue, PersonCount = 2, CalculatedPrice = 0
                },
                new RoomBooking {
                    RoomBookingId = 3, AccountId = 1, RoomId = 4, StartDate = DateTime.MinValue, EndDate = DateTime.MinValue, PersonCount = 2, CalculatedPrice = 0
                },
                new RoomBooking {
                    RoomBookingId = 4, AccountId = 2, RoomId = 1, StartDate = DateTime.MinValue, EndDate = DateTime.MinValue, PersonCount = 2, CalculatedPrice = 0
                },
                new RoomBooking {
                    RoomBookingId = 5, AccountId = 2, RoomId = 4, StartDate = DateTime.MinValue, EndDate = DateTime.MinValue, PersonCount = 2, CalculatedPrice = 0
                },
                new RoomBooking {
                    RoomBookingId = 6, AccountId = 3, RoomId = 1, StartDate = DateTime.MinValue, EndDate = DateTime.MinValue, PersonCount = 2, CalculatedPrice = 0
                },
            };

            context.RoomBookings.AddRange(testRoomBookings);
            context.SaveChanges();

            // Set up mocks ready to create the RoomBookingService
            var mockLogger = new Mock <ILogger <RoomBookingService> >();

            // If we need to mock any ILogger properties then do that here...

            // Create the RoomBookingService object for testing
            var roomBookingService = new RoomBookingService(mockLogger.Object, context);

            // -- Act --
            var result = roomBookingService.RoomBookingsForAccount(2).ToList();

            // -- Assert --
            Assert.IsTrue(result.Count() == 2, "Unexpected number of bookings returned!");
            CollectionAssert.AreEquivalent(new long[] { 4, 5 }, result.Select(b => b.RoomBookingId).OrderBy(b => b), "Unexpected booking details returned!");

            connection.Close();
        }
Пример #21
0
 public void Add(Item item)
 {
     context.Items.Add(item);
     context.SaveChanges();
 }