Пример #1
0
 public void Dispose()
 {
     if (_controllerDb != null)
     {
         _controllerDb.Dispose();
         _controllerDb = null;
     }
     if (_controllerDbScope != null)
     {
         _controllerDbScope.Dispose();
         _controllerDbScope = null;
     }
     if (_controller != null)
     {
         _controller.Dispose();
         _controller = null;
     }
     if (_initDb != null)
     {
         _initDb.Posts.RemoveRange(Posts);
         _initDb.Authors.Remove(Author);
         _initDb.SaveChanges();
         _initDb.Dispose();
         _initDb = null;
     }
     if (_initDbScope != null)
     {
         _initDbScope.Dispose();
         _initDbScope = null;
     }
 }
Пример #2
0
        public async Task TestGeneratedRowVersion()
        {
            var gct = new GeneratedRowVersion {
                Gen = 1
            };

            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                db.GeneratedRowVersion.Add(gct);
                await db.SaveChangesAsync();

                using (var scope2 = new AppDbScope())
                {
                    var db2  = scope2.AppDb;
                    var gct2 = await db2.GeneratedRowVersion.FindAsync(gct.Id);

                    gct2.Gen++;
                    await db2.SaveChangesAsync();
                }

                gct.Gen++;
                await Assert.ThrowsAsync <DbUpdateConcurrencyException>(() => db.SaveChangesAsync());
            }
        }
Пример #3
0
        public ExpressionTest()
        {
            _scope = new AppDbScope();

            // initialize simple data types
            _simple = new DataTypesSimple
            {
                TypeDateTime = new DateTime(2017, 1, 1, 0, 0, 0),
                TypeDouble   = 3.1415,
                TypeDoubleN  = -3.1415
            };
            _db.DataTypesSimple.Add(_simple);

            // initialize simple data types
            _simple2 = new DataTypesSimple
            {
                TypeDouble  = 1,
                TypeDoubleN = -1
            };
            _db.DataTypesSimple.Add(_simple2);

            // initialize variable data types
            _variable            = DataTypesVariable.CreateEmpty();
            _variable.TypeString = "EntityFramework";

            _db.DataTypesVariable.Add(_variable);
            _db.SaveChanges();
        }
 public static void Run()
 {
     Console.WriteLine("Running migrations...");
     using (var dbScope = new AppDbScope()){
         dbScope.AppDb.Database.Migrate();
     }
     Console.WriteLine("Done");
 }
        public async Task SequenceIncrement()
        {
            var sequence1 = new Sequence();
            var sequence2 = new Sequence();

            using (var scope = new AppDbScope())
            {
                scope.AppDb.Sequence.AddRange(new [] { sequence1, sequence2 });
                await scope.AppDb.SaveChangesAsync();
            }
            Assert.Equal(sequence1.Id + 1, sequence2.Id);
        }
Пример #6
0
        public async Task TestGeneratedContact()
        {
            const string email            = "*****@*****.**";
            const string address          = "123 Entity Framework Ln";
            const string city             = "Redmond";
            const string state            = "WA";
            const string zip              = "99999";
            var          addressFormatted = string.Join(", ", address, city, state, zip);

            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                void TestContact(GeneratedContact contact)
                {
                    var csb        = new MySqlConnectionStringBuilder(db.Database.GetDbConnection().ConnectionString);
                    var guidHexStr = csb.OldGuids
                                    ? BitConverter.ToString(contact.Id.ToByteArray().Take(8).ToArray()).Replace("-", "")
                                    : contact.Id.ToString().Replace("-", "").Substring(0, 16);
                    var guidTicks    = Convert.ToInt64("0x" + guidHexStr, 16);
                    var guidDateTime = new DateTime(guidTicks);

                    Assert.InRange(guidDateTime - DateTime.UtcNow, TimeSpan.FromSeconds(-5), TimeSpan.FromSeconds(5));
                    Assert.Equal(email, contact.Email);
                    Assert.Equal(addressFormatted, contact.Address);
                }

                var gen = new GeneratedContact
                {
                    Names = new JsonObject <List <string> >(new List <string> {
                        "Bob", "Bobby"
                    }),
                    ContactInfo = new JsonObject <Dictionary <string, string> >(new Dictionary <string, string>
                    {
                        { "Email", email },
                        { "Address", address },
                        { "City", city },
                        { "State", state },
                        { "Zip", zip },
                    }),
                };

                // test the entity after saving to the db
                db.GeneratedContacts.Add(gen);
                await db.SaveChangesAsync();

                TestContact(gen);

                // test the entity after fresh retreival from the database
                var genDb = await db.GeneratedContacts.FirstOrDefaultAsync(m => m.Id == gen.Id);

                TestContact(genDb);
            }
        }
Пример #7
0
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                var tryMigrate = 0;
                while (true)
                {
                    try
                    {
                        Console.WriteLine($"Migration attempt {tryMigrate + 1}/3");
                        using (var dbScope = new AppDbScope())
                            dbScope.AppDb.Database.Migrate();
                        Console.WriteLine("Migration complete");
                        break;
                    }
                    catch (MySqlException e)
                    {
                        Console.WriteLine("Migration failed");
                        Console.WriteLine(e.Message);
                        if (tryMigrate >= 2)
                        {
                            throw;
                        }
                        Console.WriteLine("Trying again in 3 seconds");
                        Thread.Sleep(TimeSpan.FromSeconds(3));
                    }
                    tryMigrate++;
                }

                var host = new WebHostBuilder()
                           .UseUrls("http://*:5000")
                           .UseKestrel()
                           .UseStartup <Startup>()
                           .Build();
                host.Run();
            }
            else
            {
                Environment.Exit(CommandRunner.Run(args));
            }
        }
        public async Task TestCrmSuperUserExplicitLoading()
        {
            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                // load just the superUser
                var superUser = await db.CrmAdmins.OrderByDescending(m => m.Id).FirstOrDefaultAsync();

                // explicit load AdminMenus
                await db.Entry(superUser).Collection(m => m.AdminMenus).LoadAsync();

                // explicit load each Menu
// this code is creating a race condition and hanging somewhere
// probably an upstream bug in EntityFramework, possibly in MySqlConnector
// needs further investigation.  this is a poor way to use Explicit Loading anyways though
//				var tasks = new List<Task>();
//				foreach (var adminMenu in superUser.AdminMenus)
//					tasks.Add(db.Entry(adminMenu).Reference(m => m.Menu).LoadAsync());
//				await Task.WhenAll(tasks);
                foreach (var adminMenu in superUser.AdminMenus)
                {
                    await db.Entry(adminMenu).Reference(m => m.Menu).LoadAsync();
                }

                // explicit load AdminRoles, eagerly loading Roles at the same time
                await db.Entry(superUser).Collection(m => m.AdminRoles).Query().Include(m => m.Role).ToListAsync();

                Assert.NotNull(superUser);
                Assert.Equal("test", superUser.Username);
                Assert.Equal("test", superUser.Password);
                Assert.Equal(5, superUser.AdminMenus.Count);
                Assert.NotNull(superUser.AdminMenus[0].Menu);
                Assert.Equal(4, superUser.AdminRoles.Count);
                Assert.NotNull(superUser.AdminRoles[0].Role);

                // queries can do more than just load!  here's an example to get counts without loading entities
                Assert.Equal(5, await db.Entry(superUser).Collection(m => m.AdminMenus).Query().CountAsync());
                Assert.Equal(4, await db.Entry(superUser).Collection(m => m.AdminRoles).Query().CountAsync());
            }
        }
        public async Task BatchInsertWorksWithMixedNoServerData()
        {
            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;

                var newCatgory = new Category()
                {
                    Name = "test"
                };

                var products = new List <Product>();

                for (var i = 0; i < 10; ++i)
                {
                    var product = new Product()
                    {
                        Name = $"Product {i}",
                    };

                    product.ProductCategories.Add(new ProductCategory()
                    {
                        Category = newCatgory
                    });

                    if (i % 2 == 1)
                    {
                        product.ParentProduct = products[i - 1];
                    }

                    products.Add(product);
                }

                db.Products.AddRange(products);

                var resultCount = await db.SaveChangesAsync();

                Assert.Equal(21, resultCount);
            }
        }
        public async Task TestCrmSuperUserEagerLoading()
        {
            using (var scope = new AppDbScope())
            {
                var db        = scope.AppDb;
                var superUser = await db.CrmAdmins
                                .OrderByDescending(m => m.Id)
                                .Include(m => m.AdminMenus)
                                .ThenInclude(m => m.Menu)
                                .Include(m => m.AdminRoles)
                                .ThenInclude(m => m.Role)
                                .FirstOrDefaultAsync();

                Assert.NotNull(superUser);
                Assert.Equal("test", superUser.Username);
                Assert.Equal("test", superUser.Password);
                Assert.Equal(5, superUser.AdminMenus.Count);
                Assert.NotNull(superUser.AdminMenus[0].Menu);
                Assert.Equal(4, superUser.AdminRoles.Count);
                Assert.NotNull(superUser.AdminRoles[0].Role);
            }
        }
Пример #11
0
        public async Task TestGeneratedTime()
        {
            var gt = new GeneratedTime {
                Name = "test"
            };

            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                db.GeneratedTime.Add(gt);
                await db.SaveChangesAsync();

                Assert.Equal(gt.CreatedDateTime, gt.UpdatedDateTime);
                Assert.Equal(gt.CreatedDateTime3, gt.UpdatedDateTime3);
                Assert.Equal(gt.CreatedDateTime6, gt.UpdatedDateTime6);
                Assert.Equal(gt.CreatedTimestamp, gt.UpdatedTimetamp);
                Assert.Equal(gt.CreatedTimestamp3, gt.UpdatedTimetamp3);
                Assert.Equal(gt.CreatedTimestamp6, gt.UpdatedTimetamp6);

                Assert.InRange(gt.CreatedDateTime3 - gt.CreatedDateTime, TimeSpan.Zero, TimeSpan.FromMilliseconds(999));
                Assert.InRange(gt.CreatedDateTime6 - gt.CreatedDateTime3, TimeSpan.Zero, TimeSpan.FromMilliseconds(0.999));

                Assert.InRange(gt.CreatedTimestamp3 - gt.CreatedTimestamp, TimeSpan.Zero, TimeSpan.FromMilliseconds(999));
                Assert.InRange(gt.CreatedTimestamp6 - gt.CreatedTimestamp3, TimeSpan.Zero, TimeSpan.FromMilliseconds(0.999));

                await Task.Delay(TimeSpan.FromSeconds(1));

                gt.Name = "test2";
                await db.SaveChangesAsync();

                Assert.NotEqual(gt.CreatedDateTime, gt.UpdatedDateTime);
                Assert.NotEqual(gt.CreatedDateTime3, gt.UpdatedDateTime3);
                Assert.NotEqual(gt.CreatedDateTime6, gt.UpdatedDateTime6);
                Assert.NotEqual(gt.CreatedTimestamp, gt.UpdatedTimetamp);
                Assert.NotEqual(gt.CreatedTimestamp3, gt.UpdatedTimetamp3);
                Assert.NotEqual(gt.CreatedTimestamp6, gt.UpdatedTimetamp6);
            }
        }
Пример #12
0
        public ControllerFixture()
        {
            _initDbScope       = new AppDbScope();
            _initDb            = _initDbScope.AppDb;
            _controllerDbScope = new AppDbScope();
            _controllerDb      = _controllerDbScope.AppDb;
            _controller        = (T)Activator.CreateInstance(typeof(T), _controllerDb);

            Author = new Author {
                Name = "author 0"
            };
            _initDb.Authors.Add(Author);
            for (var i = 0; i < 3; i++)
            {
                var post = new Post {
                    Author  = Author,
                    Title   = $"title {i}",
                    Content = $"content {i}",
                };
                Posts.Add(post);
                _initDb.Posts.Add(post);
            }
            _initDb.SaveChanges();
        }
        public DiscriminatorFixture()
        {
            var famalies = new List <PersonFamily>
            {
                new PersonFamily
                {
                    LastName = "Garrison",
                },
                new PersonFamily
                {
                    LastName = "Cartman",
                },
                new PersonFamily
                {
                    LastName = "McCormick",
                },
                new PersonFamily
                {
                    LastName = "Broflovski",
                },
                new PersonFamily
                {
                    LastName = "Marsh",
                },
            };
            var teachers = new List <PersonTeacher>
            {
                new PersonTeacher {
                    Name = "Ms. Frizzle"
                },
                new PersonTeacher {
                    Name = "Mr. Garrison", Family = famalies[0]
                },
                new PersonTeacher {
                    Name = "Mr. Hat", Family = famalies[0]
                },
            };
            var students = new List <PersonKid>
            {
                // magic school bus
                new PersonKid {
                    Name = "Arnold", Grade = 2, Teacher = teachers[0]
                },
                new PersonKid {
                    Name = "Phoebe", Grade = 2, Teacher = teachers[0]
                },
                new PersonKid {
                    Name = "Wanda", Grade = 2, Teacher = teachers[0]
                },

                // southpark
                new PersonKid {
                    Name = "Eric", Grade = 4, Teacher = teachers[1], Family = famalies[1]
                },
                new PersonKid {
                    Name = "Kenny", Grade = 4, Teacher = teachers[1], Family = famalies[2]
                },
                new PersonKid {
                    Name = "Kyle", Grade = 4, Teacher = teachers[1], Family = famalies[3]
                },
                new PersonKid {
                    Name = "Stan", Grade = 4, Teacher = teachers[1], Family = famalies[4]
                },
            };
            var parents = new List <PersonParent>
            {
                new PersonParent {
                    Name = "Liane", Occupation = "Nobody knows...", OnPta = true, Family = famalies[1]
                },
                new PersonParent {
                    Name = "Stuart", Occupation = "Unemployed", OnPta = false, Family = famalies[2]
                },
                new PersonParent {
                    Name = "Carol", Occupation = "Dishwasher at Olive Garden", OnPta = false, Family = famalies[2]
                },
                new PersonParent {
                    Name = "Sheila", Occupation = "Frequent protester", OnPta = true, Family = famalies[3]
                },
                new PersonParent {
                    Name = "Gerald", Occupation = "Lawyer", OnPta = true, Family = famalies[3]
                },
                new PersonParent {
                    Name = "Randy", Occupation = "Geologist", OnPta = true, Family = famalies[4]
                },
                new PersonParent {
                    Name = "Sharon", Occupation = "Receptionist at Tom's Rhinoplasty", OnPta = true, Family = famalies[4]
                },
            };

            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                db.People.AddRange(teachers);
                db.People.AddRange(students);
                db.People.AddRange(parents);
                db.SaveChanges();
                LowestTeacherId  = teachers.First().Id;
                HighestTeacherId = teachers.Last().Id;
            }
        }
        public async Task TestDiscriminator()
        {
            using (var scope = new AppDbScope())
            {
                var db       = scope.AppDb;
                var teachers = await db.People.OfType <PersonTeacher>()
                               .Where(m => m.Id >= _fixture.LowestTeacherId && m.Id <= _fixture.HighestTeacherId)
                               .OrderBy(m => m.Id)
                               .Include(m => m.Family)
                               .ThenInclude(m => m.Members)
                               .Include(m => m.Students)
                               .ThenInclude(m => m.Family)
                               .ThenInclude(m => m.Members)
                               .ToListAsync();

                Assert.Equal(3, teachers.Count);

                // magic school bus
                var frizzle = teachers[0];

                // ms. frizzle has 3 students
                Assert.Equal(3, frizzle.Students.Count);
                var students = new HashSet <string> {
                    "Arnold", "Phoebe", "Wanda"
                };
                foreach (var student in frizzle.Students)
                {
                    Assert.Contains(student.Name, students);
                }

                // southpark
                var garrison = teachers[1];
                var hat      = teachers[2];

                // mr. garrison has 4 student
                Assert.Equal(4, garrison.Students.Count);
                students = new HashSet <string> {
                    "Eric Cartman", "Kenny McCormick", "Kyle Broflovski", "Stan Marsh"
                };
                foreach (var student in garrison.Students)
                {
                    Assert.Contains(student.Name + " " + (student.Family?.LastName ?? ""), students);
                }

                // everyone's parents are on the PTA except for Kenny's
                var pta = new HashSet <string> {
                    "Liane Cartman", "Sheila Broflovski", "Gerald Broflovski", "Randy Marsh", "Sharon Marsh"
                };
                var ptaSize = 0;
                foreach (var student in garrison.Students)
                {
                    foreach (var member in student.Family.Members)
                    {
                        if (member is PersonParent && (member as PersonParent).OnPta)
                        {
                            ptaSize++;
                            Assert.Contains(member.Name + " " + (member.Family?.LastName ?? ""), pta);
                        }
                    }
                }
                Assert.Equal(pta.Count, ptaSize);

                // mr. hat has no students, but he is in mr. garrison's family
                Assert.Equal(0, hat.Students.Count);
                Assert.Contains(hat, garrison.Family.Members);
            }
        }
Пример #15
0
        public async Task TestDataTypesSimple()
        {
            void TestEmpty(DataTypesSimple emptyDb)
            {
                // bool
                Assert.Equal(default(bool), emptyDb.TypeBool);
                // nullable bool
                Assert.Equal(null, emptyDb.TypeBoolN);

                // integers
                Assert.Equal(default(short), emptyDb.TypeShort);
                Assert.Equal(default(ushort), emptyDb.TypeUshort);
                Assert.Equal(default(int), emptyDb.TypeInt);
                Assert.Equal(default(uint), emptyDb.TypeUint);
                Assert.Equal(default(long), emptyDb.TypeLong);
                Assert.Equal(default(ulong), emptyDb.TypeUlong);
                // nullable integers
                Assert.Equal(null, emptyDb.TypeShortN);
                Assert.Equal(null, emptyDb.TypeUshortN);
                Assert.Equal(null, emptyDb.TypeIntN);
                Assert.Equal(null, emptyDb.TypeUintN);
                Assert.Equal(null, emptyDb.TypeLongN);
                Assert.Equal(null, emptyDb.TypeUlongN);

                // decimals
                Assert.Equal(default(decimal), emptyDb.TypeDecimal);
                Assert.Equal(default(double), emptyDb.TypeDouble);
                Assert.Equal(default(float), emptyDb.TypeFloat);
                // nullable decimals
                Assert.Equal(null, emptyDb.TypeDecimalN);
                Assert.Equal(null, emptyDb.TypeDoubleN);
                Assert.Equal(null, emptyDb.TypeFloatN);

                // byte
                Assert.Equal(default(sbyte), emptyDb.TypeSbyte);
                Assert.Equal(default(byte), emptyDb.TypeByte);
                Assert.Equal(default(char), emptyDb.TypeChar);
                // nullable byte
                Assert.Equal(null, emptyDb.TypeSbyteN);
                Assert.Equal(null, emptyDb.TypeByteN);
                Assert.Equal(null, emptyDb.TypeCharN);

                // DateTime
                Assert.Equal(default(DateTime), emptyDb.TypeDateTime);
                Assert.Equal(default(DateTimeOffset), emptyDb.TypeDateTimeOffset);
                Assert.Equal(default(TimeSpan), emptyDb.TypeTimeSpan);
                // nullable DateTime
                Assert.Equal(null, emptyDb.TypeDateTimeN);
                Assert.Equal(null, emptyDb.TypeDateTimeOffsetN);
                Assert.Equal(null, emptyDb.TypeTimeSpanN);

                // Enum
                Assert.Equal(default(TestEnum), emptyDb.TypeEnum);
                Assert.Equal(default(TestEnumByte), emptyDb.TypeEnumByte);
                // nullableEnum
                Assert.Equal(null, emptyDb.TypeEnumN);
                Assert.Equal(null, emptyDb.TypeEnumByteN);

                // guid
                Assert.Equal(default(Guid), emptyDb.TypeGuid);
                // nullable guid
                Assert.Equal(null, emptyDb.TypeGuidN);
            }

            const sbyte testSbyte = (sbyte)-128;
            const byte  testByte  = (byte)255;
            const char  testChar  = 'a';
            const float testFloat = (float)1.23456789e38;

            var                dateTime       = new DateTime(2016, 10, 11, 1, 2, 3, 456);
            var                dateTimeOffset = dateTime + TimeSpan.FromMilliseconds(123.456);
            var                timeSpan       = new TimeSpan(1, 2, 3, 4, 5);
            const TestEnum     testEnum       = TestEnum.TestOne;
            const TestEnumByte testEnumByte   = TestEnumByte.TestOne;
            var                guid           = Guid.NewGuid();

            // test each data type with a valid value
            // ReSharper disable once ObjectCreationAsStatement
            DataTypesSimple NewValueMem() => new DataTypesSimple
            {
                // bool
                TypeBool = true,
                // nullable bool
                TypeBoolN = true,

                // integers
                TypeShort  = short.MinValue,
                TypeUshort = ushort.MaxValue,
                TypeInt    = int.MinValue,
                TypeUint   = uint.MaxValue,
                TypeLong   = long.MinValue,
                TypeUlong  = ulong.MaxValue,
                // nullable integers
                TypeShortN  = short.MinValue,
                TypeUshortN = ushort.MaxValue,
                TypeIntN    = int.MinValue,
                TypeUintN   = uint.MaxValue,
                TypeLongN   = long.MinValue,
                TypeUlongN  = ulong.MaxValue,

                // decimals
                TypeDecimal = decimal.MaxValue,
                TypeDouble  = double.MaxValue,
                TypeFloat   = testFloat,
                // nullable decimals
                TypeDecimalN = decimal.MaxValue,
                TypeDoubleN  = double.MaxValue,
                TypeFloatN   = testFloat,

                // byte
                TypeSbyte = testSbyte,
                TypeByte  = testByte,
                TypeChar  = testChar,
                // nullable byte
                TypeSbyteN = testSbyte,
                TypeByteN  = testByte,
                TypeCharN  = testChar,

                // DateTime
                TypeDateTime       = dateTime,
                TypeDateTimeOffset = dateTimeOffset,
                TypeTimeSpan       = timeSpan,
                // nullable DateTime
                TypeDateTimeN       = dateTime,
                TypeDateTimeOffsetN = dateTimeOffset,
                TypeTimeSpanN       = timeSpan,

                // Enum
                TypeEnum     = testEnum,
                TypeEnumByte = testEnumByte,
                // nullable Enum
                TypeEnumN     = testEnum,
                TypeEnumByteN = testEnumByte,

                // guid
                TypeGuid = guid,
                // nullable guid
                TypeGuidN = guid,
            };

            void TestValue(DataTypesSimple valueDb)
            {
                // bool
                Assert.Equal(true, valueDb.TypeBool);
                // nullable bool
                Assert.Equal(true, valueDb.TypeBoolN);

                // integers
                Assert.Equal(short.MinValue, valueDb.TypeShort);
                Assert.Equal(ushort.MaxValue, valueDb.TypeUshort);
                Assert.Equal(int.MinValue, valueDb.TypeInt);
                Assert.Equal(uint.MaxValue, valueDb.TypeUint);
                Assert.Equal(long.MinValue, valueDb.TypeLong);
                Assert.Equal(ulong.MaxValue, valueDb.TypeUlong);
                // nullable integers
                Assert.Equal(short.MinValue, valueDb.TypeShortN);
                Assert.Equal(ushort.MaxValue, valueDb.TypeUshortN);
                Assert.Equal(int.MinValue, valueDb.TypeIntN);
                Assert.Equal(uint.MaxValue, valueDb.TypeUintN);
                Assert.Equal(long.MinValue, valueDb.TypeLongN);
                Assert.Equal(ulong.MaxValue, valueDb.TypeUlongN);

                // decimals
                Assert.Equal(decimal.MaxValue, valueDb.TypeDecimal);
                Assert.Equal(double.MaxValue, valueDb.TypeDouble);
                Assert.InRange(valueDb.TypeFloat, testFloat * (1 - 7e-1), testFloat * (1 + 7e-1)); // floats have 7 digits of precision
                // nullable decimals
                Assert.Equal(decimal.MaxValue, valueDb.TypeDecimalN);
                Assert.Equal(double.MaxValue, valueDb.TypeDoubleN);
                Assert.InRange(valueDb.TypeFloatN.GetValueOrDefault(), testFloat * (1 - 7e-1), testFloat * (1 + 7e-1)); // floats have 7 digits of precision

                // byte
                Assert.Equal(testSbyte, valueDb.TypeSbyte);
                Assert.Equal(testByte, valueDb.TypeByte);
                Assert.Equal(testChar, valueDb.TypeChar);
                // nullable byte
                Assert.Equal(testSbyte, valueDb.TypeSbyte);
                Assert.Equal(testByte, valueDb.TypeByteN);
                Assert.Equal(testChar, valueDb.TypeCharN);

                // DateTime
                Assert.Equal(dateTime, valueDb.TypeDateTime);
                Assert.Equal(dateTimeOffset, valueDb.TypeDateTimeOffset);
                Assert.Equal(timeSpan, valueDb.TypeTimeSpan);
                // nullable DateTime
                Assert.Equal(dateTime, valueDb.TypeDateTimeN);
                Assert.Equal(dateTimeOffset, valueDb.TypeDateTimeOffsetN);
                Assert.Equal(timeSpan, valueDb.TypeTimeSpanN);

                // Enum
                Assert.Equal(testEnum, valueDb.TypeEnum);
                Assert.Equal(testEnumByte, valueDb.TypeEnumByte);
                // nullable Enum
                Assert.Equal(testEnum, valueDb.TypeEnumN);
                Assert.Equal(testEnumByte, valueDb.TypeEnumByteN);

                // guid
                Assert.Equal(guid, valueDb.TypeGuid);
                // nullable guid
                Assert.Equal(guid, valueDb.TypeGuidN);
            }

            // create test data objects
            var emptyMemAsync = new DataTypesSimple();
            var emptyMemSync  = new DataTypesSimple();
            var valueMemAsync = NewValueMem();
            var valueMemSync  = NewValueMem();

            // save them to the database
            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                db.DataTypesSimple.Add(emptyMemAsync);
                db.DataTypesSimple.Add(valueMemAsync);
                await db.SaveChangesAsync();

                db.DataTypesSimple.Add(emptyMemSync);
                db.DataTypesSimple.Add(valueMemSync);
                db.SaveChanges();
            }

            // load them from the database and run tests
            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                // ReSharper disable once AccessToDisposedClosure
                async Task <DataTypesSimple> FromDbAsync(DataTypesSimple dt) => await db.DataTypesSimple.FirstOrDefaultAsync(m => m.Id == dt.Id);

                // ReSharper disable once AccessToDisposedClosure
                DataTypesSimple FromDbSync(DataTypesSimple dt) => db.DataTypesSimple.FirstOrDefault(m => m.Id == dt.Id);

                TestEmpty(await FromDbAsync(emptyMemAsync));
                TestEmpty(FromDbSync(emptyMemSync));
                TestValue(await FromDbAsync(valueMemAsync));
                TestValue(FromDbSync(valueMemSync));
            }
        }
        public CrmFixture()
        {
            using (var scope = new AppDbScope())
            {
                var db         = scope.AppDb;
                var superAdmin = new CrmAdmin
                {
                    Username = "******",
                    Password = "******"
                };
                var menus = new List <CrmMenu>
                {
                    new CrmMenu {
                        Name = "Dashboard"
                    },
                    new CrmMenu {
                        Name = "Posts"
                    },
                    new CrmMenu {
                        Name = "Media"
                    },
                    new CrmMenu {
                        Name = "Comments"
                    },
                    new CrmMenu {
                        Name = "Themes"
                    }
                };
                var roles = new List <CrmRole>
                {
                    new CrmRole {
                        Name = "Viewer"
                    },
                    new CrmRole {
                        Name = "Author"
                    },
                    new CrmRole {
                        Name = "Editor"
                    },
                    new CrmRole {
                        Name = "Admin"
                    },
                };
                db.CrmMenus.AddRange(menus);
                db.CrmRoles.AddRange(roles);

                superAdmin.AdminMenus = new List <CrmAdminMenu>();
                foreach (var menu in menus)
                {
                    superAdmin.AdminMenus.Add(new CrmAdminMenu {
                        Menu = menu
                    });
                }

                superAdmin.AdminRoles = new List <CrmAdminRole>();
                foreach (var role in roles)
                {
                    superAdmin.AdminRoles.Add(new CrmAdminRole {
                        Role = role
                    });
                }
                db.CrmAdmins.Add(superAdmin);

                db.SaveChanges();
            }
        }
Пример #17
0
        public async Task TestDataTypesVariable()
        {
            void TestEmpty(DataTypesVariable valueDb)
            {
                // string not null
                Assert.Equal("", valueDb.TypeString);
                Assert.Equal("", valueDb.TypeString255);
                // string null
                Assert.Equal(null, valueDb.TypeStringN);
                Assert.Equal(null, valueDb.TypeString255N);

                // binary not null
                Assert.Equal(DataTypesVariable.EmptyByteArray, valueDb.TypeByteArray);
                Assert.Equal(DataTypesVariable.EmptyByteArray, valueDb.TypeByteArray255);
                // binary null
                Assert.Equal(null, valueDb.TypeByteArrayN);
                Assert.Equal(null, valueDb.TypeByteArray255N);

                // json not null
                Assert.Equal(DataTypesVariable.EmptyJsonArray.Json, valueDb.TypeJsonArray.Json);
                Assert.Equal(DataTypesVariable.EmptyJsonObject.Json, valueDb.TypeJsonObject.Json);
                // json null
                Assert.Equal(null, valueDb.TypeJsonArrayN);
                Assert.Equal(null, valueDb.TypeJsonObjectN);
            }

            var string255 = new string('a', 255);
            var string10K = new string('a', 10000);

            var byte255 = new byte[255];
            var byte10K = new byte[10000];

            for (var i = 0; i < byte10K.Length; i++)
            {
                if (i < 255)
                {
                    byte255[i] = (byte)'a';
                }
                byte10K[i] = (byte)'a';
            }

            var jsonArray = new JsonObject <List <string> >(new List <string> {
                "test"
            });
            var jsonObject = new JsonObject <Dictionary <string, string> >(new Dictionary <string, string> {
                { "test", "test" }
            });

            // test each data type with a valid value
            DataTypesVariable NewValueMem() => new DataTypesVariable
            {
                // string not null
                TypeString    = string10K,
                TypeString255 = string255,     // should be truncated by DBMS
                // string null
                TypeStringN    = string10K,
                TypeString255N = string255,     // should be truncated by DBMS

                // binary not null
                TypeByteArray    = byte10K,
                TypeByteArray255 = byte255,     // should be truncated by DBMS
                // binary null
                TypeByteArrayN    = byte10K,
                TypeByteArray255N = byte255,     // should be truncated by DBMS

                // json not null
                TypeJsonArray  = jsonArray,
                TypeJsonObject = jsonObject,
                // json null
                TypeJsonArrayN  = jsonArray,
                TypeJsonObjectN = jsonObject,
            };

            void TestValue(DataTypesVariable valueDb)
            {
                // string not null
                Assert.Equal(string10K, valueDb.TypeString);
                Assert.Equal(string255, valueDb.TypeString255);
                // string null
                Assert.Equal(string10K, valueDb.TypeStringN);
                Assert.Equal(string255, valueDb.TypeString255N);

                // binary not null
                Assert.Equal(byte10K, valueDb.TypeByteArray);
                Assert.Equal(byte255, valueDb.TypeByteArray255);
                // binary null
                Assert.Equal(byte10K, valueDb.TypeByteArrayN);
                Assert.Equal(byte255, valueDb.TypeByteArray255N);

                // json not null
                Assert.Equal(jsonArray.Json, valueDb.TypeJsonArray.Json);
                Assert.Equal(jsonObject.Json, valueDb.TypeJsonObject.Json);
                // json null
                Assert.Equal(jsonArray.Json, valueDb.TypeJsonArrayN.Json);
                Assert.Equal(jsonObject.Json, valueDb.TypeJsonObjectN.Json);
            }

            // create test data objects
            var emptyMemAsync = DataTypesVariable.CreateEmpty();
            var emptyMemSync  = DataTypesVariable.CreateEmpty();
            var valueMemAsync = NewValueMem();
            var valueMemSync  = NewValueMem();

            // save them to the database
            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                db.DataTypesVariable.Add(emptyMemAsync);
                db.DataTypesVariable.Add(valueMemAsync);
                await db.SaveChangesAsync();

                db.DataTypesVariable.Add(emptyMemSync);
                db.DataTypesVariable.Add(valueMemSync);
                db.SaveChanges();
            }

            // load them from the database and run tests
            using (var scope = new AppDbScope())
            {
                var db = scope.AppDb;
                // ReSharper disable once AccessToDisposedClosure
                async Task <DataTypesVariable> FromDbAsync(DataTypesVariable dt) => await db.DataTypesVariable.FirstOrDefaultAsync(m => m.Id == dt.Id);

                // ReSharper disable once AccessToDisposedClosure
                DataTypesVariable FromDbSync(DataTypesVariable dt) => db.DataTypesVariable.FirstOrDefault(m => m.Id == dt.Id);

                TestEmpty(await FromDbAsync(emptyMemAsync));
                TestEmpty(FromDbSync(emptyMemSync));
                TestValue(await FromDbAsync(valueMemAsync));
                TestValue(FromDbSync(valueMemSync));
            }
        }